sql_resources.py 39KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096
  1. # coding: utf8
  2. import transaction
  3. import re
  4. from datetime import datetime
  5. from time import mktime
  6. from os.path import normpath, dirname, basename
  7. import mimetypes
  8. from tracim.lib.content import ContentApi
  9. from tracim.lib.user import UserApi
  10. from tracim.lib.webdav import HistoryType
  11. from tracim.lib.webdav import FakeFileStream
  12. from tracim.lib.workspace import WorkspaceApi
  13. from tracim.model import data, new_revision
  14. from tracim.model.data import Content, ActionDescription
  15. from tracim.model.data import ContentType
  16. from tracim.lib.webdav.design import designThread, designPage
  17. from wsgidav import compat
  18. from wsgidav.dav_error import DAVError, HTTP_FORBIDDEN
  19. from wsgidav.dav_provider import DAVCollection, DAVNonCollection
  20. from wsgidav.dav_provider import _DAVResource
  21. from sqlalchemy.orm.exc import NoResultFound, MultipleResultsFound
  22. class ManageActions(object):
  23. """
  24. This object is used to encapsulate all Deletion/Archiving related method as to not duplicate too much code
  25. """
  26. def __init__(self, action_type: str, api: ContentApi, content: Content):
  27. self.content_api = api
  28. self.content = content
  29. self._actions = {
  30. ActionDescription.ARCHIVING: self.content_api.archive,
  31. ActionDescription.DELETION: self.content_api.delete,
  32. ActionDescription.UNARCHIVING: self.content_api.unarchive,
  33. ActionDescription.UNDELETION: self.content_api.undelete
  34. }
  35. self._to_name = {
  36. ActionDescription.ARCHIVING: 'archived',
  37. ActionDescription.DELETION: 'deleted'
  38. }
  39. self._type = action_type
  40. self._new_name = self.make_name()
  41. def action(self):
  42. try:
  43. # When undeleting/unarchiving we except a content with the new name to not exist, thus if we
  44. # don't get an error and the database request send back a result, we stop the action
  45. self.content_api.get_one_by_label_and_parent(self._new_name, self.content.parent, self.content.workspace)
  46. raise DAVError(HTTP_FORBIDDEN)
  47. except NoResultFound:
  48. with new_revision(self.content):
  49. self.content_api.update_content(self.content, self._new_name)
  50. self._actions[self._type](self.content)
  51. self.content_api.save(self.content, self._type)
  52. transaction.commit()
  53. def make_name(self) -> str:
  54. """
  55. Will create the new name, either by adding '- deleted the [date]' after the name when archiving/deleting or
  56. removing this string when undeleting/unarchiving
  57. """
  58. new_name = self.content.get_label()
  59. extension = ''
  60. # if the content has no label, the last .ext is important
  61. # thus we want to rename a file from 'file.txt' to 'file - deleted... .txt' and not 'file.txt - deleted...'
  62. is_file_name = self.content.label == ''
  63. if is_file_name:
  64. extension = re.search(r'(\.[^.]+)$', new_name).group(0)
  65. new_name = re.sub(r'(\.[^.]+)$', '', new_name)
  66. if self._type in [ActionDescription.ARCHIVING, ActionDescription.DELETION]:
  67. new_name += ' - %s the %s' % (self._to_name[self._type], datetime.now().strftime('%d-%m-%Y at %H:%M'))
  68. else:
  69. new_name = re.sub(
  70. r'( - (%s|%s) the .*)$' % (self._to_name[ActionDescription.DELETION], self._to_name[ActionDescription.ARCHIVING]),
  71. '',
  72. new_name
  73. )
  74. new_name += extension
  75. return new_name
  76. class Root(DAVCollection):
  77. """
  78. Root ressource that represents tracim's home, which contains all workspaces
  79. """
  80. def __init__(self, path: str, environ: dict):
  81. super(Root, self).__init__(path, environ)
  82. self.user = UserApi(None).get_one_by_email(environ['http_authenticator.username'])
  83. self.workspace_api = WorkspaceApi(self.user)
  84. def __repr__(self) -> str:
  85. return '<DAVCollection: Root>'
  86. def getMemberNames(self) -> [str]:
  87. """
  88. This method returns the names (here workspace's labels) of all its children
  89. Though for perfomance issue, we're not using this function anymore
  90. """
  91. return [workspace.label for workspace in self.workspace_api.get_all()]
  92. def getMember(self, label: str) -> DAVCollection:
  93. """
  94. This method returns the child Workspace that corresponds to a given name
  95. Though for perfomance issue, we're not using this function anymore
  96. """
  97. try:
  98. workspace = self.workspace_api.get_one_by_label(label)
  99. workspace_path = '%s%s%s' % (self.path, '' if self.path == '/' else '/', self.provider.transform_to_display(workspace.label))
  100. return Workspace(workspace_path, self.environ, workspace)
  101. except AttributeError:
  102. return None
  103. def createEmptyResource(self, name: str):
  104. """
  105. This method is called whenever the user wants to create a DAVNonCollection resource (files in our case).
  106. There we don't allow to create files at the root;
  107. only workspaces (thus collection) can be created.
  108. """
  109. raise DAVError(HTTP_FORBIDDEN)
  110. def createCollection(self, name: str):
  111. """
  112. This method is called whenever the user wants to create a DAVCollection resource as a child (in our case,
  113. we create workspaces as this is the root).
  114. [For now] we don't allow to create new workspaces through
  115. webdav client. Though if we come to allow it, deleting the error's raise will
  116. make it possible.
  117. """
  118. # TODO : remove comment here
  119. # raise DAVError(HTTP_FORBIDDEN)
  120. new_workspace = self.workspace_api.create_workspace(name)
  121. self.workspace_api.save(new_workspace)
  122. workspace_path = '%s%s%s' % (
  123. self.path, '' if self.path == '/' else '/', self.provider.transform_to_display(new_workspace.label))
  124. transaction.commit()
  125. return Workspace(workspace_path, self.environ, new_workspace)
  126. def getMemberList(self):
  127. """
  128. This method is called by wsgidav when requesting with a depth > 0, it will return a list of _DAVResource
  129. of all its direct children
  130. """
  131. members = []
  132. for workspace in self.workspace_api.get_all():
  133. workspace_path = '%s%s%s' % (self.path, '' if self.path == '/' else '/', workspace.label)
  134. members.append(Workspace(workspace_path, self.environ, workspace))
  135. return members
  136. class Workspace(DAVCollection):
  137. """
  138. Workspace resource corresponding to tracim's workspaces.
  139. Direct children can only be folders, though files might come later on and are supported
  140. """
  141. def __init__(self, path: str, environ: dict, workspace: data.Workspace):
  142. super(Workspace, self).__init__(path, environ)
  143. self.workspace = workspace
  144. self.content = None
  145. self.user = UserApi(None).get_one_by_email(environ['http_authenticator.username'])
  146. self.content_api = ContentApi(self.user, show_temporary=True)
  147. self._file_count = 0
  148. def __repr__(self) -> str:
  149. return "<DAVCollection: Workspace (%d)>" % self.workspace.workspace_id
  150. def getPreferredPath(self):
  151. return self.path
  152. def getCreationDate(self) -> float:
  153. return mktime(self.workspace.created.timetuple())
  154. def getDisplayName(self) -> str:
  155. return self.workspace.label
  156. def getLastModified(self) -> float:
  157. return mktime(self.workspace.updated.timetuple())
  158. def getMemberNames(self) -> [str]:
  159. retlist = []
  160. children = self.content_api.get_all(
  161. parent_id=self.content.id if self.content is not None else None,
  162. workspace=self.workspace
  163. )
  164. for content in children:
  165. # the purpose is to display .history only if there's at least one content's type that has a history
  166. if content.type != ContentType.Folder:
  167. self._file_count += 1
  168. retlist.append(content.get_label())
  169. return retlist
  170. def getMember(self, content_label: str) -> _DAVResource:
  171. return self.provider.getResourceInst(
  172. '%s/%s' % (self.path, self.provider.transform_to_display(content_label)),
  173. self.environ
  174. )
  175. def createEmptyResource(self, file_name: str):
  176. """
  177. [For now] we don't allow to create files right under workspaces.
  178. Though if we come to allow it, deleting the error's raise will make it possible.
  179. """
  180. # TODO : remove commentary here raise DAVError(HTTP_FORBIDDEN)
  181. if '/.deleted/' in self.path or '/.archived/' in self.path:
  182. raise DAVError(HTTP_FORBIDDEN)
  183. return FakeFileStream(
  184. file_name=file_name,
  185. content_api=self.content_api,
  186. workspace=self.workspace,
  187. content=None,
  188. parent=self.content,
  189. path=self.path + '/' + file_name
  190. )
  191. def createCollection(self, label: str) -> 'Folder':
  192. """
  193. Create a new folder for the current workspace. As it's not possible for the user to choose
  194. which types of content are allowed in this folder, we allow allow all of them.
  195. This method return the DAVCollection created.
  196. """
  197. if '/.deleted/' in self.path or '/.archived/' in self.path:
  198. raise DAVError(HTTP_FORBIDDEN)
  199. folder = self.content_api.create(
  200. content_type=ContentType.Folder,
  201. workspace=self.workspace,
  202. label=label,
  203. parent=self.content
  204. )
  205. subcontent = dict(
  206. folder=True,
  207. thread=True,
  208. file=True,
  209. page=True
  210. )
  211. self.content_api.set_allowed_content(folder, subcontent)
  212. self.content_api.save(folder)
  213. transaction.commit()
  214. return Folder('%s/%s' % (self.path, self.provider.transform_to_display(label)),
  215. self.environ, folder,
  216. self.workspace)
  217. def delete(self):
  218. """For now, it is not possible to delete a workspace through the webdav client."""
  219. raise DAVError(HTTP_FORBIDDEN)
  220. def supportRecursiveMove(self, destpath):
  221. return True
  222. def moveRecursive(self, destpath):
  223. if dirname(normpath(destpath)) == self.environ['http_authenticator.realm']:
  224. self.workspace.label = basename(normpath(destpath))
  225. transaction.commit()
  226. else:
  227. raise DAVError(HTTP_FORBIDDEN)
  228. def getMemberList(self) -> [_DAVResource]:
  229. members = []
  230. children = self.content_api.get_all(False, ContentType.Any, self.workspace)
  231. for content in children:
  232. content_path = '%s/%s' % (self.path, self.provider.transform_to_display(content.get_label()))
  233. if content.type == ContentType.Folder:
  234. members.append(Folder(content_path, self.environ, self.workspace, content))
  235. elif content.type == ContentType.File:
  236. self._file_count += 1
  237. members.append(File(content_path, self.environ, content))
  238. else:
  239. self._file_count += 1
  240. members.append(OtherFile(content_path, self.environ, content))
  241. if self._file_count > 0 and self.provider.show_history():
  242. members.append(
  243. HistoryFolder(
  244. path=self.path + '/' + ".history",
  245. environ=self.environ,
  246. content=self.content,
  247. workspace=self.workspace,
  248. type=HistoryType.Standard
  249. )
  250. )
  251. if self.provider.show_delete():
  252. members.append(
  253. DeletedFolder(
  254. path=self.path + '/' + ".deleted",
  255. environ=self.environ,
  256. content=self.content,
  257. workspace=self.workspace
  258. )
  259. )
  260. if self.provider.show_archive():
  261. members.append(
  262. ArchivedFolder(
  263. path=self.path + '/' + ".archived",
  264. environ=self.environ,
  265. content=self.content,
  266. workspace=self.workspace
  267. )
  268. )
  269. return members
  270. class Folder(Workspace):
  271. """
  272. Folder resource corresponding to tracim's folders.
  273. Direct children can only be either folder, files, pages or threads
  274. By default when creating new folders, we allow them to contain all types of content
  275. """
  276. def __init__(self, path: str, environ: dict, workspace: data.Workspace, content: data.Content):
  277. super(Folder, self).__init__(path, environ, workspace)
  278. self.content = content
  279. def __repr__(self) -> str:
  280. return "<DAVCollection: Folder (%s)>" % self.content.label
  281. def getCreationDate(self) -> float:
  282. return mktime(self.content.created.timetuple())
  283. def getDisplayName(self) -> str:
  284. return self.provider.transform_to_display(self.content.get_label())
  285. def getLastModified(self) -> float:
  286. return mktime(self.content.updated.timetuple())
  287. def delete(self):
  288. ManageActions(ActionDescription.DELETION, self.content_api, self.content).action()
  289. def supportRecursiveMove(self, destpath: str):
  290. return True
  291. def moveRecursive(self, destpath: str):
  292. """
  293. As we support recursive move, copymovesingle won't be called, though with copy it'll be called
  294. but i have to check if the client ever call that function...
  295. """
  296. destpath = normpath(destpath)
  297. invalid_path = False
  298. # if content is either deleted or archived, we'll check that we try moving it to the parent
  299. # if yes, then we'll unarchive / undelete them, else the action's not allowed
  300. if self.content.is_deleted or self.content.is_archived:
  301. # we remove all archived and deleted from the path and we check to the destpath
  302. # has to be equal or else path not valid
  303. # ex: /a/b/.deleted/resource, to be valid destpath has to be = /a/b/resource (no other solution)
  304. current_path = re.sub(r'/\.(deleted|archived)', '', self.path)
  305. if current_path == destpath:
  306. ManageActions(
  307. ActionDescription.UNDELETION if self.content.is_deleted else ActionDescription.UNARCHIVING,
  308. self.content_api,
  309. self.content
  310. ).action()
  311. else:
  312. invalid_path = True
  313. # if the content is not deleted / archived, check if we're trying to delete / archive it by
  314. # moving it to a .deleted / .archived folder
  315. elif basename(dirname(destpath)) in ['.deleted', '.archived']:
  316. # same test as above ^
  317. dest_path = re.sub(r'/\.(deleted|archived)', '', destpath)
  318. if dest_path == self.path:
  319. ManageActions(
  320. ActionDescription.DELETION if '.deleted' in destpath else ActionDescription.ARCHIVING,
  321. self.content_api,
  322. self.content
  323. ).action()
  324. else:
  325. invalid_path = True
  326. # else we check if the path is good (not at the root path / not in a deleted/archived path)
  327. # and we move the content
  328. else:
  329. invalid_path = any(x in destpath for x in ['.deleted', '.archived'])
  330. invalid_path = invalid_path or any(x in self.path for x in ['.deleted', '.archived'])
  331. invalid_path = invalid_path or dirname(destpath) == self.environ['http_authenticator.realm']
  332. if not invalid_path:
  333. self.move_folder(destpath)
  334. if invalid_path:
  335. raise DAVError(HTTP_FORBIDDEN)
  336. def move_folder(self, destpath):
  337. workspace_api = WorkspaceApi(self.user)
  338. workspace = self.provider.get_workspace_from_path(
  339. normpath(destpath), workspace_api
  340. )
  341. parent = self.provider.get_parent_from_path(
  342. normpath(destpath),
  343. self.content_api,
  344. workspace
  345. )
  346. with new_revision(self.content):
  347. if basename(destpath) != self.getDisplayName():
  348. self.content_api.update_content(self.content, self.provider.transform_to_bdd(basename(destpath)))
  349. self.content_api.save(self.content)
  350. else:
  351. if workspace.workspace_id == self.content.workspace.workspace_id:
  352. self.content_api.move(self.content, parent)
  353. else:
  354. self.content_api.move_recursively(self.content, parent, workspace)
  355. transaction.commit()
  356. def getMemberList(self) -> [_DAVResource]:
  357. members = []
  358. content_api = ContentApi(self.user)
  359. visible_children = content_api.get_all(
  360. self.content.content_id,
  361. ContentType.Any,
  362. self.workspace,
  363. )
  364. for content in visible_children:
  365. content_path = '%s/%s' % (self.path, self.provider.transform_to_display(content.get_label()))
  366. if content.type == ContentType.Folder:
  367. members.append(Folder(content_path, self.environ, self.workspace, content))
  368. elif content.type == ContentType.File:
  369. self._file_count += 1
  370. members.append(File(content_path, self.environ, content))
  371. else:
  372. self._file_count += 1
  373. members.append(OtherFile(content_path, self.environ, content))
  374. if self._file_count > 0 and self.provider.show_history():
  375. members.append(
  376. HistoryFolder(
  377. path=self.path + '/' + ".history",
  378. environ=self.environ,
  379. content=self.content,
  380. workspace=self.workspace,
  381. type=HistoryType.Standard
  382. )
  383. )
  384. if self.provider.show_delete():
  385. members.append(
  386. DeletedFolder(
  387. path=self.path + '/' + ".deleted",
  388. environ=self.environ,
  389. content=self.content,
  390. workspace=self.workspace
  391. )
  392. )
  393. if self.provider.show_archive():
  394. members.append(
  395. ArchivedFolder(
  396. path=self.path + '/' + ".archived",
  397. environ=self.environ,
  398. content=self.content,
  399. workspace=self.workspace
  400. )
  401. )
  402. return members
  403. class HistoryFolder(Folder):
  404. """
  405. A virtual resource which contains a sub-folder for every files (DAVNonCollection) contained in the parent
  406. folder
  407. """
  408. def __init__(self, path, environ, workspace: data.Workspace,
  409. content: data.Content=None, type: str=HistoryType.Standard):
  410. super(HistoryFolder, self).__init__(path, environ, workspace, content)
  411. self._is_archived = type == HistoryType.Archived
  412. self._is_deleted = type == HistoryType.Deleted
  413. self.content_api = ContentApi(
  414. current_user=self.user,
  415. show_archived=self._is_archived,
  416. show_deleted=self._is_deleted
  417. )
  418. def __repr__(self) -> str:
  419. return "<DAVCollection: HistoryFolder (%s)>" % self.content.file_name
  420. def getCreationDate(self) -> float:
  421. return mktime(datetime.now().timetuple())
  422. def getDisplayName(self) -> str:
  423. return '.history'
  424. def getLastModified(self) -> float:
  425. return mktime(datetime.now().timetuple())
  426. def getMember(self, content_label: str) -> _DAVResource:
  427. content = self.content_api.get_one_by_label_and_parent(
  428. content_label=content_label,
  429. content_parent=self.content
  430. )
  431. return HistoryFileFolder(
  432. path='%s/%s' % (self.path, content.get_label()),
  433. environ=self.environ,
  434. content=content)
  435. def getMemberNames(self) -> [str]:
  436. ret = []
  437. content_id = None if self.content is None else self.content.id
  438. for content in self.content_api.get_all(content_id, ContentType.Any, self.workspace):
  439. if (self._is_archived and content.is_archived or
  440. self._is_deleted and content.is_deleted or
  441. not (content.is_archived or self._is_archived or content.is_deleted or self._is_deleted))\
  442. and content.type != ContentType.Folder:
  443. ret.append(content.get_label())
  444. return ret
  445. def createEmptyResource(self, name: str):
  446. raise DAVError(HTTP_FORBIDDEN)
  447. def createCollection(self, name: str):
  448. raise DAVError(HTTP_FORBIDDEN)
  449. def delete(self):
  450. raise DAVError(HTTP_FORBIDDEN)
  451. def handleDelete(self):
  452. return True
  453. def handleCopy(self, destPath: str, depthInfinity):
  454. return True
  455. def handleMove(self, destPath: str):
  456. return True
  457. def getMemberList(self) -> [_DAVResource]:
  458. members = []
  459. if self.content:
  460. children = self.content.children
  461. else:
  462. children = self.content_api.get_all(False, ContentType.Any, self.workspace)
  463. for content in children:
  464. if content.is_archived == self._is_archived and content.is_deleted == self._is_deleted:
  465. members.append(HistoryFileFolder(
  466. path='%s/%s' % (self.path, content.get_label()),
  467. environ=self.environ,
  468. content=content))
  469. return members
  470. class DeletedFolder(HistoryFolder):
  471. """
  472. A virtual resources which exists for every folder or workspaces which contains their deleted children
  473. """
  474. def __init__(self, path: str, environ: dict, workspace: data.Workspace, content: data.Content=None):
  475. super(DeletedFolder, self).__init__(path, environ, workspace, content, HistoryType.Deleted)
  476. self._file_count = 0
  477. def __repr__(self):
  478. return "<DAVCollection: DeletedFolder (%s)" % self.content.file_name
  479. def getCreationDate(self) -> float:
  480. return mktime(datetime.now().timetuple())
  481. def getDisplayName(self) -> str:
  482. return '.deleted'
  483. def getLastModified(self) -> float:
  484. return mktime(datetime.now().timetuple())
  485. def getMember(self, content_label) -> _DAVResource:
  486. content = self.content_api.get_one_by_label_and_parent(
  487. content_label=content_label,
  488. content_parent=self.content
  489. )
  490. return self.provider.getResourceInst(
  491. path='%s/%s' % (self.path, self.provider.transform_to_display(content.get_label())),
  492. environ=self.environ
  493. )
  494. def getMemberNames(self) -> [str]:
  495. retlist = []
  496. if self.content:
  497. children = self.content.children
  498. else:
  499. children = self.content_api.get_all(False, ContentType.Any, self.workspace)
  500. for content in children:
  501. if content.is_deleted:
  502. retlist.append(content.get_label())
  503. if content.type != ContentType.Folder:
  504. self._file_count += 1
  505. return retlist
  506. def getMemberList(self) -> [_DAVResource]:
  507. members = []
  508. if self.content:
  509. children = self.content.children
  510. else:
  511. children = self.content_api.get_all(False, ContentType.Any, self.workspace)
  512. for content in children:
  513. if content.is_deleted:
  514. content_path = '%s/%s' % (self.path, self.provider.transform_to_display(content.get_label()))
  515. if content.type == ContentType.Folder:
  516. members.append(Folder(content_path, self.environ, self.workspace, content))
  517. elif content.type == ContentType.File:
  518. self._file_count += 1
  519. members.append(File(content_path, self.environ, content))
  520. else:
  521. self._file_count += 1
  522. members.append(OtherFile(content_path, self.environ, content))
  523. if self._file_count > 0 and self.provider.show_history():
  524. members.append(
  525. HistoryFolder(
  526. path=self.path + '/' + ".history",
  527. environ=self.environ,
  528. content=self.content,
  529. workspace=self.workspace,
  530. type=HistoryType.Standard
  531. )
  532. )
  533. return members
  534. class ArchivedFolder(HistoryFolder):
  535. """
  536. A virtual resources which exists for every folder or workspaces which contains their archived children
  537. """
  538. def __init__(self, path: str, environ: dict, workspace: data.Workspace, content: data.Content=None):
  539. super(ArchivedFolder, self).__init__(path, environ, workspace, content, HistoryType.Archived)
  540. self._file_count = 0
  541. def __repr__(self) -> str:
  542. return "<DAVCollection: ArchivedFolder (%s)" % self.content.file_name
  543. def getCreationDate(self) -> float:
  544. return mktime(datetime.now().timetuple())
  545. def getDisplayName(self) -> str:
  546. return '.archived'
  547. def getLastModified(self) -> float:
  548. return mktime(datetime.now().timetuple())
  549. def getMember(self, content_label) -> _DAVResource:
  550. content = self.content_api.get_one_by_label_and_parent(
  551. content_label=content_label,
  552. content_parent=self.content
  553. )
  554. return self.provider.getResourceInst(
  555. path=self.path + '/' + self.provider.transform_to_display(content.get_label()),
  556. environ=self.environ
  557. )
  558. def getMemberNames(self) -> [str]:
  559. retlist = []
  560. for content in self.content_api.get_all_with_filter(
  561. self.content if self.content is None else self.content.id, ContentType.Any):
  562. retlist.append(content.get_label())
  563. if content.type != ContentType.Folder:
  564. self._file_count += 1
  565. return retlist
  566. def getMemberList(self) -> [_DAVResource]:
  567. members = []
  568. if self.content:
  569. children = self.content.children
  570. else:
  571. children = self.content_api.get_all(False, ContentType.Any, self.workspace)
  572. for content in children:
  573. if content.is_archived:
  574. content_path = '%s/%s' % (self.path, self.provider.transform_to_display(content.get_label()))
  575. if content.type == ContentType.Folder:
  576. members.append(Folder(content_path, self.environ, self.workspace, content))
  577. elif content.type == ContentType.File:
  578. self._file_count += 1
  579. members.append(File(content_path, self.environ, content))
  580. else:
  581. self._file_count += 1
  582. members.append(OtherFile(content_path, self.environ, content))
  583. if self._file_count > 0 and self.provider.show_history():
  584. members.append(
  585. HistoryFolder(
  586. path=self.path + '/' + ".history",
  587. environ=self.environ,
  588. content=self.content,
  589. workspace=self.workspace,
  590. type=HistoryType.Standard
  591. )
  592. )
  593. return members
  594. class HistoryFileFolder(HistoryFolder):
  595. """
  596. A virtual resource that contains for a given content (file/page/thread) all its revisions
  597. """
  598. def __init__(self, path: str, environ: dict, content: data.Content):
  599. super(HistoryFileFolder, self).__init__(path, environ, content.workspace, content, HistoryType.All)
  600. def __repr__(self) -> str:
  601. return "<DAVCollection: HistoryFileFolder (%s)" % self.content.file_name
  602. def getDisplayName(self) -> str:
  603. return self.content.get_label()
  604. def createCollection(self, name):
  605. raise DAVError(HTTP_FORBIDDEN)
  606. def getMemberNames(self) -> [int]:
  607. """
  608. Usually we would return a string, but here as we're working with different
  609. revisions of the same content, we'll work with revision_id
  610. """
  611. ret = []
  612. for content in self.content.revisions:
  613. ret.append(content.revision_id)
  614. return ret
  615. def getMember(self, item_id) -> DAVCollection:
  616. revision = self.content_api.get_one_revision(item_id)
  617. left_side = '%s/(%d - %s) ' % (self.path, revision.revision_id, revision.revision_type)
  618. if self.content.type == ContentType.File:
  619. return HistoryFile(
  620. path='%s%s' % (left_side, self.provider.transform_to_display(revision.file_name)),
  621. environ=self.environ,
  622. content=self.content,
  623. content_revision=revision)
  624. else:
  625. return HistoryOtherFile(
  626. path='%s%s' % (left_side, self.provider.transform_to_display(revision.get_label())),
  627. environ=self.environ,
  628. content=self.content,
  629. content_revision=revision)
  630. def getMemberList(self) -> [_DAVResource]:
  631. members = []
  632. for content in self.content.revisions:
  633. left_side = '%s/(%d - %s) ' % (self.path, content.revision_id, content.revision_type)
  634. if self.content.type == ContentType.File:
  635. members.append(HistoryFile(
  636. path='%s%s' % (left_side, self.provider.transform_to_display(content.file_name)),
  637. environ=self.environ,
  638. content=self.content,
  639. content_revision=content)
  640. )
  641. else:
  642. members.append(HistoryOtherFile(
  643. path='%s%s' % (left_side, self.provider.transform_to_display(content.file_name)),
  644. environ=self.environ,
  645. content=self.content,
  646. content_revision=content)
  647. )
  648. return members
  649. class File(DAVNonCollection):
  650. """
  651. File resource corresponding to tracim's files
  652. """
  653. def __init__(self, path: str, environ: dict, content: Content):
  654. super(File, self).__init__(path, environ)
  655. self.content = content
  656. self.user = UserApi(None).get_one_by_email(environ['http_authenticator.username'])
  657. self.content_api = ContentApi(self.user)
  658. # this is the property that windows client except to check if the file is read-write or read-only,
  659. # but i wasn't able to set this property so you'll have to look into it >.>
  660. # self.setPropertyValue('Win32FileAttributes', '00000021')
  661. def getPreferredPath(self):
  662. fix_txt = '.txt' if self.getContentType() == 'text/plain' else mimetypes.guess_extension(self.getContentType())
  663. if not fix_txt:
  664. fix_txt = ''
  665. if self.content and self.path and (self.content.label == '' or self.path.endswith(fix_txt)):
  666. return self.path
  667. else:
  668. return self.path + fix_txt
  669. def __repr__(self) -> str:
  670. return "<DAVNonCollection: File (%d)>" % self.content.revision_id
  671. def getContentLength(self) -> int:
  672. return len(self.content.file_content)
  673. def getContentType(self) -> str:
  674. return self.content.file_mimetype
  675. def getCreationDate(self) -> float:
  676. return mktime(self.content.created.timetuple())
  677. def getDisplayName(self) -> str:
  678. return self.content.get_label()
  679. def getLastModified(self) -> float:
  680. return mktime(self.content.updated.timetuple())
  681. def getContent(self):
  682. filestream = compat.BytesIO()
  683. filestream.write(self.content.file_content)
  684. filestream.seek(0)
  685. return filestream
  686. def beginWrite(self, contentType: str=None) -> FakeFileStream:
  687. return FakeFileStream(
  688. content=self.content,
  689. content_api=self.content_api,
  690. file_name=self.content.get_label(),
  691. workspace=self.content.workspace,
  692. path=self.path
  693. )
  694. def moveRecursive(self, destpath):
  695. """As we support recursive move, copymovesingle won't be called, though with copy it'll be called
  696. but i have to check if the client ever call that function..."""
  697. destpath = normpath(destpath)
  698. invalid_path = False
  699. # if content is either deleted or archived, we'll check that we try moving it to the parent
  700. # if yes, then we'll unarchive / undelete them, else the action's not allowed
  701. if self.content.is_deleted or self.content.is_archived:
  702. # we remove all archived and deleted from the path and we check to the destpath
  703. # has to be equal or else path not valid
  704. # ex: /a/b/.deleted/resource, to be valid destpath has to be = /a/b/resource (no other solution)
  705. current_path = re.sub(r'/\.(deleted|archived)', '', self.path)
  706. if current_path == destpath:
  707. ManageActions(
  708. ActionDescription.UNDELETION if self.content.is_deleted else ActionDescription.UNARCHIVING,
  709. self.content_api,
  710. self.content
  711. ).action()
  712. else:
  713. invalid_path = True
  714. # if the content is not deleted / archived, check if we're trying to delete / archive it by
  715. # moving it to a .deleted / .archived folder
  716. elif basename(dirname(destpath)) in ['.deleted', '.archived']:
  717. # same test as above ^
  718. dest_path = re.sub(r'/\.(deleted|archived)', '', destpath)
  719. if dest_path == self.path:
  720. ManageActions(
  721. ActionDescription.DELETION if '.deleted' in destpath else ActionDescription.ARCHIVING,
  722. self.content_api,
  723. self.content
  724. ).action()
  725. else:
  726. invalid_path = True
  727. # else we check if the path is good (not at the root path / not in a deleted/archived path)
  728. # and we move the content
  729. else:
  730. invalid_path = any(x in destpath for x in ['.deleted', '.archived'])
  731. invalid_path = invalid_path or any(x in self.path for x in ['.deleted', '.archived'])
  732. invalid_path = invalid_path or dirname(destpath) == self.environ['http_authenticator.realm']
  733. if not invalid_path:
  734. self.move_file(destpath)
  735. if invalid_path:
  736. raise DAVError(HTTP_FORBIDDEN)
  737. def move_file(self, destpath):
  738. workspace = self.provider.get_workspace_from_path(
  739. normpath(destpath),
  740. WorkspaceApi(self.user)
  741. )
  742. parent = self.provider.get_parent_from_path(
  743. normpath(destpath),
  744. self.content_api,
  745. workspace
  746. )
  747. with new_revision(self.content):
  748. if basename(destpath) != self.getDisplayName():
  749. self.content_api.update_content(self.content, re.sub('\.[^\.]+$', '', self.provider.transform_to_bdd(basename(destpath))))
  750. self.content_api.save(self.content)
  751. else:
  752. self.content_api.move(
  753. item=self.content,
  754. new_parent=parent,
  755. must_stay_in_same_workspace=False,
  756. new_workspace=workspace
  757. )
  758. transaction.commit()
  759. def supportRecursiveMove(self, destPath):
  760. return True
  761. def delete(self):
  762. ManageActions(ActionDescription.DELETION, self.content_api, self.content).action()
  763. class HistoryFile(File):
  764. """
  765. A virtual resource corresponding to a specific tracim's revision's file
  766. """
  767. def __init__(self, path: str, environ: dict, content: data.Content, content_revision: data.ContentRevisionRO):
  768. super(HistoryFile, self).__init__(path, environ, content)
  769. self.content_revision = content_revision
  770. def __repr__(self) -> str:
  771. return "<DAVNonCollection: HistoryFile (%s-%s)" % (self.content.content_id, self.content.file_name)
  772. def getDisplayName(self) -> str:
  773. left_side = '(%d - %s) ' % (self.content_revision.revision_id, self.content_revision.revision_type)
  774. return '%s%s' % (left_side, self.provider.transform_to_display(self.content_revision.file_name))
  775. def getContent(self):
  776. filestream = compat.BytesIO()
  777. filestream.write(self.content_revision.file_content)
  778. filestream.seek(0)
  779. return filestream
  780. def getContentLength(self):
  781. return len(self.content_revision.file_content)
  782. def getContentType(self) -> str:
  783. return self.content_revision.file_mimetype
  784. def beginWrite(self, contentType=None):
  785. raise DAVError(HTTP_FORBIDDEN)
  786. def delete(self):
  787. raise DAVError(HTTP_FORBIDDEN)
  788. def copyMoveSingle(self, destpath, ismove):
  789. raise DAVError(HTTP_FORBIDDEN)
  790. class OtherFile(File):
  791. """
  792. File resource corresponding to tracim's page and thread
  793. """
  794. def __init__(self, path: str, environ: dict, content: data.Content):
  795. super(OtherFile, self).__init__(path, environ, content)
  796. self.content_revision = self.content.revision
  797. self.content_designed = self.design()
  798. # workaround for consistent request as we have to return a resource with a path ending with .html
  799. # when entering folder for windows, but only once because when we select it again it would have .html.html
  800. # which is no good
  801. if not self.path.endswith('.html'):
  802. self.path += '.html'
  803. def getDisplayName(self) -> str:
  804. return self.content.get_label()
  805. def getPreferredPath(self):
  806. return self.path
  807. def __repr__(self) -> str:
  808. return "<DAVNonCollection: OtherFile (%s)" % self.content.file_name
  809. def getContentLength(self) -> int:
  810. return len(self.content_designed)
  811. def getContentType(self) -> str:
  812. return 'text/html'
  813. def getContent(self):
  814. filestream = compat.BytesIO()
  815. filestream.write(bytes(self.content_designed, 'utf-8'))
  816. filestream.seek(0)
  817. return filestream
  818. def design(self):
  819. if self.content.type == ContentType.Page:
  820. return designPage(self.content, self.content_revision)
  821. else:
  822. return designThread(
  823. self.content,
  824. self.content_revision,
  825. self.content_api.get_all(self.content.content_id, ContentType.Comment)
  826. )
  827. class HistoryOtherFile(OtherFile):
  828. """
  829. A virtual resource corresponding to a specific tracim's revision's page and thread
  830. """
  831. def __init__(self, path: str, environ: dict, content: data.Content, content_revision: data.ContentRevisionRO):
  832. super(HistoryOtherFile, self).__init__(path, environ, content)
  833. self.content_revision = content_revision
  834. self.content_designed = self.design()
  835. def __repr__(self) -> str:
  836. return "<DAVNonCollection: HistoryOtherFile (%s-%s)" % (self.content.file_name, self.content.id)
  837. def getDisplayName(self) -> str:
  838. left_side = '(%d - %s) ' % (self.content_revision.revision_id, self.content_revision.revision_type)
  839. return '%s%s' % (left_side, self.provider.transform_to_display(self.content_revision.get_label()))
  840. def getContent(self):
  841. filestream = compat.BytesIO()
  842. filestream.write(bytes(self.content_designed, 'utf-8'))
  843. filestream.seek(0)
  844. return filestream
  845. def delete(self):
  846. raise DAVError(HTTP_FORBIDDEN)
  847. def copyMoveSingle(self, destpath, ismove):
  848. raise DAVError(HTTP_FORBIDDEN)