3 # Copyright (c) 2011-2012 David Bremner <david@tethera.net>
6 # - python 2.6 for json
7 # - argparse; either python 2.7, or install separately
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.
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.
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/ .
22 from __future__ import print_function
23 from __future__ import unicode_literals
30 from urllib.parse import quote
31 except ImportError: # Python 2
32 from urllib import quote
39 import xml.sax.saxutils
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
53 def __setitem__(self, key, value):
54 super(_OrderedDict, self).__setitem__(key, value)
55 self._keys.append(key)
58 for key in self._keys:
62 collections.OrderedDict = _OrderedDict
65 def read_config(path, encoding=None):
66 "Read config from json file"
75 self.running_data = {}
79 def __init__(self, header=None, footer=None):
83 def write(self, database, views, stream=None):
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)
92 self._write_view(database=database, view=view, stream=stream)
93 self._write_footer(views=views, stream=stream)
95 def _write_header(self, views, stream):
97 stream.write(self.header)
99 def _write_footer(self, views, stream):
101 stream.write(self.footer)
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)
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]
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())
127 def _write_view_header(self, view, stream):
130 def _write_threads(self, threads, stream):
131 for thread in threads:
132 for message_display_data in thread:
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]:
140 def _message_display_data(self, running_data, message):
141 headers = ('thread-id', 'message-id', 'date', 'from', 'subject')
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())
153 value = message.get_header(header)
155 (value, addr) = email.utils.parseaddr(value)
157 value = addr.split('@')[0]
159 next_running_data = data.copy()
160 for header, value in data.items():
161 if header in ['message-id', 'subject']:
163 if value == running_data.get(header, None):
165 return (next_running_data, data)
168 class HtmlPage (Page):
169 _slug_regexp = re.compile('\W+')
171 def _write_header(self, views, stream):
172 super(HtmlPage, self)._write_header(views=views, stream=stream)
173 stream.write('<ul>\n')
176 view['id'] = self._slug(view['title'])
178 '<li><a href="#{id}">{title}</a></li>\n'.format(**view))
179 stream.write('</ul>\n')
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'])
188 'The view is generated from the following query:',
192 view['query-string'],
199 def _write_threads(self, threads, stream):
202 stream.write('<table>\n')
203 for thread in threads:
204 stream.write(' <tbody>\n')
205 for message_display_data in thread:
207 ' <tr class="message-first">\n'
210 ' <td>{subject}</td>\n'
212 ).format(**message_display_data))
213 stream.write(' </tbody>\n')
214 if thread != threads[-1]:
216 ' <tbody><tr><td colspan="2"><br /></td></tr></tbody>\n')
217 stream.write('</table>\n')
219 def _message_display_data(self, *args, **kwargs):
220 running_data, display_data = super(
221 HtmlPage, self)._message_display_data(
223 if 'subject' in display_data and 'message-id' in display_data:
225 'message-id': quote(display_data['message-id']),
226 'subject': xml.sax.saxutils.escape(display_data['subject']),
228 display_data['subject'] = (
229 '<a href="http://mid.gmane.org/{message-id}">{subject}</a>'
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)
236 def _slug(self, string):
237 return self._slug_regexp.sub('-', string)
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',
243 parser.add_argument('--list-views', help='list views',
245 parser.add_argument('--get-query', help='get query for view',
248 args = parser.parse_args()
250 config = read_config(path=args.config)
252 _PAGES['text'] = Page()
253 _PAGES['html'] = HtmlPage(
254 header='''<!DOCTYPE html>
257 <meta http-equiv="Content-Type" content="text/html; charset={encoding}" />
258 <title>{title}</title>
259 <style media="screen" type="text/css">
263 tr.message-first td {{
264 padding-top: {inter_message_padding};
266 tr.message-last td {{
267 padding-bottom: {inter_message_padding};
270 padding-left: {border_radius};
271 padding-right: {border_radius};
273 tr:first-child td:first-child {{
274 border-top-left-radius: {border_radius};
276 tr:first-child td:last-child {{
277 border-top-right-radius: {border_radius};
279 tr:last-child td:first-child {{
280 border-bottom-left-radius: {border_radius};
282 tr:last-child td:last-child {{
283 border-bottom-right-radius: {border_radius};
285 tbody:nth-child(4n+1) tr td {{
286 background-color: #ffd96e;
288 tbody:nth-child(4n+3) tr td {{
289 background-color: #bce;
296 Generated: {date}<br />
300 '''.format(date=datetime.datetime.utcnow().date(),
301 title=config['meta']['title'],
302 blurb=config['meta']['blurb'],
304 inter_message_padding='0.25em',
305 border_radius='0.5em'),
306 footer='</body>\n</html>\n',
310 for view in config['views']:
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']))
319 # only import notmuch if needed
323 page = _PAGES['text']
325 page = _PAGES['html']
327 db = notmuch.Database(mode=notmuch.Database.MODE.READ_ONLY)
328 page.write(database=db, views=config['views'])