content.py 48KB

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