sql_resources.py 40KB

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