data.py 47KB

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