resources.py 50KB

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