resources.py 50KB

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