content.py 44KB

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