-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathvmg2xml.py
executable file
·132 lines (111 loc) · 4.87 KB
/
vmg2xml.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
#!/usr/bin/env python
import quopri, re, StringIO, datetime, calendar, locale
from optparse import OptionParser
buf = StringIO
Regexp = {'CellNumber': re.compile(r'TEL:(\+[0-9]*)\r'),
'Date': re.compile(r'^Date:(.*?)\r'),
'Body': re.compile(r'(?:;ENCODING=.*PRINTABLE.*\:)?(.*?)\r$'),
}
Date_conversion = re.compile(r'(\d{2})\.(\d{2})\.(\d{4}) (\d{2}):(\d{2}):(\d{2})')
# Setting locale to FR_fr for correct date formating
#locale.setlocale(locale.LC_ALL, 'fr_FR')
def extractor(field='', line='', sms_items={}):
'''
Extract a field from VMG file using a dictionnary of regexp
Special process to Body that may be on several line
'''
if field.startswith('Body'):
dict_field = 'Body'
else:
dict_field = field
try:
sms_items[dict_field] += re.search(Regexp[field], line).group(1)
# print "Found " + dict_field + ": " + sms_items[dict_field]
except AttributeError:
pass
return sms_items
def format_date(all_sms):
'''
Just split date and time components retrieved from VMG file, and
use them to construct a datetime object then replace old Date entry
in dict variable.
'''
for sms in all_sms:
match = re.search(Date_conversion, sms['Date'])
sms[
'Date'] = datetime.datetime.now() #datetime.datetime(int(match.group(3)), int(match.group(2)), int(match.group(1)), int(match.group(4)), int(match.group(5)), int(match.group(6)))
return all_sms
def construct_listing(infile):
'''
Function list all sms into a vmg file and for each one
add an entry to a list variable. Currently, script find
and store 3 informations from VMG file : Cell Number, Date
and message itself.
'''
all_sms = []
sms_items = {'CellNumber': '', 'Date': '', 'Body': ''}
Body_Complete = False
Body_In_Progress = False
Message_In_Progress = False
for line in infile.readlines():
if line.startswith('BEGIN:VMSG'):
Message_In_Progress = True
continue
if line.startswith('END:VMSG'):
Message_In_Progress = False
if Message_In_Progress:
sms_items = extractor('CellNumber', line, sms_items)
sms_items = extractor('Date', line, sms_items)
if line.startswith('BEGIN:VBODY'):
Body_In_Progress = True
continue
if line.startswith('END:VBODY'):
sms_items['Body'] = re.sub(r'=0A', ' ', sms_items['Body'])
sms_items['Body'] = quopri.decodestring(sms_items['Body'])
Body_Complete = True
Body_In_Progress = False
elif Body_In_Progress:
sms_items['Body'] = sms_items['Body'].rstrip('=')
sms_items = extractor('Body', line, sms_items)
# Populate sms list when all informations retrieved and reset information for next sms
if not Message_In_Progress and sms_items['Body']:
all_sms.append(sms_items)
sms_items = {'CellNumber': '', 'Date': '', 'Body': ''}
Body_Complete = False
return all_sms
def write_output(outfile, all_sms=[]):
'''
Just write in SMS Backup Restore xml file format the result
VMG file parsing.
'''
header = "<?xml version='1.0' encoding='UTF-8' standalone='yes' ?>\n<!--File Created By SMS Backup & Restore v6.41 on 02/11/2013 17:54:18-->\n<?xml-stylesheet type=\"text/xsl\" href=\"sms.xsl\"?>\n<smses count=\"" + str(
len(all_sms)) + "\">\n"
footer = "</smses>"
file_handler = open(outfile, mode='w')
file_handler.write(header)
for sms in all_sms:
# Added 000 to include milliseconds into timestamp.
timestamp = str(calendar.timegm(datetime.datetime.now().timetuple())) + "000"
print(timestamp)
line = '<sms protocol="0" address="' + sms[
'CellNumber'] + '" date="' + timestamp + '" type="1" subject="null" body="' + sms[
'Body'] + '" toa="null" sc_toa="null" service_center="+33660003000" read="1" status="-1" locked="0" date_sent="' + timestamp + '", readable_date="' + \
sms['Date'].strftime("%d %b %Y %H:%M:%S") + '" />\n'
file_handler.write(line)
file_handler.write(footer)
file_handler.close()
print "All SMS convert into XML format for SMS Backup Restore Android app"
def main(inputfile, outputfile):
infile = open(inputfile)
print "Going find our sms !"
all_sms = construct_listing(infile)
infile.close()
print "Found", len(all_sms), "SMS."
all_sms = format_date(all_sms)
write_output(outputfile, all_sms)
if __name__ == "__main__":
parser = OptionParser()
parser.add_option('-i', '--inputfile', dest='inputfile', help='vmg file to convert')
parser.add_option('-o', '--outputfile', dest='outputfile', help='xml file result of conversion.')
options, args = parser.parse_args()
main(**options.__dict__)