data.py 47KB

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