content.py 45KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252
  1. # -*- coding: utf-8 -*-
  2. from contextlib import contextmanager
  3. import os
  4. from operator import itemgetter
  5. import transaction
  6. from sqlalchemy import func
  7. from sqlalchemy.orm import Query
  8. __author__ = 'damien'
  9. import datetime
  10. import re
  11. import typing
  12. from tracim.lib.utils.translation import fake_translator as _
  13. from depot.manager import DepotManager
  14. from depot.io.utils import FileIntent
  15. import sqlalchemy
  16. from sqlalchemy.orm import aliased
  17. from sqlalchemy.orm import joinedload
  18. from sqlalchemy.orm.attributes import get_history
  19. from sqlalchemy.orm.session import Session
  20. from sqlalchemy import desc
  21. from sqlalchemy import distinct
  22. from sqlalchemy import or_
  23. from sqlalchemy.sql.elements import and_
  24. from tracim.lib.utils.utils import cmp_to_key
  25. from tracim.lib.core.notifications import NotifierFactory
  26. from tracim.exceptions import SameValueError
  27. from tracim.lib.utils.utils import current_date_for_filename
  28. from tracim.models.revision_protection import new_revision
  29. from tracim.models.auth import User
  30. from tracim.models.data import ActionDescription
  31. from tracim.models.data import ContentStatus
  32. from tracim.models.data import ContentRevisionRO
  33. from tracim.models.data import Content
  34. from tracim.models.data import ContentType
  35. from tracim.models.data import NodeTreeItem
  36. from tracim.models.data import RevisionReadStatus
  37. from tracim.models.data import UserRoleInWorkspace
  38. from tracim.models.data import Workspace
  39. def compare_content_for_sorting_by_type_and_name(
  40. content1: Content,
  41. content2: Content
  42. ) -> int:
  43. """
  44. :param content1:
  45. :param content2:
  46. :return: 1 if content1 > content2
  47. -1 if content1 < content2
  48. 0 if content1 = content2
  49. """
  50. if content1.type == content2.type:
  51. if content1.get_label().lower()>content2.get_label().lower():
  52. return 1
  53. elif content1.get_label().lower()<content2.get_label().lower():
  54. return -1
  55. return 0
  56. else:
  57. # TODO - D.A. - 2014-12-02 - Manage Content Types Dynamically
  58. content_type_order = [
  59. ContentType.Folder,
  60. ContentType.Page,
  61. ContentType.Thread,
  62. ContentType.File,
  63. ]
  64. content_1_type_index = content_type_order.index(content1.type)
  65. content_2_type_index = content_type_order.index(content2.type)
  66. result = content_1_type_index - content_2_type_index
  67. if result < 0:
  68. return -1
  69. elif result > 0:
  70. return 1
  71. else:
  72. return 0
  73. def compare_tree_items_for_sorting_by_type_and_name(
  74. item1: NodeTreeItem,
  75. item2: NodeTreeItem
  76. ) -> int:
  77. return compare_content_for_sorting_by_type_and_name(item1.node, item2.node)
  78. class ContentApi(object):
  79. SEARCH_SEPARATORS = ',| '
  80. SEARCH_DEFAULT_RESULT_NB = 50
  81. DISPLAYABLE_CONTENTS = (
  82. ContentType.Folder,
  83. ContentType.File,
  84. ContentType.Comment,
  85. ContentType.Thread,
  86. ContentType.Page,
  87. )
  88. def __init__(
  89. self,
  90. session: Session,
  91. current_user: typing.Optional[User],
  92. config,
  93. show_archived: bool = False,
  94. show_deleted: bool = False,
  95. show_temporary: bool = False,
  96. all_content_in_treeview: bool = True,
  97. force_show_all_types: bool = False,
  98. disable_user_workspaces_filter: bool = False,
  99. ) -> None:
  100. self._session = session
  101. self._user = current_user
  102. self._config = config
  103. self._user_id = current_user.user_id if current_user else None
  104. self._show_archived = show_archived
  105. self._show_deleted = show_deleted
  106. self._show_temporary = show_temporary
  107. self._show_all_type_of_contents_in_treeview = all_content_in_treeview
  108. self._force_show_all_types = force_show_all_types
  109. self._disable_user_workspaces_filter = disable_user_workspaces_filter
  110. @contextmanager
  111. def show(
  112. self,
  113. show_archived: bool=False,
  114. show_deleted: bool=False,
  115. show_temporary: bool=False,
  116. ) -> typing.Generator['ContentApi', None, None]:
  117. """
  118. Use this method as context manager to update show_archived,
  119. show_deleted and show_temporary properties during context.
  120. :param show_archived: show archived contents
  121. :param show_deleted: show deleted contents
  122. :param show_temporary: show temporary contents
  123. """
  124. previous_show_archived = self._show_archived
  125. previous_show_deleted = self._show_deleted
  126. previous_show_temporary = self._show_temporary
  127. try:
  128. self._show_archived = show_archived
  129. self._show_deleted = show_deleted
  130. self._show_temporary = show_temporary
  131. yield self
  132. finally:
  133. self._show_archived = previous_show_archived
  134. self._show_deleted = previous_show_deleted
  135. self._show_temporary = previous_show_temporary
  136. def get_revision_join(self) -> sqlalchemy.sql.elements.BooleanClauseList:
  137. """
  138. Return the Content/ContentRevision query join condition
  139. :return: Content/ContentRevision query join condition
  140. """
  141. return and_(Content.id == ContentRevisionRO.content_id,
  142. ContentRevisionRO.revision_id == self._session.query(
  143. ContentRevisionRO.revision_id)
  144. .filter(ContentRevisionRO.content_id == Content.id)
  145. .order_by(ContentRevisionRO.revision_id.desc())
  146. .limit(1)
  147. .correlate(Content))
  148. def get_canonical_query(self) -> Query:
  149. """
  150. Return the Content/ContentRevision base query who join these table on the last revision.
  151. :return: Content/ContentRevision Query
  152. """
  153. return self._session.query(Content)\
  154. .join(ContentRevisionRO, self.get_revision_join())
  155. @classmethod
  156. def sort_tree_items(
  157. cls,
  158. content_list: typing.List[NodeTreeItem],
  159. )-> typing.List[NodeTreeItem]:
  160. news = []
  161. for item in content_list:
  162. news.append(item)
  163. content_list.sort(key=cmp_to_key(
  164. compare_tree_items_for_sorting_by_type_and_name,
  165. ))
  166. return content_list
  167. @classmethod
  168. def sort_content(
  169. cls,
  170. content_list: typing.List[Content],
  171. ) -> typing.List[Content]:
  172. content_list.sort(key=cmp_to_key(compare_content_for_sorting_by_type_and_name))
  173. return content_list
  174. def __real_base_query(
  175. self,
  176. workspace: Workspace = None,
  177. ) -> Query:
  178. result = self.get_canonical_query()
  179. # Exclude non displayable types
  180. if not self._force_show_all_types:
  181. result = result.filter(Content.type.in_(self.DISPLAYABLE_CONTENTS))
  182. if workspace:
  183. result = result.filter(Content.workspace_id == workspace.workspace_id)
  184. # Security layer: if user provided, filter
  185. # with user workspaces privileges
  186. if self._user and not self._disable_user_workspaces_filter:
  187. user = self._session.query(User).get(self._user_id)
  188. # Filter according to user workspaces
  189. workspace_ids = [r.workspace_id for r in user.roles \
  190. if r.role>=UserRoleInWorkspace.READER]
  191. result = result.filter(or_(
  192. Content.workspace_id.in_(workspace_ids),
  193. # And allow access to non workspace document when he is owner
  194. and_(
  195. Content.workspace_id == None,
  196. Content.owner_id == self._user_id,
  197. )
  198. ))
  199. return result
  200. def _base_query(self, workspace: Workspace=None) -> Query:
  201. result = self.__real_base_query(workspace)
  202. if not self._show_deleted:
  203. result = result.filter(Content.is_deleted==False)
  204. if not self._show_archived:
  205. result = result.filter(Content.is_archived==False)
  206. if not self._show_temporary:
  207. result = result.filter(Content.is_temporary==False)
  208. return result
  209. def __revisions_real_base_query(
  210. self,
  211. workspace: Workspace=None,
  212. ) -> Query:
  213. result = self._session.query(ContentRevisionRO)
  214. # Exclude non displayable types
  215. if not self._force_show_all_types:
  216. result = result.filter(Content.type.in_(self.DISPLAYABLE_CONTENTS))
  217. if workspace:
  218. result = result.filter(ContentRevisionRO.workspace_id==workspace.workspace_id)
  219. if self._user:
  220. user = self._session.query(User).get(self._user_id)
  221. # Filter according to user workspaces
  222. workspace_ids = [r.workspace_id for r in user.roles \
  223. if r.role>=UserRoleInWorkspace.READER]
  224. result = result.filter(ContentRevisionRO.workspace_id.in_(workspace_ids))
  225. return result
  226. def _revisions_base_query(
  227. self,
  228. workspace: Workspace=None,
  229. ) -> Query:
  230. result = self.__revisions_real_base_query(workspace)
  231. if not self._show_deleted:
  232. result = result.filter(ContentRevisionRO.is_deleted==False)
  233. if not self._show_archived:
  234. result = result.filter(ContentRevisionRO.is_archived==False)
  235. if not self._show_temporary:
  236. result = result.filter(Content.is_temporary==False)
  237. return result
  238. def _hard_filtered_base_query(
  239. self,
  240. workspace: Workspace=None,
  241. ) -> Query:
  242. """
  243. If set to True, then filterign on is_deleted and is_archived will also
  244. filter parent properties. This is required for search() function which
  245. also search in comments (for example) which may be 'not deleted' while
  246. the associated content is deleted
  247. :param hard_filtering:
  248. :return:
  249. """
  250. result = self.__real_base_query(workspace)
  251. if not self._show_deleted:
  252. parent = aliased(Content)
  253. result = result.join(parent, Content.parent).\
  254. filter(Content.is_deleted==False).\
  255. filter(parent.is_deleted==False)
  256. if not self._show_archived:
  257. parent = aliased(Content)
  258. result = result.join(parent, Content.parent).\
  259. filter(Content.is_archived==False).\
  260. filter(parent.is_archived==False)
  261. if not self._show_temporary:
  262. parent = aliased(Content)
  263. result = result.join(parent, Content.parent). \
  264. filter(Content.is_temporary == False). \
  265. filter(parent.is_temporary == False)
  266. return result
  267. def get_base_query(
  268. self,
  269. workspace: Workspace,
  270. ) -> Query:
  271. return self._base_query(workspace)
  272. def get_child_folders(self, parent: Content=None, workspace: Workspace=None, filter_by_allowed_content_types: list=[], removed_item_ids: list=[], allowed_node_types=None) -> typing.List[Content]:
  273. """
  274. This method returns child items (folders or items) for left bar treeview.
  275. :param parent:
  276. :param workspace:
  277. :param filter_by_allowed_content_types:
  278. :param removed_item_ids:
  279. :param allowed_node_types: This parameter allow to hide folders for which the given type of content is not allowed.
  280. For example, if you want to move a Page from a folder to another, you should show only folders that accept pages
  281. :return:
  282. """
  283. filter_by_allowed_content_types = filter_by_allowed_content_types or [] # FDV
  284. removed_item_ids = removed_item_ids or [] # FDV
  285. if not allowed_node_types:
  286. allowed_node_types = [ContentType.Folder]
  287. elif allowed_node_types==ContentType.Any:
  288. allowed_node_types = ContentType.all()
  289. parent_id = parent.content_id if parent else None
  290. folders = self._base_query(workspace).\
  291. filter(Content.parent_id==parent_id).\
  292. filter(Content.type.in_(allowed_node_types)).\
  293. filter(Content.content_id.notin_(removed_item_ids)).\
  294. all()
  295. if not filter_by_allowed_content_types or \
  296. len(filter_by_allowed_content_types)<=0:
  297. # Standard case for the left treeview: we want to show all contents
  298. # in the left treeview... so we still filter because for example
  299. # comments must not appear in the treeview
  300. return [folder for folder in folders \
  301. if folder.type in ContentType.allowed_types_for_folding()]
  302. # Now this is a case of Folders only (used for moving content)
  303. # When moving a content, you must get only folders that allow to be filled
  304. # with the type of content you want to move
  305. result = []
  306. for folder in folders:
  307. for allowed_content_type in filter_by_allowed_content_types:
  308. is_folder = folder.type == ContentType.Folder
  309. content_type__allowed = folder.properties['allowed_content'][allowed_content_type] == True
  310. if is_folder and content_type__allowed:
  311. result.append(folder)
  312. break
  313. return result
  314. def create(self, content_type: str, workspace: Workspace, parent: Content=None, label:str ='', do_save=False, is_temporary: bool=False, do_notify=True) -> Content:
  315. assert content_type in ContentType.allowed_types()
  316. if content_type == ContentType.Folder and not label:
  317. label = self.generate_folder_label(workspace, parent)
  318. content = Content()
  319. content.owner = self._user
  320. content.parent = parent
  321. content.workspace = workspace
  322. content.type = content_type
  323. content.label = label
  324. content.is_temporary = is_temporary
  325. content.revision_type = ActionDescription.CREATION
  326. if content.type in (
  327. ContentType.Page,
  328. ContentType.Thread,
  329. ):
  330. content.file_extension = '.html'
  331. if do_save:
  332. self._session.add(content)
  333. self.save(content, ActionDescription.CREATION, do_notify=do_notify)
  334. return content
  335. def create_comment(self, workspace: Workspace=None, parent: Content=None, content:str ='', do_save=False) -> Content:
  336. assert parent and parent.type!=ContentType.Folder
  337. item = Content()
  338. item.owner = self._user
  339. item.parent = parent
  340. item.workspace = workspace
  341. item.type = ContentType.Comment
  342. item.description = content
  343. item.label = ''
  344. item.revision_type = ActionDescription.COMMENT
  345. if do_save:
  346. self.save(item, ActionDescription.COMMENT)
  347. return item
  348. def get_one_from_revision(self, content_id: int, content_type: str, workspace: Workspace=None, revision_id=None) -> Content:
  349. """
  350. This method is a hack to convert a node revision item into a node
  351. :param content_id:
  352. :param content_type:
  353. :param workspace:
  354. :param revision_id:
  355. :return:
  356. """
  357. content = self.get_one(content_id, content_type, workspace)
  358. revision = self._session.query(ContentRevisionRO).filter(ContentRevisionRO.revision_id==revision_id).one()
  359. if revision.content_id==content.content_id:
  360. content.revision_to_serialize = revision.revision_id
  361. else:
  362. raise ValueError('Revision not found for given content')
  363. return content
  364. def get_one(self, content_id: int, content_type: str, workspace: Workspace=None) -> Content:
  365. if not content_id:
  366. return None
  367. if content_type==ContentType.Any:
  368. return self._base_query(workspace).filter(Content.content_id==content_id).one()
  369. return self._base_query(workspace).filter(Content.content_id==content_id).filter(Content.type==content_type).one()
  370. def get_one_revision(self, revision_id: int = None) -> ContentRevisionRO:
  371. """
  372. This method allow us to get directly any revision with its id
  373. :param revision_id: The content's revision's id that we want to return
  374. :return: An item Content linked with the correct revision
  375. """
  376. assert revision_id is not None# DYN_REMOVE
  377. revision = self._session.query(ContentRevisionRO).filter(ContentRevisionRO.revision_id == revision_id).one()
  378. return revision
  379. # INFO - A.P - 2017-07-03 - python file object getter
  380. # in case of we cook a version of preview manager that allows a pythonic
  381. # access to files
  382. # def get_one_revision_file(self, revision_id: int = None):
  383. # """
  384. # This function allows us to directly get a Python file object from its
  385. # revision identifier.
  386. # :param revision_id: The revision id of the file we want to return
  387. # :return: The corresponding Python file object
  388. # """
  389. # revision = self.get_one_revision(revision_id)
  390. # return DepotManager.get().get(revision.depot_file)
  391. def get_one_revision_filepath(self, revision_id: int = None) -> str:
  392. """
  393. This method allows us to directly get a file path from its revision
  394. identifier.
  395. :param revision_id: The revision id of the filepath we want to return
  396. :return: The corresponding filepath
  397. """
  398. revision = self.get_one_revision(revision_id)
  399. depot = DepotManager.get()
  400. depot_stored_file = depot.get(revision.depot_file) # type: StoredFile
  401. depot_file_path = depot_stored_file._file_path # type: str
  402. return depot_file_path
  403. def get_one_by_label_and_parent(
  404. self,
  405. content_label: str,
  406. content_parent: Content=None,
  407. ) -> Content:
  408. """
  409. This method let us request the database to obtain a Content with its name and parent
  410. :param content_label: Either the content's label or the content's filename if the label is None
  411. :param content_parent: The parent's content
  412. :param workspace: The workspace's content
  413. :return The corresponding Content
  414. """
  415. workspace = content_parent.workspace if content_parent else None
  416. query = self._base_query(workspace)
  417. parent_id = content_parent.content_id if content_parent else None
  418. query = query.filter(Content.parent_id == parent_id)
  419. file_name, file_extension = os.path.splitext(content_label)
  420. return query.filter(
  421. or_(
  422. and_(
  423. Content.type == ContentType.File,
  424. Content.label == file_name,
  425. Content.file_extension == file_extension,
  426. ),
  427. and_(
  428. Content.type == ContentType.Thread,
  429. Content.label == file_name,
  430. ),
  431. and_(
  432. Content.type == ContentType.Page,
  433. Content.label == file_name,
  434. ),
  435. and_(
  436. Content.type == ContentType.Folder,
  437. Content.label == content_label,
  438. ),
  439. )
  440. ).one()
  441. def get_one_by_label_and_parent_labels(
  442. self,
  443. content_label: str,
  444. workspace: Workspace,
  445. content_parent_labels: [str]=None,
  446. ):
  447. """
  448. Return content with it's label, workspace and parents labels (optional)
  449. :param content_label: label of content (label or file_name)
  450. :param workspace: workspace containing all of this
  451. :param content_parent_labels: Ordered list of labels representing path
  452. of folder (without workspace label).
  453. E.g.: ['foo', 'bar'] for complete path /Workspace1/foo/bar folder
  454. :return: Found Content
  455. """
  456. query = self._base_query(workspace)
  457. parent_folder = None
  458. # Grab content parent folder if parent path given
  459. if content_parent_labels:
  460. parent_folder = self.get_folder_with_workspace_path_labels(
  461. content_parent_labels,
  462. workspace,
  463. )
  464. # Build query for found content by label
  465. content_query = self.filter_query_for_content_label_as_path(
  466. query=query,
  467. content_label_as_file=content_label,
  468. )
  469. # Modify query to apply parent folder filter if any
  470. if parent_folder:
  471. content_query = content_query.filter(
  472. Content.parent_id == parent_folder.content_id,
  473. )
  474. else:
  475. content_query = content_query.filter(
  476. Content.parent_id == None,
  477. )
  478. # Filter with workspace
  479. content_query = content_query.filter(
  480. Content.workspace_id == workspace.workspace_id,
  481. )
  482. # Return the content
  483. return content_query\
  484. .order_by(
  485. Content.revision_id.desc(),
  486. )\
  487. .one()
  488. def get_folder_with_workspace_path_labels(
  489. self,
  490. path_labels: [str],
  491. workspace: Workspace,
  492. ) -> Content:
  493. """
  494. Return a Content folder for given relative path.
  495. TODO BS 20161124: Not safe if web interface allow folder duplicate names
  496. :param path_labels: List of labels representing path of folder
  497. (without workspace label).
  498. E.g.: ['foo', 'bar'] for complete path /Workspace1/foo/bar folder
  499. :param workspace: workspace of folders
  500. :return: Content folder
  501. """
  502. query = self._base_query(workspace)
  503. folder = None
  504. for label in path_labels:
  505. # Filter query on label
  506. folder_query = query \
  507. .filter(
  508. Content.type == ContentType.Folder,
  509. Content.label == label,
  510. Content.workspace_id == workspace.workspace_id,
  511. )
  512. # Search into parent folder (if already deep)
  513. if folder:
  514. folder_query = folder_query\
  515. .filter(
  516. Content.parent_id == folder.content_id,
  517. )
  518. else:
  519. folder_query = folder_query \
  520. .filter(Content.parent_id == None)
  521. # Get thirst corresponding folder
  522. folder = folder_query \
  523. .order_by(Content.revision_id.desc()) \
  524. .one()
  525. return folder
  526. def filter_query_for_content_label_as_path(
  527. self,
  528. query: Query,
  529. content_label_as_file: str,
  530. is_case_sensitive: bool = False,
  531. ) -> Query:
  532. """
  533. Apply normalised filters to found Content corresponding as given label.
  534. :param query: query to modify
  535. :param content_label_as_file: label in this
  536. FILE version, use Content.get_label_as_file().
  537. :param is_case_sensitive: Take care about case or not
  538. :return: modified query
  539. """
  540. file_name, file_extension = os.path.splitext(content_label_as_file)
  541. label_filter = Content.label == content_label_as_file
  542. file_name_filter = Content.label == file_name
  543. file_extension_filter = Content.file_extension == file_extension
  544. if not is_case_sensitive:
  545. label_filter = func.lower(Content.label) == \
  546. func.lower(content_label_as_file)
  547. file_name_filter = func.lower(Content.label) == \
  548. func.lower(file_name)
  549. file_extension_filter = func.lower(Content.file_extension) == \
  550. func.lower(file_extension)
  551. return query.filter(or_(
  552. and_(
  553. Content.type == ContentType.File,
  554. file_name_filter,
  555. file_extension_filter,
  556. ),
  557. and_(
  558. Content.type == ContentType.Thread,
  559. file_name_filter,
  560. file_extension_filter,
  561. ),
  562. and_(
  563. Content.type == ContentType.Page,
  564. file_name_filter,
  565. file_extension_filter,
  566. ),
  567. and_(
  568. Content.type == ContentType.Folder,
  569. label_filter,
  570. ),
  571. ))
  572. def get_all(self, parent_id: int=None, content_type: str=ContentType.Any, workspace: Workspace=None) -> typing.List[Content]:
  573. assert parent_id is None or isinstance(parent_id, int) # DYN_REMOVE
  574. assert content_type is not None# DYN_REMOVE
  575. assert isinstance(content_type, str) # DYN_REMOVE
  576. resultset = self._base_query(workspace)
  577. if content_type!=ContentType.Any:
  578. resultset = resultset.filter(Content.type==content_type)
  579. if parent_id:
  580. resultset = resultset.filter(Content.parent_id==parent_id)
  581. if parent_id is False:
  582. resultset = resultset.filter(Content.parent_id == None)
  583. return resultset.all()
  584. def get_children(self, parent_id: int, content_types: list, workspace: Workspace=None) -> typing.List[Content]:
  585. """
  586. Return parent_id childs of given content_types
  587. :param parent_id: parent id
  588. :param content_types: list of types
  589. :param workspace: workspace filter
  590. :return: list of content
  591. """
  592. resultset = self._base_query(workspace)
  593. resultset = resultset.filter(Content.type.in_(content_types))
  594. if parent_id:
  595. resultset = resultset.filter(Content.parent_id==parent_id)
  596. if parent_id is False:
  597. resultset = resultset.filter(Content.parent_id == None)
  598. return resultset.all()
  599. # TODO find an other name to filter on is_deleted / is_archived
  600. def get_all_with_filter(self, parent_id: int=None, content_type: str=ContentType.Any, workspace: Workspace=None) -> typing.List[Content]:
  601. assert parent_id is None or isinstance(parent_id, int) # DYN_REMOVE
  602. assert content_type is not None# DYN_REMOVE
  603. assert isinstance(content_type, str) # DYN_REMOVE
  604. resultset = self._base_query(workspace)
  605. if content_type != ContentType.Any:
  606. resultset = resultset.filter(Content.type==content_type)
  607. resultset = resultset.filter(Content.is_deleted == self._show_deleted)
  608. resultset = resultset.filter(Content.is_archived == self._show_archived)
  609. resultset = resultset.filter(Content.is_temporary == self._show_temporary)
  610. resultset = resultset.filter(Content.parent_id==parent_id)
  611. return resultset.all()
  612. def get_all_without_exception(self, content_type: str, workspace: Workspace=None) -> typing.List[Content]:
  613. assert content_type is not None# DYN_REMOVE
  614. resultset = self._base_query(workspace)
  615. if content_type != ContentType.Any:
  616. resultset = resultset.filter(Content.type==content_type)
  617. return resultset.all()
  618. def get_last_active(self, parent_id: int, content_type: str, workspace: Workspace=None, limit=10) -> typing.List[Content]:
  619. assert parent_id is None or isinstance(parent_id, int) # DYN_REMOVE
  620. assert content_type is not None# DYN_REMOVE
  621. assert isinstance(content_type, str) # DYN_REMOVE
  622. resultset = self._base_query(workspace) \
  623. .filter(Content.workspace_id == Workspace.workspace_id) \
  624. .filter(Workspace.is_deleted.is_(False)) \
  625. .order_by(desc(Content.updated))
  626. if content_type!=ContentType.Any:
  627. resultset = resultset.filter(Content.type==content_type)
  628. if parent_id:
  629. resultset = resultset.filter(Content.parent_id==parent_id)
  630. result = []
  631. for item in resultset:
  632. new_item = None
  633. if ContentType.Comment == item.type:
  634. new_item = item.parent
  635. else:
  636. new_item = item
  637. # INFO - D.A. - 2015-05-20
  638. # We do not want to show only one item if the last 10 items are
  639. # comments about one thread for example
  640. if new_item not in result:
  641. result.append(new_item)
  642. if len(result) >= limit:
  643. break
  644. return result
  645. def get_last_unread(self, parent_id: int, content_type: str,
  646. workspace: Workspace=None, limit=10) -> typing.List[Content]:
  647. assert parent_id is None or isinstance(parent_id, int) # DYN_REMOVE
  648. assert content_type is not None# DYN_REMOVE
  649. assert isinstance(content_type, str) # DYN_REMOVE
  650. read_revision_ids = self._session.query(RevisionReadStatus.revision_id) \
  651. .filter(RevisionReadStatus.user_id==self._user_id)
  652. not_read_revisions = self._revisions_base_query(workspace) \
  653. .filter(~ContentRevisionRO.revision_id.in_(read_revision_ids)) \
  654. .filter(ContentRevisionRO.workspace_id == Workspace.workspace_id) \
  655. .filter(Workspace.is_deleted.is_(False)) \
  656. .subquery()
  657. not_read_content_ids_query = self._session.query(
  658. distinct(not_read_revisions.c.content_id)
  659. )
  660. not_read_content_ids = list(map(
  661. itemgetter(0),
  662. not_read_content_ids_query,
  663. ))
  664. not_read_contents = self._base_query(workspace) \
  665. .filter(Content.content_id.in_(not_read_content_ids)) \
  666. .order_by(desc(Content.updated))
  667. if content_type != ContentType.Any:
  668. not_read_contents = not_read_contents.filter(
  669. Content.type==content_type)
  670. else:
  671. not_read_contents = not_read_contents.filter(
  672. Content.type!=ContentType.Folder)
  673. if parent_id:
  674. not_read_contents = not_read_contents.filter(
  675. Content.parent_id==parent_id)
  676. result = []
  677. for item in not_read_contents:
  678. new_item = None
  679. if ContentType.Comment == item.type:
  680. new_item = item.parent
  681. else:
  682. new_item = item
  683. # INFO - D.A. - 2015-05-20
  684. # We do not want to show only one item if the last 10 items are
  685. # comments about one thread for example
  686. if new_item not in result:
  687. result.append(new_item)
  688. if len(result) >= limit:
  689. break
  690. return result
  691. def set_allowed_content(self, folder: Content, allowed_content_dict:dict):
  692. """
  693. :param folder: the given folder instance
  694. :param allowed_content_dict: must be something like this:
  695. dict(
  696. folder = True
  697. thread = True,
  698. file = False,
  699. page = True
  700. )
  701. :return:
  702. """
  703. properties = dict(allowed_content = allowed_content_dict)
  704. folder.properties = properties
  705. def set_status(self, content: Content, new_status: str):
  706. if new_status in ContentStatus.allowed_values():
  707. content.status = new_status
  708. content.revision_type = ActionDescription.STATUS_UPDATE
  709. else:
  710. raise ValueError('The given value {} is not allowed'.format(new_status))
  711. def move(self, item: Content,
  712. new_parent: Content,
  713. must_stay_in_same_workspace:bool=True,
  714. new_workspace:Workspace=None):
  715. if must_stay_in_same_workspace:
  716. if new_parent and new_parent.workspace_id != item.workspace_id:
  717. raise ValueError('the item should stay in the same workspace')
  718. item.parent = new_parent
  719. if new_parent:
  720. item.workspace = new_parent.workspace
  721. elif new_workspace:
  722. item.workspace = new_workspace
  723. item.revision_type = ActionDescription.MOVE
  724. def copy(
  725. self,
  726. item: Content,
  727. new_parent: Content=None,
  728. new_label: str=None,
  729. do_save: bool=True,
  730. do_notify: bool=True,
  731. ) -> Content:
  732. """
  733. Copy nearly all content, revision included. Children not included, see
  734. "copy_children" for this.
  735. :param item: Item to copy
  736. :param new_parent: new parent of the new copied item
  737. :param new_label: new label of the new copied item
  738. :param do_notify: notify copy or not
  739. :return: Newly copied item
  740. """
  741. if (not new_parent and not new_label) or (new_parent == item.parent and new_label == item.label): # nopep8
  742. # TODO - G.M - 08-03-2018 - Use something else than value error
  743. raise ValueError("You can't copy file into itself")
  744. if new_parent:
  745. workspace = new_parent.workspace
  746. parent = new_parent
  747. else:
  748. workspace = item.workspace
  749. parent = item.parent
  750. label = new_label or item.label
  751. content = item.copy(parent)
  752. # INFO - GM - 15-03-2018 - add "copy" revision
  753. with new_revision(
  754. session=self._session,
  755. tm=transaction.manager,
  756. content=content,
  757. force_create_new_revision=True
  758. ) as rev:
  759. rev.parent = parent
  760. rev.workspace = workspace
  761. rev.label = label
  762. rev.revision_type = ActionDescription.COPY
  763. rev.properties['origin'] = {
  764. 'content': item.id,
  765. 'revision': item.last_revision.revision_id,
  766. }
  767. if do_save:
  768. self.save(content, ActionDescription.COPY, do_notify=do_notify)
  769. return content
  770. def copy_children(self, origin_content: Content, new_content: Content):
  771. for child in origin_content.children:
  772. self.copy(child, new_content)
  773. def move_recursively(self, item: Content,
  774. new_parent: Content, new_workspace: Workspace):
  775. self.move(item, new_parent, False, new_workspace)
  776. self.save(item, do_notify=False)
  777. for child in item.children:
  778. with new_revision(child):
  779. self.move_recursively(child, item, new_workspace)
  780. return
  781. def update_content(self, item: Content, new_label: str, new_content: str=None) -> Content:
  782. if item.label==new_label and item.description==new_content:
  783. # TODO - G.M - 20-03-2018 - Fix internatization for webdav access.
  784. # Internatization disabled in libcontent for now.
  785. raise SameValueError('The content did not changed')
  786. item.owner = self._user
  787. item.label = new_label
  788. item.description = new_content if new_content else item.description # TODO: convert urls into links
  789. item.revision_type = ActionDescription.EDITION
  790. return item
  791. def update_file_data(self, item: Content, new_filename: str, new_mimetype: str, new_content: bytes) -> Content:
  792. if new_mimetype == item.file_mimetype and \
  793. new_content == item.depot_file.file.read():
  794. raise SameValueError('The content did not changed')
  795. item.owner = self._user
  796. item.file_name = new_filename
  797. item.file_mimetype = new_mimetype
  798. item.depot_file = FileIntent(
  799. new_content,
  800. new_filename,
  801. new_mimetype,
  802. )
  803. item.revision_type = ActionDescription.REVISION
  804. return item
  805. def archive(self, content: Content):
  806. content.owner = self._user
  807. content.is_archived = True
  808. # TODO - G.M - 12-03-2018 - Inspect possible label conflict problem
  809. # INFO - G.M - 12-03-2018 - Set label name to avoid trouble when
  810. # un-archiving file.
  811. content.label = '{label}-{action}-{date}'.format(
  812. label=content.label,
  813. action='archived',
  814. date=current_date_for_filename()
  815. )
  816. content.revision_type = ActionDescription.ARCHIVING
  817. def unarchive(self, content: Content):
  818. content.owner = self._user
  819. content.is_archived = False
  820. content.revision_type = ActionDescription.UNARCHIVING
  821. def delete(self, content: Content):
  822. content.owner = self._user
  823. content.is_deleted = True
  824. # TODO - G.M - 12-03-2018 - Inspect possible label conflict problem
  825. # INFO - G.M - 12-03-2018 - Set label name to avoid trouble when
  826. # un-deleting file.
  827. content.label = '{label}-{action}-{date}'.format(
  828. label=content.label,
  829. action='deleted',
  830. date=current_date_for_filename()
  831. )
  832. content.revision_type = ActionDescription.DELETION
  833. def undelete(self, content: Content):
  834. content.owner = self._user
  835. content.is_deleted = False
  836. content.revision_type = ActionDescription.UNDELETION
  837. def mark_read__all(self,
  838. read_datetime: datetime=None,
  839. do_flush: bool=True,
  840. recursive: bool=True
  841. ):
  842. itemset = self.get_last_unread(None, ContentType.Any)
  843. for item in itemset:
  844. self.mark_read(item, read_datetime, do_flush, recursive)
  845. def mark_read__workspace(self,
  846. workspace : Workspace,
  847. read_datetime: datetime=None,
  848. do_flush: bool=True,
  849. recursive: bool=True
  850. ):
  851. itemset = self.get_last_unread(None, ContentType.Any, workspace)
  852. for item in itemset:
  853. self.mark_read(item, read_datetime, do_flush, recursive)
  854. def mark_read(self, content: Content,
  855. read_datetime: datetime=None,
  856. do_flush: bool=True, recursive: bool=True) -> Content:
  857. assert self._user
  858. assert content
  859. # The algorithm is:
  860. # 1. define the read datetime
  861. # 2. update all revisions related to current Content
  862. # 3. do the same for all child revisions
  863. # (ie parent_id is content_id of current content)
  864. if not read_datetime:
  865. read_datetime = datetime.datetime.now()
  866. viewed_revisions = self._session.query(ContentRevisionRO) \
  867. .filter(ContentRevisionRO.content_id==content.content_id).all()
  868. for revision in viewed_revisions:
  869. revision.read_by[self._user] = read_datetime
  870. if recursive:
  871. # mark read :
  872. # - all children
  873. # - parent stuff (if you mark a comment as read,
  874. # then you have seen the parent)
  875. # - parent comments
  876. for child in content.get_valid_children():
  877. self.mark_read(child, read_datetime=read_datetime,
  878. do_flush=False)
  879. if ContentType.Comment == content.type:
  880. self.mark_read(content.parent, read_datetime=read_datetime,
  881. do_flush=False, recursive=False)
  882. for comment in content.parent.get_comments():
  883. if comment != content:
  884. self.mark_read(comment, read_datetime=read_datetime,
  885. do_flush=False, recursive=False)
  886. if do_flush:
  887. self.flush()
  888. return content
  889. def mark_unread(self, content: Content, do_flush=True) -> Content:
  890. assert self._user
  891. assert content
  892. revisions = self._session.query(ContentRevisionRO) \
  893. .filter(ContentRevisionRO.content_id==content.content_id).all()
  894. for revision in revisions:
  895. del revision.read_by[self._user]
  896. for child in content.get_valid_children():
  897. self.mark_unread(child, do_flush=False)
  898. if do_flush:
  899. self.flush()
  900. return content
  901. def flush(self):
  902. self._session.flush()
  903. def save(self, content: Content, action_description: str=None, do_flush=True, do_notify=True):
  904. """
  905. Save an object, flush the session and set the revision_type property
  906. :param content:
  907. :param action_description:
  908. :return:
  909. """
  910. assert action_description is None or action_description in ActionDescription.allowed_values()
  911. if not action_description:
  912. # See if the last action has been modified
  913. if content.revision_type==None or len(get_history(content.revision, 'revision_type'))<=0:
  914. # The action has not been modified, so we set it to default edition
  915. action_description = ActionDescription.EDITION
  916. if action_description:
  917. content.revision_type = action_description
  918. if do_flush:
  919. # INFO - 2015-09-03 - D.A.
  920. # There are 2 flush because of the use
  921. # of triggers for content creation
  922. #
  923. # (when creating a content, actually this is an insert of a new
  924. # revision in content_revisions ; so the mark_read operation need
  925. # to get full real data from database before to be prepared.
  926. self._session.add(content)
  927. self._session.flush()
  928. # TODO - 2015-09-03 - D.A. - Do not use triggers
  929. # We should create a new ContentRevisionRO object instead of Content
  930. # This would help managing view/not viewed status
  931. self.mark_read(content, do_flush=True)
  932. if do_notify:
  933. self.do_notify(content)
  934. def do_notify(self, content: Content):
  935. """
  936. Allow to force notification for a given content. By default, it is
  937. called during the .save() operation
  938. :param content:
  939. :return:
  940. """
  941. NotifierFactory.create(
  942. config=self._config,
  943. current_user=self._user,
  944. session=self._session,
  945. ).notify_content_update(content)
  946. def get_keywords(self, search_string, search_string_separators=None) -> [str]:
  947. """
  948. :param search_string: a list of coma-separated keywords
  949. :return: a list of str (each keyword = 1 entry
  950. """
  951. search_string_separators = search_string_separators or ContentApi.SEARCH_SEPARATORS
  952. keywords = []
  953. if search_string:
  954. keywords = [keyword.strip() for keyword in re.split(search_string_separators, search_string)]
  955. return keywords
  956. def search(self, keywords: [str]) -> Query:
  957. """
  958. :return: a sorted list of Content items
  959. """
  960. if len(keywords)<=0:
  961. return None
  962. filter_group_label = list(Content.label.ilike('%{}%'.format(keyword)) for keyword in keywords)
  963. filter_group_desc = list(Content.description.ilike('%{}%'.format(keyword)) for keyword in keywords)
  964. title_keyworded_items = self._hard_filtered_base_query().\
  965. filter(or_(*(filter_group_label+filter_group_desc))).\
  966. options(joinedload('children_revisions')).\
  967. options(joinedload('parent'))
  968. return title_keyworded_items
  969. def get_all_types(self) -> typing.List[ContentType]:
  970. labels = ContentType.all()
  971. content_types = []
  972. for label in labels:
  973. content_types.append(ContentType(label))
  974. return ContentType.sorted(content_types)
  975. def exclude_unavailable(
  976. self,
  977. contents: typing.List[Content],
  978. ) -> typing.List[Content]:
  979. """
  980. Update and return list with content under archived/deleted removed.
  981. :param contents: List of contents to parse
  982. """
  983. for content in contents[:]:
  984. if self.content_under_deleted(content) or self.content_under_archived(content):
  985. contents.remove(content)
  986. return contents
  987. def content_under_deleted(self, content: Content) -> bool:
  988. if content.parent:
  989. if content.parent.is_deleted:
  990. return True
  991. if content.parent.parent:
  992. return self.content_under_deleted(content.parent)
  993. return False
  994. def content_under_archived(self, content: Content) -> bool:
  995. if content.parent:
  996. if content.parent.is_archived:
  997. return True
  998. if content.parent.parent:
  999. return self.content_under_archived(content.parent)
  1000. return False
  1001. def find_one_by_unique_property(
  1002. self,
  1003. property_name: str,
  1004. property_value: str,
  1005. workspace: Workspace=None,
  1006. ) -> Content:
  1007. """
  1008. Return Content who contains given property.
  1009. Raise sqlalchemy.orm.exc.MultipleResultsFound if more than one Content
  1010. contains this property value.
  1011. :param property_name: Name of property
  1012. :param property_value: Value of property
  1013. :param workspace: Workspace who contains Content
  1014. :return: Found Content
  1015. """
  1016. # TODO - 20160602 - Bastien: Should be JSON type query
  1017. # see https://www.compose.io/articles/using-json-extensions-in-\
  1018. # postgresql-from-python-2/
  1019. query = self._base_query(workspace=workspace).filter(
  1020. Content._properties.like(
  1021. '%"{property_name}": "{property_value}"%'.format(
  1022. property_name=property_name,
  1023. property_value=property_value,
  1024. )
  1025. )
  1026. )
  1027. return query.one()
  1028. def generate_folder_label(
  1029. self,
  1030. workspace: Workspace,
  1031. parent: Content=None,
  1032. ) -> str:
  1033. """
  1034. Generate a folder label
  1035. :param workspace: Future folder workspace
  1036. :param parent: Parent of foture folder (can be None)
  1037. :return: Generated folder name
  1038. """
  1039. query = self._base_query(workspace=workspace)\
  1040. .filter(Content.label.ilike('{0}%'.format(
  1041. _('New folder'),
  1042. )))
  1043. if parent:
  1044. query = query.filter(Content.parent == parent)
  1045. return _('New folder {0}').format(
  1046. query.count() + 1,
  1047. )