Base.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294
  1. """ Base repository support """
  2. # Copyright (C) 2002-2016 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. import re
  18. import os.path
  19. from sys import exc_info
  20. from offlineimap import CustomConfig
  21. from offlineimap.ui import getglobalui
  22. from offlineimap.error import OfflineImapError
  23. class BaseRepository(CustomConfig.ConfigHelperMixin):
  24. def __init__(self, reposname, account):
  25. self.ui = getglobalui()
  26. self.account = account
  27. self.config = account.getconfig()
  28. self.name = reposname
  29. self.localeval = account.getlocaleval()
  30. self._accountname = self.account.getname()
  31. self._readonly = self.getconfboolean('readonly', False)
  32. self.uiddir = os.path.join(self.config.getmetadatadir(), 'Repository-' + self.name)
  33. if not os.path.exists(self.uiddir):
  34. os.mkdir(self.uiddir, 0o700)
  35. self.mapdir = os.path.join(self.uiddir, 'UIDMapping')
  36. if not os.path.exists(self.mapdir):
  37. os.mkdir(self.mapdir, 0o700)
  38. # FIXME: self.uiddir variable name is lying about itself.
  39. self.uiddir = os.path.join(self.uiddir, 'FolderValidity')
  40. if not os.path.exists(self.uiddir):
  41. os.mkdir(self.uiddir, 0o700)
  42. self.nametrans = lambda foldername: foldername
  43. self.folderfilter = lambda foldername: 1
  44. self.folderincludes = []
  45. self.foldersort = None
  46. self.newmail_hook = None
  47. if self.config.has_option(self.getsection(), 'nametrans'):
  48. self.nametrans = self.localeval.eval(
  49. self.getconf('nametrans'), {'re': re})
  50. if self.config.has_option(self.getsection(), 'folderfilter'):
  51. self.folderfilter = self.localeval.eval(
  52. self.getconf('folderfilter'), {'re': re})
  53. if self.config.has_option(self.getsection(), 'folderincludes'):
  54. self.folderincludes = self.localeval.eval(
  55. self.getconf('folderincludes'), {'re': re})
  56. if self.config.has_option(self.getsection(), 'foldersort'):
  57. self.foldersort = self.localeval.eval(
  58. self.getconf('foldersort'), {'re': re})
  59. def restore_atime(self):
  60. """Sets folders' atime back to their values after a sync
  61. Controlled by the 'restoreatime' config parameter (default
  62. False), applies only to local Maildir mailboxes and does nothing
  63. on all other repository types."""
  64. pass
  65. def connect(self):
  66. """Establish a connection to the remote, if necessary. This exists
  67. so that IMAP connections can all be established up front, gathering
  68. passwords as needed. It was added in order to support the
  69. error recovery -- we need to connect first outside of the error
  70. trap in order to validate the password, and that's the point of
  71. this function."""
  72. pass
  73. def holdordropconnections(self):
  74. pass
  75. def dropconnections(self):
  76. pass
  77. def getaccount(self):
  78. return self.account
  79. def getname(self):
  80. return self.name
  81. def __str__(self):
  82. return self.name
  83. @property
  84. def accountname(self):
  85. """Account name as string"""
  86. return self._accountname
  87. def getuiddir(self):
  88. return self.uiddir
  89. def getmapdir(self):
  90. return self.mapdir
  91. # Interface from CustomConfig.ConfigHelperMixin
  92. def getsection(self):
  93. return 'Repository ' + self.name
  94. # Interface from CustomConfig.ConfigHelperMixin
  95. def getconfig(self):
  96. return self.config
  97. @property
  98. def readonly(self):
  99. """Is the repository readonly?"""
  100. return self._readonly
  101. def getlocaleval(self):
  102. return self.account.getlocaleval()
  103. def getfolders(self):
  104. """Returns a list of ALL folders on this server."""
  105. return []
  106. def forgetfolders(self):
  107. """Forgets the cached list of folders, if any. Useful to run
  108. after a sync run."""
  109. pass
  110. def getsep(self):
  111. raise NotImplementedError
  112. def getkeywordmap(self):
  113. raise NotImplementedError
  114. def should_sync_folder(self, fname):
  115. """Should this folder be synced?"""
  116. return fname in self.folderincludes or self.folderfilter(fname)
  117. def should_create_folders(self):
  118. """Is folder creation enabled on this repository?
  119. It is disabled by either setting the whole repository
  120. 'readonly' or by using the 'createfolders' setting."""
  121. return (not self._readonly) and \
  122. self.getconfboolean('createfolders', True)
  123. def makefolder(self, foldername):
  124. """Create a new folder."""
  125. raise NotImplementedError
  126. def deletefolder(self, foldername):
  127. raise NotImplementedError
  128. def getfolder(self, foldername):
  129. raise NotImplementedError
  130. def sync_folder_structure(self, local_repo, status_repo):
  131. """Sync the folders structure.
  132. It does NOT sync the contents of those folders. nametrans rules
  133. in both directions will be honored
  134. Configuring nametrans on BOTH repositories could lead to infinite folder
  135. creation cycles."""
  136. if not self.should_create_folders() and not local_repo.should_create_folders():
  137. # Quick exit if no folder creation is enabled on either side.
  138. return
  139. remote_repo = self
  140. remote_hash, local_hash = {}, {}
  141. for folder in remote_repo.getfolders():
  142. remote_hash[folder.getname()] = folder
  143. for folder in local_repo.getfolders():
  144. local_hash[folder.getname()] = folder
  145. # Create new folders from remote to local.
  146. for remote_name, remote_folder in remote_hash.items():
  147. # Don't create on local_repo, if it is readonly.
  148. if not local_repo.should_create_folders():
  149. break
  150. # Apply remote nametrans and fix serparator.
  151. local_name = remote_folder.getvisiblename().replace(
  152. remote_repo.getsep(), local_repo.getsep())
  153. if remote_folder.sync_this and not local_name in local_hash.keys():
  154. try:
  155. local_repo.makefolder(local_name)
  156. # Need to refresh list.
  157. local_repo.forgetfolders()
  158. except OfflineImapError as e:
  159. self.ui.error(e, exc_info()[2],
  160. "Creating folder %s on repository %s"%
  161. (local_name, local_repo))
  162. raise
  163. status_repo.makefolder(local_name.replace(
  164. local_repo.getsep(), status_repo.getsep()))
  165. # Create new folders from local to remote.
  166. for local_name, local_folder in local_hash.items():
  167. if not remote_repo.should_create_folders():
  168. # Don't create missing folder on readonly repo.
  169. break
  170. # Apply reverse nametrans and fix serparator.
  171. remote_name = local_folder.getvisiblename().replace(
  172. local_repo.getsep(), remote_repo.getsep())
  173. if local_folder.sync_this and not remote_name in remote_hash.keys():
  174. # Would the remote filter out the new folder name? In this case
  175. # don't create it.
  176. if not remote_repo.should_sync_folder(remote_name):
  177. self.ui.debug('', "Not creating folder '%s' (repository '%s"
  178. "') as it would be filtered out on that repository."%
  179. (remote_name, self))
  180. continue
  181. # nametrans sanity check! Does remote nametrans lead to the
  182. # original local name?
  183. #
  184. # Apply remote nametrans to see if we end up with the same
  185. # name. We have:
  186. # - remote_name: local_name -> reverse nametrans + separator
  187. # We want local_name == loop_name from:
  188. # - remote_name -> remote (nametrans + separator) -> loop_name
  189. #
  190. # Get IMAPFolder and see if the reverse nametrans works fine.
  191. # TODO: getfolder() works only because we succeed in getting
  192. # inexisting folders which I would like to change. Take care!
  193. tmp_remotefolder = remote_repo.getfolder(remote_name)
  194. loop_name = tmp_remotefolder.getvisiblename().replace(
  195. remote_repo.getsep(), local_repo.getsep())
  196. if local_name != loop_name:
  197. raise OfflineImapError("INFINITE FOLDER CREATION DETECTED! "
  198. "Folder '%s' (repository '%s') would be created as fold"
  199. "er '%s' (repository '%s'). The latter becomes '%s' in "
  200. "return, leading to infinite folder creation cycles.\n "
  201. "SOLUTION: 1) Do set your nametrans rules on both repos"
  202. "itories so they lead to identical names if applied bac"
  203. "k and forth. 2) Use folderfilter settings on a reposit"
  204. "ory to prevent some folders from being created on the "
  205. "other side."%
  206. (local_folder.getname(), local_repo, remote_name,
  207. remote_repo,
  208. loop_name),
  209. OfflineImapError.ERROR.REPO)
  210. # End sanity check, actually create the folder.
  211. try:
  212. remote_repo.makefolder(remote_name)
  213. # Need to refresh list.
  214. self.forgetfolders()
  215. except OfflineImapError as e:
  216. self.ui.error(e, exc_info()[2], "Creating folder %s on "
  217. "repository %s"% (remote_name, remote_repo))
  218. raise
  219. status_repo.makefolder(local_name.replace(
  220. local_repo.getsep(), status_repo.getsep()))
  221. # Find deleted folders.
  222. # TODO: We don't delete folders right now.
  223. return None
  224. def startkeepalive(self):
  225. """The default implementation will do nothing."""
  226. pass
  227. def stopkeepalive(self):
  228. """Stop keep alive, but don't bother waiting
  229. for the threads to terminate."""
  230. pass
  231. def getlocalroot(self):
  232. """ Local root folder for storing messages.
  233. Will not be set for remote repositories."""
  234. return None