content.py 47KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302
  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. # INFO - G.M - 2018-07-05 - convert with
  617. # content type object to support legacy slug
  618. content_type_object = ContentType(content_type)
  619. resultset = resultset.filter(Content.type.in_(content_type_object.alias()))
  620. if parent_id:
  621. resultset = resultset.filter(Content.parent_id==parent_id)
  622. if parent_id == 0 or parent_id is False:
  623. resultset = resultset.filter(Content.parent_id == None)
  624. # parent_id == None give all contents
  625. return resultset.all()
  626. def get_children(self, parent_id: int, content_types: list, workspace: Workspace=None) -> typing.List[Content]:
  627. """
  628. Return parent_id childs of given content_types
  629. :param parent_id: parent id
  630. :param content_types: list of types
  631. :param workspace: workspace filter
  632. :return: list of content
  633. """
  634. resultset = self._base_query(workspace)
  635. resultset = resultset.filter(Content.type.in_(content_types))
  636. if parent_id:
  637. resultset = resultset.filter(Content.parent_id==parent_id)
  638. if parent_id is False:
  639. resultset = resultset.filter(Content.parent_id == None)
  640. return resultset.all()
  641. # TODO find an other name to filter on is_deleted / is_archived
  642. def get_all_with_filter(self, parent_id: int=None, content_type: str=ContentType.Any, workspace: Workspace=None) -> typing.List[Content]:
  643. assert parent_id is None or isinstance(parent_id, int) # DYN_REMOVE
  644. assert content_type is not None# DYN_REMOVE
  645. assert isinstance(content_type, str) # DYN_REMOVE
  646. resultset = self._base_query(workspace)
  647. if content_type != ContentType.Any:
  648. resultset = resultset.filter(Content.type==content_type)
  649. resultset = resultset.filter(Content.is_deleted == self._show_deleted)
  650. resultset = resultset.filter(Content.is_archived == self._show_archived)
  651. resultset = resultset.filter(Content.is_temporary == self._show_temporary)
  652. resultset = resultset.filter(Content.parent_id==parent_id)
  653. return resultset.all()
  654. def get_all_without_exception(self, content_type: str, workspace: Workspace=None) -> typing.List[Content]:
  655. assert content_type is not None# DYN_REMOVE
  656. resultset = self._base_query(workspace)
  657. if content_type != ContentType.Any:
  658. resultset = resultset.filter(Content.type==content_type)
  659. return resultset.all()
  660. def get_last_active(self, parent_id: int, content_type: str, workspace: Workspace=None, limit=10) -> typing.List[Content]:
  661. assert parent_id is None or isinstance(parent_id, int) # DYN_REMOVE
  662. assert content_type is not None# DYN_REMOVE
  663. assert isinstance(content_type, str) # DYN_REMOVE
  664. resultset = self._base_query(workspace) \
  665. .filter(Content.workspace_id == Workspace.workspace_id) \
  666. .filter(Workspace.is_deleted.is_(False)) \
  667. .order_by(desc(Content.updated))
  668. if content_type!=ContentType.Any:
  669. resultset = resultset.filter(Content.type==content_type)
  670. if parent_id:
  671. resultset = resultset.filter(Content.parent_id==parent_id)
  672. result = []
  673. for item in resultset:
  674. new_item = None
  675. if ContentType.Comment == item.type:
  676. new_item = item.parent
  677. else:
  678. new_item = item
  679. # INFO - D.A. - 2015-05-20
  680. # We do not want to show only one item if the last 10 items are
  681. # comments about one thread for example
  682. if new_item not in result:
  683. result.append(new_item)
  684. if len(result) >= limit:
  685. break
  686. return result
  687. def get_last_unread(self, parent_id: int, content_type: str,
  688. workspace: Workspace=None, limit=10) -> typing.List[Content]:
  689. assert parent_id is None or isinstance(parent_id, int) # DYN_REMOVE
  690. assert content_type is not None# DYN_REMOVE
  691. assert isinstance(content_type, str) # DYN_REMOVE
  692. read_revision_ids = self._session.query(RevisionReadStatus.revision_id) \
  693. .filter(RevisionReadStatus.user_id==self._user_id)
  694. not_read_revisions = self._revisions_base_query(workspace) \
  695. .filter(~ContentRevisionRO.revision_id.in_(read_revision_ids)) \
  696. .filter(ContentRevisionRO.workspace_id == Workspace.workspace_id) \
  697. .filter(Workspace.is_deleted.is_(False)) \
  698. .subquery()
  699. not_read_content_ids_query = self._session.query(
  700. distinct(not_read_revisions.c.content_id)
  701. )
  702. not_read_content_ids = list(map(
  703. itemgetter(0),
  704. not_read_content_ids_query,
  705. ))
  706. not_read_contents = self._base_query(workspace) \
  707. .filter(Content.content_id.in_(not_read_content_ids)) \
  708. .order_by(desc(Content.updated))
  709. if content_type != ContentType.Any:
  710. not_read_contents = not_read_contents.filter(
  711. Content.type==content_type)
  712. else:
  713. not_read_contents = not_read_contents.filter(
  714. Content.type!=ContentType.Folder)
  715. if parent_id:
  716. not_read_contents = not_read_contents.filter(
  717. Content.parent_id==parent_id)
  718. result = []
  719. for item in not_read_contents:
  720. new_item = None
  721. if ContentType.Comment == item.type:
  722. new_item = item.parent
  723. else:
  724. new_item = item
  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. if len(result) >= limit:
  731. break
  732. return result
  733. def set_allowed_content(self, folder: Content, allowed_content_dict:dict):
  734. """
  735. :param folder: the given folder instance
  736. :param allowed_content_dict: must be something like this:
  737. dict(
  738. folder = True
  739. thread = True,
  740. file = False,
  741. page = True
  742. )
  743. :return:
  744. """
  745. properties = dict(allowed_content = allowed_content_dict)
  746. folder.properties = properties
  747. def set_status(self, content: Content, new_status: str):
  748. if new_status in ContentStatus.allowed_values():
  749. content.status = new_status
  750. content.revision_type = ActionDescription.STATUS_UPDATE
  751. else:
  752. raise ValueError('The given value {} is not allowed'.format(new_status))
  753. def move(self,
  754. item: Content,
  755. new_parent: Content,
  756. must_stay_in_same_workspace: bool=True,
  757. new_workspace: Workspace=None,
  758. ):
  759. if must_stay_in_same_workspace:
  760. if new_parent and new_parent.workspace_id != item.workspace_id:
  761. raise ValueError('the item should stay in the same workspace')
  762. item.parent = new_parent
  763. if new_workspace:
  764. item.workspace = new_workspace
  765. if new_parent and \
  766. new_parent.workspace_id != new_workspace.workspace_id:
  767. raise WorkspacesDoNotMatch(
  768. 'new parent workspace and new workspace should be the same.'
  769. )
  770. else:
  771. if new_parent:
  772. item.workspace = new_parent.workspace
  773. item.revision_type = ActionDescription.MOVE
  774. def copy(
  775. self,
  776. item: Content,
  777. new_parent: Content=None,
  778. new_label: str=None,
  779. do_save: bool=True,
  780. do_notify: bool=True,
  781. ) -> Content:
  782. """
  783. Copy nearly all content, revision included. Children not included, see
  784. "copy_children" for this.
  785. :param item: Item to copy
  786. :param new_parent: new parent of the new copied item
  787. :param new_label: new label of the new copied item
  788. :param do_notify: notify copy or not
  789. :return: Newly copied item
  790. """
  791. if (not new_parent and not new_label) or (new_parent == item.parent and new_label == item.label): # nopep8
  792. # TODO - G.M - 08-03-2018 - Use something else than value error
  793. raise ValueError("You can't copy file into itself")
  794. if new_parent:
  795. workspace = new_parent.workspace
  796. parent = new_parent
  797. else:
  798. workspace = item.workspace
  799. parent = item.parent
  800. label = new_label or item.label
  801. content = item.copy(parent)
  802. # INFO - GM - 15-03-2018 - add "copy" revision
  803. with new_revision(
  804. session=self._session,
  805. tm=transaction.manager,
  806. content=content,
  807. force_create_new_revision=True
  808. ) as rev:
  809. rev.parent = parent
  810. rev.workspace = workspace
  811. rev.label = label
  812. rev.revision_type = ActionDescription.COPY
  813. rev.properties['origin'] = {
  814. 'content': item.id,
  815. 'revision': item.last_revision.revision_id,
  816. }
  817. if do_save:
  818. self.save(content, ActionDescription.COPY, do_notify=do_notify)
  819. return content
  820. def copy_children(self, origin_content: Content, new_content: Content):
  821. for child in origin_content.children:
  822. self.copy(child, new_content)
  823. def move_recursively(self, item: Content,
  824. new_parent: Content, new_workspace: Workspace):
  825. self.move(item, new_parent, False, new_workspace)
  826. self.save(item, do_notify=False)
  827. for child in item.children:
  828. with new_revision(child):
  829. self.move_recursively(child, item, new_workspace)
  830. return
  831. def update_content(self, item: Content, new_label: str, new_content: str=None) -> Content:
  832. if item.label==new_label and item.description==new_content:
  833. # TODO - G.M - 20-03-2018 - Fix internatization for webdav access.
  834. # Internatization disabled in libcontent for now.
  835. raise SameValueError('The content did not changed')
  836. if not new_label:
  837. raise EmptyLabelNotAllowed()
  838. item.owner = self._user
  839. item.label = new_label
  840. item.description = new_content if new_content else item.description # TODO: convert urls into links
  841. item.revision_type = ActionDescription.EDITION
  842. return item
  843. def update_file_data(self, item: Content, new_filename: str, new_mimetype: str, new_content: bytes) -> Content:
  844. if new_mimetype == item.file_mimetype and \
  845. new_content == item.depot_file.file.read():
  846. raise SameValueError('The content did not changed')
  847. item.owner = self._user
  848. item.file_name = new_filename
  849. item.file_mimetype = new_mimetype
  850. item.depot_file = FileIntent(
  851. new_content,
  852. new_filename,
  853. new_mimetype,
  854. )
  855. item.revision_type = ActionDescription.REVISION
  856. return item
  857. def archive(self, content: Content):
  858. content.owner = self._user
  859. content.is_archived = True
  860. # TODO - G.M - 12-03-2018 - Inspect possible label conflict problem
  861. # INFO - G.M - 12-03-2018 - Set label name to avoid trouble when
  862. # un-archiving file.
  863. content.label = '{label}-{action}-{date}'.format(
  864. label=content.label,
  865. action='archived',
  866. date=current_date_for_filename()
  867. )
  868. content.revision_type = ActionDescription.ARCHIVING
  869. def unarchive(self, content: Content):
  870. content.owner = self._user
  871. content.is_archived = False
  872. content.revision_type = ActionDescription.UNARCHIVING
  873. def delete(self, content: Content):
  874. content.owner = self._user
  875. content.is_deleted = True
  876. # TODO - G.M - 12-03-2018 - Inspect possible label conflict problem
  877. # INFO - G.M - 12-03-2018 - Set label name to avoid trouble when
  878. # un-deleting file.
  879. content.label = '{label}-{action}-{date}'.format(
  880. label=content.label,
  881. action='deleted',
  882. date=current_date_for_filename()
  883. )
  884. content.revision_type = ActionDescription.DELETION
  885. def undelete(self, content: Content):
  886. content.owner = self._user
  887. content.is_deleted = False
  888. content.revision_type = ActionDescription.UNDELETION
  889. def mark_read__all(self,
  890. read_datetime: datetime=None,
  891. do_flush: bool=True,
  892. recursive: bool=True
  893. ):
  894. itemset = self.get_last_unread(None, ContentType.Any)
  895. for item in itemset:
  896. self.mark_read(item, read_datetime, do_flush, recursive)
  897. def mark_read__workspace(self,
  898. workspace : Workspace,
  899. read_datetime: datetime=None,
  900. do_flush: bool=True,
  901. recursive: bool=True
  902. ):
  903. itemset = self.get_last_unread(None, ContentType.Any, workspace)
  904. for item in itemset:
  905. self.mark_read(item, read_datetime, do_flush, recursive)
  906. def mark_read(self, content: Content,
  907. read_datetime: datetime=None,
  908. do_flush: bool=True, recursive: bool=True) -> Content:
  909. assert self._user
  910. assert content
  911. # The algorithm is:
  912. # 1. define the read datetime
  913. # 2. update all revisions related to current Content
  914. # 3. do the same for all child revisions
  915. # (ie parent_id is content_id of current content)
  916. if not read_datetime:
  917. read_datetime = datetime.datetime.now()
  918. viewed_revisions = self._session.query(ContentRevisionRO) \
  919. .filter(ContentRevisionRO.content_id==content.content_id).all()
  920. for revision in viewed_revisions:
  921. revision.read_by[self._user] = read_datetime
  922. if recursive:
  923. # mark read :
  924. # - all children
  925. # - parent stuff (if you mark a comment as read,
  926. # then you have seen the parent)
  927. # - parent comments
  928. for child in content.get_valid_children():
  929. self.mark_read(child, read_datetime=read_datetime,
  930. do_flush=False)
  931. if ContentType.Comment == content.type:
  932. self.mark_read(content.parent, read_datetime=read_datetime,
  933. do_flush=False, recursive=False)
  934. for comment in content.parent.get_comments():
  935. if comment != content:
  936. self.mark_read(comment, read_datetime=read_datetime,
  937. do_flush=False, recursive=False)
  938. if do_flush:
  939. self.flush()
  940. return content
  941. def mark_unread(self, content: Content, do_flush=True) -> Content:
  942. assert self._user
  943. assert content
  944. revisions = self._session.query(ContentRevisionRO) \
  945. .filter(ContentRevisionRO.content_id==content.content_id).all()
  946. for revision in revisions:
  947. del revision.read_by[self._user]
  948. for child in content.get_valid_children():
  949. self.mark_unread(child, do_flush=False)
  950. if do_flush:
  951. self.flush()
  952. return content
  953. def flush(self):
  954. self._session.flush()
  955. def save(self, content: Content, action_description: str=None, do_flush=True, do_notify=True):
  956. """
  957. Save an object, flush the session and set the revision_type property
  958. :param content:
  959. :param action_description:
  960. :return:
  961. """
  962. assert action_description is None or action_description in ActionDescription.allowed_values()
  963. if not action_description:
  964. # See if the last action has been modified
  965. if content.revision_type==None or len(get_history(content.revision, 'revision_type'))<=0:
  966. # The action has not been modified, so we set it to default edition
  967. action_description = ActionDescription.EDITION
  968. if action_description:
  969. content.revision_type = action_description
  970. if do_flush:
  971. # INFO - 2015-09-03 - D.A.
  972. # There are 2 flush because of the use
  973. # of triggers for content creation
  974. #
  975. # (when creating a content, actually this is an insert of a new
  976. # revision in content_revisions ; so the mark_read operation need
  977. # to get full real data from database before to be prepared.
  978. self._session.add(content)
  979. self._session.flush()
  980. # TODO - 2015-09-03 - D.A. - Do not use triggers
  981. # We should create a new ContentRevisionRO object instead of Content
  982. # This would help managing view/not viewed status
  983. self.mark_read(content, do_flush=True)
  984. if do_notify:
  985. self.do_notify(content)
  986. def do_notify(self, content: Content):
  987. """
  988. Allow to force notification for a given content. By default, it is
  989. called during the .save() operation
  990. :param content:
  991. :return:
  992. """
  993. NotifierFactory.create(
  994. config=self._config,
  995. current_user=self._user,
  996. session=self._session,
  997. ).notify_content_update(content)
  998. def get_keywords(self, search_string, search_string_separators=None) -> [str]:
  999. """
  1000. :param search_string: a list of coma-separated keywords
  1001. :return: a list of str (each keyword = 1 entry
  1002. """
  1003. search_string_separators = search_string_separators or ContentApi.SEARCH_SEPARATORS
  1004. keywords = []
  1005. if search_string:
  1006. keywords = [keyword.strip() for keyword in re.split(search_string_separators, search_string)]
  1007. return keywords
  1008. def search(self, keywords: [str]) -> Query:
  1009. """
  1010. :return: a sorted list of Content items
  1011. """
  1012. if len(keywords)<=0:
  1013. return None
  1014. filter_group_label = list(Content.label.ilike('%{}%'.format(keyword)) for keyword in keywords)
  1015. filter_group_desc = list(Content.description.ilike('%{}%'.format(keyword)) for keyword in keywords)
  1016. title_keyworded_items = self._hard_filtered_base_query().\
  1017. filter(or_(*(filter_group_label+filter_group_desc))).\
  1018. options(joinedload('children_revisions')).\
  1019. options(joinedload('parent'))
  1020. return title_keyworded_items
  1021. def get_all_types(self) -> typing.List[ContentType]:
  1022. labels = ContentType.all()
  1023. content_types = []
  1024. for label in labels:
  1025. content_types.append(ContentType(label))
  1026. return ContentType.sorted(content_types)
  1027. def exclude_unavailable(
  1028. self,
  1029. contents: typing.List[Content],
  1030. ) -> typing.List[Content]:
  1031. """
  1032. Update and return list with content under archived/deleted removed.
  1033. :param contents: List of contents to parse
  1034. """
  1035. for content in contents[:]:
  1036. if self.content_under_deleted(content) or self.content_under_archived(content):
  1037. contents.remove(content)
  1038. return contents
  1039. def content_under_deleted(self, content: Content) -> bool:
  1040. if content.parent:
  1041. if content.parent.is_deleted:
  1042. return True
  1043. if content.parent.parent:
  1044. return self.content_under_deleted(content.parent)
  1045. return False
  1046. def content_under_archived(self, content: Content) -> bool:
  1047. if content.parent:
  1048. if content.parent.is_archived:
  1049. return True
  1050. if content.parent.parent:
  1051. return self.content_under_archived(content.parent)
  1052. return False
  1053. def find_one_by_unique_property(
  1054. self,
  1055. property_name: str,
  1056. property_value: str,
  1057. workspace: Workspace=None,
  1058. ) -> Content:
  1059. """
  1060. Return Content who contains given property.
  1061. Raise sqlalchemy.orm.exc.MultipleResultsFound if more than one Content
  1062. contains this property value.
  1063. :param property_name: Name of property
  1064. :param property_value: Value of property
  1065. :param workspace: Workspace who contains Content
  1066. :return: Found Content
  1067. """
  1068. # TODO - 20160602 - Bastien: Should be JSON type query
  1069. # see https://www.compose.io/articles/using-json-extensions-in-\
  1070. # postgresql-from-python-2/
  1071. query = self._base_query(workspace=workspace).filter(
  1072. Content._properties.like(
  1073. '%"{property_name}": "{property_value}"%'.format(
  1074. property_name=property_name,
  1075. property_value=property_value,
  1076. )
  1077. )
  1078. )
  1079. return query.one()
  1080. def generate_folder_label(
  1081. self,
  1082. workspace: Workspace,
  1083. parent: Content=None,
  1084. ) -> str:
  1085. """
  1086. Generate a folder label
  1087. :param workspace: Future folder workspace
  1088. :param parent: Parent of foture folder (can be None)
  1089. :return: Generated folder name
  1090. """
  1091. query = self._base_query(workspace=workspace)\
  1092. .filter(Content.label.ilike('{0}%'.format(
  1093. _('New folder'),
  1094. )))
  1095. if parent:
  1096. query = query.filter(Content.parent == parent)
  1097. return _('New folder {0}').format(
  1098. query.count() + 1,
  1099. )