content.py 46KB

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