resources.py 50KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474
  1. # coding: utf8
  2. import logging
  3. import os
  4. import transaction
  5. import typing
  6. import re
  7. from datetime import datetime
  8. from time import mktime
  9. from os.path import dirname, basename
  10. from sqlalchemy.orm import Session
  11. from tracim_backend.config import CFG
  12. from tracim_backend.lib.core.content import ContentApi
  13. from tracim_backend.lib.core.user import UserApi
  14. from tracim_backend.lib.webdav.utils import transform_to_display, HistoryType, \
  15. FakeFileStream
  16. from tracim_backend.lib.webdav.utils import transform_to_bdd
  17. from tracim_backend.lib.core.workspace import WorkspaceApi
  18. from tracim_backend.app_models.contents import CONTENT_TYPES
  19. from tracim_backend.models.data import User, ContentRevisionRO
  20. from tracim_backend.models.data import Workspace
  21. from tracim_backend.models.data import Content
  22. from tracim_backend.models.data import ActionDescription
  23. from tracim_backend.lib.webdav.design import designThread, designPage
  24. from wsgidav import compat
  25. from wsgidav.dav_error import DAVError, HTTP_FORBIDDEN
  26. from wsgidav.dav_provider import DAVCollection, DAVNonCollection
  27. from wsgidav.dav_provider import _DAVResource
  28. from tracim_backend.lib.webdav.utils import normpath
  29. from sqlalchemy.orm.exc import NoResultFound, MultipleResultsFound
  30. from tracim_backend.models.revision_protection import new_revision
  31. logger = logging.getLogger()
  32. class ManageActions(object):
  33. """
  34. This object is used to encapsulate all Deletion/Archiving related
  35. method as to not duplicate too much code
  36. """
  37. def __init__(self,
  38. session: Session,
  39. action_type: str,
  40. api: ContentApi,
  41. content: Content
  42. ):
  43. self.session = session
  44. self.content_api = api
  45. self.content = content
  46. self._actions = {
  47. ActionDescription.ARCHIVING: self.content_api.archive,
  48. ActionDescription.DELETION: self.content_api.delete,
  49. ActionDescription.UNARCHIVING: self.content_api.unarchive,
  50. ActionDescription.UNDELETION: self.content_api.undelete
  51. }
  52. self._type = action_type
  53. def action(self):
  54. with new_revision(
  55. session=self.session,
  56. tm=transaction.manager,
  57. content=self.content,
  58. ):
  59. self._actions[self._type](self.content)
  60. self.content_api.save(self.content, self._type)
  61. transaction.commit()
  62. class RootResource(DAVCollection):
  63. """
  64. RootResource ressource that represents tracim's home, which contains all workspaces
  65. """
  66. def __init__(self, path: str, environ: dict, user: User, session: Session):
  67. super(RootResource, self).__init__(path, environ)
  68. self.user = user
  69. self.session = session
  70. # TODO BS 20170221: Web interface should list all workspace to. We
  71. # disable it here for moment. When web interface will be updated to
  72. # list all workspace, change this here to.
  73. self.workspace_api = WorkspaceApi(
  74. current_user=self.user,
  75. session=session,
  76. force_role=True,
  77. config=self.provider.app_config
  78. )
  79. def __repr__(self) -> str:
  80. return '<DAVCollection: RootResource>'
  81. def getMemberNames(self) -> [str]:
  82. """
  83. This method returns the names (here workspace's labels) of all its children
  84. Though for perfomance issue, we're not using this function anymore
  85. """
  86. return [workspace.label for workspace in self.workspace_api.get_all()]
  87. def getMember(self, label: str) -> DAVCollection:
  88. """
  89. This method returns the child Workspace that corresponds to a given name
  90. Though for perfomance issue, we're not using this function anymore
  91. """
  92. try:
  93. workspace = self.workspace_api.get_one_by_label(label)
  94. workspace_path = '%s%s%s' % (self.path, '' if self.path == '/' else '/', transform_to_display(workspace.label))
  95. return WorkspaceResource(
  96. workspace_path,
  97. self.environ,
  98. workspace,
  99. session=self.session,
  100. user=self.user,
  101. )
  102. except AttributeError:
  103. return None
  104. def createEmptyResource(self, name: str):
  105. """
  106. This method is called whenever the user wants to create a DAVNonCollection resource (files in our case).
  107. There we don't allow to create files at the root;
  108. only workspaces (thus collection) can be created.
  109. """
  110. raise DAVError(HTTP_FORBIDDEN)
  111. def createCollection(self, name: str):
  112. """
  113. This method is called whenever the user wants to create a DAVCollection resource as a child (in our case,
  114. we create workspaces as this is the root).
  115. [For now] we don't allow to create new workspaces through
  116. webdav client. Though if we come to allow it, deleting the error's raise will
  117. make it possible.
  118. """
  119. # TODO : remove comment here
  120. # raise DAVError(HTTP_FORBIDDEN)
  121. new_workspace = self.workspace_api.create_workspace(name)
  122. self.workspace_api.save(new_workspace)
  123. workspace_path = '%s%s%s' % (
  124. self.path, '' if self.path == '/' else '/', transform_to_display(new_workspace.label))
  125. transaction.commit()
  126. return WorkspaceResource(
  127. workspace_path,
  128. self.environ,
  129. new_workspace,
  130. user=self.user,
  131. session=self.session,
  132. )
  133. def getMemberList(self):
  134. """
  135. This method is called by wsgidav when requesting with a depth > 0, it will return a list of _DAVResource
  136. of all its direct children
  137. """
  138. members = []
  139. for workspace in self.workspace_api.get_all():
  140. workspace_path = '%s%s%s' % (self.path, '' if self.path == '/' else '/', workspace.label)
  141. members.append(
  142. WorkspaceResource(
  143. path=workspace_path,
  144. environ=self.environ,
  145. workspace=workspace,
  146. user=self.user,
  147. session=self.session,
  148. )
  149. )
  150. return members
  151. class WorkspaceResource(DAVCollection):
  152. """
  153. Workspace resource corresponding to tracim's workspaces.
  154. Direct children can only be folders, though files might come later on and are supported
  155. """
  156. def __init__(self,
  157. path: str,
  158. environ: dict,
  159. workspace: Workspace,
  160. user: User,
  161. session: Session
  162. ) -> None:
  163. super(WorkspaceResource, self).__init__(path, environ)
  164. self.workspace = workspace
  165. self.content = None
  166. self.user = user
  167. self.session = session
  168. self.content_api = ContentApi(
  169. current_user=self.user,
  170. session=session,
  171. config=self.provider.app_config,
  172. show_temporary=True
  173. )
  174. self._file_count = 0
  175. def __repr__(self) -> str:
  176. return "<DAVCollection: Workspace (%d)>" % self.workspace.workspace_id
  177. def getPreferredPath(self):
  178. return self.path
  179. def getCreationDate(self) -> float:
  180. return mktime(self.workspace.created.timetuple())
  181. def getDisplayName(self) -> str:
  182. return self.workspace.label
  183. def getLastModified(self) -> float:
  184. return mktime(self.workspace.updated.timetuple())
  185. def getMemberNames(self) -> [str]:
  186. retlist = []
  187. children = self.content_api.get_all(
  188. parent_id=self.content.id if self.content is not None else None,
  189. workspace=self.workspace
  190. )
  191. for content in children:
  192. # the purpose is to display .history only if there's at least one content's type that has a history
  193. if content.type != CONTENT_TYPES.Folder.slug:
  194. self._file_count += 1
  195. retlist.append(content.get_label_as_file())
  196. return retlist
  197. def getMember(self, content_label: str) -> _DAVResource:
  198. return self.provider.getResourceInst(
  199. '%s/%s' % (self.path, transform_to_display(content_label)),
  200. self.environ
  201. )
  202. def createEmptyResource(self, file_name: str):
  203. """
  204. [For now] we don't allow to create files right under workspaces.
  205. Though if we come to allow it, deleting the error's raise will make it possible.
  206. """
  207. # TODO : remove commentary here raise DAVError(HTTP_FORBIDDEN)
  208. if '/.deleted/' in self.path or '/.archived/' in self.path:
  209. raise DAVError(HTTP_FORBIDDEN)
  210. content = None
  211. # Note: To prevent bugs, check here again if resource already exist
  212. path = os.path.join(self.path, file_name)
  213. resource = self.provider.getResourceInst(path, self.environ)
  214. if resource:
  215. content = resource.content
  216. return FakeFileStream(
  217. session=self.session,
  218. file_name=file_name,
  219. content_api=self.content_api,
  220. workspace=self.workspace,
  221. content=content,
  222. parent=self.content,
  223. path=self.path + '/' + file_name
  224. )
  225. def createCollection(self, label: str) -> 'FolderResource':
  226. """
  227. Create a new folder for the current workspace. As it's not possible for the user to choose
  228. which types of content are allowed in this folder, we allow allow all of them.
  229. This method return the DAVCollection created.
  230. """
  231. if '/.deleted/' in self.path or '/.archived/' in self.path:
  232. raise DAVError(HTTP_FORBIDDEN)
  233. folder = self.content_api.create(
  234. content_type_slug=CONTENT_TYPES.Folder.slug,
  235. workspace=self.workspace,
  236. label=label,
  237. parent=self.content
  238. )
  239. self.content_api.save(folder)
  240. transaction.commit()
  241. return FolderResource('%s/%s' % (self.path, transform_to_display(label)),
  242. self.environ,
  243. content=folder,
  244. session=self.session,
  245. user=self.user,
  246. workspace=self.workspace,
  247. )
  248. def delete(self):
  249. """For now, it is not possible to delete a workspace through the webdav client."""
  250. raise DAVError(HTTP_FORBIDDEN)
  251. def supportRecursiveMove(self, destpath):
  252. return True
  253. def moveRecursive(self, destpath):
  254. if dirname(normpath(destpath)) == self.environ['http_authenticator.realm']:
  255. self.workspace.label = basename(normpath(destpath))
  256. transaction.commit()
  257. else:
  258. raise DAVError(HTTP_FORBIDDEN)
  259. def getMemberList(self) -> [_DAVResource]:
  260. members = []
  261. children = self.content_api.get_all(False, CONTENT_TYPES.Any_SLUG, self.workspace)
  262. for content in children:
  263. content_path = '%s/%s' % (self.path, transform_to_display(content.get_label_as_file()))
  264. if content.type == CONTENT_TYPES.Folder.slug:
  265. members.append(
  266. FolderResource(
  267. path=content_path,
  268. environ=self.environ,
  269. workspace=self.workspace,
  270. user=self.user,
  271. content=content,
  272. session=self.session,
  273. )
  274. )
  275. elif content.type == CONTENT_TYPES.File.slug:
  276. self._file_count += 1
  277. members.append(
  278. FileResource(
  279. path=content_path,
  280. environ=self.environ,
  281. content=content,
  282. user=self.user,
  283. session=self.session,
  284. )
  285. )
  286. else:
  287. self._file_count += 1
  288. members.append(
  289. OtherFileResource(
  290. content_path,
  291. self.environ,
  292. content,
  293. session=self.session,
  294. user=self.user,
  295. ))
  296. if self._file_count > 0 and self.provider.show_history():
  297. members.append(
  298. HistoryFolderResource(
  299. path=self.path + '/' + ".history",
  300. environ=self.environ,
  301. content=self.content,
  302. workspace=self.workspace,
  303. type=HistoryType.Standard,
  304. session=self.session,
  305. user=self.user,
  306. )
  307. )
  308. if self.provider.show_delete():
  309. members.append(
  310. DeletedFolderResource(
  311. path=self.path + '/' + ".deleted",
  312. environ=self.environ,
  313. content=self.content,
  314. workspace=self.workspace,
  315. session=self.session,
  316. user=self.user,
  317. )
  318. )
  319. if self.provider.show_archive():
  320. members.append(
  321. ArchivedFolderResource(
  322. path=self.path + '/' + ".archived",
  323. environ=self.environ,
  324. content=self.content,
  325. workspace=self.workspace,
  326. user=self.user,
  327. session=self.session,
  328. )
  329. )
  330. return members
  331. class FolderResource(WorkspaceResource):
  332. """
  333. FolderResource resource corresponding to tracim's folders.
  334. Direct children can only be either folder, files, pages or threads
  335. By default when creating new folders, we allow them to contain all types of content
  336. """
  337. def __init__(
  338. self,
  339. path: str,
  340. environ: dict,
  341. workspace: Workspace,
  342. content: Content,
  343. user: User,
  344. session: Session
  345. ):
  346. super(FolderResource, self).__init__(
  347. path=path,
  348. environ=environ,
  349. workspace=workspace,
  350. user=user,
  351. session=session,
  352. )
  353. self.content = content
  354. def __repr__(self) -> str:
  355. return "<DAVCollection: Folder (%s)>" % self.content.label
  356. def getCreationDate(self) -> float:
  357. return mktime(self.content.created.timetuple())
  358. def getDisplayName(self) -> str:
  359. return transform_to_display(self.content.get_label_as_file())
  360. def getLastModified(self) -> float:
  361. return mktime(self.content.updated.timetuple())
  362. def delete(self):
  363. ManageActions(
  364. action_type=ActionDescription.DELETION,
  365. api=self.content_api,
  366. content=self.content,
  367. session=self.session,
  368. ).action()
  369. def supportRecursiveMove(self, destpath: str):
  370. return True
  371. def moveRecursive(self, destpath: str):
  372. """
  373. As we support recursive move, copymovesingle won't be called, though with copy it'll be called
  374. but i have to check if the client ever call that function...
  375. """
  376. destpath = normpath(destpath)
  377. invalid_path = False
  378. # if content is either deleted or archived, we'll check that we try moving it to the parent
  379. # if yes, then we'll unarchive / undelete them, else the action's not allowed
  380. if self.content.is_deleted or self.content.is_archived:
  381. # we remove all archived and deleted from the path and we check to the destpath
  382. # has to be equal or else path not valid
  383. # ex: /a/b/.deleted/resource, to be valid destpath has to be = /a/b/resource (no other solution)
  384. current_path = re.sub(r'/\.(deleted|archived)', '', self.path)
  385. if current_path == destpath:
  386. ManageActions(
  387. action_type=ActionDescription.UNDELETION if self.content.is_deleted else ActionDescription.UNARCHIVING,
  388. api=self.content_api,
  389. content=self.content,
  390. session=self.session,
  391. ).action()
  392. else:
  393. invalid_path = True
  394. # if the content is not deleted / archived, check if we're trying to delete / archive it by
  395. # moving it to a .deleted / .archived folder
  396. elif basename(dirname(destpath)) in ['.deleted', '.archived']:
  397. # same test as above ^
  398. dest_path = re.sub(r'/\.(deleted|archived)', '', destpath)
  399. if dest_path == self.path:
  400. ManageActions(
  401. action_type=ActionDescription.DELETION if '.deleted' in destpath else ActionDescription.ARCHIVING,
  402. api=self.content_api,
  403. content=self.content,
  404. session=self.session,
  405. ).action()
  406. else:
  407. invalid_path = True
  408. # else we check if the path is good (not at the root path / not in a deleted/archived path)
  409. # and we move the content
  410. else:
  411. invalid_path = any(x in destpath for x in ['.deleted', '.archived'])
  412. invalid_path = invalid_path or any(x in self.path for x in ['.deleted', '.archived'])
  413. invalid_path = invalid_path or dirname(destpath) == self.environ['http_authenticator.realm']
  414. if not invalid_path:
  415. self.move_folder(destpath)
  416. if invalid_path:
  417. raise DAVError(HTTP_FORBIDDEN)
  418. def move_folder(self, destpath):
  419. workspace_api = WorkspaceApi(
  420. current_user=self.user,
  421. session=self.session,
  422. config=self.provider.app_config,
  423. )
  424. workspace = self.provider.get_workspace_from_path(
  425. normpath(destpath), workspace_api
  426. )
  427. parent = self.provider.get_parent_from_path(
  428. normpath(destpath),
  429. self.content_api,
  430. workspace
  431. )
  432. with new_revision(
  433. content=self.content,
  434. tm=transaction.manager,
  435. session=self.session,
  436. ):
  437. if basename(destpath) != self.getDisplayName():
  438. self.content_api.update_content(self.content, transform_to_bdd(basename(destpath)))
  439. self.content_api.save(self.content)
  440. else:
  441. if workspace.workspace_id == self.content.workspace.workspace_id:
  442. self.content_api.move(self.content, parent)
  443. else:
  444. self.content_api.move_recursively(self.content, parent, workspace)
  445. transaction.commit()
  446. def getMemberList(self) -> [_DAVResource]:
  447. members = []
  448. content_api = ContentApi(
  449. current_user=self.user,
  450. config=self.provider.app_config,
  451. session=self.session,
  452. )
  453. visible_children = content_api.get_all(
  454. self.content.content_id,
  455. CONTENT_TYPES.Any_SLUG,
  456. self.workspace,
  457. )
  458. for content in visible_children:
  459. content_path = '%s/%s' % (self.path, transform_to_display(content.get_label_as_file()))
  460. try:
  461. if content.type == CONTENT_TYPES.Folder.slug:
  462. members.append(
  463. FolderResource(
  464. path=content_path,
  465. environ=self.environ,
  466. workspace=self.workspace,
  467. content=content,
  468. user=self.user,
  469. session=self.session,
  470. )
  471. )
  472. elif content.type == CONTENT_TYPES.File.slug:
  473. self._file_count += 1
  474. members.append(
  475. FileResource(
  476. path=content_path,
  477. environ=self.environ,
  478. content=content,
  479. user=self.user,
  480. session=self.session,
  481. ))
  482. else:
  483. self._file_count += 1
  484. members.append(
  485. OtherFileResource(
  486. path=content_path,
  487. environ=self.environ,
  488. content=content,
  489. user=self.user,
  490. session=self.session,
  491. ))
  492. except NotImplementedError as exc:
  493. pass
  494. # except Exception as exc:
  495. # logger.exception(
  496. # 'Unable to construct member {}'.format(
  497. # content_path,
  498. # ),
  499. # exc_info=True,
  500. # )
  501. if self._file_count > 0 and self.provider.show_history():
  502. members.append(
  503. HistoryFolderResource(
  504. path=self.path + '/' + ".history",
  505. environ=self.environ,
  506. content=self.content,
  507. workspace=self.workspace,
  508. type=HistoryType.Standard,
  509. user=self.user,
  510. session=self.session,
  511. )
  512. )
  513. if self.provider.show_delete():
  514. members.append(
  515. DeletedFolderResource(
  516. path=self.path + '/' + ".deleted",
  517. environ=self.environ,
  518. content=self.content,
  519. workspace=self.workspace,
  520. user=self.user,
  521. session=self.session,
  522. )
  523. )
  524. if self.provider.show_archive():
  525. members.append(
  526. ArchivedFolderResource(
  527. path=self.path + '/' + ".archived",
  528. environ=self.environ,
  529. content=self.content,
  530. workspace=self.workspace,
  531. user=self.user,
  532. session=self.session,
  533. )
  534. )
  535. return members
  536. # TODO - G.M - 02-05-2018 - Check these object (History/Deleted/Archived Folder)
  537. # Those object are now not in used by tracim and also not tested,
  538. class HistoryFolderResource(FolderResource):
  539. """
  540. A virtual resource which contains a sub-folder for every files (DAVNonCollection) contained in the parent
  541. folder
  542. """
  543. def __init__(self,
  544. path,
  545. environ,
  546. workspace: Workspace,
  547. user: User,
  548. session: Session,
  549. content: Content=None,
  550. type: str=HistoryType.Standard
  551. ) -> None:
  552. super(HistoryFolderResource, self).__init__(
  553. path=path,
  554. environ=environ,
  555. workspace=workspace,
  556. content=content,
  557. user=user,
  558. session=session,
  559. )
  560. self._is_archived = type == HistoryType.Archived
  561. self._is_deleted = type == HistoryType.Deleted
  562. self.content_api = ContentApi(
  563. current_user=self.user,
  564. show_archived=self._is_archived,
  565. show_deleted=self._is_deleted,
  566. session=self.session,
  567. config=self.provider.app_config,
  568. )
  569. def __repr__(self) -> str:
  570. return "<DAVCollection: HistoryFolderResource (%s)>" % self.content.file_name
  571. def getCreationDate(self) -> float:
  572. return mktime(datetime.now().timetuple())
  573. def getDisplayName(self) -> str:
  574. return '.history'
  575. def getLastModified(self) -> float:
  576. return mktime(datetime.now().timetuple())
  577. def getMember(self, content_label: str) -> _DAVResource:
  578. content = self.content_api.get_one_by_label_and_parent(
  579. content_label=content_label,
  580. content_parent=self.content
  581. )
  582. return HistoryFileFolderResource(
  583. path='%s/%s' % (self.path, content.get_label_as_file()),
  584. environ=self.environ,
  585. content=content,
  586. session=self.session,
  587. user=self.user,
  588. )
  589. def getMemberNames(self) -> [str]:
  590. ret = []
  591. content_id = None if self.content is None else self.content.id
  592. for content in self.content_api.get_all(content_id, CONTENT_TYPES.Any_SLUG, self.workspace):
  593. if (self._is_archived and content.is_archived or
  594. self._is_deleted and content.is_deleted or
  595. not (content.is_archived or self._is_archived or content.is_deleted or self._is_deleted))\
  596. and content.type != CONTENT_TYPES.Folder.slug:
  597. ret.append(content.get_label_as_file())
  598. return ret
  599. def createEmptyResource(self, name: str):
  600. raise DAVError(HTTP_FORBIDDEN)
  601. def createCollection(self, name: str):
  602. raise DAVError(HTTP_FORBIDDEN)
  603. def delete(self):
  604. raise DAVError(HTTP_FORBIDDEN)
  605. def handleDelete(self):
  606. return True
  607. def handleCopy(self, destPath: str, depthInfinity):
  608. return True
  609. def handleMove(self, destPath: str):
  610. return True
  611. def getMemberList(self) -> [_DAVResource]:
  612. members = []
  613. if self.content:
  614. children = self.content.children
  615. else:
  616. children = self.content_api.get_all(False, CONTENT_TYPES.Any_SLUG, self.workspace)
  617. for content in children:
  618. if content.is_archived == self._is_archived and content.is_deleted == self._is_deleted:
  619. members.append(HistoryFileFolderResource(
  620. path='%s/%s' % (self.path, content.get_label_as_file()),
  621. environ=self.environ,
  622. content=content,
  623. user=self.user,
  624. session=self.session,
  625. ))
  626. return members
  627. class DeletedFolderResource(HistoryFolderResource):
  628. """
  629. A virtual resources which exists for every folder or workspaces which contains their deleted children
  630. """
  631. def __init__(
  632. self,
  633. path: str,
  634. environ: dict,
  635. workspace: Workspace,
  636. user: User,
  637. session: Session,
  638. content: Content=None
  639. ):
  640. super(DeletedFolderResource, self).__init__(
  641. path=path,
  642. environ=environ,
  643. workspace=workspace,
  644. user=user,
  645. content=content,
  646. session=session,
  647. type=HistoryType.Deleted
  648. )
  649. self._file_count = 0
  650. def __repr__(self):
  651. return "<DAVCollection: DeletedFolderResource (%s)" % self.content.file_name
  652. def getCreationDate(self) -> float:
  653. return mktime(datetime.now().timetuple())
  654. def getDisplayName(self) -> str:
  655. return '.deleted'
  656. def getLastModified(self) -> float:
  657. return mktime(datetime.now().timetuple())
  658. def getMember(self, content_label) -> _DAVResource:
  659. content = self.content_api.get_one_by_label_and_parent(
  660. content_label=content_label,
  661. content_parent=self.content
  662. )
  663. return self.provider.getResourceInst(
  664. path='%s/%s' % (self.path, transform_to_display(content.get_label_as_file())),
  665. environ=self.environ
  666. )
  667. def getMemberNames(self) -> [str]:
  668. retlist = []
  669. if self.content:
  670. children = self.content.children
  671. else:
  672. children = self.content_api.get_all(False, CONTENT_TYPES.Any_SLUG, self.workspace)
  673. for content in children:
  674. if content.is_deleted:
  675. retlist.append(content.get_label_as_file())
  676. if content.type != CONTENT_TYPES.Folder.slug:
  677. self._file_count += 1
  678. return retlist
  679. def getMemberList(self) -> [_DAVResource]:
  680. members = []
  681. if self.content:
  682. children = self.content.children
  683. else:
  684. children = self.content_api.get_all(False, CONTENT_TYPES.Any_SLUG, self.workspace)
  685. for content in children:
  686. if content.is_deleted:
  687. content_path = '%s/%s' % (self.path, transform_to_display(content.get_label_as_file()))
  688. if content.type == CONTENT_TYPES.Folder.slug:
  689. members.append(
  690. FolderResource(
  691. content_path,
  692. self.environ,
  693. self.workspace,
  694. content,
  695. user=self.user,
  696. session=self.session,
  697. ))
  698. elif content.type == CONTENT_TYPES.File.slug:
  699. self._file_count += 1
  700. members.append(
  701. FileResource(
  702. content_path,
  703. self.environ,
  704. content,
  705. user=self.user,
  706. session=self.session,
  707. )
  708. )
  709. else:
  710. self._file_count += 1
  711. members.append(
  712. OtherFileResource(
  713. content_path,
  714. self.environ,
  715. content,
  716. user=self.user,
  717. session=self.session,
  718. ))
  719. if self._file_count > 0 and self.provider.show_history():
  720. members.append(
  721. HistoryFolderResource(
  722. path=self.path + '/' + ".history",
  723. environ=self.environ,
  724. content=self.content,
  725. workspace=self.workspace,
  726. user=self.user,
  727. type=HistoryType.Standard,
  728. session=self.session,
  729. )
  730. )
  731. return members
  732. class ArchivedFolderResource(HistoryFolderResource):
  733. """
  734. A virtual resources which exists for every folder or workspaces which contains their archived children
  735. """
  736. def __init__(
  737. self,
  738. path: str,
  739. environ: dict,
  740. workspace: Workspace,
  741. user: User,
  742. session: Session,
  743. content: Content=None
  744. ):
  745. super(ArchivedFolderResource, self).__init__(
  746. path=path,
  747. environ=environ,
  748. workspace=workspace,
  749. user=user,
  750. content=content,
  751. session=session,
  752. type=HistoryType.Archived
  753. )
  754. self._file_count = 0
  755. def __repr__(self) -> str:
  756. return "<DAVCollection: ArchivedFolderResource (%s)" % self.content.file_name
  757. def getCreationDate(self) -> float:
  758. return mktime(datetime.now().timetuple())
  759. def getDisplayName(self) -> str:
  760. return '.archived'
  761. def getLastModified(self) -> float:
  762. return mktime(datetime.now().timetuple())
  763. def getMember(self, content_label) -> _DAVResource:
  764. content = self.content_api.get_one_by_label_and_parent(
  765. content_label=content_label,
  766. content_parent=self.content
  767. )
  768. return self.provider.getResourceInst(
  769. path=self.path + '/' + transform_to_display(content.get_label_as_file()),
  770. environ=self.environ
  771. )
  772. def getMemberNames(self) -> [str]:
  773. retlist = []
  774. for content in self.content_api.get_all_with_filter(
  775. self.content if self.content is None else self.content.id, CONTENT_TYPES.Any_SLUG):
  776. retlist.append(content.get_label_as_file())
  777. if content.type != CONTENT_TYPES.Folder.slug:
  778. self._file_count += 1
  779. return retlist
  780. def getMemberList(self) -> [_DAVResource]:
  781. members = []
  782. if self.content:
  783. children = self.content.children
  784. else:
  785. children = self.content_api.get_all(False, CONTENT_TYPES.Any_SLUG, self.workspace)
  786. for content in children:
  787. if content.is_archived:
  788. content_path = '%s/%s' % (self.path, transform_to_display(content.get_label_as_file()))
  789. if content.type == CONTENT_TYPES.Folder.slug:
  790. members.append(
  791. FolderResource(
  792. content_path,
  793. self.environ,
  794. self.workspace,
  795. content,
  796. user=self.user,
  797. session=self.session,
  798. ))
  799. elif content.type == CONTENT_TYPES.File.slug:
  800. self._file_count += 1
  801. members.append(
  802. FileResource(
  803. content_path,
  804. self.environ,
  805. content,
  806. user=self.user,
  807. session=self.session,
  808. ))
  809. else:
  810. self._file_count += 1
  811. members.append(
  812. OtherFileResource(
  813. content_path,
  814. self.environ,
  815. content,
  816. user=self.user,
  817. session=self.session,
  818. ))
  819. if self._file_count > 0 and self.provider.show_history():
  820. members.append(
  821. HistoryFolderResource(
  822. path=self.path + '/' + ".history",
  823. environ=self.environ,
  824. content=self.content,
  825. workspace=self.workspace,
  826. user=self.user,
  827. type=HistoryType.Standard,
  828. session=self.session,
  829. )
  830. )
  831. return members
  832. class HistoryFileFolderResource(HistoryFolderResource):
  833. """
  834. A virtual resource that contains for a given content (file/page/thread) all its revisions
  835. """
  836. def __init__(
  837. self,
  838. path: str,
  839. environ: dict,
  840. content: Content,
  841. user: User,
  842. session: Session
  843. ) -> None:
  844. super(HistoryFileFolderResource, self).__init__(
  845. path=path,
  846. environ=environ,
  847. workspace=content.workspace,
  848. content=content,
  849. user=user,
  850. session=session,
  851. type=HistoryType.All,
  852. )
  853. def __repr__(self) -> str:
  854. return "<DAVCollection: HistoryFileFolderResource (%s)" % self.content.file_name
  855. def getDisplayName(self) -> str:
  856. return self.content.get_label_as_file()
  857. def createCollection(self, name):
  858. raise DAVError(HTTP_FORBIDDEN)
  859. def getMemberNames(self) -> [int]:
  860. """
  861. Usually we would return a string, but here as we're working with different
  862. revisions of the same content, we'll work with revision_id
  863. """
  864. ret = []
  865. for content in self.content.revisions:
  866. ret.append(content.revision_id)
  867. return ret
  868. def getMember(self, item_id) -> DAVNonCollection:
  869. revision = self.content_api.get_one_revision(item_id)
  870. left_side = '%s/(%d - %s) ' % (self.path, revision.revision_id, revision.revision_type)
  871. if self.content.type == CONTENT_TYPES.File.slug:
  872. return HistoryFileResource(
  873. path='%s%s' % (left_side, transform_to_display(revision.file_name)),
  874. environ=self.environ,
  875. content=self.content,
  876. content_revision=revision,
  877. session=self.session,
  878. user=self.user,
  879. )
  880. else:
  881. return HistoryOtherFile(
  882. path='%s%s' % (left_side, transform_to_display(revision.get_label_as_file())),
  883. environ=self.environ,
  884. content=self.content,
  885. content_revision=revision,
  886. session=self.session,
  887. user=self.user,
  888. )
  889. def getMemberList(self) -> [_DAVResource]:
  890. members = []
  891. for content in self.content.revisions:
  892. left_side = '%s/(%d - %s) ' % (self.path, content.revision_id, content.revision_type)
  893. if self.content.type == CONTENT_TYPES.File.slug:
  894. members.append(HistoryFileResource(
  895. path='%s%s' % (left_side, transform_to_display(content.file_name)),
  896. environ=self.environ,
  897. content=self.content,
  898. content_revision=content,
  899. user=self.user,
  900. session=self.session,
  901. )
  902. )
  903. else:
  904. members.append(HistoryOtherFile(
  905. path='%s%s' % (left_side, transform_to_display(content.file_name)),
  906. environ=self.environ,
  907. content=self.content,
  908. content_revision=content,
  909. user=self.user,
  910. session=self.session,
  911. )
  912. )
  913. return members
  914. class FileResource(DAVNonCollection):
  915. """
  916. FileResource resource corresponding to tracim's files
  917. """
  918. def __init__(
  919. self,
  920. path: str,
  921. environ: dict,
  922. content: Content,
  923. user: User,
  924. session: Session,
  925. ) -> None:
  926. super(FileResource, self).__init__(path, environ)
  927. self.content = content
  928. self.user = user
  929. self.session = session
  930. self.content_api = ContentApi(
  931. current_user=self.user,
  932. config=self.provider.app_config,
  933. session=self.session,
  934. )
  935. # this is the property that windows client except to check if the file is read-write or read-only,
  936. # but i wasn't able to set this property so you'll have to look into it >.>
  937. # self.setPropertyValue('Win32FileAttributes', '00000021')
  938. def __repr__(self) -> str:
  939. return "<DAVNonCollection: FileResource (%d)>" % self.content.revision_id
  940. def getContentLength(self) -> int:
  941. return self.content.depot_file.file.content_length
  942. def getContentType(self) -> str:
  943. return self.content.file_mimetype
  944. def getCreationDate(self) -> float:
  945. return mktime(self.content.created.timetuple())
  946. def getDisplayName(self) -> str:
  947. return self.content.file_name
  948. def getLastModified(self) -> float:
  949. return mktime(self.content.updated.timetuple())
  950. def getContent(self) -> typing.BinaryIO:
  951. filestream = compat.BytesIO()
  952. filestream.write(self.content.depot_file.file.read())
  953. filestream.seek(0)
  954. return filestream
  955. def beginWrite(self, contentType: str=None) -> FakeFileStream:
  956. return FakeFileStream(
  957. content=self.content,
  958. content_api=self.content_api,
  959. file_name=self.content.get_label_as_file(),
  960. workspace=self.content.workspace,
  961. path=self.path,
  962. session=self.session,
  963. )
  964. def moveRecursive(self, destpath):
  965. """As we support recursive move, copymovesingle won't be called, though with copy it'll be called
  966. but i have to check if the client ever call that function..."""
  967. destpath = normpath(destpath)
  968. invalid_path = False
  969. # if content is either deleted or archived, we'll check that we try moving it to the parent
  970. # if yes, then we'll unarchive / undelete them, else the action's not allowed
  971. if self.content.is_deleted or self.content.is_archived:
  972. # we remove all archived and deleted from the path and we check to the destpath
  973. # has to be equal or else path not valid
  974. # ex: /a/b/.deleted/resource, to be valid destpath has to be = /a/b/resource (no other solution)
  975. current_path = re.sub(r'/\.(deleted|archived)', '', self.path)
  976. if current_path == destpath:
  977. ManageActions(
  978. action_type=ActionDescription.UNDELETION if self.content.is_deleted else ActionDescription.UNARCHIVING,
  979. api=self.content_api,
  980. content=self.content,
  981. session=self.session,
  982. ).action()
  983. else:
  984. invalid_path = True
  985. # if the content is not deleted / archived, check if we're trying to delete / archive it by
  986. # moving it to a .deleted / .archived folder
  987. elif basename(dirname(destpath)) in ['.deleted', '.archived']:
  988. # same test as above ^
  989. dest_path = re.sub(r'/\.(deleted|archived)', '', destpath)
  990. if dest_path == self.path:
  991. ManageActions(
  992. action_type=ActionDescription.DELETION if '.deleted' in destpath else ActionDescription.ARCHIVING,
  993. api=self.content_api,
  994. content=self.content,
  995. session=self.session,
  996. ).action()
  997. else:
  998. invalid_path = True
  999. # else we check if the path is good (not at the root path / not in a deleted/archived path)
  1000. # and we move the content
  1001. else:
  1002. invalid_path = any(x in destpath for x in ['.deleted', '.archived'])
  1003. invalid_path = invalid_path or any(x in self.path for x in ['.deleted', '.archived'])
  1004. invalid_path = invalid_path or dirname(destpath) == self.environ['http_authenticator.realm']
  1005. if not invalid_path:
  1006. self.move_file(destpath)
  1007. if invalid_path:
  1008. raise DAVError(HTTP_FORBIDDEN)
  1009. def move_file(self, destpath: str) -> None:
  1010. """
  1011. Move file mean changing the path to access to a file. This can mean
  1012. simple renaming(1), moving file from a directory to one another(2)
  1013. but also renaming + moving file from a directory to one another at
  1014. the same time (3).
  1015. (1): move /dir1/file1 -> /dir1/file2
  1016. (2): move /dir1/file1 -> /dir2/file1
  1017. (3): move /dir1/file1 -> /dir2/file2
  1018. :param destpath: destination path of webdav move
  1019. :return: nothing
  1020. """
  1021. workspace = self.content.workspace
  1022. parent = self.content.parent
  1023. with new_revision(
  1024. content=self.content,
  1025. tm=transaction.manager,
  1026. session=self.session,
  1027. ):
  1028. # INFO - G.M - 2018-03-09 - First, renaming file if needed
  1029. if basename(destpath) != self.getDisplayName():
  1030. new_given_file_name = transform_to_bdd(basename(destpath))
  1031. new_file_name, new_file_extension = \
  1032. os.path.splitext(new_given_file_name)
  1033. self.content_api.update_content(
  1034. self.content,
  1035. new_file_name,
  1036. )
  1037. self.content.file_extension = new_file_extension
  1038. self.content_api.save(self.content)
  1039. # INFO - G.M - 2018-03-09 - Moving file if needed
  1040. workspace_api = WorkspaceApi(
  1041. current_user=self.user,
  1042. session=self.session,
  1043. config=self.provider.app_config,
  1044. )
  1045. content_api = ContentApi(
  1046. current_user=self.user,
  1047. session=self.session,
  1048. config=self.provider.app_config
  1049. )
  1050. destination_workspace = self.provider.get_workspace_from_path(
  1051. destpath,
  1052. workspace_api,
  1053. )
  1054. destination_parent = self.provider.get_parent_from_path(
  1055. destpath,
  1056. content_api,
  1057. destination_workspace,
  1058. )
  1059. if destination_parent != parent or destination_workspace != workspace: # nopep8
  1060. # INFO - G.M - 12-03-2018 - Avoid moving the file "at the same place" # nopep8
  1061. # if the request does not result in a real move.
  1062. self.content_api.move(
  1063. item=self.content,
  1064. new_parent=destination_parent,
  1065. must_stay_in_same_workspace=False,
  1066. new_workspace=destination_workspace
  1067. )
  1068. transaction.commit()
  1069. def copyMoveSingle(self, destpath, isMove):
  1070. if isMove:
  1071. # INFO - G.M - 12-03-2018 - This case should not happen
  1072. # As far as moveRecursive method exist, all move should not go
  1073. # through this method. If such case appear, try replace this to :
  1074. ####
  1075. # self.move_file(destpath)
  1076. # return
  1077. ####
  1078. raise NotImplemented
  1079. new_file_name = None
  1080. new_file_extension = None
  1081. # Inspect destpath
  1082. if basename(destpath) != self.getDisplayName():
  1083. new_given_file_name = transform_to_bdd(basename(destpath))
  1084. new_file_name, new_file_extension = \
  1085. os.path.splitext(new_given_file_name)
  1086. workspace_api = WorkspaceApi(
  1087. current_user=self.user,
  1088. session=self.session,
  1089. config=self.provider.app_config,
  1090. )
  1091. content_api = ContentApi(
  1092. current_user=self.user,
  1093. session=self.session,
  1094. config=self.provider.app_config
  1095. )
  1096. destination_workspace = self.provider.get_workspace_from_path(
  1097. destpath,
  1098. workspace_api,
  1099. )
  1100. destination_parent = self.provider.get_parent_from_path(
  1101. destpath,
  1102. content_api,
  1103. destination_workspace,
  1104. )
  1105. workspace = self.content.workspace
  1106. parent = self.content.parent
  1107. new_content = self.content_api.copy(
  1108. item=self.content,
  1109. new_label=new_file_name,
  1110. new_parent=destination_parent,
  1111. )
  1112. self.content_api.copy_children(self.content, new_content)
  1113. transaction.commit()
  1114. def supportRecursiveMove(self, destPath):
  1115. return True
  1116. def delete(self):
  1117. ManageActions(
  1118. action_type=ActionDescription.DELETION,
  1119. api=self.content_api,
  1120. content=self.content,
  1121. session=self.session,
  1122. ).action()
  1123. class HistoryFileResource(FileResource):
  1124. """
  1125. A virtual resource corresponding to a specific tracim's revision's file
  1126. """
  1127. def __init__(self, path: str, environ: dict, content: Content, user: User, session: Session, content_revision: ContentRevisionRO):
  1128. super(HistoryFileResource, self).__init__(path, environ, content, user=user, session=session)
  1129. self.content_revision = content_revision
  1130. def __repr__(self) -> str:
  1131. return "<DAVNonCollection: HistoryFileResource (%s-%s)" % (self.content.content_id, self.content.file_name)
  1132. def getDisplayName(self) -> str:
  1133. left_side = '(%d - %s) ' % (self.content_revision.revision_id, self.content_revision.revision_type)
  1134. return '%s%s' % (left_side, transform_to_display(self.content_revision.file_name))
  1135. def getContent(self):
  1136. filestream = compat.BytesIO()
  1137. filestream.write(self.content_revision.depot_file.file.read())
  1138. filestream.seek(0)
  1139. return filestream
  1140. def getContentLength(self):
  1141. return self.content_revision.depot_file.file.content_length
  1142. def getContentType(self) -> str:
  1143. return self.content_revision.file_mimetype
  1144. def beginWrite(self, contentType=None):
  1145. raise DAVError(HTTP_FORBIDDEN)
  1146. def delete(self):
  1147. raise DAVError(HTTP_FORBIDDEN)
  1148. def copyMoveSingle(self, destpath, ismove):
  1149. raise DAVError(HTTP_FORBIDDEN)
  1150. class OtherFileResource(FileResource):
  1151. """
  1152. FileResource resource corresponding to tracim's page and thread
  1153. """
  1154. def __init__(self, path: str, environ: dict, content: Content, user:User, session: Session):
  1155. super(OtherFileResource, self).__init__(path, environ, content, user=user, session=session)
  1156. self.content_revision = self.content.revision
  1157. self.content_designed = self.design()
  1158. # workaround for consistent request as we have to return a resource with a path ending with .html
  1159. # when entering folder for windows, but only once because when we select it again it would have .html.html
  1160. # which is no good
  1161. if not self.path.endswith('.html'):
  1162. self.path += '.html'
  1163. def getDisplayName(self) -> str:
  1164. return self.content.get_label_as_file()
  1165. def getPreferredPath(self):
  1166. return self.path
  1167. def __repr__(self) -> str:
  1168. return "<DAVNonCollection: OtherFileResource (%s)" % self.content.file_name
  1169. def getContentLength(self) -> int:
  1170. return len(self.content_designed)
  1171. def getContentType(self) -> str:
  1172. return 'text/html'
  1173. def getContent(self):
  1174. filestream = compat.BytesIO()
  1175. filestream.write(bytes(self.content_designed, 'utf-8'))
  1176. filestream.seek(0)
  1177. return filestream
  1178. def design(self):
  1179. if self.content.type == CONTENT_TYPES.Page.slug:
  1180. return designPage(self.content, self.content_revision)
  1181. else:
  1182. return designThread(
  1183. self.content,
  1184. self.content_revision,
  1185. self.content_api.get_all(self.content.content_id, CONTENT_TYPES.Comment.slug)
  1186. )
  1187. class HistoryOtherFile(OtherFileResource):
  1188. """
  1189. A virtual resource corresponding to a specific tracim's revision's page and thread
  1190. """
  1191. def __init__(self,
  1192. path: str,
  1193. environ: dict,
  1194. content: Content,
  1195. user:User,
  1196. content_revision: ContentRevisionRO,
  1197. session: Session):
  1198. super(HistoryOtherFile, self).__init__(
  1199. path,
  1200. environ,
  1201. content,
  1202. user=user,
  1203. session=session
  1204. )
  1205. self.content_revision = content_revision
  1206. self.content_designed = self.design()
  1207. def __repr__(self) -> str:
  1208. return "<DAVNonCollection: HistoryOtherFile (%s-%s)" % (self.content.file_name, self.content.id)
  1209. def getDisplayName(self) -> str:
  1210. left_side = '(%d - %s) ' % (self.content_revision.revision_id, self.content_revision.revision_type)
  1211. return '%s%s' % (left_side, transform_to_display(self.content_revision.get_label_as_file()))
  1212. def getContent(self):
  1213. filestream = compat.BytesIO()
  1214. filestream.write(bytes(self.content_designed, 'utf-8'))
  1215. filestream.seek(0)
  1216. return filestream
  1217. def delete(self):
  1218. raise DAVError(HTTP_FORBIDDEN)
  1219. def copyMoveSingle(self, destpath, ismove):
  1220. raise DAVError(HTTP_FORBIDDEN)