data.py 50KB

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