data.py 49KB

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