resources.py 50KB

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