content.py 51KB

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