content.py 46KB

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