content.py 48KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319
  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 ='', filename: str = '', do_save=False, is_temporary: bool=False, do_notify=True) -> Content:
  336. # TODO - G.M - 2018-07-16 - raise Exception instead of assert
  337. assert content_type in ContentType.allowed_types()
  338. assert not (label and filename)
  339. if content_type == ContentType.Folder and not label:
  340. label = self.generate_folder_label(workspace, parent)
  341. content = Content()
  342. if filename:
  343. # INFO - G.M - 2018-07-04 - File_name setting automatically
  344. # set label and file_extension
  345. content.file_name = label
  346. elif label:
  347. content.label = label
  348. else:
  349. if content_type == ContentType.Comment:
  350. # INFO - G.M - 2018-07-16 - Default label for comments is
  351. # empty string.
  352. content.label = ''
  353. else:
  354. raise EmptyLabelNotAllowed('Content of this type should have a valid label') # nopep8
  355. content.owner = self._user
  356. content.parent = parent
  357. content.workspace = workspace
  358. content.type = content_type
  359. content.is_temporary = is_temporary
  360. content.revision_type = ActionDescription.CREATION
  361. if content.type in (
  362. ContentType.Page,
  363. ContentType.Thread,
  364. ):
  365. content.file_extension = '.html'
  366. if do_save:
  367. self._session.add(content)
  368. self.save(content, ActionDescription.CREATION, do_notify=do_notify)
  369. return content
  370. def create_comment(self, workspace: Workspace=None, parent: Content=None, content:str ='', do_save=False) -> Content:
  371. assert parent and parent.type != ContentType.Folder
  372. if not content:
  373. raise EmptyCommentContentNotAllowed()
  374. item = Content()
  375. item.owner = self._user
  376. item.parent = parent
  377. if not workspace:
  378. workspace = item.parent.workspace
  379. item.workspace = workspace
  380. item.type = ContentType.Comment
  381. item.description = content
  382. item.label = ''
  383. item.revision_type = ActionDescription.COMMENT
  384. if do_save:
  385. self.save(item, ActionDescription.COMMENT)
  386. return item
  387. def get_one_from_revision(self, content_id: int, content_type: str, workspace: Workspace=None, revision_id=None) -> Content:
  388. """
  389. This method is a hack to convert a node revision item into a node
  390. :param content_id:
  391. :param content_type:
  392. :param workspace:
  393. :param revision_id:
  394. :return:
  395. """
  396. content = self.get_one(content_id, content_type, workspace)
  397. revision = self._session.query(ContentRevisionRO).filter(ContentRevisionRO.revision_id==revision_id).one()
  398. if revision.content_id==content.content_id:
  399. content.revision_to_serialize = revision.revision_id
  400. else:
  401. raise ValueError('Revision not found for given content')
  402. return content
  403. def get_one(self, content_id: int, content_type: str, workspace: Workspace=None, parent: Content=None) -> Content:
  404. if not content_id:
  405. return None
  406. base_request = self._base_query(workspace).filter(Content.content_id==content_id)
  407. if content_type!=ContentType.Any:
  408. base_request = base_request.filter(Content.type==content_type)
  409. if parent:
  410. base_request = base_request.filter(Content.parent_id==parent.content_id) # nopep8
  411. try:
  412. content = base_request.one()
  413. except NoResultFound as exc:
  414. # TODO - G.M - 2018-07-16 - Add better support for all different
  415. # error case who can happened here
  416. # like content doesn't exist, wrong parent, wrong content_type, wrong workspace,
  417. # wrong access to this workspace, wrong base filter according
  418. # to content_status.
  419. raise ContentNotFound('Content "{}" not found in database'.format(content_id)) from exc # nopep8
  420. return content
  421. def get_one_revision(self, revision_id: int = None) -> ContentRevisionRO:
  422. """
  423. This method allow us to get directly any revision with its id
  424. :param revision_id: The content's revision's id that we want to return
  425. :return: An item Content linked with the correct revision
  426. """
  427. assert revision_id is not None# DYN_REMOVE
  428. revision = self._session.query(ContentRevisionRO).filter(ContentRevisionRO.revision_id == revision_id).one()
  429. return revision
  430. # INFO - A.P - 2017-07-03 - python file object getter
  431. # in case of we cook a version of preview manager that allows a pythonic
  432. # access to files
  433. # def get_one_revision_file(self, revision_id: int = None):
  434. # """
  435. # This function allows us to directly get a Python file object from its
  436. # revision identifier.
  437. # :param revision_id: The revision id of the file we want to return
  438. # :return: The corresponding Python file object
  439. # """
  440. # revision = self.get_one_revision(revision_id)
  441. # return DepotManager.get().get(revision.depot_file)
  442. def get_one_revision_filepath(self, revision_id: int = None) -> str:
  443. """
  444. This method allows us to directly get a file path from its revision
  445. identifier.
  446. :param revision_id: The revision id of the filepath we want to return
  447. :return: The corresponding filepath
  448. """
  449. revision = self.get_one_revision(revision_id)
  450. depot = DepotManager.get()
  451. depot_stored_file = depot.get(revision.depot_file) # type: StoredFile
  452. depot_file_path = depot_stored_file._file_path # type: str
  453. return depot_file_path
  454. def get_one_by_label_and_parent(
  455. self,
  456. content_label: str,
  457. content_parent: Content=None,
  458. ) -> Content:
  459. """
  460. This method let us request the database to obtain a Content with its name and parent
  461. :param content_label: Either the content's label or the content's filename if the label is None
  462. :param content_parent: The parent's content
  463. :param workspace: The workspace's content
  464. :return The corresponding Content
  465. """
  466. workspace = content_parent.workspace if content_parent else None
  467. query = self._base_query(workspace)
  468. parent_id = content_parent.content_id if content_parent else None
  469. query = query.filter(Content.parent_id == parent_id)
  470. file_name, file_extension = os.path.splitext(content_label)
  471. return query.filter(
  472. or_(
  473. and_(
  474. Content.type == ContentType.File,
  475. Content.label == file_name,
  476. Content.file_extension == file_extension,
  477. ),
  478. and_(
  479. Content.type == ContentType.Thread,
  480. Content.label == file_name,
  481. ),
  482. and_(
  483. Content.type == ContentType.Page,
  484. Content.label == file_name,
  485. ),
  486. and_(
  487. Content.type == ContentType.Folder,
  488. Content.label == content_label,
  489. ),
  490. )
  491. ).one()
  492. def get_one_by_label_and_parent_labels(
  493. self,
  494. content_label: str,
  495. workspace: Workspace,
  496. content_parent_labels: [str]=None,
  497. ):
  498. """
  499. Return content with it's label, workspace and parents labels (optional)
  500. :param content_label: label of content (label or file_name)
  501. :param workspace: workspace containing all of this
  502. :param content_parent_labels: Ordered list of labels representing path
  503. of folder (without workspace label).
  504. E.g.: ['foo', 'bar'] for complete path /Workspace1/foo/bar folder
  505. :return: Found Content
  506. """
  507. query = self._base_query(workspace)
  508. parent_folder = None
  509. # Grab content parent folder if parent path given
  510. if content_parent_labels:
  511. parent_folder = self.get_folder_with_workspace_path_labels(
  512. content_parent_labels,
  513. workspace,
  514. )
  515. # Build query for found content by label
  516. content_query = self.filter_query_for_content_label_as_path(
  517. query=query,
  518. content_label_as_file=content_label,
  519. )
  520. # Modify query to apply parent folder filter if any
  521. if parent_folder:
  522. content_query = content_query.filter(
  523. Content.parent_id == parent_folder.content_id,
  524. )
  525. else:
  526. content_query = content_query.filter(
  527. Content.parent_id == None,
  528. )
  529. # Filter with workspace
  530. content_query = content_query.filter(
  531. Content.workspace_id == workspace.workspace_id,
  532. )
  533. # Return the content
  534. return content_query\
  535. .order_by(
  536. Content.revision_id.desc(),
  537. )\
  538. .one()
  539. def get_folder_with_workspace_path_labels(
  540. self,
  541. path_labels: [str],
  542. workspace: Workspace,
  543. ) -> Content:
  544. """
  545. Return a Content folder for given relative path.
  546. TODO BS 20161124: Not safe if web interface allow folder duplicate names
  547. :param path_labels: List of labels representing path of folder
  548. (without workspace label).
  549. E.g.: ['foo', 'bar'] for complete path /Workspace1/foo/bar folder
  550. :param workspace: workspace of folders
  551. :return: Content folder
  552. """
  553. query = self._base_query(workspace)
  554. folder = None
  555. for label in path_labels:
  556. # Filter query on label
  557. folder_query = query \
  558. .filter(
  559. Content.type == ContentType.Folder,
  560. Content.label == label,
  561. Content.workspace_id == workspace.workspace_id,
  562. )
  563. # Search into parent folder (if already deep)
  564. if folder:
  565. folder_query = folder_query\
  566. .filter(
  567. Content.parent_id == folder.content_id,
  568. )
  569. else:
  570. folder_query = folder_query \
  571. .filter(Content.parent_id == None)
  572. # Get thirst corresponding folder
  573. folder = folder_query \
  574. .order_by(Content.revision_id.desc()) \
  575. .one()
  576. return folder
  577. def filter_query_for_content_label_as_path(
  578. self,
  579. query: Query,
  580. content_label_as_file: str,
  581. is_case_sensitive: bool = False,
  582. ) -> Query:
  583. """
  584. Apply normalised filters to found Content corresponding as given label.
  585. :param query: query to modify
  586. :param content_label_as_file: label in this
  587. FILE version, use Content.get_label_as_file().
  588. :param is_case_sensitive: Take care about case or not
  589. :return: modified query
  590. """
  591. file_name, file_extension = os.path.splitext(content_label_as_file)
  592. label_filter = Content.label == content_label_as_file
  593. file_name_filter = Content.label == file_name
  594. file_extension_filter = Content.file_extension == file_extension
  595. if not is_case_sensitive:
  596. label_filter = func.lower(Content.label) == \
  597. func.lower(content_label_as_file)
  598. file_name_filter = func.lower(Content.label) == \
  599. func.lower(file_name)
  600. file_extension_filter = func.lower(Content.file_extension) == \
  601. func.lower(file_extension)
  602. return query.filter(or_(
  603. and_(
  604. Content.type == ContentType.File,
  605. file_name_filter,
  606. file_extension_filter,
  607. ),
  608. and_(
  609. Content.type == ContentType.Thread,
  610. file_name_filter,
  611. file_extension_filter,
  612. ),
  613. and_(
  614. Content.type == ContentType.Page,
  615. file_name_filter,
  616. file_extension_filter,
  617. ),
  618. and_(
  619. Content.type == ContentType.Folder,
  620. label_filter,
  621. ),
  622. ))
  623. def get_all(self, parent_id: int=None, content_type: str=ContentType.Any, workspace: Workspace=None) -> typing.List[Content]:
  624. assert parent_id is None or isinstance(parent_id, int) # DYN_REMOVE
  625. if not content_type:
  626. content_type = ContentType.Any
  627. resultset = self._base_query(workspace)
  628. if content_type!=ContentType.Any:
  629. # INFO - G.M - 2018-07-05 - convert with
  630. # content type object to support legacy slug
  631. content_type_object = ContentType(content_type)
  632. resultset = resultset.filter(Content.type.in_(content_type_object.get_slug_aliases()))
  633. if parent_id:
  634. resultset = resultset.filter(Content.parent_id==parent_id)
  635. if parent_id == 0 or parent_id is False:
  636. resultset = resultset.filter(Content.parent_id == None)
  637. # parent_id == None give all contents
  638. return resultset.all()
  639. def get_children(self, parent_id: int, content_types: list, workspace: Workspace=None) -> typing.List[Content]:
  640. """
  641. Return parent_id childs of given content_types
  642. :param parent_id: parent id
  643. :param content_types: list of types
  644. :param workspace: workspace filter
  645. :return: list of content
  646. """
  647. resultset = self._base_query(workspace)
  648. resultset = resultset.filter(Content.type.in_(content_types))
  649. if parent_id:
  650. resultset = resultset.filter(Content.parent_id==parent_id)
  651. if parent_id is False:
  652. resultset = resultset.filter(Content.parent_id == None)
  653. return resultset.all()
  654. # TODO find an other name to filter on is_deleted / is_archived
  655. def get_all_with_filter(self, parent_id: int=None, content_type: str=ContentType.Any, workspace: Workspace=None) -> typing.List[Content]:
  656. assert parent_id is None or isinstance(parent_id, int) # DYN_REMOVE
  657. assert content_type is not None# DYN_REMOVE
  658. assert isinstance(content_type, str) # DYN_REMOVE
  659. resultset = self._base_query(workspace)
  660. if content_type != ContentType.Any:
  661. resultset = resultset.filter(Content.type==content_type)
  662. resultset = resultset.filter(Content.is_deleted == self._show_deleted)
  663. resultset = resultset.filter(Content.is_archived == self._show_archived)
  664. resultset = resultset.filter(Content.is_temporary == self._show_temporary)
  665. resultset = resultset.filter(Content.parent_id==parent_id)
  666. return resultset.all()
  667. def get_all_without_exception(self, content_type: str, workspace: Workspace=None) -> typing.List[Content]:
  668. assert content_type is not None# DYN_REMOVE
  669. resultset = self._base_query(workspace)
  670. if content_type != ContentType.Any:
  671. resultset = resultset.filter(Content.type==content_type)
  672. return resultset.all()
  673. def get_last_active(self, parent_id: int, content_type: str, workspace: Workspace=None, limit=10) -> typing.List[Content]:
  674. assert parent_id is None or isinstance(parent_id, int) # DYN_REMOVE
  675. assert content_type is not None# DYN_REMOVE
  676. assert isinstance(content_type, str) # DYN_REMOVE
  677. resultset = self._base_query(workspace) \
  678. .filter(Content.workspace_id == Workspace.workspace_id) \
  679. .filter(Workspace.is_deleted.is_(False)) \
  680. .order_by(desc(Content.updated))
  681. if content_type!=ContentType.Any:
  682. resultset = resultset.filter(Content.type==content_type)
  683. if parent_id:
  684. resultset = resultset.filter(Content.parent_id==parent_id)
  685. result = []
  686. for item in resultset:
  687. new_item = None
  688. if ContentType.Comment == item.type:
  689. new_item = item.parent
  690. else:
  691. new_item = item
  692. # INFO - D.A. - 2015-05-20
  693. # We do not want to show only one item if the last 10 items are
  694. # comments about one thread for example
  695. if new_item not in result:
  696. result.append(new_item)
  697. if len(result) >= limit:
  698. break
  699. return result
  700. def get_last_unread(self, parent_id: int, content_type: str,
  701. workspace: Workspace=None, limit=10) -> typing.List[Content]:
  702. assert parent_id is None or isinstance(parent_id, int) # DYN_REMOVE
  703. assert content_type is not None# DYN_REMOVE
  704. assert isinstance(content_type, str) # DYN_REMOVE
  705. read_revision_ids = self._session.query(RevisionReadStatus.revision_id) \
  706. .filter(RevisionReadStatus.user_id==self._user_id)
  707. not_read_revisions = self._revisions_base_query(workspace) \
  708. .filter(~ContentRevisionRO.revision_id.in_(read_revision_ids)) \
  709. .filter(ContentRevisionRO.workspace_id == Workspace.workspace_id) \
  710. .filter(Workspace.is_deleted.is_(False)) \
  711. .subquery()
  712. not_read_content_ids_query = self._session.query(
  713. distinct(not_read_revisions.c.content_id)
  714. )
  715. not_read_content_ids = list(map(
  716. itemgetter(0),
  717. not_read_content_ids_query,
  718. ))
  719. not_read_contents = self._base_query(workspace) \
  720. .filter(Content.content_id.in_(not_read_content_ids)) \
  721. .order_by(desc(Content.updated))
  722. if content_type != ContentType.Any:
  723. not_read_contents = not_read_contents.filter(
  724. Content.type==content_type)
  725. else:
  726. not_read_contents = not_read_contents.filter(
  727. Content.type!=ContentType.Folder)
  728. if parent_id:
  729. not_read_contents = not_read_contents.filter(
  730. Content.parent_id==parent_id)
  731. result = []
  732. for item in not_read_contents:
  733. new_item = None
  734. if ContentType.Comment == item.type:
  735. new_item = item.parent
  736. else:
  737. new_item = item
  738. # INFO - D.A. - 2015-05-20
  739. # We do not want to show only one item if the last 10 items are
  740. # comments about one thread for example
  741. if new_item not in result:
  742. result.append(new_item)
  743. if len(result) >= limit:
  744. break
  745. return result
  746. def set_allowed_content(self, folder: Content, allowed_content_dict:dict):
  747. """
  748. :param folder: the given folder instance
  749. :param allowed_content_dict: must be something like this:
  750. dict(
  751. folder = True
  752. thread = True,
  753. file = False,
  754. page = True
  755. )
  756. :return:
  757. """
  758. properties = dict(allowed_content = allowed_content_dict)
  759. folder.properties = properties
  760. def set_status(self, content: Content, new_status: str):
  761. if new_status in ContentStatus.allowed_values():
  762. content.status = new_status
  763. content.revision_type = ActionDescription.STATUS_UPDATE
  764. else:
  765. raise ValueError('The given value {} is not allowed'.format(new_status))
  766. def move(self,
  767. item: Content,
  768. new_parent: Content,
  769. must_stay_in_same_workspace: bool=True,
  770. new_workspace: Workspace=None,
  771. ):
  772. if must_stay_in_same_workspace:
  773. if new_parent and new_parent.workspace_id != item.workspace_id:
  774. raise ValueError('the item should stay in the same workspace')
  775. item.parent = new_parent
  776. if new_workspace:
  777. item.workspace = new_workspace
  778. if new_parent and \
  779. new_parent.workspace_id != new_workspace.workspace_id:
  780. raise WorkspacesDoNotMatch(
  781. 'new parent workspace and new workspace should be the same.'
  782. )
  783. else:
  784. if new_parent:
  785. item.workspace = new_parent.workspace
  786. item.revision_type = ActionDescription.MOVE
  787. def copy(
  788. self,
  789. item: Content,
  790. new_parent: Content=None,
  791. new_label: str=None,
  792. do_save: bool=True,
  793. do_notify: bool=True,
  794. ) -> Content:
  795. """
  796. Copy nearly all content, revision included. Children not included, see
  797. "copy_children" for this.
  798. :param item: Item to copy
  799. :param new_parent: new parent of the new copied item
  800. :param new_label: new label of the new copied item
  801. :param do_notify: notify copy or not
  802. :return: Newly copied item
  803. """
  804. if (not new_parent and not new_label) or (new_parent == item.parent and new_label == item.label): # nopep8
  805. # TODO - G.M - 08-03-2018 - Use something else than value error
  806. raise ValueError("You can't copy file into itself")
  807. if new_parent:
  808. workspace = new_parent.workspace
  809. parent = new_parent
  810. else:
  811. workspace = item.workspace
  812. parent = item.parent
  813. label = new_label or item.label
  814. content = item.copy(parent)
  815. # INFO - GM - 15-03-2018 - add "copy" revision
  816. with new_revision(
  817. session=self._session,
  818. tm=transaction.manager,
  819. content=content,
  820. force_create_new_revision=True
  821. ) as rev:
  822. rev.parent = parent
  823. rev.workspace = workspace
  824. rev.label = label
  825. rev.revision_type = ActionDescription.COPY
  826. rev.properties['origin'] = {
  827. 'content': item.id,
  828. 'revision': item.last_revision.revision_id,
  829. }
  830. if do_save:
  831. self.save(content, ActionDescription.COPY, do_notify=do_notify)
  832. return content
  833. def copy_children(self, origin_content: Content, new_content: Content):
  834. for child in origin_content.children:
  835. self.copy(child, new_content)
  836. def move_recursively(self, item: Content,
  837. new_parent: Content, new_workspace: Workspace):
  838. self.move(item, new_parent, False, new_workspace)
  839. self.save(item, do_notify=False)
  840. for child in item.children:
  841. with new_revision(
  842. session=self._session,
  843. tm=transaction.manager,
  844. content=child
  845. ):
  846. self.move_recursively(child, item, new_workspace)
  847. return
  848. def update_content(self, item: Content, new_label: str, new_content: str=None) -> Content:
  849. if item.label==new_label and item.description==new_content:
  850. # TODO - G.M - 20-03-2018 - Fix internatization for webdav access.
  851. # Internatization disabled in libcontent for now.
  852. raise SameValueError('The content did not changed')
  853. if not new_label:
  854. raise EmptyLabelNotAllowed()
  855. item.owner = self._user
  856. item.label = new_label
  857. item.description = new_content if new_content else item.description # TODO: convert urls into links
  858. item.revision_type = ActionDescription.EDITION
  859. return item
  860. def update_file_data(self, item: Content, new_filename: str, new_mimetype: str, new_content: bytes) -> Content:
  861. if new_mimetype == item.file_mimetype and \
  862. new_content == item.depot_file.file.read():
  863. raise SameValueError('The content did not changed')
  864. item.owner = self._user
  865. item.file_name = new_filename
  866. item.file_mimetype = new_mimetype
  867. item.depot_file = FileIntent(
  868. new_content,
  869. new_filename,
  870. new_mimetype,
  871. )
  872. item.revision_type = ActionDescription.REVISION
  873. return item
  874. def archive(self, content: Content):
  875. content.owner = self._user
  876. content.is_archived = True
  877. # TODO - G.M - 12-03-2018 - Inspect possible label conflict problem
  878. # INFO - G.M - 12-03-2018 - Set label name to avoid trouble when
  879. # un-archiving file.
  880. content.label = '{label}-{action}-{date}'.format(
  881. label=content.label,
  882. action='archived',
  883. date=current_date_for_filename()
  884. )
  885. content.revision_type = ActionDescription.ARCHIVING
  886. def unarchive(self, content: Content):
  887. content.owner = self._user
  888. content.is_archived = False
  889. content.revision_type = ActionDescription.UNARCHIVING
  890. def delete(self, content: Content):
  891. content.owner = self._user
  892. content.is_deleted = True
  893. # TODO - G.M - 12-03-2018 - Inspect possible label conflict problem
  894. # INFO - G.M - 12-03-2018 - Set label name to avoid trouble when
  895. # un-deleting file.
  896. content.label = '{label}-{action}-{date}'.format(
  897. label=content.label,
  898. action='deleted',
  899. date=current_date_for_filename()
  900. )
  901. content.revision_type = ActionDescription.DELETION
  902. def undelete(self, content: Content):
  903. content.owner = self._user
  904. content.is_deleted = False
  905. content.revision_type = ActionDescription.UNDELETION
  906. def mark_read__all(self,
  907. read_datetime: datetime=None,
  908. do_flush: bool=True,
  909. recursive: bool=True
  910. ):
  911. itemset = self.get_last_unread(None, ContentType.Any)
  912. for item in itemset:
  913. self.mark_read(item, read_datetime, do_flush, recursive)
  914. def mark_read__workspace(self,
  915. workspace : Workspace,
  916. read_datetime: datetime=None,
  917. do_flush: bool=True,
  918. recursive: bool=True
  919. ):
  920. itemset = self.get_last_unread(None, ContentType.Any, workspace)
  921. for item in itemset:
  922. self.mark_read(item, read_datetime, do_flush, recursive)
  923. def mark_read(self, content: Content,
  924. read_datetime: datetime=None,
  925. do_flush: bool=True, recursive: bool=True) -> Content:
  926. assert self._user
  927. assert content
  928. # The algorithm is:
  929. # 1. define the read datetime
  930. # 2. update all revisions related to current Content
  931. # 3. do the same for all child revisions
  932. # (ie parent_id is content_id of current content)
  933. if not read_datetime:
  934. read_datetime = datetime.datetime.now()
  935. viewed_revisions = self._session.query(ContentRevisionRO) \
  936. .filter(ContentRevisionRO.content_id==content.content_id).all()
  937. for revision in viewed_revisions:
  938. revision.read_by[self._user] = read_datetime
  939. if recursive:
  940. # mark read :
  941. # - all children
  942. # - parent stuff (if you mark a comment as read,
  943. # then you have seen the parent)
  944. # - parent comments
  945. for child in content.get_valid_children():
  946. self.mark_read(child, read_datetime=read_datetime,
  947. do_flush=False)
  948. if ContentType.Comment == content.type:
  949. self.mark_read(content.parent, read_datetime=read_datetime,
  950. do_flush=False, recursive=False)
  951. for comment in content.parent.get_comments():
  952. if comment != content:
  953. self.mark_read(comment, read_datetime=read_datetime,
  954. do_flush=False, recursive=False)
  955. if do_flush:
  956. self.flush()
  957. return content
  958. def mark_unread(self, content: Content, do_flush=True) -> Content:
  959. assert self._user
  960. assert content
  961. revisions = self._session.query(ContentRevisionRO) \
  962. .filter(ContentRevisionRO.content_id==content.content_id).all()
  963. for revision in revisions:
  964. del revision.read_by[self._user]
  965. for child in content.get_valid_children():
  966. self.mark_unread(child, do_flush=False)
  967. if do_flush:
  968. self.flush()
  969. return content
  970. def flush(self):
  971. self._session.flush()
  972. def save(self, content: Content, action_description: str=None, do_flush=True, do_notify=True):
  973. """
  974. Save an object, flush the session and set the revision_type property
  975. :param content:
  976. :param action_description:
  977. :return:
  978. """
  979. assert action_description is None or action_description in ActionDescription.allowed_values()
  980. if not action_description:
  981. # See if the last action has been modified
  982. if content.revision_type==None or len(get_history(content.revision, 'revision_type'))<=0:
  983. # The action has not been modified, so we set it to default edition
  984. action_description = ActionDescription.EDITION
  985. if action_description:
  986. content.revision_type = action_description
  987. if do_flush:
  988. # INFO - 2015-09-03 - D.A.
  989. # There are 2 flush because of the use
  990. # of triggers for content creation
  991. #
  992. # (when creating a content, actually this is an insert of a new
  993. # revision in content_revisions ; so the mark_read operation need
  994. # to get full real data from database before to be prepared.
  995. self._session.add(content)
  996. self._session.flush()
  997. # TODO - 2015-09-03 - D.A. - Do not use triggers
  998. # We should create a new ContentRevisionRO object instead of Content
  999. # This would help managing view/not viewed status
  1000. self.mark_read(content, do_flush=True)
  1001. if do_notify:
  1002. self.do_notify(content)
  1003. def do_notify(self, content: Content):
  1004. """
  1005. Allow to force notification for a given content. By default, it is
  1006. called during the .save() operation
  1007. :param content:
  1008. :return:
  1009. """
  1010. NotifierFactory.create(
  1011. config=self._config,
  1012. current_user=self._user,
  1013. session=self._session,
  1014. ).notify_content_update(content)
  1015. def get_keywords(self, search_string, search_string_separators=None) -> [str]:
  1016. """
  1017. :param search_string: a list of coma-separated keywords
  1018. :return: a list of str (each keyword = 1 entry
  1019. """
  1020. search_string_separators = search_string_separators or ContentApi.SEARCH_SEPARATORS
  1021. keywords = []
  1022. if search_string:
  1023. keywords = [keyword.strip() for keyword in re.split(search_string_separators, search_string)]
  1024. return keywords
  1025. def search(self, keywords: [str]) -> Query:
  1026. """
  1027. :return: a sorted list of Content items
  1028. """
  1029. if len(keywords)<=0:
  1030. return None
  1031. filter_group_label = list(Content.label.ilike('%{}%'.format(keyword)) for keyword in keywords)
  1032. filter_group_desc = list(Content.description.ilike('%{}%'.format(keyword)) for keyword in keywords)
  1033. title_keyworded_items = self._hard_filtered_base_query().\
  1034. filter(or_(*(filter_group_label+filter_group_desc))).\
  1035. options(joinedload('children_revisions')).\
  1036. options(joinedload('parent'))
  1037. return title_keyworded_items
  1038. def get_all_types(self) -> typing.List[ContentType]:
  1039. labels = ContentType.all()
  1040. content_types = []
  1041. for label in labels:
  1042. content_types.append(ContentType(label))
  1043. return ContentType.sorted(content_types)
  1044. def exclude_unavailable(
  1045. self,
  1046. contents: typing.List[Content],
  1047. ) -> typing.List[Content]:
  1048. """
  1049. Update and return list with content under archived/deleted removed.
  1050. :param contents: List of contents to parse
  1051. """
  1052. for content in contents[:]:
  1053. if self.content_under_deleted(content) or self.content_under_archived(content):
  1054. contents.remove(content)
  1055. return contents
  1056. def content_under_deleted(self, content: Content) -> bool:
  1057. if content.parent:
  1058. if content.parent.is_deleted:
  1059. return True
  1060. if content.parent.parent:
  1061. return self.content_under_deleted(content.parent)
  1062. return False
  1063. def content_under_archived(self, content: Content) -> bool:
  1064. if content.parent:
  1065. if content.parent.is_archived:
  1066. return True
  1067. if content.parent.parent:
  1068. return self.content_under_archived(content.parent)
  1069. return False
  1070. def find_one_by_unique_property(
  1071. self,
  1072. property_name: str,
  1073. property_value: str,
  1074. workspace: Workspace=None,
  1075. ) -> Content:
  1076. """
  1077. Return Content who contains given property.
  1078. Raise sqlalchemy.orm.exc.MultipleResultsFound if more than one Content
  1079. contains this property value.
  1080. :param property_name: Name of property
  1081. :param property_value: Value of property
  1082. :param workspace: Workspace who contains Content
  1083. :return: Found Content
  1084. """
  1085. # TODO - 20160602 - Bastien: Should be JSON type query
  1086. # see https://www.compose.io/articles/using-json-extensions-in-\
  1087. # postgresql-from-python-2/
  1088. query = self._base_query(workspace=workspace).filter(
  1089. Content._properties.like(
  1090. '%"{property_name}": "{property_value}"%'.format(
  1091. property_name=property_name,
  1092. property_value=property_value,
  1093. )
  1094. )
  1095. )
  1096. return query.one()
  1097. def generate_folder_label(
  1098. self,
  1099. workspace: Workspace,
  1100. parent: Content=None,
  1101. ) -> str:
  1102. """
  1103. Generate a folder label
  1104. :param workspace: Future folder workspace
  1105. :param parent: Parent of foture folder (can be None)
  1106. :return: Generated folder name
  1107. """
  1108. query = self._base_query(workspace=workspace)\
  1109. .filter(Content.label.ilike('{0}%'.format(
  1110. _('New folder'),
  1111. )))
  1112. if parent:
  1113. query = query.filter(Content.parent == parent)
  1114. return _('New folder {0}').format(
  1115. query.count() + 1,
  1116. )