content.py 47KB

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