3 # Generate an HTML page with the result of one or more notmuch
4 # searches, (with links to gmane views of each email if available).
6 # Copyright (c) 2011-2012 David Bremner <david@tethera.net>
9 # - python 2.6 for json
10 # - argparse; either python 2.7, or install separately
12 # This program is free software: you can redistribute it and/or modify
13 # it under the terms of the GNU General Public License as published by
14 # the Free Software Foundation, either version 3 of the License, or
15 # (at your option) any later version.
17 # This program is distributed in the hope that it will be useful,
18 # but WITHOUT ANY WARRANTY; without even the implied warranty of
19 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 # GNU General Public License for more details.
22 # You should have received a copy of the GNU General Public License
23 # along with this program. If not, see http://www.gnu.org/licenses/ .
25 from __future__ import print_function
26 from __future__ import unicode_literals
33 from urllib.parse import quote
34 except ImportError: # Python 2
35 from urllib import quote
42 import xml.sax.saxutils
49 if not hasattr(collections, 'OrderedDict'): # Python 2.6 or earlier
50 class _OrderedDict (dict):
51 "Just enough of a stub to get through Page._get_threads"
52 def __init__(self, *args, **kwargs):
53 super(_OrderedDict, self).__init__(*args, **kwargs)
54 self._keys = [] # record key order
56 def __setitem__(self, key, value):
57 super(_OrderedDict, self).__setitem__(key, value)
58 self._keys.append(key)
61 for key in self._keys:
65 collections.OrderedDict = _OrderedDict
68 def read_config(path, encoding=None):
69 "Read config from json file"
78 self.running_data = {}
82 def __init__(self, header=None, footer=None):
86 def write(self, database, views, stream=None):
89 byte_stream = sys.stdout.buffer
90 except AttributeError: # Python 2
91 byte_stream = sys.stdout
92 stream = codecs.getwriter(encoding=_ENCODING)(stream=byte_stream)
93 self._write_header(views=views, stream=stream)
95 self._write_view(database=database, view=view, stream=stream)
96 self._write_footer(views=views, stream=stream)
98 def _write_header(self, views, stream):
100 stream.write(self.header)
102 def _write_footer(self, views, stream):
104 stream.write(self.footer)
106 def _write_view(self, database, view, stream):
107 if 'query-string' not in view:
108 query = view['query']
109 view['query-string'] = ' and '.join(query)
110 q = notmuch.Query(database, view['query-string'])
111 q.set_sort(notmuch.Query.SORT.OLDEST_FIRST)
112 threads = self._get_threads(messages=q.search_messages())
113 self._write_view_header(view=view, stream=stream)
114 self._write_threads(threads=threads, stream=stream)
116 def _get_threads(self, messages):
117 threads = collections.OrderedDict()
118 for message in messages:
119 thread_id = message.get_thread_id()
120 if thread_id in threads:
121 thread = threads[thread_id]
124 threads[thread_id] = thread
125 thread.running_data, display_data = self._message_display_data(
126 running_data=thread.running_data, message=message)
127 thread.append(display_data)
128 return list(threads.values())
130 def _write_view_header(self, view, stream):
133 def _write_threads(self, threads, stream):
134 for thread in threads:
135 for message_display_data in thread:
137 ('{date:10.10s} {from:20.20s} {subject:40.40s}\n'
138 '{message-id-term:>72}\n'
139 ).format(**message_display_data))
140 if thread != threads[-1]:
143 def _message_display_data(self, running_data, message):
144 headers = ('thread-id', 'message-id', 'date', 'from', 'subject')
146 for header in headers:
147 if header == 'thread-id':
148 value = message.get_thread_id()
149 elif header == 'message-id':
150 value = message.get_message_id()
151 data['message-id-term'] = 'id:"{0}"'.format(value)
152 elif header == 'date':
153 value = str(datetime.datetime.utcfromtimestamp(
154 message.get_date()).date())
156 value = message.get_header(header)
158 (value, addr) = email.utils.parseaddr(value)
160 value = addr.split('@')[0]
162 next_running_data = data.copy()
163 for header, value in data.items():
164 if header in ['message-id', 'subject']:
166 if value == running_data.get(header, None):
168 return (next_running_data, data)
171 class HtmlPage (Page):
172 _slug_regexp = re.compile('\W+')
174 def _write_header(self, views, stream):
175 super(HtmlPage, self)._write_header(views=views, stream=stream)
176 stream.write('<ul>\n')
179 view['id'] = self._slug(view['title'])
181 '<li><a href="#{id}">{title}</a></li>\n'.format(**view))
182 stream.write('</ul>\n')
184 def _write_view_header(self, view, stream):
185 stream.write('<h3 id="{id}">{title}</h3>\n'.format(**view))
186 stream.write('<p>\n')
187 if 'comment' in view:
188 stream.write(view['comment'])
191 'The view is generated from the following query:',
195 view['query-string'],
202 def _write_threads(self, threads, stream):
205 stream.write('<table>\n')
206 for thread in threads:
207 stream.write(' <tbody>\n')
208 for message_display_data in thread:
210 ' <tr class="message-first">\n'
213 ' <td>{subject}</td>\n'
215 ).format(**message_display_data))
216 stream.write(' </tbody>\n')
217 if thread != threads[-1]:
219 ' <tbody><tr><td colspan="2"><br /></td></tr></tbody>\n')
220 stream.write('</table>\n')
222 def _message_display_data(self, *args, **kwargs):
223 running_data, display_data = super(
224 HtmlPage, self)._message_display_data(
226 if 'subject' in display_data and 'message-id' in display_data:
228 'message-id': quote(display_data['message-id']),
229 'subject': xml.sax.saxutils.escape(display_data['subject']),
231 display_data['subject'] = (
232 '<a href="http://mid.gmane.org/{message-id}">{subject}</a>'
234 for key in ['message-id', 'from']:
235 if key in display_data:
236 display_data[key] = xml.sax.saxutils.escape(display_data[key])
237 return (running_data, display_data)
239 def _slug(self, string):
240 return self._slug_regexp.sub('-', string)
242 parser = argparse.ArgumentParser()
243 parser.add_argument('config', help='path to configuration file', metavar='CONFIG_FILE')
244 parser.add_argument('--text', help='output plain text format',
246 parser.add_argument('--list-views', help='list views',
248 parser.add_argument('--get-query', help='get query for view',
251 args = parser.parse_args()
253 config = read_config(path=args.config)
255 _PAGES['text'] = Page()
256 _PAGES['html'] = HtmlPage(
257 header='''<!DOCTYPE html>
260 <meta http-equiv="Content-Type" content="text/html; charset={encoding}" />
261 <title>{title}</title>
262 <style media="screen" type="text/css">
266 tr.message-first td {{
267 padding-top: {inter_message_padding};
269 tr.message-last td {{
270 padding-bottom: {inter_message_padding};
273 padding-left: {border_radius};
274 padding-right: {border_radius};
276 tr:first-child td:first-child {{
277 border-top-left-radius: {border_radius};
279 tr:first-child td:last-child {{
280 border-top-right-radius: {border_radius};
282 tr:last-child td:first-child {{
283 border-bottom-left-radius: {border_radius};
285 tr:last-child td:last-child {{
286 border-bottom-right-radius: {border_radius};
288 tbody:nth-child(4n+1) tr td {{
289 background-color: #ffd96e;
291 tbody:nth-child(4n+3) tr td {{
292 background-color: #bce;
299 Generated: {date}<br />
303 '''.format(date=datetime.datetime.utcnow().date(),
304 title=config['meta']['title'],
305 blurb=config['meta']['blurb'],
307 inter_message_padding='0.25em',
308 border_radius='0.5em'),
309 footer='</body>\n</html>\n',
313 for view in config['views']:
316 elif args.get_query != None:
317 for view in config['views']:
318 if args.get_query == view['title']:
319 print(' and '.join(view['query']))
322 # only import notmuch if needed
326 page = _PAGES['text']
328 page = _PAGES['html']
330 db = notmuch.Database(mode=notmuch.Database.MODE.READ_ONLY)
331 page.write(database=db, views=config['views'])