resources.py 45KB

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