data.py 52KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521
  1. # -*- coding: utf-8 -*-
  2. import typing
  3. import datetime as datetime_root
  4. import json
  5. import os
  6. from datetime import datetime
  7. from babel.dates import format_timedelta
  8. from bs4 import BeautifulSoup
  9. from sqlalchemy import Column, inspect, Index
  10. from sqlalchemy import ForeignKey
  11. from sqlalchemy import Sequence
  12. from sqlalchemy.ext.associationproxy import association_proxy
  13. from sqlalchemy.ext.hybrid import hybrid_property
  14. from sqlalchemy.orm import backref
  15. from sqlalchemy.orm import relationship
  16. from sqlalchemy.orm.attributes import InstrumentedAttribute
  17. from sqlalchemy.orm.collections import attribute_mapped_collection
  18. from sqlalchemy.types import Boolean
  19. from sqlalchemy.types import DateTime
  20. from sqlalchemy.types import Integer
  21. from sqlalchemy.types import Text
  22. from sqlalchemy.types import Unicode
  23. from depot.fields.sqlalchemy import UploadedFileField
  24. from depot.fields.upload import UploadedFile
  25. from depot.io.utils import FileIntent
  26. from tracim_backend.lib.utils.translation import fake_translator as l_
  27. from tracim_backend.lib.utils.translation import get_locale
  28. from tracim_backend.exceptions import ContentRevisionUpdateError
  29. from tracim_backend.models.meta import DeclarativeBase
  30. from tracim_backend.models.auth import User
  31. from tracim_backend.models.roles import WorkspaceRoles
  32. DEFAULT_PROPERTIES = dict(
  33. allowed_content=dict(
  34. folder=True,
  35. file=True,
  36. page=True,
  37. thread=True,
  38. ),
  39. )
  40. class Workspace(DeclarativeBase):
  41. __tablename__ = 'workspaces'
  42. workspace_id = Column(Integer, Sequence('seq__workspaces__workspace_id'), autoincrement=True, primary_key=True)
  43. label = Column(Unicode(1024), unique=False, nullable=False, default='')
  44. description = Column(Text(), unique=False, nullable=False, default='')
  45. calendar_enabled = Column(Boolean, unique=False, nullable=False, default=False)
  46. # Default value datetime.utcnow,
  47. # see: http://stackoverflow.com/a/13370382/801924 (or http://pastebin.com/VLyWktUn)
  48. created = Column(DateTime, unique=False, nullable=False, default=datetime.utcnow)
  49. # Default value datetime.utcnow,
  50. # see: http://stackoverflow.com/a/13370382/801924 (or http://pastebin.com/VLyWktUn)
  51. updated = Column(DateTime, unique=False, nullable=False, default=datetime.utcnow)
  52. is_deleted = Column(Boolean, unique=False, nullable=False, default=False)
  53. revisions = relationship("ContentRevisionRO")
  54. @hybrid_property
  55. def contents(self) -> ['Content']:
  56. # Return a list of unique revisions parent content
  57. contents = []
  58. for revision in self.revisions:
  59. # TODO BS 20161209: This ``revision.node.workspace`` make a lot
  60. # of SQL queries !
  61. if revision.node.workspace == self and revision.node not in contents:
  62. contents.append(revision.node)
  63. return contents
  64. # TODO - G-M - 27-03-2018 - [Calendar] Replace this in context model object
  65. # @property
  66. # def calendar_url(self) -> str:
  67. # # TODO - 20160531 - Bastien: Cyclic import if import in top of file
  68. # from tracim.lib.calendar import CalendarManager
  69. # calendar_manager = CalendarManager(None)
  70. #
  71. # return calendar_manager.get_workspace_calendar_url(self.workspace_id)
  72. def get_user_role(self, user: User) -> int:
  73. for role in user.roles:
  74. if role.workspace.workspace_id==self.workspace_id:
  75. return role.role
  76. return UserRoleInWorkspace.NOT_APPLICABLE
  77. def get_label(self):
  78. """ this method is for interoperability with Content class"""
  79. return self.label
  80. def get_allowed_content_types(self):
  81. # @see Content.get_allowed_content_types()
  82. return CONTENT_TYPES.endpoint_allowed_types_slug()
  83. def get_valid_children(
  84. self,
  85. content_types: list=None,
  86. show_deleted: bool=False,
  87. show_archived: bool=False,
  88. ):
  89. for child in self.contents:
  90. # we search only direct children
  91. if not child.parent \
  92. and (show_deleted or not child.is_deleted) \
  93. and (show_archived or not child.is_archived):
  94. if not content_types or child.type in content_types:
  95. yield child
  96. class UserRoleInWorkspace(DeclarativeBase):
  97. __tablename__ = 'user_workspace'
  98. user_id = Column(Integer, ForeignKey('users.user_id'), nullable=False, default=None, primary_key=True)
  99. workspace_id = Column(Integer, ForeignKey('workspaces.workspace_id'), nullable=False, default=None, primary_key=True)
  100. role = Column(Integer, nullable=False, default=0, primary_key=False)
  101. do_notify = Column(Boolean, unique=False, nullable=False, default=False)
  102. workspace = relationship('Workspace', remote_side=[Workspace.workspace_id], backref='roles', lazy='joined')
  103. user = relationship('User', remote_side=[User.user_id], backref='roles')
  104. NOT_APPLICABLE = WorkspaceRoles.NOT_APPLICABLE.level
  105. READER = WorkspaceRoles.READER.level
  106. CONTRIBUTOR = WorkspaceRoles.CONTRIBUTOR.level
  107. CONTENT_MANAGER = WorkspaceRoles.CONTENT_MANAGER.level
  108. WORKSPACE_MANAGER = WorkspaceRoles.WORKSPACE_MANAGER.level
  109. # TODO - G.M - 10-04-2018 - [Cleanup] Drop this
  110. # SLUG = {
  111. # NOT_APPLICABLE: 'not-applicable',
  112. # READER: 'reader',
  113. # CONTRIBUTOR: 'contributor',
  114. # CONTENT_MANAGER: 'content-manager',
  115. # WORKSPACE_MANAGER: 'workspace-manager',
  116. # }
  117. # LABEL = dict()
  118. # LABEL[0] = l_('N/A')
  119. # LABEL[1] = l_('Reader')
  120. # LABEL[2] = l_('Contributor')
  121. # LABEL[4] = l_('Content Manager')
  122. # LABEL[8] = l_('Workspace Manager')
  123. # TODO - G.M - 10-04-2018 - [Cleanup] Drop this
  124. #
  125. # STYLE = dict()
  126. # STYLE[0] = ''
  127. # STYLE[1] = 'color: #1fdb11;'
  128. # STYLE[2] = 'color: #759ac5;'
  129. # STYLE[4] = 'color: #ea983d;'
  130. # STYLE[8] = 'color: #F00;'
  131. #
  132. # ICON = dict()
  133. # ICON[0] = ''
  134. # ICON[1] = 'fa-eye'
  135. # ICON[2] = 'fa-pencil'
  136. # ICON[4] = 'fa-graduation-cap'
  137. # ICON[8] = 'fa-legal'
  138. #
  139. #
  140. # @property
  141. # def fa_icon(self):
  142. # return UserRoleInWorkspace.ICON[self.role]
  143. #
  144. # @property
  145. # def style(self):
  146. # return UserRoleInWorkspace.STYLE[self.role]
  147. #
  148. def role_object(self):
  149. return WorkspaceRoles.get_role_from_level(level=self.role)
  150. def role_as_label(self):
  151. return self.role_object().label
  152. @classmethod
  153. def get_all_role_values(cls) -> typing.List[int]:
  154. """
  155. Return all valid role value
  156. """
  157. return [role.level for role in WorkspaceRoles.get_all_valid_role()]
  158. @classmethod
  159. def get_all_role_slug(cls) -> typing.List[str]:
  160. """
  161. Return all valid role slug
  162. """
  163. # INFO - G.M - 25-05-2018 - Be carefull, as long as this method
  164. # and get_all_role_values are both used for API, this method should
  165. # return item in the same order as get_all_role_values
  166. return [role.slug for role in WorkspaceRoles.get_all_valid_role()]
  167. # TODO - G.M - 10-04-2018 - [Cleanup] Drop this
  168. # class RoleType(object):
  169. # def __init__(self, role_id):
  170. # self.role_type_id = role_id
  171. # self.fa_icon = UserRoleInWorkspace.ICON[role_id]
  172. # self.role_label = UserRoleInWorkspace.LABEL[role_id]
  173. # self.css_style = UserRoleInWorkspace.STYLE[role_id]
  174. # TODO - G.M - 09-04-2018 [Cleanup] It this items really needed ?
  175. # class LinkItem(object):
  176. # def __init__(self, href, label):
  177. # self.href = href
  178. # self.label = label
  179. class ActionDescription(object):
  180. """
  181. Allowed status are:
  182. - open
  183. - closed-validated
  184. - closed-invalidated
  185. - closed-deprecated
  186. """
  187. COPY = 'copy'
  188. ARCHIVING = 'archiving'
  189. COMMENT = 'content-comment'
  190. CREATION = 'creation'
  191. DELETION = 'deletion'
  192. EDITION = 'edition' # Default action if unknow
  193. REVISION = 'revision'
  194. STATUS_UPDATE = 'status-update'
  195. UNARCHIVING = 'unarchiving'
  196. UNDELETION = 'undeletion'
  197. MOVE = 'move'
  198. # TODO - G.M - 10-04-2018 - [Cleanup] Drop this
  199. _ICONS = {
  200. 'archiving': 'archive',
  201. 'content-comment': 'comment-o',
  202. 'creation': 'magic',
  203. 'deletion': 'trash',
  204. 'edition': 'edit',
  205. 'revision': 'history',
  206. 'status-update': 'random',
  207. 'unarchiving': 'file-archive-o',
  208. 'undeletion': 'trash-o',
  209. 'move': 'arrows',
  210. 'copy': 'files-o',
  211. }
  212. #
  213. # _LABELS = {
  214. # 'archiving': l_('archive'),
  215. # 'content-comment': l_('Item commented'),
  216. # 'creation': l_('Item created'),
  217. # 'deletion': l_('Item deleted'),
  218. # 'edition': l_('item modified'),
  219. # 'revision': l_('New revision'),
  220. # 'status-update': l_('New status'),
  221. # 'unarchiving': l_('Item unarchived'),
  222. # 'undeletion': l_('Item undeleted'),
  223. # 'move': l_('Item moved'),
  224. # 'copy': l_('Item copied'),
  225. # }
  226. def __init__(self, id):
  227. assert id in ActionDescription.allowed_values()
  228. self.id = id
  229. # FIXME - G.M - 17-04-2018 - Label and fa_icon needed for webdav
  230. # design template,
  231. # find a way to not rely on this.
  232. self.label = self.id
  233. self.fa_icon = ActionDescription._ICONS[id]
  234. #self.icon = self.fa_icon
  235. # TODO - G.M - 10-04-2018 - [Cleanup] Drop this
  236. # self.label = ActionDescription._LABELS[id]
  237. # self.css = ''
  238. @classmethod
  239. def allowed_values(cls):
  240. return [cls.ARCHIVING,
  241. cls.COMMENT,
  242. cls.CREATION,
  243. cls.DELETION,
  244. cls.EDITION,
  245. cls.REVISION,
  246. cls.STATUS_UPDATE,
  247. cls.UNARCHIVING,
  248. cls.UNDELETION,
  249. cls.MOVE,
  250. cls.COPY,
  251. ]
  252. from tracim_backend.models.contents import CONTENT_STATUS
  253. from tracim_backend.models.contents import ContentStatus
  254. from tracim_backend.models.contents import CONTENT_TYPES
  255. # TODO - G.M - 30-05-2018 - Drop this old code when whe are sure nothing
  256. # is lost .
  257. # class ContentStatus(object):
  258. # """
  259. # Allowed status are:
  260. # - open
  261. # - closed-validated
  262. # - closed-invalidated
  263. # - closed-deprecated
  264. # """
  265. #
  266. # OPEN = 'open'
  267. # CLOSED_VALIDATED = 'closed-validated'
  268. # CLOSED_UNVALIDATED = 'closed-unvalidated'
  269. # CLOSED_DEPRECATED = 'closed-deprecated'
  270. #
  271. # # TODO - G.M - 10-04-2018 - [Cleanup] Drop this
  272. # # _LABELS = {'open': l_('work in progress'),
  273. # # 'closed-validated': l_('closed — validated'),
  274. # # 'closed-unvalidated': l_('closed — cancelled'),
  275. # # 'closed-deprecated': l_('deprecated')}
  276. # #
  277. # # _LABELS_THREAD = {'open': l_('subject in progress'),
  278. # # 'closed-validated': l_('subject closed — resolved'),
  279. # # 'closed-unvalidated': l_('subject closed — cancelled'),
  280. # # 'closed-deprecated': l_('deprecated')}
  281. # #
  282. # # _LABELS_FILE = {'open': l_('work in progress'),
  283. # # 'closed-validated': l_('closed — validated'),
  284. # # 'closed-unvalidated': l_('closed — cancelled'),
  285. # # 'closed-deprecated': l_('deprecated')}
  286. # #
  287. # # _ICONS = {
  288. # # 'open': 'fa fa-square-o',
  289. # # 'closed-validated': 'fa fa-check-square-o',
  290. # # 'closed-unvalidated': 'fa fa-close',
  291. # # 'closed-deprecated': 'fa fa-warning',
  292. # # }
  293. # #
  294. # # _CSS = {
  295. # # 'open': 'tracim-status-open',
  296. # # 'closed-validated': 'tracim-status-closed-validated',
  297. # # 'closed-unvalidated': 'tracim-status-closed-unvalidated',
  298. # # 'closed-deprecated': 'tracim-status-closed-deprecated',
  299. # # }
  300. #
  301. # def __init__(self,
  302. # id,
  303. # # TODO - G.M - 10-04-2018 - [Cleanup] Drop this
  304. # # type=''
  305. # ):
  306. # self.id = id
  307. # # TODO - G.M - 10-04-2018 - [Cleanup] Drop this
  308. # # self.icon = ContentStatus._ICONS[id]
  309. # # self.css = ContentStatus._CSS[id]
  310. # #
  311. # # if type==CONTENT_TYPES.Thread.slug:
  312. # # self.label = ContentStatus._LABELS_THREAD[id]
  313. # # elif type==CONTENT_TYPES.File.slug:
  314. # # self.label = ContentStatus._LABELS_FILE[id]
  315. # # else:
  316. # # self.label = ContentStatus._LABELS[id]
  317. #
  318. #
  319. # @classmethod
  320. # def all(cls, type='') -> ['ContentStatus']:
  321. # # TODO - G.M - 10-04-2018 - [Cleanup] Drop this
  322. # # all = []
  323. # # all.append(ContentStatus('open', type))
  324. # # all.append(ContentStatus('closed-validated', type))
  325. # # all.append(ContentStatus('closed-unvalidated', type))
  326. # # all.append(ContentStatus('closed-deprecated', type))
  327. # # return all
  328. # status_list = list()
  329. # for elem in cls.allowed_values():
  330. # status_list.append(ContentStatus(elem))
  331. # return status_list
  332. #
  333. # @classmethod
  334. # def allowed_values(cls):
  335. # # TODO - G.M - 10-04-2018 - [Cleanup] Drop this
  336. # # return ContentStatus._LABELS.keys()
  337. # return [
  338. # ContentStatus.OPEN,
  339. # ContentStatus.CLOSED_UNVALIDATED,
  340. # ContentStatus.CLOSED_VALIDATED,
  341. # ContentStatus.CLOSED_DEPRECATED
  342. # ]
  343. # class ContentType(object):
  344. # Any = 'any'
  345. #
  346. # Folder = 'folder'
  347. # File = 'file'
  348. # Comment = 'comment'
  349. # Thread = 'thread'
  350. # Page = 'page'
  351. # Event = 'event'
  352. #
  353. # # TODO - G.M - 10-04-2018 - [Cleanup] Do we really need this ?
  354. # # _STRING_LIST_SEPARATOR = ','
  355. #
  356. # # TODO - G.M - 10-04-2018 - [Cleanup] Drop this
  357. # # _ICONS = { # Deprecated
  358. # # 'dashboard': 'fa-home',
  359. # # 'workspace': 'fa-bank',
  360. # # 'folder': 'fa fa-folder-open-o',
  361. # # 'file': 'fa fa-paperclip',
  362. # # 'page': 'fa fa-file-text-o',
  363. # # 'thread': 'fa fa-comments-o',
  364. # # 'comment': 'fa fa-comment-o',
  365. # # 'event': 'fa fa-calendar-o',
  366. # # }
  367. # #
  368. # # _CSS_ICONS = {
  369. # # 'dashboard': 'fa fa-home',
  370. # # 'workspace': 'fa fa-bank',
  371. # # 'folder': 'fa fa-folder-open-o',
  372. # # 'file': 'fa fa-paperclip',
  373. # # 'page': 'fa fa-file-text-o',
  374. # # 'thread': 'fa fa-comments-o',
  375. # # 'comment': 'fa fa-comment-o',
  376. # # 'event': 'fa fa-calendar-o',
  377. # # }
  378. # #
  379. # # _CSS_COLORS = {
  380. # # 'dashboard': 't-dashboard-color',
  381. # # 'workspace': 't-less-visible',
  382. # # 'folder': 't-folder-color',
  383. # # 'file': 't-file-color',
  384. # # 'page': 't-page-color',
  385. # # 'thread': 't-thread-color',
  386. # # 'comment': 't-thread-color',
  387. # # 'event': 't-event-color',
  388. # # }
  389. #
  390. # _ORDER_WEIGHT = {
  391. # 'folder': 0,
  392. # 'page': 1,
  393. # 'thread': 2,
  394. # 'file': 3,
  395. # 'comment': 4,
  396. # 'event': 5,
  397. # }
  398. #
  399. # # TODO - G.M - 10-04-2018 - [Cleanup] Drop this
  400. # # _LABEL = {
  401. # # 'dashboard': '',
  402. # # 'workspace': l_('workspace'),
  403. # # 'folder': l_('folder'),
  404. # # 'file': l_('file'),
  405. # # 'page': l_('page'),
  406. # # 'thread': l_('thread'),
  407. # # 'comment': l_('comment'),
  408. # # 'event': l_('event'),
  409. # # }
  410. # #
  411. # # _DELETE_LABEL = {
  412. # # 'dashboard': '',
  413. # # 'workspace': l_('Delete this workspace'),
  414. # # 'folder': l_('Delete this folder'),
  415. # # 'file': l_('Delete this file'),
  416. # # 'page': l_('Delete this page'),
  417. # # 'thread': l_('Delete this thread'),
  418. # # 'comment': l_('Delete this comment'),
  419. # # 'event': l_('Delete this event'),
  420. # # }
  421. # #
  422. # # @classmethod
  423. # # def get_icon(cls, type: str):
  424. # # assert(type in ContentType._ICONS) # DYN_REMOVE
  425. # # return ContentType._ICONS[type]
  426. #
  427. # @classmethod
  428. # def all(cls):
  429. # return cls.allowed_types()
  430. #
  431. # @classmethod
  432. # def allowed_types(cls):
  433. # return [cls.Folder, cls.File, cls.Comment, cls.Thread, cls.Page,
  434. # cls.Event]
  435. #
  436. # @classmethod
  437. # def allowed_types_for_folding(cls):
  438. # # This method is used for showing only "main"
  439. # # types in the left-side treeview
  440. # return [cls.Folder, cls.File, cls.Thread, cls.Page]
  441. #
  442. # # TODO - G.M - 10-04-2018 - [Cleanup] Drop this
  443. # # @classmethod
  444. # # def allowed_types_from_str(cls, allowed_types_as_string: str):
  445. # # allowed_types = []
  446. # # # HACK - THIS
  447. # # for item in allowed_types_as_string.split(ContentType._STRING_LIST_SEPARATOR):
  448. # # if item and item in ContentType.allowed_types_for_folding():
  449. # # allowed_types.append(item)
  450. # # return allowed_types
  451. # #
  452. # # @classmethod
  453. # # def fill_url(cls, content: 'Content'):
  454. # # # TODO - DYNDATATYPE - D.A. - 2014-12-02
  455. # # # Make this code dynamic loading data types
  456. # #
  457. # # if content.type==CONTENT_TYPES.Folder.slug:
  458. # # return '/workspaces/{}/folders/{}'.format(content.workspace_id, content.content_id)
  459. # # elif content.type==CONTENT_TYPES.File.slug:
  460. # # return '/workspaces/{}/folders/{}/files/{}'.format(content.workspace_id, content.parent_id, content.content_id)
  461. # # elif content.type==CONTENT_TYPES.Thread.slug:
  462. # # return '/workspaces/{}/folders/{}/threads/{}'.format(content.workspace_id, content.parent_id, content.content_id)
  463. # # elif content.type==CONTENT_TYPES.Page.slug:
  464. # # return '/workspaces/{}/folders/{}/pages/{}'.format(content.workspace_id, content.parent_id, content.content_id)
  465. # #
  466. # # @classmethod
  467. # # def fill_url_for_workspace(cls, workspace: Workspace):
  468. # # # TODO - DYNDATATYPE - D.A. - 2014-12-02
  469. # # # Make this code dynamic loading data types
  470. # # return '/workspaces/{}'.format(workspace.workspace_id)
  471. #
  472. # @classmethod
  473. # def sorted(cls, types: ['ContentType']) -> ['ContentType']:
  474. # return sorted(types, key=lambda content_type: content_type.priority)
  475. #
  476. # @property
  477. # def type(self):
  478. # return self.id
  479. #
  480. # def __init__(self, type):
  481. # self.id = type
  482. # # TODO - G.M - 10-04-2018 - [Cleanup] Drop this
  483. # # self.icon = ContentType._CSS_ICONS[type]
  484. # # self.color = ContentType._CSS_COLORS[type] # deprecated
  485. # # self.css = ContentType._CSS_COLORS[type]
  486. # # self.label = ContentType._LABEL[type]
  487. # self.priority = ContentType._ORDER_WEIGHT[type]
  488. #
  489. # def toDict(self):
  490. # return dict(id=self.type,
  491. # type=self.type,
  492. # # TODO - G.M - 10-04-2018 - [Cleanup] Drop this
  493. # # icon=self.icon,
  494. # # color=self.color,
  495. # # label=self.label,
  496. # priority=self.priority)
  497. class ContentChecker(object):
  498. @classmethod
  499. def check_properties(cls, item):
  500. if item.type == CONTENT_TYPES.Folder.slug:
  501. properties = item.properties
  502. if 'allowed_content' not in properties.keys():
  503. return False
  504. if 'folders' not in properties['allowed_content']:
  505. return False
  506. if 'files' not in properties['allowed_content']:
  507. return False
  508. if 'pages' not in properties['allowed_content']:
  509. return False
  510. if 'threads' not in properties['allowed_content']:
  511. return False
  512. return True
  513. if item.type == CONTENT_TYPES.Event.slug:
  514. properties = item.properties
  515. if 'name' not in properties.keys():
  516. return False
  517. if 'raw' not in properties.keys():
  518. return False
  519. if 'start' not in properties.keys():
  520. return False
  521. if 'end' not in properties.keys():
  522. return False
  523. return True
  524. # TODO - G.M - 15-03-2018 - Choose only correct Content-type for origin
  525. # Only content who can be copied need this
  526. if item.type == CONTENT_TYPES.Any_SLUG:
  527. properties = item.properties
  528. if 'origin' in properties.keys():
  529. return True
  530. raise NotImplementedError
  531. @classmethod
  532. def reset_properties(cls, item):
  533. if item.type == CONTENT_TYPES.Folder.slug:
  534. item.properties = DEFAULT_PROPERTIES
  535. return
  536. raise NotImplementedError
  537. class ContentRevisionRO(DeclarativeBase):
  538. """
  539. Revision of Content. It's immutable, update or delete an existing ContentRevisionRO will throw
  540. ContentRevisionUpdateError errors.
  541. """
  542. __tablename__ = 'content_revisions'
  543. revision_id = Column(Integer, primary_key=True)
  544. content_id = Column(Integer, ForeignKey('content.id'), nullable=False)
  545. # TODO - G.M - 2018-06-177 - [author] Owner should be renamed "author"
  546. owner_id = Column(Integer, ForeignKey('users.user_id'), nullable=True)
  547. label = Column(Unicode(1024), unique=False, nullable=False)
  548. description = Column(Text(), unique=False, nullable=False, default='')
  549. file_extension = Column(
  550. Unicode(255),
  551. unique=False,
  552. nullable=False,
  553. server_default='',
  554. )
  555. file_mimetype = Column(Unicode(255), unique=False, nullable=False, default='')
  556. # INFO - A.P - 2017-07-03 - Depot Doc
  557. # http://depot.readthedocs.io/en/latest/#attaching-files-to-models
  558. # http://depot.readthedocs.io/en/latest/api.html#module-depot.fields
  559. depot_file = Column(UploadedFileField, unique=False, nullable=True)
  560. properties = Column('properties', Text(), unique=False, nullable=False, default='')
  561. type = Column(Unicode(32), unique=False, nullable=False)
  562. status = Column(Unicode(32), unique=False, nullable=False, default=str(CONTENT_STATUS.get_default_status().slug))
  563. created = Column(DateTime, unique=False, nullable=False, default=datetime.utcnow)
  564. updated = Column(DateTime, unique=False, nullable=False, default=datetime.utcnow)
  565. is_deleted = Column(Boolean, unique=False, nullable=False, default=False)
  566. is_archived = Column(Boolean, unique=False, nullable=False, default=False)
  567. is_temporary = Column(Boolean, unique=False, nullable=False, default=False)
  568. revision_type = Column(Unicode(32), unique=False, nullable=False, default='')
  569. workspace_id = Column(Integer, ForeignKey('workspaces.workspace_id'), unique=False, nullable=True)
  570. workspace = relationship('Workspace', remote_side=[Workspace.workspace_id])
  571. parent_id = Column(Integer, ForeignKey('content.id'), nullable=True, default=None)
  572. parent = relationship("Content", foreign_keys=[parent_id], back_populates="children_revisions")
  573. node = relationship("Content", foreign_keys=[content_id], back_populates="revisions")
  574. # TODO - G.M - 2018-06-177 - [author] Owner should be renamed "author"
  575. owner = relationship('User', remote_side=[User.user_id])
  576. """ List of column copied when make a new revision from another """
  577. _cloned_columns = (
  578. 'content_id',
  579. 'created',
  580. 'description',
  581. 'file_mimetype',
  582. 'file_extension',
  583. 'is_archived',
  584. 'is_deleted',
  585. 'label',
  586. 'owner',
  587. 'owner_id',
  588. 'parent',
  589. 'parent_id',
  590. 'properties',
  591. 'revision_type',
  592. 'status',
  593. 'type',
  594. 'updated',
  595. 'workspace',
  596. 'workspace_id',
  597. 'is_temporary',
  598. )
  599. # Read by must be used like this:
  600. # read_datetime = revision.ready_by[<User instance>]
  601. # if user did not read the content, then a key error is raised
  602. read_by = association_proxy(
  603. 'revision_read_statuses', # name of the attribute
  604. 'view_datetime', # attribute the value is taken from
  605. creator=lambda k, v: \
  606. RevisionReadStatus(user=k, view_datetime=v)
  607. )
  608. @property
  609. def file_name(self):
  610. return '{0}{1}'.format(
  611. self.label,
  612. self.file_extension,
  613. )
  614. @classmethod
  615. def new_from(cls, revision: 'ContentRevisionRO') -> 'ContentRevisionRO':
  616. """
  617. Return new instance of ContentRevisionRO where properties are copied from revision parameter.
  618. Look at ContentRevisionRO._cloned_columns to see what columns are copieds.
  619. :param revision: revision to copy
  620. :type revision: ContentRevisionRO
  621. :return: new revision from revision parameter
  622. :rtype: ContentRevisionRO
  623. """
  624. new_rev = cls()
  625. for column_name in cls._cloned_columns:
  626. column_value = getattr(revision, column_name)
  627. setattr(new_rev, column_name, column_value)
  628. new_rev.updated = datetime.utcnow()
  629. if revision.depot_file:
  630. new_rev.depot_file = FileIntent(
  631. revision.depot_file.file.read(),
  632. revision.file_name,
  633. revision.file_mimetype,
  634. )
  635. return new_rev
  636. @classmethod
  637. def copy(
  638. cls,
  639. revision: 'ContentRevisionRO',
  640. parent: 'Content'
  641. ) -> 'ContentRevisionRO':
  642. copy_rev = cls()
  643. import copy
  644. copy_columns = cls._cloned_columns
  645. for column_name in copy_columns:
  646. # INFO - G-M - 15-03-2018 - set correct parent
  647. if column_name == 'parent_id':
  648. column_value = copy.copy(parent.id)
  649. elif column_name == 'parent':
  650. column_value = copy.copy(parent)
  651. else:
  652. column_value = copy.copy(getattr(revision, column_name))
  653. setattr(copy_rev, column_name, column_value)
  654. # copy attached_file
  655. if revision.depot_file:
  656. copy_rev.depot_file = FileIntent(
  657. revision.depot_file.file.read(),
  658. revision.file_name,
  659. revision.file_mimetype,
  660. )
  661. return copy_rev
  662. def __setattr__(self, key: str, value: 'mixed'):
  663. """
  664. ContentRevisionUpdateError is raised if tried to update column and revision own identity
  665. :param key: attribute name
  666. :param value: attribute value
  667. :return:
  668. """
  669. if key in ('_sa_instance_state', ): # Prevent infinite loop from SQLAlchemy code and altered set
  670. return super().__setattr__(key, value)
  671. # FIXME - G.M - 28-03-2018 - Cycling Import
  672. from tracim_backend.models.revision_protection import RevisionsIntegrity
  673. if inspect(self).has_identity \
  674. and key in self._cloned_columns \
  675. and not RevisionsIntegrity.is_updatable(self):
  676. raise ContentRevisionUpdateError(
  677. "Can't modify revision. To work on new revision use tracim.model.new_revision " +
  678. "context manager.")
  679. super().__setattr__(key, value)
  680. def get_status(self) -> ContentStatus:
  681. return CONTENT_STATUS.get_one_by_slug(self.status)
  682. def get_label(self) -> str:
  683. return self.label or self.file_name or ''
  684. def get_last_action(self) -> ActionDescription:
  685. return ActionDescription(self.revision_type)
  686. def has_new_information_for(self, user: User) -> bool:
  687. """
  688. :param user: the _session current user
  689. :return: bool, True if there is new information for given user else False
  690. False if the user is None
  691. """
  692. if not user:
  693. return False
  694. if user not in self.read_by.keys():
  695. return True
  696. return False
  697. def get_label_as_file(self):
  698. file_extension = self.file_extension or ''
  699. if self.type == CONTENT_TYPES.Thread.slug:
  700. file_extension = '.html'
  701. elif self.type == CONTENT_TYPES.Page.slug:
  702. file_extension = '.html'
  703. return '{0}{1}'.format(
  704. self.label,
  705. file_extension,
  706. )
  707. # TODO - G.M - 2018-06-177 - [author] Owner should be renamed "author"
  708. Index('idx__content_revisions__owner_id', ContentRevisionRO.owner_id)
  709. Index('idx__content_revisions__parent_id', ContentRevisionRO.parent_id)
  710. class Content(DeclarativeBase):
  711. """
  712. Content is used as a virtual representation of ContentRevisionRO.
  713. content.PROPERTY (except for content.id, content.revisions, content.children_revisions) will return
  714. value of most recent revision of content.
  715. # UPDATE A CONTENT
  716. To update an existing Content, you must use tracim.model.new_revision context manager:
  717. content = my_sontent_getter_method()
  718. with new_revision(content):
  719. content.description = 'foo bar baz'
  720. DBSession.flush()
  721. # QUERY CONTENTS
  722. To query contents you will need to join your content query with ContentRevisionRO. Join
  723. condition is available at tracim.lib.content.ContentApi#_get_revision_join:
  724. content = DBSession.query(Content).join(ContentRevisionRO, ContentApi._get_revision_join())
  725. .filter(Content.label == 'foo')
  726. .one()
  727. ContentApi provide also prepared Content at tracim.lib.content.ContentApi#get_canonical_query:
  728. content = ContentApi.get_canonical_query()
  729. .filter(Content.label == 'foo')
  730. .one()
  731. """
  732. __tablename__ = 'content'
  733. revision_to_serialize = -0 # This flag allow to serialize a given revision if required by the user
  734. id = Column(Integer, primary_key=True)
  735. # TODO - A.P - 2017-09-05 - revisions default sorting
  736. # The only sorting that makes sens is ordering by "updated" field. But:
  737. # - its content will soon replace the one of "created",
  738. # - this "updated" field will then be dropped.
  739. # So for now, we order by "revision_id" explicitly, but remember to switch
  740. # to "created" once "updated" removed.
  741. # https://github.com/tracim/tracim/issues/336
  742. revisions = relationship("ContentRevisionRO",
  743. foreign_keys=[ContentRevisionRO.content_id],
  744. back_populates="node",
  745. order_by="ContentRevisionRO.revision_id")
  746. children_revisions = relationship("ContentRevisionRO",
  747. foreign_keys=[ContentRevisionRO.parent_id],
  748. back_populates="parent")
  749. @hybrid_property
  750. def content_id(self) -> int:
  751. return self.revision.content_id
  752. @content_id.setter
  753. def content_id(self, value: int) -> None:
  754. self.revision.content_id = value
  755. @content_id.expression
  756. def content_id(cls) -> InstrumentedAttribute:
  757. return ContentRevisionRO.content_id
  758. @hybrid_property
  759. def revision_id(self) -> int:
  760. return self.revision.revision_id
  761. @revision_id.setter
  762. def revision_id(self, value: int):
  763. self.revision.revision_id = value
  764. @revision_id.expression
  765. def revision_id(cls) -> InstrumentedAttribute:
  766. return ContentRevisionRO.revision_id
  767. # TODO - G.M - 2018-06-177 - [author] Owner should be renamed "author"
  768. # and should be author of first revision.
  769. @hybrid_property
  770. def owner_id(self) -> int:
  771. return self.revision.owner_id
  772. @owner_id.setter
  773. def owner_id(self, value: int) -> None:
  774. self.revision.owner_id = value
  775. @owner_id.expression
  776. def owner_id(cls) -> InstrumentedAttribute:
  777. return ContentRevisionRO.owner_id
  778. @hybrid_property
  779. def label(self) -> str:
  780. return self.revision.label
  781. @label.setter
  782. def label(self, value: str) -> None:
  783. self.revision.label = value
  784. @label.expression
  785. def label(cls) -> InstrumentedAttribute:
  786. return ContentRevisionRO.label
  787. @hybrid_property
  788. def description(self) -> str:
  789. return self.revision.description
  790. @description.setter
  791. def description(self, value: str) -> None:
  792. self.revision.description = value
  793. @description.expression
  794. def description(cls) -> InstrumentedAttribute:
  795. return ContentRevisionRO.description
  796. @hybrid_property
  797. def file_name(self) -> str:
  798. return '{0}{1}'.format(
  799. self.revision.label,
  800. self.revision.file_extension,
  801. )
  802. @file_name.setter
  803. def file_name(self, value: str) -> None:
  804. file_name, file_extension = os.path.splitext(value)
  805. if not self.revision.label:
  806. self.revision.label = file_name
  807. self.revision.file_extension = file_extension
  808. @file_name.expression
  809. def file_name(cls) -> InstrumentedAttribute:
  810. return ContentRevisionRO.file_name + ContentRevisionRO.file_extension
  811. @hybrid_property
  812. def file_extension(self) -> str:
  813. return self.revision.file_extension
  814. @file_extension.setter
  815. def file_extension(self, value: str) -> None:
  816. self.revision.file_extension = value
  817. @file_extension.expression
  818. def file_extension(cls) -> InstrumentedAttribute:
  819. return ContentRevisionRO.file_extension
  820. @hybrid_property
  821. def file_mimetype(self) -> str:
  822. return self.revision.file_mimetype
  823. @file_mimetype.setter
  824. def file_mimetype(self, value: str) -> None:
  825. self.revision.file_mimetype = value
  826. @file_mimetype.expression
  827. def file_mimetype(cls) -> InstrumentedAttribute:
  828. return ContentRevisionRO.file_mimetype
  829. @hybrid_property
  830. def _properties(self) -> str:
  831. return self.revision.properties
  832. @_properties.setter
  833. def _properties(self, value: str) -> None:
  834. self.revision.properties = value
  835. @_properties.expression
  836. def _properties(cls) -> InstrumentedAttribute:
  837. return ContentRevisionRO.properties
  838. @hybrid_property
  839. def type(self) -> str:
  840. return self.revision.type
  841. @type.setter
  842. def type(self, value: str) -> None:
  843. self.revision.type = value
  844. @type.expression
  845. def type(cls) -> InstrumentedAttribute:
  846. return ContentRevisionRO.type
  847. @hybrid_property
  848. def status(self) -> str:
  849. return self.revision.status
  850. @status.setter
  851. def status(self, value: str) -> None:
  852. self.revision.status = value
  853. @status.expression
  854. def status(cls) -> InstrumentedAttribute:
  855. return ContentRevisionRO.status
  856. @hybrid_property
  857. def created(self) -> datetime:
  858. return self.revision.created
  859. @created.setter
  860. def created(self, value: datetime) -> None:
  861. self.revision.created = value
  862. @created.expression
  863. def created(cls) -> InstrumentedAttribute:
  864. return ContentRevisionRO.created
  865. @hybrid_property
  866. def updated(self) -> datetime:
  867. return self.revision.updated
  868. @updated.setter
  869. def updated(self, value: datetime) -> None:
  870. self.revision.updated = value
  871. @updated.expression
  872. def updated(cls) -> InstrumentedAttribute:
  873. return ContentRevisionRO.updated
  874. @hybrid_property
  875. def is_deleted(self) -> bool:
  876. return self.revision.is_deleted
  877. @is_deleted.setter
  878. def is_deleted(self, value: bool) -> None:
  879. self.revision.is_deleted = value
  880. @is_deleted.expression
  881. def is_deleted(cls) -> InstrumentedAttribute:
  882. return ContentRevisionRO.is_deleted
  883. @hybrid_property
  884. def is_archived(self) -> bool:
  885. return self.revision.is_archived
  886. @is_archived.setter
  887. def is_archived(self, value: bool) -> None:
  888. self.revision.is_archived = value
  889. @is_archived.expression
  890. def is_archived(cls) -> InstrumentedAttribute:
  891. return ContentRevisionRO.is_archived
  892. @hybrid_property
  893. def is_temporary(self) -> bool:
  894. return self.revision.is_temporary
  895. @is_temporary.setter
  896. def is_temporary(self, value: bool) -> None:
  897. self.revision.is_temporary = value
  898. @is_temporary.expression
  899. def is_temporary(cls) -> InstrumentedAttribute:
  900. return ContentRevisionRO.is_temporary
  901. @hybrid_property
  902. def revision_type(self) -> str:
  903. return self.revision.revision_type
  904. @revision_type.setter
  905. def revision_type(self, value: str) -> None:
  906. self.revision.revision_type = value
  907. @revision_type.expression
  908. def revision_type(cls) -> InstrumentedAttribute:
  909. return ContentRevisionRO.revision_type
  910. @hybrid_property
  911. def workspace_id(self) -> int:
  912. return self.revision.workspace_id
  913. @workspace_id.setter
  914. def workspace_id(self, value: int) -> None:
  915. self.revision.workspace_id = value
  916. @workspace_id.expression
  917. def workspace_id(cls) -> InstrumentedAttribute:
  918. return ContentRevisionRO.workspace_id
  919. @hybrid_property
  920. def workspace(self) -> Workspace:
  921. return self.revision.workspace
  922. @workspace.setter
  923. def workspace(self, value: Workspace) -> None:
  924. self.revision.workspace = value
  925. @workspace.expression
  926. def workspace(cls) -> InstrumentedAttribute:
  927. return ContentRevisionRO.workspace
  928. @hybrid_property
  929. def parent_id(self) -> int:
  930. return self.revision.parent_id
  931. @parent_id.setter
  932. def parent_id(self, value: int) -> None:
  933. self.revision.parent_id = value
  934. @parent_id.expression
  935. def parent_id(cls) -> InstrumentedAttribute:
  936. return ContentRevisionRO.parent_id
  937. @hybrid_property
  938. def parent(self) -> 'Content':
  939. return self.revision.parent
  940. @parent.setter
  941. def parent(self, value: 'Content') -> None:
  942. self.revision.parent = value
  943. @parent.expression
  944. def parent(cls) -> InstrumentedAttribute:
  945. return ContentRevisionRO.parent
  946. @hybrid_property
  947. def node(self) -> 'Content':
  948. return self.revision.node
  949. @node.setter
  950. def node(self, value: 'Content') -> None:
  951. self.revision.node = value
  952. @node.expression
  953. def node(cls) -> InstrumentedAttribute:
  954. return ContentRevisionRO.node
  955. # TODO - G.M - 2018-06-177 - [author] Owner should be renamed "author"
  956. # and should be author of first revision.
  957. @hybrid_property
  958. def owner(self) -> User:
  959. return self.revision.owner
  960. @owner.setter
  961. def owner(self, value: User) -> None:
  962. self.revision.owner = value
  963. @owner.expression
  964. def owner(cls) -> InstrumentedAttribute:
  965. return ContentRevisionRO.owner
  966. @hybrid_property
  967. def children(self) -> ['Content']:
  968. """
  969. :return: list of children Content
  970. :rtype Content
  971. """
  972. # Return a list of unique revisions parent content
  973. return list(set([revision.node for revision in self.children_revisions]))
  974. @property
  975. def revision(self) -> ContentRevisionRO:
  976. return self.get_current_revision()
  977. @property
  978. def first_revision(self) -> ContentRevisionRO:
  979. return self.revisions[0] # FIXME
  980. @property
  981. def last_revision(self) -> ContentRevisionRO:
  982. return self.revisions[-1]
  983. @property
  984. def is_editable(self) -> bool:
  985. return not self.is_archived and not self.is_deleted
  986. @property
  987. def is_active(self) -> bool:
  988. return self.is_editable
  989. @property
  990. def depot_file(self) -> UploadedFile:
  991. return self.revision.depot_file
  992. @depot_file.setter
  993. def depot_file(self, value):
  994. self.revision.depot_file = value
  995. def get_current_revision(self) -> ContentRevisionRO:
  996. if not self.revisions:
  997. return self.new_revision()
  998. # If last revisions revision don't have revision_id, return it we just add it.
  999. if self.revisions[-1].revision_id is None:
  1000. return self.revisions[-1]
  1001. # Revisions should be ordred by revision_id but we ensure that here
  1002. revisions = sorted(self.revisions, key=lambda revision: revision.revision_id)
  1003. return revisions[-1]
  1004. def new_revision(self) -> ContentRevisionRO:
  1005. """
  1006. Return and assign to this content a new revision.
  1007. If it's a new content, revision is totally new.
  1008. If this content already own revision, revision is build from last revision.
  1009. :return:
  1010. """
  1011. if not self.revisions:
  1012. self.revisions.append(ContentRevisionRO())
  1013. return self.revisions[0]
  1014. new_rev = ContentRevisionRO.new_from(self.get_current_revision())
  1015. self.revisions.append(new_rev)
  1016. return new_rev
  1017. def get_valid_children(self, content_types: list=None) -> ['Content']:
  1018. for child in self.children:
  1019. if not child.is_deleted and not child.is_archived:
  1020. if not content_types or child.type in content_types:
  1021. yield child.node
  1022. @hybrid_property
  1023. def properties(self) -> dict:
  1024. """ return a structure decoded from json content of _properties """
  1025. if not self._properties:
  1026. return DEFAULT_PROPERTIES
  1027. return json.loads(self._properties)
  1028. @properties.setter
  1029. def properties(self, properties_struct: dict) -> None:
  1030. """ encode a given structure into json and store it in _properties attribute"""
  1031. self._properties = json.dumps(properties_struct)
  1032. ContentChecker.check_properties(self)
  1033. def created_as_delta(self, delta_from_datetime:datetime=None):
  1034. if not delta_from_datetime:
  1035. delta_from_datetime = datetime.utcnow()
  1036. return format_timedelta(delta_from_datetime - self.created,
  1037. locale=get_locale())
  1038. def datetime_as_delta(self, datetime_object,
  1039. delta_from_datetime:datetime=None):
  1040. if not delta_from_datetime:
  1041. delta_from_datetime = datetime.utcnow()
  1042. return format_timedelta(delta_from_datetime - datetime_object,
  1043. locale=get_locale())
  1044. def get_child_nb(self, content_type: str, content_status = ''):
  1045. child_nb = 0
  1046. for child in self.get_valid_children():
  1047. if child.type == content_type or content_type.slug == CONTENT_TYPES.Any_SLUG:
  1048. if not content_status:
  1049. child_nb = child_nb+1
  1050. elif content_status==child.status:
  1051. child_nb = child_nb+1
  1052. return child_nb
  1053. def get_label(self):
  1054. return self.label or self.file_name or ''
  1055. def get_label_as_file(self) -> str:
  1056. """
  1057. :return: Return content label in file representation context
  1058. """
  1059. return self.revision.get_label_as_file()
  1060. def get_status(self) -> ContentStatus:
  1061. return CONTENT_STATUS.get_one_by_slug(
  1062. self.status,
  1063. )
  1064. def get_last_action(self) -> ActionDescription:
  1065. return ActionDescription(self.revision_type)
  1066. def get_simple_last_activity_date(self) -> datetime_root.datetime:
  1067. """
  1068. Get last activity_date, comments_included. Do not search recursively
  1069. in revision or children.
  1070. :return:
  1071. """
  1072. last_revision_date = self.updated
  1073. for comment in self.get_comments():
  1074. if comment.updated > last_revision_date:
  1075. last_revision_date = comment.updated
  1076. return last_revision_date
  1077. def get_last_activity_date(self) -> datetime_root.datetime:
  1078. """
  1079. Get last activity date with complete recursive search
  1080. :return:
  1081. """
  1082. last_revision_date = self.updated
  1083. for revision in self.revisions:
  1084. if revision.updated > last_revision_date:
  1085. last_revision_date = revision.updated
  1086. for child in self.children:
  1087. if child.updated > last_revision_date:
  1088. last_revision_date = child.updated
  1089. return last_revision_date
  1090. def has_new_information_for(self, user: User) -> bool:
  1091. """
  1092. :param user: the _session current user
  1093. :return: bool, True if there is new information for given user else False
  1094. False if the user is None
  1095. """
  1096. revision = self.get_current_revision()
  1097. if not user:
  1098. return False
  1099. if user not in revision.read_by.keys():
  1100. # The user did not read this item, so yes!
  1101. return True
  1102. for child in self.get_valid_children():
  1103. if child.has_new_information_for(user):
  1104. return True
  1105. return False
  1106. def get_comments(self):
  1107. children = []
  1108. for child in self.children:
  1109. if CONTENT_TYPES.Comment.slug == child.type and not child.is_deleted and not child.is_archived:
  1110. children.append(child.node)
  1111. return children
  1112. def get_last_comment_from(self, user: User) -> 'Content':
  1113. # TODO - Make this more efficient
  1114. last_comment_updated = None
  1115. last_comment = None
  1116. for comment in self.get_comments():
  1117. if user.user_id == comment.owner.user_id:
  1118. if not last_comment or last_comment_updated<comment.updated:
  1119. # take only the latest comment !
  1120. last_comment = comment
  1121. last_comment_updated = comment.updated
  1122. return last_comment
  1123. def get_previous_revision(self) -> 'ContentRevisionRO':
  1124. rev_ids = [revision.revision_id for revision in self.revisions]
  1125. rev_ids.sort()
  1126. if len(rev_ids)>=2:
  1127. revision_rev_id = rev_ids[-2]
  1128. for revision in self.revisions:
  1129. if revision.revision_id == revision_rev_id:
  1130. return revision
  1131. return None
  1132. def description_as_raw_text(self):
  1133. # 'html.parser' fixes a hanging bug
  1134. # see http://stackoverflow.com/questions/12618567/problems-running-beautifulsoup4-within-apache-mod-python-django
  1135. return BeautifulSoup(self.description, 'html.parser').text
  1136. def get_allowed_content_types(self):
  1137. types = []
  1138. try:
  1139. allowed_types = self.properties['allowed_content']
  1140. for type_label, is_allowed in allowed_types.items():
  1141. if is_allowed:
  1142. types.append(CONTENT_TYPES.get_one_by_slug(type_label))
  1143. except Exception as e:
  1144. print(e.__str__())
  1145. print('----- /*\ *****')
  1146. raise ValueError('Not allowed content property')
  1147. return types
  1148. def get_history(self, drop_empty_revision=False) -> '[VirtualEvent]':
  1149. events = []
  1150. for comment in self.get_comments():
  1151. events.append(VirtualEvent.create_from_content(comment))
  1152. revisions = sorted(self.revisions, key=lambda rev: rev.revision_id)
  1153. for revision in revisions:
  1154. # INFO - G.M - 09-03-2018 - Do not show file revision with empty
  1155. # file to have a more clear view of revision.
  1156. # Some webdav client create empty file before uploading, we must
  1157. # have possibility to not show the related revision
  1158. if drop_empty_revision:
  1159. if revision.depot_file and revision.depot_file.file.content_length == 0: # nopep8
  1160. # INFO - G.M - 12-03-2018 -Always show the last and
  1161. # first revision.
  1162. if revision != revisions[-1] and revision != revisions[0]:
  1163. continue
  1164. events.append(VirtualEvent.create_from_content_revision(revision))
  1165. sorted_events = sorted(events,
  1166. key=lambda event: event.created, reverse=True)
  1167. return sorted_events
  1168. @classmethod
  1169. def format_path(cls, url_template: str, content: 'Content') -> str:
  1170. wid = content.workspace.workspace_id
  1171. fid = content.parent_id # May be None if no parent
  1172. ctype = content.type
  1173. cid = content.content_id
  1174. return url_template.format(wid=wid, fid=fid, ctype=ctype, cid=cid)
  1175. def copy(self, parent):
  1176. cpy_content = Content()
  1177. for rev in self.revisions:
  1178. cpy_rev = ContentRevisionRO.copy(rev, parent)
  1179. cpy_content.revisions.append(cpy_rev)
  1180. return cpy_content
  1181. class RevisionReadStatus(DeclarativeBase):
  1182. __tablename__ = 'revision_read_status'
  1183. revision_id = Column(Integer, ForeignKey('content_revisions.revision_id', ondelete='CASCADE', onupdate='CASCADE'), primary_key=True)
  1184. user_id = Column(Integer, ForeignKey('users.user_id', ondelete='CASCADE', onupdate='CASCADE'), primary_key=True)
  1185. # Default value datetime.utcnow, see: http://stackoverflow.com/a/13370382/801924 (or http://pastebin.com/VLyWktUn)
  1186. view_datetime = Column(DateTime, unique=False, nullable=False, default=datetime.utcnow)
  1187. content_revision = relationship(
  1188. 'ContentRevisionRO',
  1189. backref=backref(
  1190. 'revision_read_statuses',
  1191. collection_class=attribute_mapped_collection('user'),
  1192. cascade='all, delete-orphan'
  1193. ))
  1194. user = relationship('User', backref=backref(
  1195. 'revision_readers',
  1196. collection_class=attribute_mapped_collection('view_datetime'),
  1197. cascade='all, delete-orphan'
  1198. ))
  1199. class NodeTreeItem(object):
  1200. """
  1201. This class implements a model that allow to simply represents
  1202. the left-panel menu items. This model is used by dbapi but
  1203. is not directly related to sqlalchemy and database
  1204. """
  1205. def __init__(
  1206. self,
  1207. node: Content,
  1208. children: typing.List['NodeTreeItem'],
  1209. is_selected: bool = False,
  1210. ):
  1211. self.node = node
  1212. self.children = children
  1213. self.is_selected = is_selected
  1214. class VirtualEvent(object):
  1215. @classmethod
  1216. def create_from(cls, object):
  1217. if Content == object.__class__:
  1218. return cls.create_from_content(object)
  1219. elif ContentRevisionRO == object.__class__:
  1220. return cls.create_from_content_revision(object)
  1221. @classmethod
  1222. def create_from_content(cls, content: Content):
  1223. label = content.get_label()
  1224. if content.type == CONTENT_TYPES.Comment.slug:
  1225. # TODO - G.M - 10-04-2018 - [Cleanup] Remove label param
  1226. # from this object ?
  1227. label = l_('<strong>{}</strong> wrote:').format(content.owner.get_display_name())
  1228. return VirtualEvent(id=content.content_id,
  1229. created=content.created,
  1230. owner=content.owner,
  1231. type=ActionDescription(content.revision_type),
  1232. label=label,
  1233. content=content.description,
  1234. ref_object=content)
  1235. @classmethod
  1236. def create_from_content_revision(cls, revision: ContentRevisionRO):
  1237. action_description = ActionDescription(revision.revision_type)
  1238. return VirtualEvent(id=revision.revision_id,
  1239. created=revision.updated,
  1240. owner=revision.owner,
  1241. type=action_description,
  1242. label=action_description.label,
  1243. content='',
  1244. ref_object=revision)
  1245. def __init__(self, id, created, owner, type, label, content, ref_object):
  1246. self.id = id
  1247. self.created = created
  1248. self.owner = owner
  1249. self.type = type
  1250. self.label = label
  1251. self.content = content
  1252. self.ref_object = ref_object
  1253. assert hasattr(type, 'id')
  1254. # TODO - G.M - 10-04-2018 - [Cleanup] Drop this
  1255. # assert hasattr(type, 'css')
  1256. # assert hasattr(type, 'fa_icon')
  1257. # assert hasattr(type, 'label')
  1258. def created_as_delta(self, delta_from_datetime:datetime=None):
  1259. if not delta_from_datetime:
  1260. delta_from_datetime = datetime.utcnow()
  1261. return format_timedelta(delta_from_datetime - self.created,
  1262. locale=get_locale())
  1263. def create_readable_date(self, delta_from_datetime:datetime=None):
  1264. aff = ''
  1265. if not delta_from_datetime:
  1266. delta_from_datetime = datetime.utcnow()
  1267. delta = delta_from_datetime - self.created
  1268. if delta.days > 0:
  1269. if delta.days >= 365:
  1270. aff = '%d year%s ago' % (delta.days/365, 's' if delta.days/365>=2 else '')
  1271. elif delta.days >= 30:
  1272. aff = '%d month%s ago' % (delta.days/30, 's' if delta.days/30>=2 else '')
  1273. else:
  1274. aff = '%d day%s ago' % (delta.days, 's' if delta.days>=2 else '')
  1275. else:
  1276. if delta.seconds < 60:
  1277. aff = '%d second%s ago' % (delta.seconds, 's' if delta.seconds>1 else '')
  1278. elif delta.seconds/60 < 60:
  1279. aff = '%d minute%s ago' % (delta.seconds/60, 's' if delta.seconds/60>=2 else '')
  1280. else:
  1281. aff = '%d hour%s ago' % (delta.seconds/3600, 's' if delta.seconds/3600>=2 else '')
  1282. return aff