content.py 49KB

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