]> git.notmuchmail.org Git - notmuch/blob - notmuch
implement sort order for notmuch show
[notmuch] / notmuch
1 #!/usr/bin/env python
2 """This is a notmuch implementation in python. 
3 It's goal is to allow running the test suite on the cnotmuch python bindings.
4
5 This "binary" honors the NOTMUCH_CONFIG environmen variable for reading a user's
6 notmuch configuration (e.g. the database path).
7
8    (c) 2010 by Sebastian Spaeth <Sebastian@SSpaeth.de>
9                Jesse Rosenthal <jrosenthal@jhu.edu>
10    This code is licensed under the GNU GPL v3+.
11 """
12 from __future__ import with_statement # This isn't required in Python 2.6
13 import sys, os, re, logging
14 from subprocess import call
15 from cnotmuch.notmuch import Database, Query
16 PREFIX=re.compile('(\w+):(.*$)')
17 #TODO Handle variable: NOTMUCH-CONFIG
18
19 #-------------------------------------------------------------------------
20 def get_user_email_addresses():
21         """ Reads a user's notmuch config and returns his email addresses as list (name, primary_address, other_address1,...)"""
22         import email.utils
23         from ConfigParser import SafeConfigParser
24         config = SafeConfigParser()
25         conf_f = os.getenv('NOTMUCH_CONFIG',
26                            os.path.expanduser('~/.notmuch-config'))
27         config.read(conf_f)
28         if not config.has_option('user','name'): name = ""
29         else:name = config.get('user','name')
30
31         if not config.has_option('user','primary_email'): mail = ""
32         else:mail = config.get('user','primary_email')
33
34         if not config.has_option('user','other_email'): other = []
35         else:other = config.get('user','other_email').rstrip(';').split(';')
36
37         other.insert(0, mail)
38         other.insert(0, name)
39         return other
40 #-------------------------------------------------------------------------
41 HELPTEXT="""The notmuch mail system.
42
43 Usage: notmuch <command> [args...]
44
45 Where <command> and [args...] are as follows:
46
47         setup   Interactively setup notmuch for first use.
48
49         new     [--verbose]
50
51                 Find and import new messages to the notmuch database.
52
53         search  [options...] <search-terms> [...]
54
55                 Search for messages matching the given search terms.
56
57         show    <search-terms> [...]
58
59                 Show all messages matching the search terms.
60
61         count   <search-terms> [...]
62
63                 Count messages matching the search terms.
64
65         reply   [options...] <search-terms> [...]
66
67                 Construct a reply template for a set of messages.
68
69         tag     +<tag>|-<tag> [...] [--] <search-terms> [...]
70
71                 Add/remove tags for all messages matching the search terms.
72
73         dump    [<filename>]
74
75                 Create a plain-text dump of the tags for each message.
76
77         restore <filename>
78
79                 Restore the tags from the given dump file (see 'dump').
80
81         search-tags     [<search-terms> [...] ]
82
83                 List all tags found in the database or matching messages.
84
85         help    [<command>]
86
87                 This message, or more detailed help for the named command.
88
89 Use "notmuch help <command>" for more details on each command.
90 And "notmuch help search-terms" for the common search-terms syntax.
91 """
92 #-------------------------------------------------------------------------
93 #TODO: replace the dynamic pieces
94 USAGE="""Notmuch is configured and appears to have a database. Excellent!
95
96 At this point you can start exploring the functionality of notmuch by
97 using commands such as:
98
99         notmuch search tag:inbox
100
101         notmuch search to:"Sebastian Spaeth"
102
103         notmuch search from:"Sebastian@SSpaeth.de"
104
105         notmuch search subject:"my favorite things"
106
107 See "notmuch help search" for more details.
108
109 You can also use "notmuch show" with any of the thread IDs resulting
110 from a search. Finally, you may want to explore using a more sophisticated
111 interface to notmuch such as the emacs interface implemented in notmuch.el
112 or any other interface described at http://notmuchmail.org
113
114 And don't forget to run "notmuch new" whenever new mail arrives.
115
116 Have fun, and may your inbox never have much mail.
117 """
118 #-------------------------------------------------------------------------
119 def quote_reply(oldbody ,date, from_address):
120    """Transform a mail body into a quote text starting with On blah, x wrote:
121    :param body: a str with a mail body
122    :returns: The new payload of the email.message()
123    """
124    from cStringIO import StringIO
125
126    #we get handed a string, wrap it in a file-like object
127    oldbody = StringIO(oldbody)
128    newbody = StringIO()
129
130    newbody.write("On %s, %s wrote:\n" % (date, from_address))
131
132    for line in oldbody:
133       newbody.write("> " + line)
134
135    return newbody.getvalue()
136     
137 def format_reply(msgs):
138    """Gets handed Messages() and displays the reply to them"""
139    import email
140
141    for msg in msgs:
142       f = open(msg.get_filename(),"r")
143       reply = email.message_from_file(f)
144
145       #handle the easy non-multipart case:
146       if not reply.is_multipart():
147          reply.set_payload(quote_reply(reply.get_payload(),
148                                        reply['date'],reply['from']))
149       else:
150          #handle the tricky multipart case
151          deleted = ""
152          """A string describing which nontext attachements have been deleted"""
153          delpayloads = []
154          """A list of payload indices to be deleted"""
155
156          payloads = reply.get_payload()
157
158          for i, part in enumerate(payloads):
159
160             mime_main = part.get_content_maintype()
161             if mime_main not in ['multipart', 'message', 'text']:
162                deleted += "Non-text part: %s\n" % (part.get_content_type())
163                payloads[i].set_payload("Non-text part: %s" % (part.get_content_type()))
164                payloads[i].set_type('text/plain')
165                delpayloads.append(i)
166             else:
167                # payloads[i].set_payload("Text part: %s" % (part.get_content_type()))
168                payloads[i].set_payload(quote_reply(payloads[i].get_payload(),reply['date'],reply['from']))
169
170
171          # Delete those payloads that we don't need anymore
172          for i in reversed(sorted(delpayloads)):
173             del payloads[i]
174
175       #Back to single- and multipart handling
176
177       my_addresses = get_user_email_addresses()
178       used_address = None
179       # filter our email addresses from all to: cc: and bcc: fields
180       # if we find one of "my" addresses being used, 
181       # it is stored in used_address
182       for header in ['To', 'CC', 'Bcc']:
183          if not header in reply:
184             #only handle fields that exist
185             continue
186          addresses = email.utils.getaddresses(reply.get_all(header,[]))
187          purged_addr = []
188          for name, mail in addresses:
189             if mail in my_addresses[1:]:
190                used_address = email.utils.formataddr((my_addresses[0],mail))
191             else:
192                purged_addr.append(email.utils.formataddr((name,mail)))
193
194          if len(purged_addr):
195             reply.replace_header(header, ", ".join(purged_addr))
196          else: 
197             #we deleted all addresses, delete the header
198             del reply[header]
199
200       # Use our primary email address to the From
201       # (save original from line, we still need it)
202       orig_from = reply['From']
203       del reply['From']
204       reply['From'] = used_address if used_address \
205           else email.utils.formataddr((my_addresses[0],my_addresses[1]))
206       
207       #reinsert the Subject after the From
208       orig_subject = reply['Subject']
209       del reply['Subject']
210       reply['Subject'] = 'Re: ' + orig_subject
211
212       # Calculate our new To: field
213       new_to = orig_from
214       # add all remaining original 'To' addresses
215       if 'To' in reply:
216          new_to += ", " + reply['To']
217       del reply['To']
218       reply.add_header('To', new_to)
219
220       # Add our primary email address to the BCC
221       new_bcc = my_addresses[1]
222       if reply.has_key('Bcc'):
223          new_bcc += ', '  + reply['Bcc']
224          del reply['Bcc']
225       reply['Bcc'] = new_bcc
226
227       # Set replies 'In-Reply-To' header to original's Message-ID
228       if reply.has_key('Message-ID') :
229          del reply['In-Reply-To']
230          reply['In-Reply-To'] = reply['Message-ID']
231
232       #Add original's Message-ID to replies 'References' header.
233       if reply.has_key('References'):
234          ref = reply['References'] + ' ' +reply['Message-ID']
235       else:
236          ref = reply['Message-ID']
237       del reply['References']
238       reply['References'] = ref
239       
240       # Delete the original Message-ID.
241       del(reply['Message-ID'])
242
243       # filter all existing headers but a few and delete them from 'reply'
244       delheaders = filter(lambda x: x not in ['From','To','Subject','CC','Bcc',
245                                               'In-Reply-To', 'References',
246                                               'Content-Type'],reply.keys())
247       map(reply.__delitem__, delheaders)
248
249       """
250 From: Sebastian Spaeth <Sebastian@SSpaeth.de>
251 Subject: Re: Template =?iso-8859-1?b?Zvxy?= das Kochrezept
252 In-Reply-To: <4A6D55F9.6040405@SSpaeth.de>
253 References:  <4A6D55F9.6040405@SSpaeth.de>
254       """
255    #return without Unixfrom
256    return reply.as_string(False)
257 #-------------------------------------------------------------------------
258 def quote_query_line(argv):
259    #mangle arguments wrapping terms with spaces in quotes
260    for i in xrange(0,len(argv)):
261       if argv[i].find(' ') >= 0:
262          #if we use prefix:termWithSpaces, put quotes around term
263          m = PREFIX.match(argv[i])
264          if m:
265             argv[i] = '%s:"%s"' % (m.group(1), m.group(2))
266          else:
267             argv[i] = '"'+argv[i]+'"'
268    return ' '.join(argv)
269
270 if __name__ == '__main__':
271
272    # Handle command line options
273    #-------------------------------------
274    # No option given, print USAGE and exit
275    if len(sys.argv) == 1:
276       print USAGE
277    #-------------------------------------
278    elif sys.argv[1] == 'setup':
279        """Interactively setup notmuch for first use."""
280        print "Not implemented."
281    #-------------------------------------
282    elif sys.argv[1] == 'new':
283        """ Interactively setup notmuch for first use. """
284        #print "Not implemented. We cheat by calling the proper notmuch"
285        call(['notmuch new'],shell=True)
286    #-------------------------------------
287    elif sys.argv[1] == 'help':
288        if len(sys.argv) == 2: print HELPTEXT
289        else: print "Not implemented"
290    #-------------------------------------
291    elif sys.argv[1] == 'search':
292       db = Database()
293       query_string = ''
294       sort_order="newest-first"
295       first_search_term = None
296       for (i, arg) in enumerate(sys.argv[1:]):
297           if arg.startswith('--sort='):
298              sort_order=arg.split("=")[1]
299              if not sort_order in ("oldest-first", "newest-first"):
300                 raise Exception("unknown sort order")
301           elif not arg.startswith('--'):
302               #save the position of the first sys.argv that is a search term
303               first_search_term = i+1
304
305       if first_search_term:
306           #mangle arguments wrapping terms with spaces in quotes
307           querystr = quote_query_line(sys.argv[first_search_term:])
308
309       
310       logging.debug("search "+querystr)
311       qry = Query(db,querystr)
312       if sort_order == "oldest-first":
313          qry.set_sort(Query.SORT.OLDEST_FIRST)
314       else:
315          qry.set_sort(Query.SORT.NEWEST_FIRST)
316       t = qry.search_threads()
317
318       for thread in t:
319          print(str(thread))
320
321    #-------------------------------------
322    elif sys.argv[1] == 'show':
323       entire_thread = False
324       db = Database()
325       out_format="text"
326       querystr=''
327       first_search_term = None
328
329       #ugly homegrown option parsing
330       #TODO: use OptionParser
331       for (i, arg) in enumerate(sys.argv[1:]):
332           if arg == '--entire-thread':
333               entire_thread = True
334           elif arg.startswith("--format="):
335               out_format = arg.split("=")[1]
336               if out_format == 'json':
337                   #for compatibility use --entire-thread for json
338                   entire_thread = True
339               if not out_format in ("json", "text"):
340                   raise Exception("unknown format")
341           elif not arg.startswith('--'):
342               #save the position of the first sys.argv that is a search term
343               first_search_term = i+1
344
345       if first_search_term:
346           #mangle arguments wrapping terms with spaces in quotes
347           querystr = quote_query_line(sys.argv[first_search_term:])
348
349       logging.debug("show "+querystr)
350       t = Query(db,querystr).search_threads()
351
352       first_toplevel=True
353       if out_format.lower()=="json":
354          sys.stdout.write("[")
355
356       for thrd in t:
357          msgs = thrd.get_toplevel_messages()
358
359          if not first_toplevel:
360             if out_format.lower()=="json":
361                sys.stdout.write(", ")
362
363          first_toplevel = False
364
365          msgs.print_messages(out_format, 0, entire_thread)
366
367       if out_format.lower() == "json":
368          sys.stdout.write("]")
369       sys.stdout.write("\n")
370
371    #-------------------------------------
372    elif sys.argv[1] == 'reply':
373       db = Database()
374       if len(sys.argv) == 2:
375          #no search term. abort
376          print("Error: notmuch reply requires at least one search term.")
377          sys.exit()
378
379       #mangle arguments wrapping terms with spaces in quotes
380       querystr = quote_query_line(sys.argv[2:])
381       logging.debug("reply "+querystr)
382       msgs = Query(db,querystr).search_messages()
383       print (format_reply(msgs))
384
385    #-------------------------------------
386    elif sys.argv[1] == 'count':
387       if len(sys.argv) == 2:
388          #no further search term, count all
389          querystr=''
390       else:
391          #mangle arguments wrapping terms with spaces in quotes
392          querystr = quote_query_line(sys.argv[2:])
393       print(Database().create_query(querystr).count_messages())
394       
395    #-------------------------------------
396    elif sys.argv[1] == 'tag':
397       #build lists of tags to be added and removed
398       add, remove = [], []
399       while not sys.argv[2]=='--' and \
400             (sys.argv[2].startswith('+') or sys.argv[2].startswith('-')):
401          if sys.argv[2].startswith('+'):
402             #append to add list without initial +
403             add.append(sys.argv.pop(2)[1:])
404          else:
405             #append to remove list without initial -
406             remove.append(sys.argv.pop(2)[1:])
407       #skip eventual '--'
408       if sys.argv[2]=='--': sys.argv.pop(2)
409       #the rest is search terms
410       querystr = quote_query_line(sys.argv[2:])
411       logging.debug("tag search-term "+querystr)
412       db = Database(mode=Database.MODE.READ_WRITE)
413       m  = Query(db,querystr).search_messages()
414       for msg in m:
415          #actually add and remove all tags
416          map(msg.add_tag, add)
417          map(msg.remove_tag, remove)
418    #-------------------------------------
419    elif sys.argv[1] == 'search-tags':
420       if len(sys.argv) == 2:
421          #no further search term
422          print("\n".join(Database().get_all_tags()))
423       else:
424          #mangle arguments wrapping terms with spaces in quotes
425          querystr = quote_query_line(sys.argv[2:])
426          logging.debug("search-term "+querystr)
427          db = Database()
428          m  = Query(db,querystr).search_messages()
429          print("\n".join([t for t in m.collect_tags()]))
430    #-------------------------------------
431    elif sys.argv[1] == 'dump':
432       #TODO: implement "dump <filename>"
433       if len(sys.argv) == 2:
434          f = sys.stdout
435       else:
436          f = open(sys.argv[2],"w")
437       db = Database()
438       q = Query(db,'')
439       q.set_sort(Query.SORT.MESSAGE_ID)
440       m = q.search_messages()
441       for msg in m:
442          f.write("%s (%s)\n" % (msg.get_message_id(), msg.get_tags()))
443    #-------------------------------------
444    elif sys.argv[1] == 'restore':
445       import re
446       if len(sys.argv) == 2:
447          print("No filename given. Reading dump from stdin.")
448          f = sys.stdin
449       else:
450          f = open(sys.argv[2],"r")
451       #split the msg id and the tags
452       MSGID_TAGS = re.compile("(\S+)\s\((.*)\)$")
453       db = Database(mode=Database.MODE.READ_WRITE)
454
455       #read each line of the dump file
456       for line in f:
457          m = MSGID_TAGS.match(line)
458          if not m:
459             sys.stderr.write("Warning: Ignoring invalid input line: %s" % 
460                              line)
461             continue
462          # split line in components and fetch message
463          msg_id = m.group(1)
464          new_tags= set(m.group(2).split())
465          msg    = db.find_message(msg_id)
466
467          if msg == None:
468             sys.stderr.write(
469                "Warning: Cannot apply tags to missing message: %s\n" % id)
470             continue
471
472          #do nothing if the old set of tags is the same as the new one
473          old_tags = set(msg.get_tags())
474          if old_tags == new_tags: continue
475
476          #set the new tags
477          msg.freeze()
478          #only remove tags if the new ones are not a superset anyway
479          if not (new_tags > old_tags): msg.remove_all_tags()
480          for tag in new_tags: msg.add_tag(tag)
481          msg.thaw()
482             
483    #-------------------------------------
484    else:
485        # unknown command
486        print "Error: Unknown command '%s' (see \"notmuch help\")" % sys.argv[1]
487
488
489    #TODO: implement
490    """
491 setup
492 new
493 show    <search-terms> [...]
494 reply   [options...] <search-terms> [...]
495 restore <filename>
496    """