content.py 53KB

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