content.py 46KB

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