resources.py 49KB

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