Gmail.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374
  1. # Gmail IMAP folder support
  2. # Copyright (C) 2002-2017 John Goerzen & contributors.
  3. #
  4. # This program is free software; you can redistribute it and/or modify
  5. # it under the terms of the GNU General Public License as published by
  6. # the Free Software Foundation; either version 2 of the License, or
  7. # (at your option) any later version.
  8. #
  9. # This program is distributed in the hope that it will be useful,
  10. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. # GNU General Public License for more details.
  13. #
  14. # You should have received a copy of the GNU General Public License
  15. # along with this program; if not, write to the Free Software
  16. # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
  17. """Folder implementation to support features of the Gmail IMAP server."""
  18. import re
  19. from sys import exc_info
  20. from offlineimap import imaputil, imaplibutil, OfflineImapError
  21. import offlineimap.accounts
  22. from .IMAP import IMAPFolder
  23. class GmailFolder(IMAPFolder):
  24. """Folder implementation to support features of the Gmail IMAP server.
  25. Removing a message from a folder will only remove the "label" from
  26. the message and keep it in the "All mails" folder. To really delete
  27. a message it needs to be copied to the Trash folder. However, this
  28. is dangerous as our folder moves are implemented as a 1) delete in
  29. one folder and 2) append to the other. If 2 comes before 1, this
  30. will effectively delete the message from all folders. So we cannot
  31. do that until we have a smarter folder move mechanism.
  32. For more information on the Gmail IMAP server:
  33. http://mail.google.com/support/bin/answer.py?answer=77657&topic=12815
  34. https://developers.google.com/google-apps/gmail/imap_extensions
  35. """
  36. def __init__(self, imapserver, name, repository, decode=True):
  37. super(GmailFolder, self).__init__(imapserver, name, repository, decode)
  38. # The header under which labels are stored
  39. self.labelsheader = self.repository.account.getconf('labelsheader', 'X-Keywords')
  40. # enables / disables label sync
  41. self.synclabels = self.repository.account.getconfboolean('synclabels', False)
  42. # if synclabels is enabled, add a 4th pass to sync labels
  43. if self.synclabels:
  44. self.imap_query.insert(0, 'X-GM-LABELS')
  45. self.syncmessagesto_passes.append(self.syncmessagesto_labels)
  46. # Labels to be left alone
  47. ignorelabels = self.repository.account.getconf('ignorelabels', '')
  48. self.ignorelabels = set([v for v in re.split(r'\s*,\s*', ignorelabels) if len(v)])
  49. def getmessage(self, uid):
  50. """Retrieve message with UID from the IMAP server (incl body). Also
  51. gets Gmail labels and embeds them into the message.
  52. :returns: the message body or throws and OfflineImapError
  53. (probably severity MESSAGE) if e.g. no message with
  54. this UID could be found.
  55. """
  56. data = self._fetch_from_imap(str(uid), self.retrycount)
  57. # data looks now e.g.
  58. # ['320 (X-GM-LABELS (...) UID 17061 BODY[] {2565}',<email.message.EmailMessage object>]
  59. # we only asked for one message, and that msg is in data[1].
  60. msg = data[1]
  61. # Embed the labels into the message headers
  62. if self.synclabels:
  63. m = re.search(r'X-GM-LABELS\s*[(](.*)[)]', data[0])
  64. if m:
  65. labels = set([imaputil.dequote(lb) for lb in imaputil.imapsplit(m.group(1))])
  66. else:
  67. labels = set()
  68. labels = labels - self.ignorelabels
  69. labels_str = imaputil.format_labels_string(self.labelsheader, sorted(labels))
  70. # First remove old label headers that may be in the message body retrieved
  71. # from gmail Then add a labels header with current gmail labels.
  72. self.deletemessageheaders(msg, self.labelsheader)
  73. self.addmessageheader(msg, self.labelsheader, labels_str)
  74. if self.ui.is_debugging('imap'):
  75. # Optimization: don't create the debugging objects unless needed
  76. msg_s = msg.as_string(policy=self.policy['8bit-RFC'])
  77. if len(msg_s) > 200:
  78. dbg_output = "%s...%s" % (msg_s[:150], msg_s[-50:])
  79. else:
  80. dbg_output = msg_s
  81. self.ui.debug('imap', "Returned object from fetching %d: '%s'" %
  82. (uid, dbg_output))
  83. return msg
  84. def getmessagelabels(self, uid):
  85. if 'labels' in self.messagelist[uid]:
  86. return self.messagelist[uid]['labels']
  87. else:
  88. return set()
  89. # Interface from BaseFolder
  90. def msglist_item_initializer(self, uid):
  91. return {'uid': uid, 'flags': set(), 'labels': set(), 'time': 0}
  92. # TODO: merge this code with the parent's cachemessagelist:
  93. # TODO: they have too much common logics.
  94. def cachemessagelist(self, min_date=None, min_uid=None):
  95. if not self.synclabels:
  96. return super(GmailFolder, self).cachemessagelist(
  97. min_date=min_date, min_uid=min_uid)
  98. self.dropmessagelistcache()
  99. self.ui.collectingdata(None, self)
  100. imapobj = self.imapserver.acquireconnection()
  101. try:
  102. msgsToFetch = self._msgs_to_fetch(
  103. imapobj, min_date=min_date, min_uid=min_uid)
  104. if not msgsToFetch:
  105. return # No messages to sync
  106. # Get the flags and UIDs for these.
  107. #
  108. # NB: msgsToFetch are sequential numbers, not UID's
  109. res_type, response = imapobj.fetch("%s" % msgsToFetch,
  110. '(FLAGS X-GM-LABELS UID)')
  111. if res_type != 'OK':
  112. raise OfflineImapError(
  113. "FETCHING UIDs in folder [%s]%s failed. " %
  114. (self.getrepository(), self) +
  115. "Server responded '[%s] %s'" %
  116. (res_type, response),
  117. OfflineImapError.ERROR.FOLDER,
  118. exc_info()[2])
  119. finally:
  120. self.imapserver.releaseconnection(imapobj)
  121. for messagestr in response:
  122. # looks like: '1 (FLAGS (\\Seen Old) X-GM-LABELS (\\Inbox \\Favorites) UID 4807)' or None if no msg
  123. # Discard initial message number.
  124. if messagestr is None:
  125. continue
  126. # We need a str messagestr
  127. if isinstance(messagestr, bytes):
  128. messagestr = messagestr.decode(encoding='utf-8')
  129. messagestr = messagestr.split(' ', 1)[1]
  130. # e.g.: {'X-GM-LABELS': '("Webserver (RW.net)" "\\Inbox" GInbox)', 'FLAGS': '(\\Seen)', 'UID': '275440'}
  131. options = imaputil.flags2hash(messagestr)
  132. if 'UID' not in options:
  133. self.ui.warn('No UID in message with options %s' %
  134. str(options), minor=1)
  135. else:
  136. uid = int(options['UID'])
  137. self.messagelist[uid] = self.msglist_item_initializer(uid)
  138. flags = imaputil.flagsimap2maildir(options['FLAGS'])
  139. # e.g.: '("Webserver (RW.net)" "\\Inbox" GInbox)'
  140. m = re.search('^[(](.*)[)]', options['X-GM-LABELS'])
  141. if m:
  142. labels = set([imaputil.dequote(lb) for lb in imaputil.imapsplit(m.group(1))])
  143. else:
  144. labels = set()
  145. labels = labels - self.ignorelabels
  146. if isinstance(messagestr, str):
  147. messagestr = bytes(messagestr, 'utf-8')
  148. rtime = imaplibutil.Internaldate2epoch(messagestr)
  149. self.messagelist[uid] = {'uid': uid, 'flags': flags, 'labels': labels, 'time': rtime}
  150. def savemessage(self, uid, msg, flags, rtime):
  151. """Save the message on the Server
  152. This backend always assigns a new uid, so the uid arg is ignored.
  153. This function will update the self.messagelist dict to contain
  154. the new message after sucessfully saving it, including labels.
  155. See folder/Base for details. Note that savemessage() does not
  156. check against dryrun settings, so you need to ensure that
  157. savemessage is never called in a dryrun mode.
  158. :param uid: Message UID
  159. :param msg: Message object
  160. :param flags: Message flags
  161. :param rtime: A timestamp to be used as the mail date
  162. :returns: the UID of the new message as assigned by the server. If the
  163. message is saved, but it's UID can not be found, it will
  164. return 0. If the message can't be written (folder is
  165. read-only for example) it will return -1."""
  166. if not self.synclabels:
  167. return super(GmailFolder, self).savemessage(uid, msg, flags, rtime)
  168. labels = set()
  169. for hstr in self.getmessageheaderlist(msg, self.labelsheader):
  170. labels.update(imaputil.labels_from_header(self.labelsheader, hstr))
  171. ret = super(GmailFolder, self).savemessage(uid, msg, flags, rtime)
  172. self.savemessagelabels(ret, labels)
  173. return ret
  174. def _messagelabels_aux(self, arg, uidlist, labels):
  175. """Common code to savemessagelabels and addmessagelabels"""
  176. labels = labels - self.ignorelabels
  177. uidlist = [uid for uid in uidlist if uid > 0]
  178. if len(uidlist) > 0:
  179. imapobj = self.imapserver.acquireconnection()
  180. try:
  181. labels_str = '(' + ' '.join([imaputil.quote(lb) for lb in labels]) + ')'
  182. # Coalesce uid's into ranges
  183. uid_str = imaputil.uid_sequence(uidlist)
  184. result = self._store_to_imap(imapobj, uid_str, arg, labels_str)
  185. except imapobj.readonly:
  186. self.ui.labelstoreadonly(self, uidlist, labels)
  187. return None
  188. finally:
  189. self.imapserver.releaseconnection(imapobj)
  190. if result:
  191. retlabels = imaputil.flags2hash(imaputil.imapsplit(result)[1])['X-GM-LABELS']
  192. retlabels = set([imaputil.dequote(lb) for lb in imaputil.imapsplit(retlabels)])
  193. return retlabels
  194. return None
  195. def savemessagelabels(self, uid, labels):
  196. """Change a message's labels to `labels`.
  197. Note that this function does not check against dryrun settings,
  198. so you need to ensure that it is never called in a dryrun mode."""
  199. if uid in self.messagelist and 'labels' in self.messagelist[uid]:
  200. oldlabels = self.messagelist[uid]['labels']
  201. else:
  202. oldlabels = set()
  203. labels = labels - self.ignorelabels
  204. newlabels = labels | (oldlabels & self.ignorelabels)
  205. if oldlabels != newlabels:
  206. result = self._messagelabels_aux('X-GM-LABELS', [uid], newlabels)
  207. if result:
  208. self.messagelist[uid]['labels'] = newlabels
  209. else:
  210. self.messagelist[uid]['labels'] = oldlabels
  211. def addmessageslabels(self, uidlist, labels):
  212. """Add `labels` to all messages in uidlist.
  213. Note that this function does not check against dryrun settings,
  214. so you need to ensure that it is never called in a dryrun mode."""
  215. labels = labels - self.ignorelabels
  216. result = self._messagelabels_aux('+X-GM-LABELS', uidlist, labels)
  217. if result:
  218. for uid in uidlist:
  219. self.messagelist[uid]['labels'] = self.messagelist[uid]['labels'] | labels
  220. def deletemessageslabels(self, uidlist, labels):
  221. """Delete `labels` from all messages in uidlist.
  222. Note that this function does not check against dryrun settings,
  223. so you need to ensure that it is never called in a dryrun mode."""
  224. labels = labels - self.ignorelabels
  225. result = self._messagelabels_aux('-X-GM-LABELS', uidlist, labels)
  226. if result:
  227. for uid in uidlist:
  228. self.messagelist[uid]['labels'] = self.messagelist[uid]['labels'] - labels
  229. def copymessageto(self, uid, dstfolder, statusfolder, register=1):
  230. """Copies a message from self to dst if needed, updating the status
  231. Note that this function does not check against dryrun settings,
  232. so you need to ensure that it is never called in a
  233. dryrun mode.
  234. :param uid: uid of the message to be copied.
  235. :param dstfolder: A BaseFolder-derived instance
  236. :param statusfolder: A LocalStatusFolder instance
  237. :param register: whether we should register a new thread."
  238. :returns: Nothing on success, or raises an Exception."""
  239. # Check if we are really copying
  240. realcopy = uid > 0 and not dstfolder.uidexists(uid)
  241. # first copy the message
  242. super(GmailFolder, self).copymessageto(uid, dstfolder, statusfolder, register)
  243. # sync labels and mtime now when the message is new (the embedded labels are up to date)
  244. # otherwise we may be spending time for nothing, as they will get updated on a later pass.
  245. if realcopy and self.synclabels:
  246. try:
  247. mtime = dstfolder.getmessagemtime(uid)
  248. labels = dstfolder.getmessagelabels(uid)
  249. statusfolder.savemessagelabels(uid, labels, mtime=mtime)
  250. # dstfolder is not GmailMaildir.
  251. except NotImplementedError:
  252. return
  253. def syncmessagesto_labels(self, dstfolder, statusfolder):
  254. """Pass 4: Label Synchronization (Gmail only)
  255. Compare label mismatches in self with those in statusfolder. If
  256. msg has a valid UID and exists on dstfolder (has not e.g. been
  257. deleted there), sync the labels change to both dstfolder and
  258. statusfolder.
  259. This function checks and protects us from action in dryrun mode.
  260. """
  261. # This applies the labels message by message, as this makes more sense for a
  262. # Maildir target. If applied with an other Gmail IMAP target it would not be
  263. # the fastest thing in the world though...
  264. uidlist = []
  265. # filter the uids (fast)
  266. try:
  267. for uid in self.getmessageuidlist():
  268. # bail out on CTRL-C or SIGTERM
  269. if offlineimap.accounts.Account.abort_NOW_signal.is_set():
  270. break
  271. # Ignore messages with negative UIDs missed by pass 1 and
  272. # don't do anything if the message has been deleted remotely
  273. if uid < 0 or not dstfolder.uidexists(uid):
  274. continue
  275. selflabels = self.getmessagelabels(uid) - self.ignorelabels
  276. if statusfolder.uidexists(uid):
  277. statuslabels = statusfolder.getmessagelabels(uid) - self.ignorelabels
  278. else:
  279. statuslabels = set()
  280. if selflabels != statuslabels:
  281. uidlist.append(uid)
  282. # now sync labels (slow)
  283. mtimes = {}
  284. labels = {}
  285. for i, uid in enumerate(uidlist):
  286. # bail out on CTRL-C or SIGTERM
  287. if offlineimap.accounts.Account.abort_NOW_signal.is_set():
  288. break
  289. selflabels = self.getmessagelabels(uid) - self.ignorelabels
  290. if statusfolder.uidexists(uid):
  291. statuslabels = statusfolder.getmessagelabels(uid) - self.ignorelabels
  292. else:
  293. statuslabels = set()
  294. if selflabels != statuslabels:
  295. self.ui.settinglabels(uid, i + 1, len(uidlist), sorted(selflabels), dstfolder)
  296. if self.repository.account.dryrun:
  297. continue # don't actually add in a dryrun
  298. dstfolder.savemessagelabels(uid, selflabels, ignorelabels=self.ignorelabels)
  299. mtime = dstfolder.getmessagemtime(uid)
  300. mtimes[uid] = mtime
  301. labels[uid] = selflabels
  302. # Update statusfolder in a single DB transaction. It is safe, as if something fails,
  303. # statusfolder will be updated on the next run.
  304. statusfolder.savemessageslabelsbulk(labels)
  305. statusfolder.savemessagesmtimebulk(mtimes)
  306. except NotImplementedError:
  307. self.ui.warn("Can't sync labels. You need to configure a local repository of type GmailMaildir")