resources.py 45KB

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