Translation update done using Pootle.
[wammu.git] / Wammu / MailWriter.py
blob7c725053f5504899e9e105af19e8b1a4ed82691b
1 # -*- coding: UTF-8 -*-
2 # vim: expandtab sw=4 ts=4 sts=4:
3 '''
4 Wammu - Phone manager
5 Module for writing SMS to Email.
6 '''
7 __author__ = 'Michal Čihař'
8 __email__ = 'michal@cihar.com'
9 __license__ = '''
10 Copyright © 2003 - 2010 Michal Čihař
12 This program is free software; you can redistribute it and/or modify it
13 under the terms of the GNU General Public License version 2 as published by
14 the Free Software Foundation.
16 This program is distributed in the hope that it will be useful, but WITHOUT
17 ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
18 FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
19 more details.
21 You should have received a copy of the GNU General Public License along with
22 this program; if not, write to the Free Software Foundation, Inc.,
23 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
24 '''
26 from Wammu.Utils import SearchNumber
27 from Wammu.MessageDisplay import SmsTextFormat
28 from email.MIMEAudio import MIMEAudio
29 from email.MIMEImage import MIMEImage
30 from email.MIMEText import MIMEText
31 from email.MIMEMultipart import MIMEMultipart
32 import email.Utils
33 import md5
34 import time
35 import tempfile
36 import os
37 import wx
38 import Wammu.Data
39 if Wammu.gammu_error == None:
40 import gammu
42 HEADER_FORMAT = 'X-Wammu-%s'
43 CID_FORMAT = '%d*sms@wammu.sms'
44 PARTS_TO_HEADER = [
45 'Folder',
46 'Memory',
47 'Location',
48 'Name',
49 'Type',
50 'State',
51 'Class',
52 'MessageReference',
56 def XPMToPNG(image):
57 '''
58 Convert XPM data to PNG image.
60 @todo: I'd like to avoid creating temporary file, but even PIL doesn't
61 seem to provide such functionality.
62 '''
63 handle, name = tempfile.mkstemp()
64 os.close(handle)
65 bitmap = wx.BitmapFromXPMData(image)
66 bitmap.SaveFile(name, wx.BITMAP_TYPE_PNG)
67 f = file(name)
68 data = f.read()
69 f.close()
70 os.unlink(name)
71 return data
73 def RingtoneToMIDI(data):
74 '''
75 Converts ringtone to MIDI data.
77 @todo: I'd like to avoid creating temporary file, but Gammmu doesn't
78 provide such functionality.
79 '''
80 handle, name = tempfile.mkstemp()
81 f = os.fdopen(handle, 'w+')
82 gammu.SaveRingtone(f, data, 'mid')
83 f.seek(0)
84 data = f.read()
85 f.close()
86 os.unlink(name)
87 return data
89 def DateToString(date):
90 '''
91 Convert date to RFC 2822 format.
92 '''
93 return email.Utils.formatdate(time.mktime(date.timetuple()), True)
95 def SMSToMail(cfg, sms, lookuplist = None, mailbox = False):
96 '''
97 Converts SMS to formated mail. It will contain all images and sounds from
98 message and predefined animations. Also text formatting is preserved in
99 HTML.
101 msg = MIMEMultipart('related', None, None, type='text/html')
102 prepend = ''
103 name = ''
104 if lookuplist != None:
105 i = SearchNumber(lookuplist, sms['Number'])
106 if i != -1:
107 msg.add_header(HEADER_FORMAT % 'ContactID', str(i))
108 name = '%s ' % lookuplist[i]['Name']
110 for header in PARTS_TO_HEADER:
111 msg.add_header(HEADER_FORMAT % header, unicode(sms['SMS'][0][header]))
112 msg.add_header(HEADER_FORMAT % 'SMSC', sms['SMS'][0]['SMSC']['Number'])
113 if sms['SMS'][0]['SMSCDateTime'] is not None:
114 msg.add_header(HEADER_FORMAT % 'SMSCDate',
115 DateToString(sms['SMS'][0]['SMSCDateTime']))
117 remote = '%s<%s@wammu.sms>' % (name, sms['Number'].replace(' ', '_'))
118 local = cfg.Read('/MessageExport/From')
120 if sms['SMS'][0]['Type'] == 'Submit':
121 msg['To'] = remote
122 msg['From'] = local
123 else:
124 msg['To'] = local
125 msg['From'] = remote
126 prepend = ('Received: from %s via GSM\n' %
127 unicode(sms['SMS'][0]['SMSC']['Number'])) + prepend
129 if len(sms['Name']) > 0 :
130 msg['Subject'] = SmsTextFormat(cfg, sms['Name'], False)
131 else:
132 msg['Subject'] = SmsTextFormat(cfg, sms['Text'], False)[:50] + '...'
134 if sms['DateTime'] is not None:
135 msg['Date'] = DateToString(sms['DateTime'])
137 if sms.has_key('SMSInfo'):
138 text = ''
139 cid = 0
140 for i in sms['SMSInfo']['Entries']:
141 if i['ID'] in Wammu.Data.SMSIDs['PredefinedAnimation']:
142 if i['Number'] > len(Wammu.Data.PredefinedAnimations):
143 sub = MIMEImage(XPMToPNG(Wammu.Data.UnknownPredefined))
144 else:
145 img = Wammu.Data.PredefinedAnimations[i['Number']][1]
146 xpm = XPMToPNG(img)
147 sub = MIMEImage(xpm)
148 sub.add_header('Content-ID', '<%s>' % CID_FORMAT % cid)
149 sub.add_header('Content-Disposition', 'inline')
150 msg.attach(sub)
151 text = text + '<img src="cid:%s">' % (CID_FORMAT % cid)
152 cid = cid + 1
154 # FIXME: need sounds
155 if 0 and i['ID'] in Wammu.Data.SMSIDs['PredefinedSound']:
156 if i['Number'] >= len(Wammu.Data.PredefinedSounds):
157 sub = ''
158 else:
159 sub = ''
160 sub.add_header('Content-Disposition', 'attachment')
161 msg.attach(sub)
163 if i['ID'] in Wammu.Data.SMSIDs['Sound']:
164 sub = MIMEAudio(RingtoneToMIDI(i['Ringtone']), 'midi')
165 sub.add_header('Content-Disposition', 'attachment')
166 msg.attach(sub)
168 if i['ID'] in Wammu.Data.SMSIDs['Text']:
169 fmt = '%s'
170 for format_data in Wammu.Data.TextFormats:
171 for name, dummy, style in format_data[1:]:
172 if i.has_key(name) and i[name]:
173 fmt = style % fmt
174 text = text + (fmt % SmsTextFormat(cfg, i['Buffer']))
176 if i['ID'] in Wammu.Data.SMSIDs['Bitmap']:
177 for bitmap in i['Bitmap']:
178 sub = MIMEImage(XPMToPNG(bitmap['XPM']))
179 sub.add_header('Content-ID', '<%s>' % CID_FORMAT % cid)
180 sub.add_header('Content-Disposition', 'inline')
181 msg.attach(sub)
182 text = text + '<img src="cid:%s">' % (CID_FORMAT % cid)
183 cid = cid + 1
185 if i['ID'] in Wammu.Data.SMSIDs['Animation']:
186 for bitmap in i['Bitmap']:
187 sub = MIMEImage(XPMToPNG(bitmap['XPM']))
188 sub.add_header('Content-ID', '<%s>' % CID_FORMAT % cid)
189 sub.add_header('Content-Disposition', 'inline')
190 msg.attach(sub)
191 text = text + '<img src="cid:%s">' % (CID_FORMAT % cid)
192 cid = cid + 1
194 else:
195 text = SmsTextFormat(cfg, sms['Text'])
197 html = '<html><head></head><body>%s</body></html>'
198 sub = MIMEText(html % text.encode('utf-8'), 'html', 'utf-8')
199 msg.attach(sub)
201 if sms['DateTime'] is not None:
202 filename = '%s-%s-%s.eml' % (
203 sms['SMS'][0]['Type'],
204 sms['DateTime'].strftime("%Y%m%d%H%M%S"),
205 md5.new(sms['Text'].encode('utf-8')).hexdigest())
206 else:
207 filename = '%s-%s.eml' % (
208 sms['SMS'][0]['Type'],
209 md5.new(sms['Text'].encode('utf-8')).hexdigest())
211 # Add message ID
212 msgid = '<%s@%s>' % (filename[:-4], sms['Number'].replace(' ', '_'))
213 msg.add_header('Message-ID', msgid)
215 if mailbox:
216 if sms['DateTime'] is None:
217 timestamp = time.asctime(time.localtime(None))
218 else:
219 timestamp = time.asctime(sms['DateTime'].timetuple())
220 prepend = ('From wammu@wammu.sms %s\n' % timestamp) + prepend
222 return filename, prepend + msg.as_string(), msgid