content.py 47KB

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