2 from ctypes import c_int, c_char_p, c_void_p, c_uint, c_uint64, c_bool, byref
3 from cnotmuch.globals import nmlib, STATUS, NotmuchError, Enum
5 from datetime import date
7 class Database(object):
8 """Represents a notmuch database (wraps notmuch_database_t)
10 .. note:: Do remember that as soon as we tear down this object,
11 all underlying derived objects such as queries, threads,
12 messages, tags etc will be freed by the underlying library
13 as well. Accessing these objects will lead to segfaults and
14 other unexpected behavior. See above for more details.
17 """Class attribute to cache user's default database"""
19 MODE = Enum(['READ_ONLY','READ_WRITE'])
20 """Constants: Mode in which to open the database"""
22 """notmuch_database_get_path (notmuch_database_t *database)"""
23 _get_path = nmlib.notmuch_database_get_path
24 _get_path.restype = c_char_p
26 """notmuch_database_get_version"""
27 _get_version = nmlib.notmuch_database_get_version
28 _get_version.restype = c_uint
30 """notmuch_database_open (const char *path, notmuch_database_mode_t mode)"""
31 _open = nmlib.notmuch_database_open
32 _open.restype = c_void_p
34 """ notmuch_database_find_message """
35 _find_message = nmlib.notmuch_database_find_message
36 _find_message.restype = c_void_p
38 """notmuch_database_get_all_tags (notmuch_database_t *database)"""
39 _get_all_tags = nmlib.notmuch_database_get_all_tags
40 _get_all_tags.restype = c_void_p
42 """ notmuch_database_create(const char *path):"""
43 _create = nmlib.notmuch_database_create
44 _create.restype = c_void_p
46 def __init__(self, path=None, create=False, mode= 0):
47 """If *path* is *None*, we will try to read a users notmuch
48 configuration and use his configured database. The location of the
49 configuration file can be specified through the environment variable
50 *NOTMUCH_CONFIG*, falling back to the default `~/.notmuch-config`.
52 If *create* is `True`, the database will always be created in
53 :attr:`MODE`.READ_WRITE mode. Default mode for opening is READ_ONLY.
55 :param path: Directory to open/create the database in (see
56 above for behavior if `None`)
57 :type path: `str` or `None`
58 :param create: Pass `False` to open an existing, `True` to create a new
61 :param mode: Mode to open a database in. Is always
62 :attr:`MODE`.READ_WRITE when creating a new one.
63 :type mode: :attr:`MODE`
65 :exception: :exc:`NotmuchError` in case of failure.
69 # no path specified. use a user's default database
70 if Database._std_db_path is None:
71 #the following line throws a NotmuchError if it fails
72 Database._std_db_path = self._get_user_default_db()
73 path = Database._std_db_path
80 def _verify_initialized_db(self):
81 """Raises a NotmuchError in case self._db is still None"""
83 raise NotmuchError(STATUS.NOT_INITIALIZED)
85 def create(self, path):
86 """Creates a new notmuch database
88 This function is used by __init__() and usually does not need
89 to be called directly. It wraps the underlying
90 *notmuch_database_create* function and creates a new notmuch
91 database at *path*. It will always return a database in
92 :attr:`MODE`.READ_WRITE mode as creating an empty database for
93 reading only does not make a great deal of sense.
95 :param path: A directory in which we should create the database.
98 :exception: :exc:`NotmuchError` in case of any failure
99 (after printing an error message on stderr).
101 if self._db is not None:
103 message="Cannot create db, this Database() already has an open one.")
105 res = Database._create(path, Database.MODE.READ_WRITE)
109 message="Could not create the specified database")
112 def open(self, path, mode= 0):
113 """Opens an existing database
115 This function is used by __init__() and usually does not need
116 to be called directly. It wraps the underlying
117 *notmuch_database_open* function.
119 :param status: Open the database in read-only or read-write mode
120 :type status: :attr:`MODE`
122 :exception: Raises :exc:`NotmuchError` in case
123 of any failure (after printing an error message on stderr).
126 res = Database._open(path, mode)
130 message="Could not open the specified database")
134 """Returns the file path of an open database
136 Wraps notmuch_database_get_path"""
137 # Raise a NotmuchError if not initialized
138 self._verify_initialized_db()
140 return Database._get_path(self._db)
142 def get_version(self):
143 """Returns the database format version
145 :returns: The database version as positive integer
146 :exception: :exc:`NotmuchError` with STATUS.NOT_INITIALIZED if
147 the database was not intitialized.
149 # Raise a NotmuchError if not initialized
150 self._verify_initialized_db()
152 return Database._get_version (self._db)
154 def needs_upgrade(self):
155 """Does this database need to be upgraded before writing to it?
157 If this function returns True then no functions that modify the
158 database (:meth:`add_message`, :meth:`add_tag`,
159 :meth:`Directory.set_mtime`, etc.) will work unless :meth:`upgrade`
160 is called successfully first.
162 :returns: `True` or `False`
163 :exception: :exc:`NotmuchError` with STATUS.NOT_INITIALIZED if
164 the database was not intitialized.
166 # Raise a NotmuchError if not initialized
167 self._verify_initialized_db()
169 return notmuch_database_needs_upgrade(self.db)
171 def add_message(self, filename):
172 """Adds a new message to the database
174 `filename` should be a path relative to the path of the open
175 database (see :meth:`get_path`), or else should be an absolute
176 filename with initial components that match the path of the
179 The file should be a single mail message (not a multi-message mbox)
180 that is expected to remain at its current location, since the
181 notmuch database will reference the filename, and will not copy the
182 entire contents of the file.
184 :returns: On success, we return
186 1) a :class:`Message` object that can be used for things
187 such as adding tags to the just-added message.
188 2) one of the following STATUS values:
191 Message successfully added to database.
192 STATUS.DUPLICATE_MESSAGE_ID
193 Message has the same message ID as another message already
194 in the database. The new filename was successfully added
195 to the message in the database.
197 :rtype: 2-tuple(:class:`Message`, STATUS)
199 :exception: Raises a :exc:`NotmuchError` with the following meaning.
200 If such an exception occurs, nothing was added to the database.
203 An error occurred trying to open the file, (such as
204 permission denied, or file not found, etc.).
205 STATUS.FILE_NOT_EMAIL
206 The contents of filename don't look like an email message.
207 STATUS.READ_ONLY_DATABASE
208 Database was opened in read-only mode so no message can
210 STATUS.NOT_INITIALIZED
211 The database has not been initialized.
213 # Raise a NotmuchError if not initialized
214 self._verify_initialized_db()
217 status = nmlib.notmuch_database_add_message(self._db,
221 if not status in [STATUS.SUCCESS,STATUS.DUPLICATE_MESSAGE_ID]:
222 raise NotmuchError(status)
224 #construct Message() and return
225 msg = Message(msg_p, self)
228 def remove_message(self, filename):
229 """Removes a message from the given notmuch database
231 Note that only this particular filename association is removed from
232 the database. If the same message (as determined by the message ID)
233 is still available via other filenames, then the message will
234 persist in the database for those filenames. When the last filename
235 is removed for a particular message, the database content for that
236 message will be entirely removed.
238 :returns: A STATUS.* value with the following meaning:
241 The last filename was removed and the message was removed
243 STATUS.DUPLICATE_MESSAGE_ID
244 This filename was removed but the message persists in the
245 database with at least one other filename.
247 :exception: Raises a :exc:`NotmuchError` with the following meaning.
248 If such an exception occurs, nothing was removed from the database.
250 STATUS.READ_ONLY_DATABASE
251 Database was opened in read-only mode so no message can be
253 STATUS.NOT_INITIALIZED
254 The database has not been initialized.
256 # Raise a NotmuchError if not initialized
257 self._verify_initialized_db()
259 status = nmlib.notmuch_database_remove_message(self._db,
262 def find_message(self, msgid):
263 """Returns a :class:`Message` as identified by its message ID
265 Wraps the underlying *notmuch_database_find_message* function.
267 :param msgid: The message ID
269 :returns: :class:`Message` or `None` if no message is found or if an
270 out-of-memory situation occurs.
271 :exception: :exc:`NotmuchError` with STATUS.NOT_INITIALIZED if
272 the database was not intitialized.
274 # Raise a NotmuchError if not initialized
275 self._verify_initialized_db()
277 msg_p = Database._find_message(self._db, msgid)
280 return Message(msg_p, self)
282 def get_all_tags(self):
283 """Returns :class:`Tags` with a list of all tags found in the database
285 :returns: :class:`Tags`
286 :execption: :exc:`NotmuchError` with STATUS.NULL_POINTER on error
288 # Raise a NotmuchError if not initialized
289 self._verify_initialized_db()
291 tags_p = Database._get_all_tags (self._db)
293 raise NotmuchError(STATUS.NULL_POINTER)
294 return Tags(tags_p, self)
297 return "'Notmuch DB " + self.get_path() + "'"
300 """Close and free the notmuch database if needed"""
301 if self._db is not None:
302 logging.debug("Freeing the database now")
303 nmlib.notmuch_database_close(self._db)
305 def _get_user_default_db(self):
306 """ Reads a user's notmuch config and returns his db location
308 Throws a NotmuchError if it cannot find it"""
309 from ConfigParser import SafeConfigParser
310 config = SafeConfigParser()
311 conf_f = os.getenv('NOTMUCH_CONFIG',
312 os.path.expanduser('~/.notmuch-config'))
314 if not config.has_option('database','path'):
315 raise NotmuchError(message=
316 "No DB path specified and no user default found")
317 return config.get('database','path')
321 """Property returning a pointer to `notmuch_database_t` or `None`
323 This should normally not be needed by a user (and is not yet
324 guaranteed to remain stable in future versions).
328 #------------------------------------------------------------------------------
330 """Represents a search query on an opened :class:`Database`.
332 A query selects and filters a subset of messages from the notmuch
333 database we derive from.
335 Technically, it wraps the underlying *notmuch_query_t* struct.
337 .. note:: Do remember that as soon as we tear down this object,
338 all underlying derived objects such as threads,
339 messages, tags etc will be freed by the underlying library
340 as well. Accessing these objects will lead to segfaults and
341 other unexpected behavior. See above for more details.
344 SORT = Enum(['OLDEST_FIRST','NEWEST_FIRST','MESSAGE_ID'])
345 """Constants: Sort order in which to return results"""
347 """notmuch_query_create"""
348 _create = nmlib.notmuch_query_create
349 _create.restype = c_void_p
351 """notmuch_query_search_messages"""
352 _search_messages = nmlib.notmuch_query_search_messages
353 _search_messages.restype = c_void_p
356 """notmuch_query_count_messages"""
357 _count_messages = nmlib.notmuch_query_count_messages
358 _count_messages.restype = c_uint
360 def __init__(self, db, querystr):
362 :param db: An open database which we derive the Query from.
363 :type db: :class:`Database`
364 :param querystr: The query string for the message.
369 self.create(db, querystr)
371 def create(self, db, querystr):
372 """Creates a new query derived from a Database
374 This function is utilized by __init__() and usually does not need to
377 :param db: Database to create the query from.
378 :type db: :class:`Database`
379 :param querystr: The query string
382 :exception: :exc:`NotmuchError`
384 * STATUS.NOT_INITIALIZED if db is not inited
385 * STATUS.NULL_POINTER if the query creation failed
389 raise NotmuchError(STATUS.NOT_INITIALIZED)
390 # create reference to parent db to keep it alive
393 # create query, return None if too little mem available
394 query_p = Query._create(db.db_p, querystr)
396 NotmuchError(STATUS.NULL_POINTER)
397 self._query = query_p
399 def set_sort(self, sort):
400 """Set the sort order future results will be delivered in
402 Wraps the underlying *notmuch_query_set_sort* function.
404 :param sort: Sort order (see :attr:`Query.SORT`)
406 :exception: :exc:`NotmuchError` STATUS.NOT_INITIALIZED if query has not
409 if self._query is None:
410 raise NotmuchError(STATUS.NOT_INITIALIZED)
412 nmlib.notmuch_query_set_sort(self._query, sort)
414 def search_messages(self):
415 """Filter messages according to the query and return
416 :class:`Messages` in the defined sort order
418 Technically, it wraps the underlying
419 *notmuch_query_search_messages* function.
421 :returns: :class:`Messages`
422 :exception: :exc:`NotmuchError`
424 * STATUS.NOT_INITIALIZED if query is not inited
425 * STATUS.NULL_POINTER if search_messages failed
427 if self._query is None:
428 raise NotmuchError(STATUS.NOT_INITIALIZED)
430 msgs_p = Query._search_messages(self._query)
433 NotmuchError(STATUS.NULL_POINTER)
435 return Messages(msgs_p,self)
437 def count_messages(self):
438 """Estimate the number of messages matching the query
440 This function performs a search and returns Xapian's best
441 guess as to the number of matching messages. It is much faster
442 than performing :meth:`search_messages` and counting the
443 result with `len()` (although it always returned the same
444 result in my tests). Technically, it wraps the underlying
445 *notmuch_query_count_messages* function.
447 :returns: :class:`Messages`
448 :exception: :exc:`NotmuchError`
450 * STATUS.NOT_INITIALIZED if query is not inited
452 if self._query is None:
453 raise NotmuchError(STATUS.NOT_INITIALIZED)
455 return Query._count_messages(self._query)
458 """Close and free the Query"""
459 if self._query is not None:
460 logging.debug("Freeing the Query now")
461 nmlib.notmuch_query_destroy (self._query)
463 #------------------------------------------------------------------------------
465 """Represents a list of notmuch tags
467 This object provides an iterator over a list of notmuch tags. Do
468 note that the underlying library only provides a one-time iterator
469 (it cannot reset the iterator to the start). Thus iterating over
470 the function will "exhaust" the list of tags, and a subsequent
471 iteration attempt will raise a :exc:`NotmuchError`
472 STATUS.NOT_INITIALIZED. Also note, that any function that uses
473 iteration (nearly all) will also exhaust the tags. So both::
475 for tag in tags: print tag
479 number_of_tags = len(tags)
483 #str() iterates over all tags to construct a space separated list
486 will "exhaust" the Tags. If you need to re-iterate over a list of
487 tags you will need to retrieve a new :class:`Tags` object.
491 _get = nmlib.notmuch_tags_get
492 _get.restype = c_char_p
494 def __init__(self, tags_p, parent=None):
496 :param tags_p: A pointer to an underlying *notmuch_tags_t*
497 structure. These are not publically exposed, so a user
498 will almost never instantiate a :class:`Tags` object
499 herself. They are usually handed back as a result,
500 e.g. in :meth:`Database.get_all_tags`. *tags_p* must be
501 valid, we will raise an :exc:`NotmuchError`
502 (STATUS.NULL_POINTER) if it is `None`.
503 :type tags_p: :class:`ctypes.c_void_p`
504 :param parent: The parent object (ie :class:`Database` or
505 :class:`Message` these tags are derived from, and saves a
506 reference to it, so we can automatically delete the db object
507 once all derived objects are dead.
508 :TODO: Make the iterator optionally work more than once by
509 cache the tags in the Python object(?)
512 NotmuchError(STATUS.NULL_POINTER)
515 #save reference to parent object so we keep it alive
516 self._parent = parent
517 logging.debug("Inited Tags derived from %s" %(repr(parent)))
520 """ Make Tags an iterator """
524 if self._tags is None:
525 raise NotmuchError(STATUS.NOT_INITIALIZED)
527 if not nmlib.notmuch_tags_valid(self._tags):
531 tag = Tags._get (self._tags)
532 nmlib.notmuch_tags_move_to_next(self._tags)
536 """len(:class:`Tags`) returns the number of contained tags
538 .. note:: As this iterates over the tags, we will not be able
539 to iterate over them again (as in retrieve them)! If
540 the tags have been exhausted already, this will raise a
541 :exc:`NotmuchError` STATUS.NOT_INITIALIZED on
544 if self._tags is None:
545 raise NotmuchError(STATUS.NOT_INITIALIZED)
548 while nmlib.notmuch_tags_valid(self._msgs):
549 nmlib.notmuch_tags_move_to_next(self._msgs)
555 """The str() representation of Tags() is a space separated list of tags
557 .. note:: As this iterates over the tags, we will not be able
558 to iterate over them again (as in retrieve them)! If
559 the tags have been exhausted already, this will raise a
560 :exc:`NotmuchError` STATUS.NOT_INITIALIZED on
563 return " ".join(self)
566 """Close and free the notmuch tags"""
567 if self._tags is not None:
568 logging.debug("Freeing the Tags now")
569 nmlib.notmuch_tags_destroy (self._tags)
572 #------------------------------------------------------------------------------
573 class Messages(object):
574 """Represents a list of notmuch messages
576 This object provides an iterator over a list of notmuch messages
577 (Technically, it provides a wrapper for the underlying
578 *notmuch_messages_t* structure). Do note that the underlying
579 library only provides a one-time iterator (it cannot reset the
580 iterator to the start). Thus iterating over the function will
581 "exhaust" the list of messages, and a subsequent iteration attempt
582 will raise a :exc:`NotmuchError` STATUS.NOT_INITIALIZED. Also
583 note, that any function that uses iteration will also
584 exhaust the messages. So both::
586 for msg in msgs: print msg
590 number_of_msgs = len(msgs)
592 will "exhaust" the Messages. If you need to re-iterate over a list of
593 messages you will need to retrieve a new :class:`Messages` object.
595 Things are not as bad as it seems though, you can store and reuse
596 the single Message objects as often as you want as long as you
597 keep the parent Messages object around. (Recall that due to
598 hierarchical memory allocation, all derived Message objects will
599 be invalid when we delete the parent Messages() object, even if it
600 was already "exhausted".) So this works::
603 msgs = Query(db,'').search_messages() #get a Messages() object
608 # msgs is "exhausted" now and even len(msgs) will raise an exception.
609 # However it will be kept around until all retrieved Message() objects are
610 # also deleted. If you did e.g. an explicit del(msgs) here, the
611 # following lines would fail.
613 # You can reiterate over *msglist* however as often as you want.
614 # It is simply a list with Message objects.
616 print (msglist[0].get_filename())
617 print (msglist[1].get_filename())
618 print (msglist[0].get_message_id())
622 _get = nmlib.notmuch_messages_get
623 _get.restype = c_void_p
625 _collect_tags = nmlib.notmuch_messages_collect_tags
626 _collect_tags.restype = c_void_p
628 def __init__(self, msgs_p, parent=None):
630 :param msgs_p: A pointer to an underlying *notmuch_messages_t*
631 structure. These are not publically exposed, so a user
632 will almost never instantiate a :class:`Messages` object
633 herself. They are usually handed back as a result,
634 e.g. in :meth:`Query.search_messages`. *msgs_p* must be
635 valid, we will raise an :exc:`NotmuchError`
636 (STATUS.NULL_POINTER) if it is `None`.
637 :type msgs_p: :class:`ctypes.c_void_p`
638 :param parent: The parent object
639 (ie :class:`Query`) these tags are derived from. It saves
640 a reference to it, so we can automatically delete the db
641 object once all derived objects are dead.
642 :TODO: Make the iterator work more than once and cache the tags in
643 the Python object.(?)
646 NotmuchError(STATUS.NULL_POINTER)
649 #store parent, so we keep them alive as long as self is alive
650 self._parent = parent
651 logging.debug("Inited Messages derived from %s" %(str(parent)))
653 def collect_tags(self):
654 """Return the unique :class:`Tags` in the contained messages
656 :returns: :class:`Tags`
657 :exceptions: :exc:`NotmuchError` STATUS.NOT_INITIALIZED if not inited
659 .. note:: :meth:`collect_tags` will iterate over the messages and
660 therefore will not allow further iterations.
662 if self._msgs is None:
663 raise NotmuchError(STATUS.NOT_INITIALIZED)
665 # collect all tags (returns NULL on error)
666 tags_p = Messages._collect_tags (self._msgs)
667 #reset _msgs as we iterated over it and can do so only once
671 raise NotmuchError(STATUS.NULL_POINTER)
672 return Tags(tags_p, self)
675 """ Make Messages an iterator """
679 if self._msgs is None:
680 raise NotmuchError(STATUS.NOT_INITIALIZED)
682 if not nmlib.notmuch_messages_valid(self._msgs):
686 msg = Message(Messages._get (self._msgs), self)
687 nmlib.notmuch_messages_move_to_next(self._msgs)
691 """len(:class:`Messages`) returns the number of contained messages
693 .. note:: As this iterates over the messages, we will not be able to
694 iterate over them again (as in retrieve them)!
696 if self._msgs is None:
697 raise NotmuchError(STATUS.NOT_INITIALIZED)
700 while nmlib.notmuch_messages_valid(self._msgs):
701 nmlib.notmuch_messages_move_to_next(self._msgs)
709 """Close and free the notmuch Messages"""
710 if self._msgs is not None:
711 logging.debug("Freeing the Messages now")
712 nmlib.notmuch_messages_destroy (self._msgs)
715 #------------------------------------------------------------------------------
716 class Message(object):
717 """Represents a single Email message
719 Technically, this wraps the underlying *notmuch_message_t* structure.
722 """notmuch_message_get_filename (notmuch_message_t *message)"""
723 _get_filename = nmlib.notmuch_message_get_filename
724 _get_filename.restype = c_char_p
726 """notmuch_message_get_message_id (notmuch_message_t *message)"""
727 _get_message_id = nmlib.notmuch_message_get_message_id
728 _get_message_id.restype = c_char_p
730 """notmuch_message_get_thread_id"""
731 _get_thread_id = nmlib.notmuch_message_get_thread_id
732 _get_thread_id.restype = c_char_p
734 """notmuch_message_get_tags (notmuch_message_t *message)"""
735 _get_tags = nmlib.notmuch_message_get_tags
736 _get_tags.restype = c_void_p
738 _get_date = nmlib.notmuch_message_get_date
739 _get_date.restype = c_uint64
741 _get_header = nmlib.notmuch_message_get_header
742 _get_header.restype = c_char_p
744 def __init__(self, msg_p, parent=None):
746 :param msg_p: A pointer to an internal notmuch_message_t
747 Structure. If it is `None`, we will raise an :exc:`NotmuchError`
749 :param parent: A 'parent' object is passed which this message is
750 derived from. We save a reference to it, so we can
751 automatically delete the parent object once all derived
755 NotmuchError(STATUS.NULL_POINTER)
757 #keep reference to parent, so we keep it alive
758 self._parent = parent
759 logging.debug("Inited Message derived from %s" %(str(parent)))
762 def get_message_id(self):
763 """Returns the message ID
765 :returns: String with a message ID
766 :exception: :exc:`NotmuchError` STATUS.NOT_INITIALIZED if the message
769 if self._msg is None:
770 raise NotmuchError(STATUS.NOT_INITIALIZED)
771 return Message._get_message_id(self._msg)
773 def get_thread_id(self):
774 """Returns the thread ID
776 The returned string belongs to 'message' will only be valid for as
777 long as the message is valid.
779 This function will not return None since Notmuch ensures that every
780 message belongs to a single thread.
782 :returns: String with a thread ID
783 :exception: :exc:`NotmuchError` STATUS.NOT_INITIALIZED if the message
786 if self._msg is None:
787 raise NotmuchError(STATUS.NOT_INITIALIZED)
789 return Message._get_thread_id (self._msg);
792 """Returns time_t of the message date
794 For the original textual representation of the Date header from the
795 message call notmuch_message_get_header() with a header value of
798 :returns: a time_t timestamp
800 :exception: :exc:`NotmuchError` STATUS.NOT_INITIALIZED if the message
803 if self._msg is None:
804 raise NotmuchError(STATUS.NOT_INITIALIZED)
805 return Message._get_date(self._msg)
807 def get_header(self, header):
808 """Returns a message header
810 This returns any message header that is stored in the notmuch database.
811 This is only a selected subset of headers, which is currently:
813 TODO: add stored headers
815 :param header: The name of the header to be retrieved.
816 It is not case-sensitive (TODO: confirm).
818 :returns: The header value as string
819 :exception: :exc:`NotmuchError`
821 * STATUS.NOT_INITIALIZED if the message
823 * STATUS.NULL_POINTER, if no header was found
825 if self._msg is None:
826 raise NotmuchError(STATUS.NOT_INITIALIZED)
828 #Returns NULL if any error occurs.
829 header = Message._get_header (self._msg, header)
831 raise NotmuchError(STATUS.NULL_POINTER)
834 def get_filename(self):
835 """Return the file path of the message file
837 :returns: Absolute file path & name of the message file
838 :exception: :exc:`NotmuchError` STATUS.NOT_INITIALIZED if the message
841 if self._msg is None:
842 raise NotmuchError(STATUS.NOT_INITIALIZED)
843 return Message._get_filename(self._msg)
846 """ Return the message tags
848 :returns: Message tags
849 :rtype: :class:`Tags`
850 :exception: :exc:`NotmuchError`
852 * STATUS.NOT_INITIALIZED if the message
854 * STATUS.NULL_POINTER, on error
856 if self._msg is None:
857 raise NotmuchError(STATUS.NOT_INITIALIZED)
859 tags_p = Message._get_tags(self._msg)
861 raise NotmuchError(STATUS.NULL_POINTER)
862 return Tags(tags_p, self)
864 def add_tag(self, tag):
865 """Add a tag to the given message
867 Adds a tag to the current message. The maximal tag length is defined in
868 the notmuch library and is currently 200 bytes.
870 :param tag: String with a 'tag' to be added.
871 :returns: STATUS.SUCCESS if the tag was successfully added.
872 Raises an exception otherwise.
873 :exception: :exc:`NotmuchError`. They have the following meaning:
876 The 'tag' argument is NULL
878 The length of 'tag' is too long
879 (exceeds Message.NOTMUCH_TAG_MAX)
880 STATUS.READ_ONLY_DATABASE
881 Database was opened in read-only mode so message cannot be
883 STATUS.NOT_INITIALIZED
884 The message has not been initialized.
886 if self._msg is None:
887 raise NotmuchError(STATUS.NOT_INITIALIZED)
889 status = nmlib.notmuch_message_add_tag (self._msg, tag)
891 if STATUS.SUCCESS == status:
895 raise NotmuchError(status)
897 def remove_tag(self, tag):
898 """Removes a tag from the given message
900 If the message has no such tag, this is a non-operation and
901 will report success anyway.
903 :param tag: String with a 'tag' to be removed.
904 :returns: STATUS.SUCCESS if the tag was successfully removed or if
905 the message had no such tag.
906 Raises an exception otherwise.
907 :exception: :exc:`NotmuchError`. They have the following meaning:
910 The 'tag' argument is NULL
912 The length of 'tag' is too long
913 (exceeds NOTMUCH_TAG_MAX)
914 STATUS.READ_ONLY_DATABASE
915 Database was opened in read-only mode so message cannot
917 STATUS.NOT_INITIALIZED
918 The message has not been initialized.
920 if self._msg is None:
921 raise NotmuchError(STATUS.NOT_INITIALIZED)
923 status = nmlib.notmuch_message_remove_tag(self._msg, tag)
925 if STATUS.SUCCESS == status:
929 raise NotmuchError(status)
931 def remove_all_tags(self):
932 """Removes all tags from the given message.
934 See :meth:`freeze` for an example showing how to safely
937 :returns: STATUS.SUCCESS if the tags were successfully removed.
938 Raises an exception otherwise.
939 :exception: :exc:`NotmuchError`. They have the following meaning:
941 STATUS.READ_ONLY_DATABASE
942 Database was opened in read-only mode so message cannot
944 STATUS.NOT_INITIALIZED
945 The message has not been initialized.
947 if self._msg is None:
948 raise NotmuchError(STATUS.NOT_INITIALIZED)
950 status = nmlib.notmuch_message_remove_all_tags(self._msg)
952 if STATUS.SUCCESS == status:
956 raise NotmuchError(status)
959 """Freezes the current state of 'message' within the database
961 This means that changes to the message state, (via :meth:`add_tag`,
962 :meth:`remove_tag`, and :meth:`remove_all_tags`), will not be
963 committed to the database until the message is :meth:`thaw`ed.
965 Multiple calls to freeze/thaw are valid and these calls will
966 "stack". That is there must be as many calls to thaw as to freeze
967 before a message is actually thawed.
969 The ability to do freeze/thaw allows for safe transactions to
970 change tag values. For example, explicitly setting a message to
971 have a given set of tags might look like this::
974 msg.remove_all_tags()
979 With freeze/thaw used like this, the message in the database is
980 guaranteed to have either the full set of original tag values, or
981 the full set of new tag values, but nothing in between.
983 Imagine the example above without freeze/thaw and the operation
984 somehow getting interrupted. This could result in the message being
985 left with no tags if the interruption happened after
986 :meth:`remove_all_tags` but before :meth:`add_tag`.
988 :returns: STATUS.SUCCESS if the message was successfully frozen.
989 Raises an exception otherwise.
990 :exception: :exc:`NotmuchError`. They have the following meaning:
992 STATUS.READ_ONLY_DATABASE
993 Database was opened in read-only mode so message cannot
995 STATUS.NOT_INITIALIZED
996 The message has not been initialized.
998 if self._msg is None:
999 raise NotmuchError(STATUS.NOT_INITIALIZED)
1001 status = nmlib.notmuch_message_freeze(self._msg)
1003 if STATUS.SUCCESS == status:
1007 raise NotmuchError(status)
1010 """Thaws the current 'message'
1012 Thaw the current 'message', synchronizing any changes that may have
1013 occurred while 'message' was frozen into the notmuch database.
1015 See :meth:`freeze` for an example of how to use this
1016 function to safely provide tag changes.
1018 Multiple calls to freeze/thaw are valid and these calls with
1019 "stack". That is there must be as many calls to thaw as to freeze
1020 before a message is actually thawed.
1022 :returns: STATUS.SUCCESS if the message was successfully frozen.
1023 Raises an exception otherwise.
1024 :exception: :exc:`NotmuchError`. They have the following meaning:
1026 STATUS.UNBALANCED_FREEZE_THAW
1027 An attempt was made to thaw an unfrozen message.
1028 That is, there have been an unbalanced number of calls
1029 to :meth:`freeze` and :meth:`thaw`.
1030 STATUS.NOT_INITIALIZED
1031 The message has not been initialized.
1033 if self._msg is None:
1034 raise NotmuchError(STATUS.NOT_INITIALIZED)
1036 status = nmlib.notmuch_message_thaw(self._msg)
1038 if STATUS.SUCCESS == status:
1042 raise NotmuchError(status)
1046 """A message() is represented by a 1-line summary"""
1048 msg['from'] = self.get_header('from')
1049 msg['tags'] = str(self.get_tags())
1050 msg['date'] = date.fromtimestamp(self.get_date())
1051 return "%(from)s (%(date)s) (%(tags)s)" % (msg)
1053 def format_as_text(self):
1054 """Output like notmuch show (Not implemented)"""
1058 """Close and free the notmuch Message"""
1059 if self._msg is not None:
1060 logging.debug("Freeing the Message now")
1061 nmlib.notmuch_message_destroy (self._msg)