data.py 49KB

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