accounts.py 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694
  1. # Copyright (C) 2003-2016 John Goerzen & contributors
  2. #
  3. # This program is free software; you can redistribute it and/or modify
  4. # it under the terms of the GNU General Public License as published by
  5. # the Free Software Foundation; either version 2 of the License, or
  6. # (at your option) any later version.
  7. #
  8. # This program is distributed in the hope that it will be useful,
  9. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. # GNU General Public License for more details.
  12. #
  13. # You should have received a copy of the GNU General Public License
  14. # along with this program; if not, write to the Free Software
  15. # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
  16. from subprocess import Popen, PIPE
  17. from threading import Event, Lock
  18. import os
  19. import time
  20. from sys import exc_info
  21. import traceback
  22. from offlineimap import mbnames, CustomConfig, OfflineImapError
  23. from offlineimap import globals
  24. from offlineimap.repository import Repository
  25. from offlineimap.ui import getglobalui
  26. from offlineimap.threadutil import InstanceLimitedThread
  27. FOLDER_NAMESPACE = 'LIMITED_FOLDER_'
  28. # Key: account name, Value: Dict of Key: remotefolder name, Value: lock.
  29. SYNC_MUTEXES = {}
  30. SYNC_MUTEXES_LOCK = Lock()
  31. try:
  32. import portalocker
  33. except:
  34. try:
  35. import fcntl
  36. except:
  37. pass # Ok if this fails, we can do without.
  38. # FIXME: spaghetti code alert!
  39. def getaccountlist(customconfig):
  40. # Account names in a list.
  41. return [name.lstrip() for name in customconfig.getsectionlist('Account')]
  42. class Account(CustomConfig.ConfigHelperMixin):
  43. """Represents an account (ie. 2 repositories) to sync.
  44. Most of the time you will actually want to use the derived
  45. :class:`accounts.SyncableAccount` which contains all functions used
  46. for syncing an account."""
  47. # Signal gets set when we should stop looping.
  48. abort_soon_signal = Event()
  49. # Signal gets set on CTRL-C/SIGTERM.
  50. abort_NOW_signal = Event()
  51. def __init__(self, config, name):
  52. """
  53. :param config: Representing the offlineimap configuration file.
  54. :type config: :class:`offlineimap.CustomConfig.CustomConfigParser`
  55. :param name: A (str) string denoting the name of the Account
  56. as configured.
  57. """
  58. self.config = config
  59. self.name = name
  60. self.metadatadir = config.getmetadatadir()
  61. self.localeval = config.getlocaleval()
  62. # Store utf-8 support as a property of Account object
  63. self.utf_8_support = self.getconfboolean('utf8foldernames', False)
  64. # Current :mod:`offlineimap.ui`, can be used for logging:
  65. self.ui = getglobalui()
  66. self.refreshperiod = self.getconffloat('autorefresh', 0.0)
  67. self.dryrun = self.config.getboolean('general', 'dry-run')
  68. self.quicknum = 0
  69. if self.refreshperiod < 0:
  70. self.ui.warn("autorefresh for %s is negative, fixing it to 0." %
  71. name)
  72. self.refreshperiod = 0.0
  73. if self.refreshperiod == 0.0:
  74. self.refreshperiod = None
  75. self.remoterepos = None
  76. self.localrepos = None
  77. self.statusrepos = None
  78. def getlocaleval(self):
  79. return self.localeval
  80. # Interface from CustomConfig.ConfigHelperMixin
  81. def getconfig(self):
  82. return self.config
  83. def getname(self):
  84. return self.name
  85. def __str__(self):
  86. return self.name
  87. def getaccountmeta(self):
  88. return os.path.join(self.metadatadir, 'Account-' + self.name)
  89. # Interface from CustomConfig.ConfigHelperMixin
  90. def getsection(self):
  91. return 'Account ' + self.getname()
  92. @classmethod
  93. def set_abort_event(cls, config, signum):
  94. """Set skip sleep/abort event for all accounts.
  95. If we want to skip a current (or the next) sleep, or if we want
  96. to abort an autorefresh loop, the main thread can use
  97. set_abort_event() to send the corresponding signal. Signum = 1
  98. implies that we want all accounts to abort or skip the current
  99. or next sleep phase. Signum = 2 will end the autorefresh loop,
  100. ie all accounts will return after they finished a sync. signum=3
  101. means, abort NOW, e.g. on SIGINT or SIGTERM.
  102. This is a class method, it will send the signal to all accounts.
  103. """
  104. if signum == 1:
  105. # resync signal, set config option for all accounts
  106. for acctsection in getaccountlist(config):
  107. config.set('Account ' + acctsection, "skipsleep", '1')
  108. elif signum == 2:
  109. # don't autorefresh anymore
  110. cls.abort_soon_signal.set()
  111. elif signum == 3:
  112. # abort ASAP
  113. cls.abort_NOW_signal.set()
  114. def get_abort_event(self):
  115. """Checks if an abort signal had been sent.
  116. If the 'skipsleep' config option for this account had been set,
  117. with `set_abort_event(config, 1)` it will get cleared in this
  118. function. Ie, we will only skip one sleep and not all.
  119. :returns: True, if the main thread had called
  120. :meth:`set_abort_event` earlier, otherwise 'False'.
  121. """
  122. skipsleep = self.getconfboolean("skipsleep", 0)
  123. if skipsleep:
  124. self.config.set(self.getsection(), "skipsleep", '0')
  125. return skipsleep or Account.abort_soon_signal.is_set() or \
  126. Account.abort_NOW_signal.is_set()
  127. def _sleeper(self):
  128. """Sleep if the account is set to autorefresh.
  129. :returns: 0:timeout expired, 1: canceled the timer,
  130. 2:request to abort the program,
  131. 100: if configured to not sleep at all.
  132. """
  133. if not self.refreshperiod:
  134. return 100
  135. kaobjs = []
  136. if hasattr(self, 'localrepos'):
  137. kaobjs.append(self.localrepos)
  138. if hasattr(self, 'remoterepos'):
  139. kaobjs.append(self.remoterepos)
  140. for item in kaobjs:
  141. item.startkeepalive()
  142. refreshperiod = int(self.refreshperiod * 60)
  143. sleepresult = self.ui.sleep(refreshperiod, self)
  144. # Cancel keepalive
  145. for item in kaobjs:
  146. item.stopkeepalive()
  147. if sleepresult:
  148. if Account.abort_soon_signal.is_set() or \
  149. Account.abort_NOW_signal.is_set():
  150. return 2
  151. self.quicknum = 0
  152. return 1
  153. return 0
  154. def serverdiagnostics(self):
  155. """Output diagnostics for all involved repositories."""
  156. remote_repo = Repository(self, 'remote')
  157. local_repo = Repository(self, 'local')
  158. # status_repo = Repository(self, 'status')
  159. self.ui.serverdiagnostics(remote_repo, 'Remote')
  160. self.ui.serverdiagnostics(local_repo, 'Local')
  161. # self.ui.serverdiagnostics(statusrepos, 'Status')
  162. def deletefolder(self, foldername):
  163. remote_repo = Repository(self, 'remote')
  164. try:
  165. if self.dryrun:
  166. self.ui.info("would try to remove '%s' on remote of '%s' "
  167. "account" % (foldername, self))
  168. else:
  169. remote_repo.deletefolder(foldername)
  170. self.ui.info("Folder '%s' deleted." % foldername)
  171. return 0
  172. except Exception as e:
  173. self.ui.error(e)
  174. return 1
  175. class SyncableAccount(Account):
  176. """A syncable email account connecting 2 repositories.
  177. Derives from :class:`accounts.Account` but contains the additional
  178. functions :meth:`syncrunner`, :meth:`sync`, :meth:`syncfolders`,
  179. used for syncing.
  180. In multi-threaded mode, one instance of this object is run per "account"
  181. thread."""
  182. def __init__(self, *args, **kwargs):
  183. Account.__init__(self, *args, **kwargs)
  184. self._lockfd = None
  185. self._lockfilepath = os.path.join(
  186. self.config.getmetadatadir(), "%s.lock" % self)
  187. def __lock(self):
  188. """Lock the account, throwing an exception if it is locked already."""
  189. self._lockfd = open(self._lockfilepath, 'w')
  190. try:
  191. portalocker.lock(self._lockfd, portalocker.LOCK_EX)
  192. except NameError:
  193. # portalocker not available for Windows.
  194. try:
  195. fcntl.lockf(self._lockfd, fcntl.LOCK_EX | fcntl.LOCK_NB)
  196. except NameError:
  197. pass # fnctl not available, disable file locking... :(
  198. except IOError:
  199. raise OfflineImapError(
  200. "Could not lock account %s. Is another "
  201. "instance using this account?" % self,
  202. OfflineImapError.ERROR.REPO,
  203. exc_info()[2])
  204. except IOError:
  205. self._lockfd.close()
  206. raise OfflineImapError(
  207. "Could not lock account %s. Is another "
  208. "instance using this account?" % self,
  209. OfflineImapError.ERROR.REPO,
  210. exc_info()[2])
  211. def _unlock(self):
  212. """Unlock the account, deleting the lock file"""
  213. # If we own the lock file, delete it
  214. if self._lockfd and not self._lockfd.closed:
  215. try:
  216. portalocker.unlock(self._lockfd)
  217. except NameError:
  218. pass
  219. self._lockfd.close()
  220. try:
  221. os.unlink(self._lockfilepath)
  222. except OSError:
  223. pass # Failed to delete for some reason.
  224. def syncrunner(self):
  225. """The target for both single and multi-threaded modes."""
  226. self.ui.registerthread(self)
  227. try:
  228. accountmetadata = self.getaccountmeta()
  229. if not os.path.exists(accountmetadata):
  230. os.mkdir(accountmetadata, 0o700)
  231. self.remoterepos = Repository(self, 'remote')
  232. self.localrepos = Repository(self, 'local')
  233. self.statusrepos = Repository(self, 'status')
  234. except OfflineImapError as e:
  235. self.ui.error(e, exc_info()[2])
  236. if e.severity >= OfflineImapError.ERROR.CRITICAL:
  237. raise
  238. return
  239. # Loop account sync if needed (bail out after 3 failures).
  240. looping = 3
  241. while looping:
  242. self.ui.acct(self)
  243. try:
  244. self.__lock()
  245. self.__sync()
  246. except (KeyboardInterrupt, SystemExit):
  247. raise
  248. except OfflineImapError as e:
  249. # Stop looping and bubble up Exception if needed.
  250. if e.severity >= OfflineImapError.ERROR.REPO:
  251. if looping:
  252. looping -= 1
  253. if e.severity >= OfflineImapError.ERROR.CRITICAL:
  254. raise
  255. self.ui.error(e, exc_info()[2])
  256. except Exception as e:
  257. self.ui.error(e, exc_info()[2],
  258. msg="While attempting to sync account '%s'" %
  259. self)
  260. else:
  261. # After success sync, reset the looping counter to 3.
  262. if self.refreshperiod:
  263. looping = 3
  264. finally:
  265. self.ui.acctdone(self)
  266. self._unlock()
  267. if looping and self._sleeper() >= 2:
  268. looping = 0
  269. def get_local_folder(self, remotefolder):
  270. """Return the corresponding local folder for a given remotefolder."""
  271. return self.localrepos.getfolder(
  272. remotefolder.getvisiblename().
  273. replace(self.remoterepos.getsep(), self.localrepos.getsep()))
  274. # The syncrunner will loop on this method. This means it is called more than
  275. # once during the run.
  276. def __sync(self):
  277. """Synchronize the account once, then return.
  278. Assumes that `self.remoterepos`, `self.localrepos`, and
  279. `self.statusrepos` has already been populated, so it should only
  280. be called from the :meth:`syncrunner` function."""
  281. folderthreads = []
  282. quickconfig = self.getconfint('quick', 0)
  283. if quickconfig < 0:
  284. quick = True
  285. elif quickconfig > 0:
  286. if self.quicknum == 0 or self.quicknum > quickconfig:
  287. self.quicknum = 1
  288. quick = False
  289. else:
  290. self.quicknum = self.quicknum + 1
  291. quick = True
  292. else:
  293. quick = False
  294. hook = self.getconf('presynchook', '')
  295. self.callhook(hook, "quick" if quick else "full")
  296. if self.utf_8_support and self.remoterepos.getdecodefoldernames():
  297. raise OfflineImapError("Configuration mismatch in account " +
  298. "'%s'. " % self.getname() +
  299. "\nAccount setting 'utf8foldernames' and repository " +
  300. "setting 'decodefoldernames'\nmay not be used at the " +
  301. "same time. This account has not been synchronized.\n" +
  302. "Please check the configuration and documentation.",
  303. OfflineImapError.ERROR.REPO)
  304. try:
  305. startedThread = False
  306. remoterepos = self.remoterepos
  307. localrepos = self.localrepos
  308. statusrepos = self.statusrepos
  309. # Init repos with list of folders, so we have them (and the
  310. # folder delimiter etc).
  311. remoterepos.getfolders()
  312. localrepos.getfolders()
  313. remoterepos.sync_folder_structure(localrepos, statusrepos)
  314. # Replicate the folderstructure between REMOTE to LOCAL.
  315. if not localrepos.getconfboolean('readonly', False):
  316. self.ui.syncfolders(remoterepos, localrepos)
  317. # Iterate through all folders on the remote repo and sync.
  318. for remotefolder in remoterepos.getfolders():
  319. # Check for CTRL-C or SIGTERM.
  320. if Account.abort_NOW_signal.is_set():
  321. break
  322. if not remotefolder.sync_this:
  323. self.ui.debug('', "Not syncing filtered folder '%s'"
  324. "[%s]" % (remotefolder.getname(), remoterepos))
  325. continue # Ignore filtered folder.
  326. # The remote folder names must not have the local sep char in
  327. # their names since this would cause troubles while converting
  328. # the name back (from local to remote).
  329. sep = localrepos.getsep()
  330. if (sep != os.path.sep and
  331. sep != remoterepos.getsep() and
  332. sep in remotefolder.getname()):
  333. self.ui.warn('', "Ignoring folder '%s' due to unsupported "
  334. "'%s' character serving as local separator." %
  335. (remotefolder.getname(), localrepos.getsep()))
  336. continue # Ignore unsupported folder name.
  337. localfolder = self.get_local_folder(remotefolder)
  338. if not localfolder.sync_this:
  339. self.ui.debug('', "Not syncing filtered folder '%s'"
  340. "[%s]" % (localfolder.getname(), localfolder.repository))
  341. continue # Ignore filtered folder.
  342. if not globals.options.singlethreading:
  343. thread = InstanceLimitedThread(
  344. limitNamespace="%s%s" % (
  345. FOLDER_NAMESPACE, self.remoterepos.getname()),
  346. target=syncfolder,
  347. name="Folder %s [acc: %s]" % (
  348. remotefolder.getexplainedname(), self),
  349. args=(self, remotefolder, quick)
  350. )
  351. thread.start()
  352. folderthreads.append(thread)
  353. else:
  354. syncfolder(self, remotefolder, quick)
  355. startedThread = True
  356. # Wait for all threads to finish.
  357. for thr in folderthreads:
  358. thr.join()
  359. if startedThread is True:
  360. mbnames.writeIntermediateFile(self.name) # Write out mailbox names.
  361. else:
  362. msg = "Account {}: no folder to sync (folderfilter issue?)".format(self)
  363. raise OfflineImapError(msg, OfflineImapError.ERROR.REPO)
  364. localrepos.forgetfolders()
  365. remoterepos.forgetfolders()
  366. except:
  367. # Error while syncing. Drop all connections that we have, they
  368. # might be bogus by now (e.g. after suspend).
  369. localrepos.dropconnections()
  370. remoterepos.dropconnections()
  371. raise
  372. else:
  373. # Sync went fine. Hold or drop depending on config.
  374. localrepos.holdordropconnections()
  375. remoterepos.holdordropconnections()
  376. hook = self.getconf('postsynchook', '')
  377. self.callhook(hook, "quick" if quick else "full")
  378. def callhook(self, cmd, syncmode):
  379. # Check for CTRL-C or SIGTERM and run postsynchook.
  380. if Account.abort_NOW_signal.is_set():
  381. return
  382. if not cmd:
  383. return
  384. try:
  385. self.ui.callhook("Calling hook: " + cmd)
  386. if self.dryrun:
  387. return
  388. environ = os.environ.copy()
  389. environ['OFFLINEIMAPSYNCMODE'] = syncmode
  390. p = Popen(cmd, shell=True,
  391. stdin=PIPE, stdout=PIPE, stderr=PIPE,
  392. close_fds=True, env=environ)
  393. stdout, stderr = p.communicate()
  394. self.ui.callhook("Hook stdout: %s\nHook stderr:%s\n"
  395. % (stdout.decode('utf-8'), stderr.decode('utf-8')))
  396. self.ui.callhook("Hook return code: %d" % p.returncode)
  397. except (KeyboardInterrupt, SystemExit):
  398. raise
  399. except Exception as e:
  400. self.ui.error(e, exc_info()[2], msg="Calling hook")
  401. # XXX: This function should likely be refactored. This should not be passed the
  402. # account instance.
  403. def syncfolder(account, remotefolder, quick):
  404. """Synchronizes given remote folder for the specified account.
  405. Filtered folders on the remote side will not invoke this function.
  406. When called in concurrently for the same localfolder, syncs are
  407. serialized."""
  408. def acquire_mutex():
  409. account_name = account.getname()
  410. localfolder_name = localfolder.getfullname()
  411. with SYNC_MUTEXES_LOCK:
  412. if SYNC_MUTEXES.get(account_name) is None:
  413. SYNC_MUTEXES[account_name] = {}
  414. # The localfolder full name is good to uniquely identify the sync
  415. # transaction.
  416. if SYNC_MUTEXES[account_name].get(localfolder_name) is None:
  417. # XXX: This lock could be an external file lock so we can remove
  418. # the lock at the account level.
  419. SYNC_MUTEXES[account_name][localfolder_name] = Lock()
  420. # Acquire the lock.
  421. SYNC_MUTEXES[account_name][localfolder_name].acquire()
  422. def release_mutex():
  423. SYNC_MUTEXES[account.getname()][localfolder.getfullname()].release()
  424. def check_uid_validity():
  425. # If either the local or the status folder has messages and
  426. # there is a UID validity problem, warn and abort. If there are
  427. # no messages, UW IMAPd loses UIDVALIDITY. But we don't really
  428. # need it if both local folders are empty. So, in that case,
  429. # just save it off.
  430. if localfolder.getmessagecount() > 0 or statusfolder.getmessagecount() > 0:
  431. if not localfolder.check_uidvalidity():
  432. ui.validityproblem(localfolder)
  433. localfolder.repository.restore_atime()
  434. return
  435. if not remotefolder.check_uidvalidity():
  436. ui.validityproblem(remotefolder)
  437. localrepos.restore_atime()
  438. return
  439. else:
  440. # Both folders empty, just save new UIDVALIDITY.
  441. localfolder.save_uidvalidity()
  442. remotefolder.save_uidvalidity()
  443. def cachemessagelists_upto_date(date):
  444. """Returns messages with uid > min(uids of messages newer than date)."""
  445. remotefolder.cachemessagelist(
  446. min_date=time.gmtime(time.mktime(date) + 24 * 60 * 60))
  447. uids = remotefolder.getmessageuidlist()
  448. localfolder.dropmessagelistcache()
  449. if len(uids) > 0:
  450. # Reload the remote message list from min_uid. This avoid issues for
  451. # old messages, which has been added from local on any previous run
  452. # (IOW, message is older than maxage _and_ has high enough UID).
  453. remotefolder.dropmessagelistcache()
  454. remotefolder.cachemessagelist(min_uid=min(uids))
  455. localfolder.cachemessagelist(min_uid=min(uids))
  456. else:
  457. # Remote folder UIDs list is empty for the given range. We still
  458. # might have valid local UIDs for this range (e.g.: new local
  459. # emails).
  460. localfolder.cachemessagelist(min_date=date)
  461. uids = localfolder.getmessageuidlist()
  462. # Take care to only consider positive uids. Negative UIDs might be
  463. # present due to new emails.
  464. uids = [uid for uid in uids if uid > 0]
  465. if len(uids) > 0:
  466. # Update the remote cache list for this new min(uids).
  467. remotefolder.dropmessagelistcache()
  468. remotefolder.cachemessagelist(min_uid=min(uids))
  469. def cachemessagelists_startdate(new, partial, date):
  470. """Retrieve messagelists when startdate has been set for
  471. the folder 'partial'.
  472. Idea: suppose you want to clone the messages after date in one
  473. account (partial) to a new one (new). If new is empty, then copy
  474. messages in partial newer than date to new, and keep track of the
  475. min uid. On subsequent syncs, sync all the messages in new against
  476. those after that min uid in partial. This is a partial replacement
  477. for maxage in the IMAP-IMAP sync case, where maxage doesn't work:
  478. the UIDs of the messages in localfolder might not be in the same
  479. order as those of corresponding messages in remotefolder, so if L in
  480. local corresponds to R in remote, the ranges [L, ...] and [R, ...]
  481. might not correspond. But, if we're cloning a folder into a new one,
  482. [min_uid, ...] does correspond to [1, ...].
  483. This is just for IMAP-IMAP. For Maildir-IMAP, use maxage instead."""
  484. new.cachemessagelist()
  485. min_uid = partial.retrieve_min_uid()
  486. if min_uid is None: # min_uid file didn't exist
  487. if len(new.getmessageuidlist()) > 0:
  488. raise OfflineImapError("To use startdate on Repository %s, "
  489. "Repository %s must be empty" %
  490. (partial.repository.name, new.repository.name),
  491. OfflineImapError.ERROR.MESSAGE)
  492. else:
  493. partial.cachemessagelist(min_date=date)
  494. # messagelist.keys() instead of getuidmessagelist() because in
  495. # the UID mapped case we want the actual local UIDs, not their
  496. # remote counterparts.
  497. positive_uids = [uid for uid in list(partial.messagelist.keys()) if uid > 0]
  498. if len(positive_uids) > 0:
  499. min_uid = min(positive_uids)
  500. else:
  501. min_uid = 1
  502. partial.save_min_uid(min_uid)
  503. else:
  504. partial.cachemessagelist(min_uid=min_uid)
  505. remoterepos = account.remoterepos
  506. localrepos = account.localrepos
  507. statusrepos = account.statusrepos
  508. ui = getglobalui()
  509. ui.registerthread(account)
  510. try:
  511. # Load local folder.
  512. localfolder = account.get_local_folder(remotefolder)
  513. # Acquire the mutex to start syncing.
  514. acquire_mutex()
  515. # Add the folder to the mbnames mailboxes.
  516. mbnames.add(account.name, localrepos.getlocalroot(),
  517. localfolder.getname())
  518. # Load status folder.
  519. statusfolder = statusrepos.getfolder(remotefolder.getvisiblename().
  520. replace(remoterepos.getsep(), statusrepos.getsep()))
  521. statusfolder.openfiles()
  522. statusfolder.cachemessagelist()
  523. # Load local folder.
  524. ui.syncingfolder(remoterepos, remotefolder, localrepos, localfolder)
  525. # Retrieve messagelists, taking into account age-restriction
  526. # options.
  527. maxage = localfolder.getmaxage()
  528. localstart = localfolder.getstartdate()
  529. remotestart = remotefolder.getstartdate()
  530. if (maxage is not None) + (localstart is not None) + (remotestart is not None) > 1:
  531. raise OfflineImapError("You can set at most one of the "
  532. "following: maxage, startdate (for the local "
  533. "folder), startdate (for the remote folder)",
  534. OfflineImapError.ERROR.REPO,
  535. exc_info()[2])
  536. if (maxage is not None or localstart or remotestart) and quick:
  537. # IMAP quickchanged isn't compatible with options that
  538. # involve restricting the messagelist, since the "quick"
  539. # check can only retrieve a full list of UIDs in the folder.
  540. ui.warn("Quick syncs (-q) not supported in conjunction "
  541. "with maxage or startdate; ignoring -q.")
  542. if maxage is not None:
  543. cachemessagelists_upto_date(maxage)
  544. check_uid_validity()
  545. elif localstart is not None:
  546. cachemessagelists_startdate(remotefolder, localfolder,
  547. localstart)
  548. check_uid_validity()
  549. elif remotestart is not None:
  550. cachemessagelists_startdate(localfolder, remotefolder,
  551. remotestart)
  552. check_uid_validity()
  553. else:
  554. localfolder.cachemessagelist()
  555. if quick:
  556. if (not localfolder.quickchanged(statusfolder) and
  557. not remotefolder.quickchanged(statusfolder)):
  558. ui.skippingfolder(remotefolder)
  559. localrepos.restore_atime()
  560. return
  561. check_uid_validity()
  562. remotefolder.cachemessagelist()
  563. # Synchronize remote changes.
  564. if not localrepos.getconfboolean('readonly', False):
  565. ui.syncingmessages(remoterepos, remotefolder, localrepos, localfolder)
  566. remotefolder.syncmessagesto(localfolder, statusfolder)
  567. else:
  568. ui.debug('', "Not syncing to read-only repository '%s'" %
  569. localrepos.getname())
  570. # Synchronize local changes.
  571. if not remoterepos.getconfboolean('readonly', False):
  572. ui.syncingmessages(localrepos, localfolder, remoterepos, remotefolder)
  573. localfolder.syncmessagesto(remotefolder, statusfolder)
  574. else:
  575. ui.debug('', "Not syncing to read-only repository '%s'" %
  576. remoterepos.getname())
  577. statusfolder.save()
  578. localrepos.restore_atime()
  579. except (KeyboardInterrupt, SystemExit):
  580. raise
  581. except OfflineImapError as e:
  582. # Bubble up severe Errors, skip folder otherwise.
  583. if e.severity > OfflineImapError.ERROR.FOLDER:
  584. raise
  585. else:
  586. ui.error(e, exc_info()[2], msg="Aborting sync, folder '%s' "
  587. "[acc: '%s']" % (localfolder, account))
  588. except Exception as e:
  589. ui.error(e, msg="ERROR in syncfolder for %s folder %s: %s" %
  590. (account, remotefolder.getvisiblename(), traceback.format_exc()))
  591. finally:
  592. for folder in ["statusfolder", "localfolder", "remotefolder"]:
  593. if folder in locals():
  594. locals()[folder].dropmessagelistcache()
  595. statusfolder.closefiles()
  596. # Release the mutex of this sync transaction.
  597. release_mutex()