content.py 47KB

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