1 from ctypes import c_char_p, c_void_p, c_long
2 from datetime import date
3 from cnotmuch.globals import nmlib, STATUS, NotmuchError
4 from cnotmuch.tag import Tags
5 #------------------------------------------------------------------------------
6 class Messages(object):
7 """Represents a list of notmuch messages
9 This object provides an iterator over a list of notmuch messages
10 (Technically, it provides a wrapper for the underlying
11 *notmuch_messages_t* structure). Do note that the underlying
12 library only provides a one-time iterator (it cannot reset the
13 iterator to the start). Thus iterating over the function will
14 "exhaust" the list of messages, and a subsequent iteration attempt
15 will raise a :exc:`NotmuchError` STATUS.NOT_INITIALIZED. Also
16 note, that any function that uses iteration will also
17 exhaust the messages. So both::
19 for msg in msgs: print msg
23 number_of_msgs = len(msgs)
25 will "exhaust" the Messages. If you need to re-iterate over a list of
26 messages you will need to retrieve a new :class:`Messages` object.
28 Things are not as bad as it seems though, you can store and reuse
29 the single Message objects as often as you want as long as you
30 keep the parent Messages object around. (Recall that due to
31 hierarchical memory allocation, all derived Message objects will
32 be invalid when we delete the parent Messages() object, even if it
33 was already "exhausted".) So this works::
36 msgs = Query(db,'').search_messages() #get a Messages() object
41 # msgs is "exhausted" now and even len(msgs) will raise an exception.
42 # However it will be kept around until all retrieved Message() objects are
43 # also deleted. If you did e.g. an explicit del(msgs) here, the
44 # following lines would fail.
46 # You can reiterate over *msglist* however as often as you want.
47 # It is simply a list with Message objects.
49 print (msglist[0].get_filename())
50 print (msglist[1].get_filename())
51 print (msglist[0].get_message_id())
55 _get = nmlib.notmuch_messages_get
56 _get.restype = c_void_p
58 _collect_tags = nmlib.notmuch_messages_collect_tags
59 _collect_tags.restype = c_void_p
61 def __init__(self, msgs_p, parent=None):
63 :param msgs_p: A pointer to an underlying *notmuch_messages_t*
64 structure. These are not publically exposed, so a user
65 will almost never instantiate a :class:`Messages` object
66 herself. They are usually handed back as a result,
67 e.g. in :meth:`Query.search_messages`. *msgs_p* must be
68 valid, we will raise an :exc:`NotmuchError`
69 (STATUS.NULL_POINTER) if it is `None`.
70 :type msgs_p: :class:`ctypes.c_void_p`
71 :param parent: The parent object
72 (ie :class:`Query`) these tags are derived from. It saves
73 a reference to it, so we can automatically delete the db
74 object once all derived objects are dead.
75 :TODO: Make the iterator work more than once and cache the tags in
79 NotmuchError(STATUS.NULL_POINTER)
82 #store parent, so we keep them alive as long as self is alive
85 def collect_tags(self):
86 """Return the unique :class:`Tags` in the contained messages
88 :returns: :class:`Tags`
89 :exceptions: :exc:`NotmuchError` STATUS.NOT_INITIALIZED if not inited
91 .. note:: :meth:`collect_tags` will iterate over the messages and
92 therefore will not allow further iterations.
94 if self._msgs is None:
95 raise NotmuchError(STATUS.NOT_INITIALIZED)
97 # collect all tags (returns NULL on error)
98 tags_p = Messages._collect_tags (self._msgs)
99 #reset _msgs as we iterated over it and can do so only once
103 raise NotmuchError(STATUS.NULL_POINTER)
104 return Tags(tags_p, self)
107 """ Make Messages an iterator """
111 if self._msgs is None:
112 raise NotmuchError(STATUS.NOT_INITIALIZED)
114 if not nmlib.notmuch_messages_valid(self._msgs):
118 msg = Message(Messages._get (self._msgs), self)
119 nmlib.notmuch_messages_move_to_next(self._msgs)
123 """len(:class:`Messages`) returns the number of contained messages
125 .. note:: As this iterates over the messages, we will not be able to
126 iterate over them again! So this will fail::
129 msgs = Database().create_query('').search_message()
130 if len(msgs) > 0: #this 'exhausts' msgs
131 # next line raises NotmuchError(STATUS.NOT_INITIALIZED)!!!
132 for msg in msgs: print msg
134 Most of the time, using the
135 :meth:`Query.count_messages` is therefore more
136 appropriate (and much faster). While not guaranteeing
137 that it will return the exact same number than len(),
138 in my tests it effectively always did so.
140 if self._msgs is None:
141 raise NotmuchError(STATUS.NOT_INITIALIZED)
144 while nmlib.notmuch_messages_valid(self._msgs):
145 nmlib.notmuch_messages_move_to_next(self._msgs)
153 """Close and free the notmuch Messages"""
154 if self._msgs is not None:
155 nmlib.notmuch_messages_destroy (self._msgs)
158 #------------------------------------------------------------------------------
159 class Message(object):
160 """Represents a single Email message
162 Technically, this wraps the underlying *notmuch_message_t* structure.
165 """notmuch_message_get_filename (notmuch_message_t *message)"""
166 _get_filename = nmlib.notmuch_message_get_filename
167 _get_filename.restype = c_char_p
169 """notmuch_message_get_message_id (notmuch_message_t *message)"""
170 _get_message_id = nmlib.notmuch_message_get_message_id
171 _get_message_id.restype = c_char_p
173 """notmuch_message_get_thread_id"""
174 _get_thread_id = nmlib.notmuch_message_get_thread_id
175 _get_thread_id.restype = c_char_p
177 """notmuch_message_get_replies"""
178 _get_replies = nmlib.notmuch_message_get_replies
179 _get_replies.restype = c_void_p
181 """notmuch_message_get_tags (notmuch_message_t *message)"""
182 _get_tags = nmlib.notmuch_message_get_tags
183 _get_tags.restype = c_void_p
185 _get_date = nmlib.notmuch_message_get_date
186 _get_date.restype = c_long
188 _get_header = nmlib.notmuch_message_get_header
189 _get_header.restype = c_char_p
191 def __init__(self, msg_p, parent=None):
193 :param msg_p: A pointer to an internal notmuch_message_t
194 Structure. If it is `None`, we will raise an :exc:`NotmuchError`
196 :param parent: A 'parent' object is passed which this message is
197 derived from. We save a reference to it, so we can
198 automatically delete the parent object once all derived
202 NotmuchError(STATUS.NULL_POINTER)
204 #keep reference to parent, so we keep it alive
205 self._parent = parent
208 def get_message_id(self):
209 """Returns the message ID
211 :returns: String with a message ID
212 :exception: :exc:`NotmuchError` STATUS.NOT_INITIALIZED if the message
215 if self._msg is None:
216 raise NotmuchError(STATUS.NOT_INITIALIZED)
217 return Message._get_message_id(self._msg)
219 def get_thread_id(self):
220 """Returns the thread ID
222 The returned string belongs to 'message' will only be valid for as
223 long as the message is valid.
225 This function will not return None since Notmuch ensures that every
226 message belongs to a single thread.
228 :returns: String with a thread ID
229 :exception: :exc:`NotmuchError` STATUS.NOT_INITIALIZED if the message
232 if self._msg is None:
233 raise NotmuchError(STATUS.NOT_INITIALIZED)
235 return Message._get_thread_id (self._msg);
237 def get_replies(self):
238 """Gets all direct replies to this message as :class:`Messages` iterator
240 .. note:: This call only makes sense if 'message' was
241 ultimately obtained from a :class:`Thread` object, (such as
242 by coming directly from the result of calling
243 :meth:`Thread.get_toplevel_messages` or by any number of
244 subsequent calls to :meth:`get_replies`). If this message was
245 obtained through some non-thread means, (such as by a call
246 to :meth:`Query.search_messages`), then this function will
249 :returns: :class:`Messages` or `None` if there are no replies to
251 :exception: :exc:`NotmuchError` STATUS.NOT_INITIALIZED if the message
254 if self._msg is None:
255 raise NotmuchError(STATUS.NOT_INITIALIZED)
257 msgs_p = Message._get_replies(self._msg);
262 return Messages(msgs_p,self)
265 """Returns time_t of the message date
267 For the original textual representation of the Date header from the
268 message call notmuch_message_get_header() with a header value of
271 :returns: A time_t timestamp.
273 :exception: :exc:`NotmuchError` STATUS.NOT_INITIALIZED if the message
276 if self._msg is None:
277 raise NotmuchError(STATUS.NOT_INITIALIZED)
278 return Message._get_date(self._msg)
280 def get_header(self, header):
281 """Returns a message header
283 This returns any message header that is stored in the notmuch database.
284 This is only a selected subset of headers, which is currently:
286 TODO: add stored headers
288 :param header: The name of the header to be retrieved.
289 It is not case-sensitive (TODO: confirm).
291 :returns: The header value as string
292 :exception: :exc:`NotmuchError`
294 * STATUS.NOT_INITIALIZED if the message
296 * STATUS.NULL_POINTER, if no header was found
298 if self._msg is None:
299 raise NotmuchError(STATUS.NOT_INITIALIZED)
301 #Returns NULL if any error occurs.
302 header = Message._get_header (self._msg, header)
304 raise NotmuchError(STATUS.NULL_POINTER)
307 def get_filename(self):
308 """Returns the file path of the message file
310 :returns: Absolute file path & name of the message file
311 :exception: :exc:`NotmuchError` STATUS.NOT_INITIALIZED if the message
314 if self._msg is None:
315 raise NotmuchError(STATUS.NOT_INITIALIZED)
316 return Message._get_filename(self._msg)
319 """Returns the message tags
321 :returns: A :class:`Tags` iterator.
322 :exception: :exc:`NotmuchError`
324 * STATUS.NOT_INITIALIZED if the message
326 * STATUS.NULL_POINTER, on error
328 if self._msg is None:
329 raise NotmuchError(STATUS.NOT_INITIALIZED)
331 tags_p = Message._get_tags(self._msg)
333 raise NotmuchError(STATUS.NULL_POINTER)
334 return Tags(tags_p, self)
336 def add_tag(self, tag):
337 """Adds a tag to the given message
339 Adds a tag to the current message. The maximal tag length is defined in
340 the notmuch library and is currently 200 bytes.
342 :param tag: String with a 'tag' to be added.
343 :returns: STATUS.SUCCESS if the tag was successfully added.
344 Raises an exception otherwise.
345 :exception: :exc:`NotmuchError`. They have the following meaning:
348 The 'tag' argument is NULL
350 The length of 'tag' is too long
351 (exceeds Message.NOTMUCH_TAG_MAX)
352 STATUS.READ_ONLY_DATABASE
353 Database was opened in read-only mode so message cannot be
355 STATUS.NOT_INITIALIZED
356 The message has not been initialized.
358 if self._msg is None:
359 raise NotmuchError(STATUS.NOT_INITIALIZED)
361 status = nmlib.notmuch_message_add_tag (self._msg, tag)
363 if STATUS.SUCCESS == status:
367 raise NotmuchError(status)
369 def remove_tag(self, tag):
370 """Removes a tag from the given message
372 If the message has no such tag, this is a non-operation and
373 will report success anyway.
375 :param tag: String with a 'tag' to be removed.
376 :returns: STATUS.SUCCESS if the tag was successfully removed or if
377 the message had no such tag.
378 Raises an exception otherwise.
379 :exception: :exc:`NotmuchError`. They have the following meaning:
382 The 'tag' argument is NULL
384 The length of 'tag' is too long
385 (exceeds NOTMUCH_TAG_MAX)
386 STATUS.READ_ONLY_DATABASE
387 Database was opened in read-only mode so message cannot
389 STATUS.NOT_INITIALIZED
390 The message has not been initialized.
392 if self._msg is None:
393 raise NotmuchError(STATUS.NOT_INITIALIZED)
395 status = nmlib.notmuch_message_remove_tag(self._msg, tag)
397 if STATUS.SUCCESS == status:
401 raise NotmuchError(status)
403 def remove_all_tags(self):
404 """Removes all tags from the given message.
406 See :meth:`freeze` for an example showing how to safely
409 :returns: STATUS.SUCCESS if the tags were successfully removed.
410 Raises an exception otherwise.
411 :exception: :exc:`NotmuchError`. They have the following meaning:
413 STATUS.READ_ONLY_DATABASE
414 Database was opened in read-only mode so message cannot
416 STATUS.NOT_INITIALIZED
417 The message has not been initialized.
419 if self._msg is None:
420 raise NotmuchError(STATUS.NOT_INITIALIZED)
422 status = nmlib.notmuch_message_remove_all_tags(self._msg)
424 if STATUS.SUCCESS == status:
428 raise NotmuchError(status)
431 """Freezes the current state of 'message' within the database
433 This means that changes to the message state, (via :meth:`add_tag`,
434 :meth:`remove_tag`, and :meth:`remove_all_tags`), will not be
435 committed to the database until the message is :meth:`thaw`ed.
437 Multiple calls to freeze/thaw are valid and these calls will
438 "stack". That is there must be as many calls to thaw as to freeze
439 before a message is actually thawed.
441 The ability to do freeze/thaw allows for safe transactions to
442 change tag values. For example, explicitly setting a message to
443 have a given set of tags might look like this::
446 msg.remove_all_tags()
451 With freeze/thaw used like this, the message in the database is
452 guaranteed to have either the full set of original tag values, or
453 the full set of new tag values, but nothing in between.
455 Imagine the example above without freeze/thaw and the operation
456 somehow getting interrupted. This could result in the message being
457 left with no tags if the interruption happened after
458 :meth:`remove_all_tags` but before :meth:`add_tag`.
460 :returns: STATUS.SUCCESS if the message was successfully frozen.
461 Raises an exception otherwise.
462 :exception: :exc:`NotmuchError`. They have the following meaning:
464 STATUS.READ_ONLY_DATABASE
465 Database was opened in read-only mode so message cannot
467 STATUS.NOT_INITIALIZED
468 The message has not been initialized.
470 if self._msg is None:
471 raise NotmuchError(STATUS.NOT_INITIALIZED)
473 status = nmlib.notmuch_message_freeze(self._msg)
475 if STATUS.SUCCESS == status:
479 raise NotmuchError(status)
482 """Thaws the current 'message'
484 Thaw the current 'message', synchronizing any changes that may have
485 occurred while 'message' was frozen into the notmuch database.
487 See :meth:`freeze` for an example of how to use this
488 function to safely provide tag changes.
490 Multiple calls to freeze/thaw are valid and these calls with
491 "stack". That is there must be as many calls to thaw as to freeze
492 before a message is actually thawed.
494 :returns: STATUS.SUCCESS if the message was successfully frozen.
495 Raises an exception otherwise.
496 :exception: :exc:`NotmuchError`. They have the following meaning:
498 STATUS.UNBALANCED_FREEZE_THAW
499 An attempt was made to thaw an unfrozen message.
500 That is, there have been an unbalanced number of calls
501 to :meth:`freeze` and :meth:`thaw`.
502 STATUS.NOT_INITIALIZED
503 The message has not been initialized.
505 if self._msg is None:
506 raise NotmuchError(STATUS.NOT_INITIALIZED)
508 status = nmlib.notmuch_message_thaw(self._msg)
510 if STATUS.SUCCESS == status:
514 raise NotmuchError(status)
518 """A message() is represented by a 1-line summary"""
520 msg['from'] = self.get_header('from')
521 msg['tags'] = str(self.get_tags())
522 msg['date'] = date.fromtimestamp(self.get_date())
523 replies = self.get_replies()
524 msg['replies'] = len(replies) if replies is not None else -1
525 return "%(from)s (%(date)s) (%(tags)s) (%(replies)d) replies" % (msg)
527 def format_as_text(self):
528 """Output like notmuch show (Not implemented)"""
532 """Close and free the notmuch Message"""
533 if self._msg is not None:
534 nmlib.notmuch_message_destroy (self._msg)