content.py 58KB

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