content.py 45KB

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