data.py 50KB

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