content.py 57KB

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