data.py 50KB

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