]> git.cworth.org Git - obsolete/notmuch-to-html/blob - notmuch-to-html
Make the configuration file a required argument.
[obsolete/notmuch-to-html] / notmuch-to-html
1 #!/usr/bin/python
2 #
3 # Copyright (c) 2011-2012 David Bremner <david@tethera.net>
4 #
5 # dependencies
6 #       - python 2.6 for json
7 #       - argparse; either python 2.7, or install separately
8 #
9 # This program is free software: you can redistribute it and/or modify
10 # it under the terms of the GNU General Public License as published by
11 # the Free Software Foundation, either version 3 of the License, or
12 # (at your option) any later version.
13 #
14 # This program is distributed in the hope that it will be useful,
15 # but WITHOUT ANY WARRANTY; without even the implied warranty of
16 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17 # GNU General Public License for more details.
18 #
19 # You should have received a copy of the GNU General Public License
20 # along with this program.  If not, see http://www.gnu.org/licenses/ .
21
22 from __future__ import print_function
23 from __future__ import unicode_literals
24
25 import codecs
26 import collections
27 import datetime
28 import email.utils
29 try:  # Python 3
30     from urllib.parse import quote
31 except ImportError:  # Python 2
32     from urllib import quote
33 import json
34 import argparse
35 import os
36 import re
37 import sys
38 import subprocess
39 import xml.sax.saxutils
40
41
42 _ENCODING = 'UTF-8'
43 _PAGES = {}
44
45
46 if not hasattr(collections, 'OrderedDict'):  # Python 2.6 or earlier
47     class _OrderedDict (dict):
48         "Just enough of a stub to get through Page._get_threads"
49         def __init__(self, *args, **kwargs):
50             super(_OrderedDict, self).__init__(*args, **kwargs)
51             self._keys = []  # record key order
52
53         def __setitem__(self, key, value):
54             super(_OrderedDict, self).__setitem__(key, value)
55             self._keys.append(key)
56
57         def values(self):
58             for key in self._keys:
59                 yield self[key]
60
61
62     collections.OrderedDict = _OrderedDict
63
64
65 def read_config(path, encoding=None):
66     "Read config from json file"
67     if not encoding:
68         encoding = _ENCODING
69     fp = open(path)
70     return json.load(fp)
71
72
73 class Thread (list):
74     def __init__(self):
75         self.running_data = {}
76
77
78 class Page (object):
79     def __init__(self, header=None, footer=None):
80         self.header = header
81         self.footer = footer
82
83     def write(self, database, views, stream=None):
84         if not stream:
85             try:  # Python 3
86                 byte_stream = sys.stdout.buffer
87             except AttributeError:  # Python 2
88                 byte_stream = sys.stdout
89             stream = codecs.getwriter(encoding=_ENCODING)(stream=byte_stream)
90         self._write_header(views=views, stream=stream)
91         for view in views:
92             self._write_view(database=database, view=view, stream=stream)
93         self._write_footer(views=views, stream=stream)
94
95     def _write_header(self, views, stream):
96         if self.header:
97             stream.write(self.header)
98
99     def _write_footer(self, views, stream):
100         if self.footer:
101             stream.write(self.footer)
102
103     def _write_view(self, database, view, stream):
104         if 'query-string' not in view:
105             query = view['query']
106             view['query-string'] = ' and '.join(query)
107         q = notmuch.Query(database, view['query-string'])
108         q.set_sort(notmuch.Query.SORT.OLDEST_FIRST)
109         threads = self._get_threads(messages=q.search_messages())
110         self._write_view_header(view=view, stream=stream)
111         self._write_threads(threads=threads, stream=stream)
112
113     def _get_threads(self, messages):
114         threads = collections.OrderedDict()
115         for message in messages:
116             thread_id = message.get_thread_id()
117             if thread_id in threads:
118                 thread = threads[thread_id]
119             else:
120                 thread = Thread()
121                 threads[thread_id] = thread
122             thread.running_data, display_data = self._message_display_data(
123                 running_data=thread.running_data, message=message)
124             thread.append(display_data)
125         return list(threads.values())
126
127     def _write_view_header(self, view, stream):
128         pass
129
130     def _write_threads(self, threads, stream):
131         for thread in threads:
132             for message_display_data in thread:
133                 stream.write(
134                     ('{date:10.10s} {from:20.20s} {subject:40.40s}\n'
135                      '{message-id-term:>72}\n'
136                      ).format(**message_display_data))
137             if thread != threads[-1]:
138                 stream.write('\n')
139
140     def _message_display_data(self, running_data, message):
141         headers = ('thread-id', 'message-id', 'date', 'from', 'subject')
142         data = {}
143         for header in headers:
144             if header == 'thread-id':
145                 value = message.get_thread_id()
146             elif header == 'message-id':
147                 value = message.get_message_id()
148                 data['message-id-term'] = 'id:"{0}"'.format(value)
149             elif header == 'date':
150                 value = str(datetime.datetime.utcfromtimestamp(
151                     message.get_date()).date())
152             else:
153                 value = message.get_header(header)
154             if header == 'from':
155                 (value, addr) = email.utils.parseaddr(value)
156                 if not value:
157                     value = addr.split('@')[0]
158             data[header] = value
159         next_running_data = data.copy()
160         for header, value in data.items():
161             if header in ['message-id', 'subject']:
162                 continue
163             if value == running_data.get(header, None):
164                 data[header] = ''
165         return (next_running_data, data)
166
167
168 class HtmlPage (Page):
169     _slug_regexp = re.compile('\W+')
170
171     def _write_header(self, views, stream):
172         super(HtmlPage, self)._write_header(views=views, stream=stream)
173         stream.write('<ul>\n')
174         for view in views:
175             if 'id' not in view:
176                 view['id'] = self._slug(view['title'])
177             stream.write(
178                 '<li><a href="#{id}">{title}</a></li>\n'.format(**view))
179         stream.write('</ul>\n')
180
181     def _write_view_header(self, view, stream):
182         stream.write('<h3 id="{id}">{title}</h3>\n'.format(**view))
183         stream.write('<p>\n')
184         if 'comment' in view:
185             stream.write(view['comment'])
186             stream.write('\n')
187         for line in [
188                 'The view is generated from the following query:',
189                 '</p>',
190                 '<p>',
191                 '  <code>',
192                 view['query-string'],
193                 '  </code>',
194                 '</p>',
195                 ]:
196             stream.write(line)
197             stream.write('\n')
198
199     def _write_threads(self, threads, stream):
200         if not threads:
201             return
202         stream.write('<table>\n')
203         for thread in threads:
204             stream.write('  <tbody>\n')
205             for message_display_data in thread:
206                 stream.write((
207                     '    <tr class="message-first">\n'
208                     '      <td>{from}</td>\n'
209                     '      <td>{date}</td>\n'
210                     '      <td>{subject}</td>\n'
211                     '    </tr>\n'
212                     ).format(**message_display_data))
213             stream.write('  </tbody>\n')
214             if thread != threads[-1]:
215                 stream.write(
216                     '  <tbody><tr><td colspan="2"><br /></td></tr></tbody>\n')
217         stream.write('</table>\n')
218
219     def _message_display_data(self, *args, **kwargs):
220         running_data, display_data = super(
221             HtmlPage, self)._message_display_data(
222                 *args, **kwargs)
223         if 'subject' in display_data and 'message-id' in display_data:
224             d = {
225                 'message-id': quote(display_data['message-id']),
226                 'subject': xml.sax.saxutils.escape(display_data['subject']),
227                 }
228             display_data['subject'] = (
229                 '<a href="http://mid.gmane.org/{message-id}">{subject}</a>'
230                 ).format(**d)
231         for key in ['message-id', 'from']:
232             if key in display_data:
233                 display_data[key] = xml.sax.saxutils.escape(display_data[key])
234         return (running_data, display_data)
235
236     def _slug(self, string):
237         return self._slug_regexp.sub('-', string)
238
239 parser = argparse.ArgumentParser()
240 parser.add_argument('config', help='path to configuration file', metavar='CONFIG_FILE')
241 parser.add_argument('--text', help='output plain text format',
242                     action='store_true')
243 parser.add_argument('--list-views', help='list views',
244                     action='store_true')
245 parser.add_argument('--get-query', help='get query for view',
246                     metavar='VIEW')
247
248 args = parser.parse_args()
249
250 config = read_config(path=args.config)
251
252 _PAGES['text'] = Page()
253 _PAGES['html'] = HtmlPage(
254     header='''<!DOCTYPE html>
255 <html lang="en">
256 <head>
257   <meta http-equiv="Content-Type" content="text/html; charset={encoding}" />
258   <title>{title}</title>
259   <style media="screen" type="text/css">
260     table {{
261       border-spacing: 0;
262     }}
263     tr.message-first td {{
264       padding-top: {inter_message_padding};
265     }}
266     tr.message-last td {{
267       padding-bottom: {inter_message_padding};
268     }}
269     td {{
270       padding-left: {border_radius};
271       padding-right: {border_radius};
272     }}
273     tr:first-child td:first-child {{
274       border-top-left-radius: {border_radius};
275     }}
276     tr:first-child td:last-child {{
277       border-top-right-radius: {border_radius};
278     }}
279     tr:last-child td:first-child {{
280       border-bottom-left-radius: {border_radius};
281     }}
282     tr:last-child td:last-child {{
283       border-bottom-right-radius: {border_radius};
284     }}
285     tbody:nth-child(4n+1) tr td {{
286       background-color: #ffd96e;
287     }}
288     tbody:nth-child(4n+3) tr td {{
289       background-color: #bce;
290     }}
291   </style>
292 </head>
293 <body>
294 <h2>{title}</h2>
295 <p>
296 Generated: {date}<br />
297 {blurb}
298 </p>
299 <h3>Views</h3>
300 '''.format(date=datetime.datetime.utcnow().date(),
301            title=config['meta']['title'],
302            blurb=config['meta']['blurb'],
303            encoding=_ENCODING,
304            inter_message_padding='0.25em',
305            border_radius='0.5em'),
306     footer='</body>\n</html>\n',
307     )
308
309 if args.list_views:
310     for view in config['views']:
311         print(view['title'])
312     sys.exit(0)
313 elif args.get_query != None:
314     for view in config['views']:
315         if args.get_query == view['title']:
316             print(' and '.join(view['query']))
317     sys.exit(0)
318 else:
319     # only import notmuch if needed
320     import notmuch
321
322 if args.text:
323     page = _PAGES['text']
324 else:
325     page = _PAGES['html']
326
327 db = notmuch.Database(mode=notmuch.Database.MODE.READ_ONLY)
328 page.write(database=db, views=config['views'])