data.py 47KB

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