Skip to content

Instantly share code, notes, and snippets.

@nathan-osman
Created April 1, 2020 05:53
Show Gist options
  • Save nathan-osman/ff7411069c448b3c0d1f3c19a3ab94be to your computer and use it in GitHub Desktop.
Save nathan-osman/ff7411069c448b3c0d1f3c19a3ab94be to your computer and use it in GitHub Desktop.
Format XML files produced by SMS Backup & Restore
from argparse import ArgumentParser
from datetime import datetime, timezone
from html import escape
import xml.etree.ElementTree as ET
class SmsFormat:
def __init__(self, f_in, f_out):
self._tree = ET.parse(f_in)
self._outf = f_out
def _write_header(self):
self._outf.write(
'''<!DOCTYPE html>
<html>
<head>
<style>
body {
font-family: sans-serif;
}
.block {
margin: 12px 0;
}
.block .timestamp {
color: #aaaaaa;
font-size: 10pt;
margin: 2px 0;
}
.block .message {
background-color: #eeeeee;
border-radius: 8px;
display: inline-block;
padding: 8px;
}
.block.highlight {
text-align: right;
}
.block.highlight .message {
background-color: #cc8899;
color: #ffffff;
}
</style>
</head>
<body>
'''
)
def _parse_message(self, c):
if c.tag != 'sms':
return
highlight = " highlight" \
if c.attrib.get('type', "2") == "2" else ""
d = datetime.fromtimestamp(
int(c.attrib.get('date')) / 1000,
).astimezone(tz=None)
self._outf.write(
f'''
<div class="block{highlight}">
<div class="timestamp">
{d.strftime('%A, %B %#d, %Y %#I:%M %p')}
</div>
<div class="message">
{escape(c.attrib['body'])}
</div>
</div>
'''
)
def _write_footer(self):
self._outf.write(
'''
</body>
</html>
'''
)
def parse(self):
self._write_header()
for c in self._tree.getroot():
self._parse_message(c)
self._write_footer()
if __name__ == '__main__':
parser = ArgumentParser()
parser.add_argument("in_file", help="XML file")
parser.add_argument("out_file", help="HTML file")
args = parser.parse_args()
with \
open(args.in_file, 'r') as f_in, \
open(args.out_file, 'w') as f_out:
SmsFormat(f_in, f_out).parse()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment