data.py 49KB

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