content.py 51KB

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