app_cfg.py 18KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557
  1. # -*- coding: utf-8 -*-
  2. """
  3. Global configuration file for TG2-specific settings in tracim.
  4. This file complements development/deployment.ini.
  5. Please note that **all the argument values are strings**. If you want to
  6. convert them into boolean, for example, you should use the
  7. :func:`paste.deploy.converters.asbool` function, as in::
  8. from paste.deploy.converters import asbool
  9. setting = asbool(global_conf.get('the_setting'))
  10. """
  11. import imp
  12. import os
  13. from urllib.parse import urlparse
  14. from depot.manager import DepotManager
  15. from paste.deploy.converters import asbool
  16. import tg
  17. from tg.configuration.milestones import environment_loaded
  18. from tgext.pluggable import plug
  19. from tgext.pluggable import replace_template
  20. import tracim
  21. from tracim.config import TracimAppConfig
  22. from tracim.lib.base import logger
  23. from tracim.lib.daemons import DaemonsManager
  24. from tracim.lib.daemons import MailSenderDaemon
  25. from tracim.lib.daemons import RadicaleDaemon
  26. from tracim.lib.daemons import WsgiDavDaemon
  27. from tracim.lib.system import InterruptManager
  28. from tracim.lib.utils import lazy_ugettext as l_
  29. from tracim.model.data import ActionDescription
  30. from tracim.model.data import ContentType
  31. base_config = TracimAppConfig()
  32. base_config.renderers = []
  33. base_config.use_toscawidgets = False
  34. base_config.use_toscawidgets2 = True
  35. base_config.package = tracim
  36. # Enable json in expose
  37. base_config.renderers.append('json')
  38. # Enable genshi in expose to have a lingua franca for extensions and pluggable
  39. # apps
  40. # you can remove this if you don't plan to use it.
  41. base_config.renderers.append('genshi')
  42. # Set the default renderer
  43. base_config.default_renderer = 'mako'
  44. base_config.renderers.append('mako')
  45. # Configure the base SQLALchemy Setup
  46. base_config.use_sqlalchemy = True
  47. base_config.model = tracim.model
  48. base_config.DBSession = tracim.model.DBSession
  49. # This value can be modified by tracim.lib.auth.wrapper.AuthConfigWrapper but
  50. # have to be specified before
  51. base_config.auth_backend = 'sqlalchemy'
  52. # base_config.flash.cookie_name
  53. # base_config.flash.default_status -> Default message status if not specified
  54. # (ok by default)
  55. base_config['flash.template'] = '''
  56. <div class="alert alert-${status}" style="margin-top: 1em;">
  57. <button type="button" class="close" data-dismiss="alert">&times;</button>
  58. <div id="${container_id}">
  59. <img src="/assets/icons/32x32/status/flash-${status}.png"/>
  60. ${message}
  61. </div>
  62. </div>
  63. '''
  64. # -> string.Template instance used as the flash template when rendered from
  65. # server side, will receive $container_id, $message and $status variables.
  66. # flash.js_call -> javascript code which will be run when displaying the flash
  67. # from javascript. Default is webflash.render(), you can use webflash.payload()
  68. # to retrieve the message and show it with your favourite library.
  69. # flash.js_template -> string.Template instance used to replace full javascript
  70. # support for flash messages. When rendering flash message for javascript usage
  71. # the following code will be used instead of providing the standard webflash
  72. # object. If you replace js_template you must also ensure cookie parsing and
  73. # delete it for already displayed messages. The template will receive:
  74. # $container_id, $cookie_name, $js_call variables.
  75. base_config['templating.genshi.name_constant_patch'] = True
  76. # Configure the authentication backend
  77. # YOU MUST CHANGE THIS VALUE IN PRODUCTION TO SECURE YOUR APP
  78. base_config.sa_auth.cookie_secret = "3283411b-1904-4554-b0e1-883863b53080"
  79. # INFO - This is the way to specialize the resetpassword email properties
  80. # plug(base_config,
  81. # 'resetpassword',
  82. # None,
  83. # mail_subject=reset_password_email_subject)
  84. plug(base_config, 'resetpassword', 'reset_password')
  85. replace_template(base_config,
  86. 'resetpassword.templates.index',
  87. 'tracim.templates.reset_password_index')
  88. replace_template(base_config,
  89. 'resetpassword.templates.change_password',
  90. 'mako:tracim.templates.reset_password_change_password')
  91. daemons = DaemonsManager()
  92. def start_daemons(manager: DaemonsManager):
  93. """Start Tracim daemons."""
  94. from tg import config
  95. cfg = CFG.get_instance()
  96. # Don't start daemons if they are disabled
  97. if config.get('disable_daemons', False):
  98. return
  99. manager.run('radicale', RadicaleDaemon)
  100. manager.run('webdav', WsgiDavDaemon)
  101. if cfg.EMAIL_PROCESSING_MODE == CFG.CST.ASYNC:
  102. manager.run('mail_sender', MailSenderDaemon)
  103. def configure_depot():
  104. """Configure Depot."""
  105. depot_storage_name = CFG.get_instance().DEPOT_STORAGE_NAME
  106. depot_storage_path = CFG.get_instance().DEPOT_STORAGE_DIR
  107. depot_storage_settings = {'depot.storage_path': depot_storage_path}
  108. DepotManager.configure(
  109. depot_storage_name,
  110. depot_storage_settings,
  111. )
  112. environment_loaded.register(lambda: start_daemons(daemons))
  113. environment_loaded.register(lambda: configure_depot())
  114. interrupt_manager = InterruptManager(os.getpid(), daemons_manager=daemons)
  115. #######
  116. #
  117. # INFO - D.A. - 2014-10-31
  118. # fake strings allowing to translate resetpassword tgapp.
  119. # TODO - Integrate these translations into tgapp-resetpassword
  120. #
  121. l_('New password')
  122. l_('Confirm new password')
  123. l_('Save new password')
  124. l_('Email address')
  125. l_('Send Request')
  126. l_('Password reset request')
  127. l_('Password reset request sent')
  128. l_('Invalid password reset request')
  129. l_('Password reset request timed out')
  130. l_('Invalid password reset request')
  131. l_('Password changed successfully')
  132. l_('''
  133. We've received a request to reset the password for this account.
  134. Please click this link to reset your password:
  135. %(password_reset_link)s
  136. If you no longer wish to make the above change, or if you did not initiate this request, please disregard and/or delete this e-mail.
  137. ''')
  138. class CFG(object):
  139. """Singleton used for easy access to config file parameters."""
  140. _instance = None
  141. @classmethod
  142. def get_instance(cls) -> 'CFG':
  143. """Get configuration singleton."""
  144. if not CFG._instance:
  145. CFG._instance = CFG()
  146. return CFG._instance
  147. def __setattr__(self, key, value):
  148. """
  149. Log-ready setter.
  150. Logs all configuration parameters except password.
  151. :param key:
  152. :param value:
  153. :return:
  154. """
  155. if 'PASSWORD' not in key and \
  156. ('URL' not in key or type(value) == str) and \
  157. 'CONTENT' not in key:
  158. # We do not show PASSWORD for security reason
  159. # we do not show URL because the associated config uses tg.lurl()
  160. # which is evaluated when at display time.
  161. # At the time of configuration setup, it can't be evaluated
  162. # We do not show CONTENT in order not to pollute log files
  163. logger.info(self, 'CONFIG: [ {} | {} ]'.format(key, value))
  164. else:
  165. logger.info(self, 'CONFIG: [ {} | <value not shown> ]'.format(key))
  166. self.__dict__[key] = value
  167. def __init__(self):
  168. """Parse configuration file."""
  169. mandatory_msg = \
  170. 'ERROR: {} configuration is mandatory. Set it before continuing.'
  171. self.DEPOT_STORAGE_DIR = tg.config.get(
  172. 'depot_storage_dir',
  173. )
  174. if not self.DEPOT_STORAGE_DIR:
  175. raise Exception(
  176. mandatory_msg.format('depot_storage_dir')
  177. )
  178. self.DEPOT_STORAGE_NAME = tg.config.get(
  179. 'depot_storage_name',
  180. )
  181. if not self.DEPOT_STORAGE_NAME:
  182. raise Exception(
  183. mandatory_msg.format('depot_storage_name')
  184. )
  185. self.PREVIEW_CACHE_DIR = tg.config.get(
  186. 'preview_cache_dir',
  187. )
  188. if not self.PREVIEW_CACHE_DIR:
  189. raise Exception(
  190. 'ERROR: preview_cache_dir configuration is mandatory. '
  191. 'Set it before continuing.'
  192. )
  193. self.DATA_UPDATE_ALLOWED_DURATION = int(tg.config.get(
  194. 'content.update.allowed.duration',
  195. 0,
  196. ))
  197. self.WEBSITE_TITLE = tg.config.get(
  198. 'website.title',
  199. 'TRACIM',
  200. )
  201. self.WEBSITE_HOME_TITLE_COLOR = tg.config.get(
  202. 'website.title.color',
  203. '#555',
  204. )
  205. self.WEBSITE_HOME_IMAGE_URL = tg.lurl(
  206. '/assets/img/home_illustration.jpg',
  207. )
  208. self.WEBSITE_HOME_BACKGROUND_IMAGE_URL = tg.lurl(
  209. '/assets/img/bg.jpg',
  210. )
  211. self.WEBSITE_BASE_URL = tg.config.get(
  212. 'website.base_url',
  213. '',
  214. )
  215. self.WEBSITE_SERVER_NAME = tg.config.get(
  216. 'website.server_name',
  217. None,
  218. )
  219. if not self.WEBSITE_SERVER_NAME:
  220. self.WEBSITE_SERVER_NAME = urlparse(self.WEBSITE_BASE_URL).hostname
  221. logger.warning(
  222. self,
  223. 'NOTE: Generated website.server_name parameter from '
  224. 'website.base_url parameter -> {0}'
  225. .format(self.WEBSITE_SERVER_NAME)
  226. )
  227. self.WEBSITE_HOME_TAG_LINE = tg.config.get(
  228. 'website.home.tag_line',
  229. '',
  230. )
  231. self.WEBSITE_SUBTITLE = tg.config.get(
  232. 'website.home.subtitle',
  233. '',
  234. )
  235. self.WEBSITE_HOME_BELOW_LOGIN_FORM = tg.config.get(
  236. 'website.home.below_login_form',
  237. '',
  238. )
  239. if tg.config.get('email.notification.from'):
  240. raise Exception(
  241. 'email.notification.from configuration is deprecated. '
  242. 'Use instead email.notification.from.email and '
  243. 'email.notification.from.default_label.'
  244. )
  245. self.EMAIL_NOTIFICATION_FROM_EMAIL = tg.config.get(
  246. 'email.notification.from.email',
  247. )
  248. self.EMAIL_NOTIFICATION_FROM_DEFAULT_LABEL = tg.config.get(
  249. 'email.notification.from.default_label'
  250. )
  251. self.EMAIL_NOTIFICATION_CONTENT_UPDATE_TEMPLATE_HTML = tg.config.get(
  252. 'email.notification.content_update.template.html',
  253. )
  254. self.EMAIL_NOTIFICATION_CONTENT_UPDATE_TEMPLATE_TEXT = tg.config.get(
  255. 'email.notification.content_update.template.text',
  256. )
  257. self.EMAIL_NOTIFICATION_CREATED_ACCOUNT_TEMPLATE_HTML = tg.config.get(
  258. 'email.notification.created_account.template.html',
  259. './tracim/templates/mail/created_account_body_html.mak',
  260. )
  261. self.EMAIL_NOTIFICATION_CREATED_ACCOUNT_TEMPLATE_TEXT = tg.config.get(
  262. 'email.notification.created_account.template.text',
  263. './tracim/templates/mail/created_account_body_text.mak',
  264. )
  265. self.EMAIL_NOTIFICATION_CONTENT_UPDATE_SUBJECT = tg.config.get(
  266. 'email.notification.content_update.subject',
  267. )
  268. self.EMAIL_NOTIFICATION_CREATED_ACCOUNT_SUBJECT = tg.config.get(
  269. 'email.notification.created_account.subject',
  270. '[{website_title}] Created account',
  271. )
  272. self.EMAIL_NOTIFICATION_PROCESSING_MODE = tg.config.get(
  273. 'email.notification.processing_mode',
  274. )
  275. self.EMAIL_NOTIFICATION_ACTIVATED = asbool(tg.config.get(
  276. 'email.notification.activated',
  277. ))
  278. self.EMAIL_NOTIFICATION_SMTP_SERVER = tg.config.get(
  279. 'email.notification.smtp.server',
  280. )
  281. self.EMAIL_NOTIFICATION_SMTP_PORT = tg.config.get(
  282. 'email.notification.smtp.port',
  283. )
  284. self.EMAIL_NOTIFICATION_SMTP_USER = tg.config.get(
  285. 'email.notification.smtp.user',
  286. )
  287. self.EMAIL_NOTIFICATION_SMTP_PASSWORD = tg.config.get(
  288. 'email.notification.smtp.password',
  289. )
  290. self.EMAIL_NOTIFICATION_LOG_FILE_PATH = tg.config.get(
  291. 'email.notification.log_file_path',
  292. None,
  293. )
  294. self.TRACKER_JS_PATH = tg.config.get(
  295. 'js_tracker_path',
  296. )
  297. self.TRACKER_JS_CONTENT = self.get_tracker_js_content(
  298. self.TRACKER_JS_PATH,
  299. )
  300. self.WEBSITE_TREEVIEW_CONTENT = tg.config.get(
  301. 'website.treeview.content',
  302. )
  303. self.EMAIL_NOTIFICATION_NOTIFIED_EVENTS = [
  304. ActionDescription.COMMENT,
  305. ActionDescription.CREATION,
  306. ActionDescription.EDITION,
  307. ActionDescription.REVISION,
  308. ActionDescription.STATUS_UPDATE
  309. ]
  310. self.EMAIL_NOTIFICATION_NOTIFIED_CONTENTS = [
  311. ContentType.Page,
  312. ContentType.Thread,
  313. ContentType.File,
  314. ContentType.Comment,
  315. # ContentType.Folder -- Folder is skipped
  316. ]
  317. self.RADICALE_SERVER_HOST = tg.config.get(
  318. 'radicale.server.host',
  319. '127.0.0.1',
  320. )
  321. self.RADICALE_SERVER_PORT = int(tg.config.get(
  322. 'radicale.server.port',
  323. 5232,
  324. ))
  325. # Note: Other parameters needed to work in SSL (cert file, etc)
  326. self.RADICALE_SERVER_SSL = asbool(tg.config.get(
  327. 'radicale.server.ssl',
  328. False,
  329. ))
  330. self.RADICALE_SERVER_FILE_SYSTEM_FOLDER = tg.config.get(
  331. 'radicale.server.filesystem.folder',
  332. )
  333. if not self.RADICALE_SERVER_FILE_SYSTEM_FOLDER:
  334. raise Exception(
  335. mandatory_msg.format('radicale.server.filesystem.folder')
  336. )
  337. self.RADICALE_SERVER_ALLOW_ORIGIN = tg.config.get(
  338. 'radicale.server.allow_origin',
  339. None,
  340. )
  341. if not self.RADICALE_SERVER_ALLOW_ORIGIN:
  342. self.RADICALE_SERVER_ALLOW_ORIGIN = self.WEBSITE_BASE_URL
  343. logger.warning(
  344. self,
  345. 'NOTE: Generated radicale.server.allow_origin parameter with '
  346. 'followings parameters: website.base_url ({0})'
  347. .format(self.WEBSITE_BASE_URL)
  348. )
  349. self.RADICALE_SERVER_REALM_MESSAGE = tg.config.get(
  350. 'radicale.server.realm_message',
  351. 'Tracim Calendar - Password Required',
  352. )
  353. self.RADICALE_CLIENT_BASE_URL_HOST = tg.config.get(
  354. 'radicale.client.base_url.host',
  355. 'http://{}:{}'.format(
  356. self.RADICALE_SERVER_HOST,
  357. self.RADICALE_SERVER_PORT,
  358. ),
  359. )
  360. self.RADICALE_CLIENT_BASE_URL_PREFIX = tg.config.get(
  361. 'radicale.client.base_url.prefix',
  362. '/',
  363. )
  364. # Ensure finished by '/'
  365. if '/' != self.RADICALE_CLIENT_BASE_URL_PREFIX[-1]:
  366. self.RADICALE_CLIENT_BASE_URL_PREFIX += '/'
  367. if '/' != self.RADICALE_CLIENT_BASE_URL_PREFIX[0]:
  368. self.RADICALE_CLIENT_BASE_URL_PREFIX \
  369. = '/' + self.RADICALE_CLIENT_BASE_URL_PREFIX
  370. if not self.RADICALE_CLIENT_BASE_URL_HOST:
  371. logger.warning(
  372. self,
  373. 'Generated radicale.client.base_url.host parameter with '
  374. 'followings parameters: website.server_name -> {}'
  375. .format(self.WEBSITE_SERVER_NAME)
  376. )
  377. self.RADICALE_CLIENT_BASE_URL_HOST = self.WEBSITE_SERVER_NAME
  378. self.RADICALE_CLIENT_BASE_URL_TEMPLATE = '{}{}'.format(
  379. self.RADICALE_CLIENT_BASE_URL_HOST,
  380. self.RADICALE_CLIENT_BASE_URL_PREFIX,
  381. )
  382. self.USER_AUTH_TOKEN_VALIDITY = int(tg.config.get(
  383. 'user.auth_token.validity',
  384. '604800',
  385. ))
  386. self.WSGIDAV_CONFIG_PATH = tg.config.get(
  387. 'wsgidav.config_path',
  388. 'wsgidav.conf',
  389. )
  390. # TODO: Convert to importlib
  391. # http://stackoverflow.com/questions/41063938/use-importlib-instead-imp-for-non-py-file
  392. self.wsgidav_config = imp.load_source(
  393. 'wsgidav_config',
  394. self.WSGIDAV_CONFIG_PATH,
  395. )
  396. self.WSGIDAV_PORT = self.wsgidav_config.port
  397. self.WSGIDAV_CLIENT_BASE_URL = tg.config.get(
  398. 'wsgidav.client.base_url',
  399. None,
  400. )
  401. if not self.WSGIDAV_CLIENT_BASE_URL:
  402. self.WSGIDAV_CLIENT_BASE_URL = \
  403. '{0}:{1}'.format(
  404. self.WEBSITE_SERVER_NAME,
  405. self.WSGIDAV_PORT,
  406. )
  407. logger.warning(
  408. self,
  409. 'NOTE: Generated wsgidav.client.base_url parameter with '
  410. 'followings parameters: website.server_name and '
  411. 'wsgidav.conf port'.format(
  412. self.WSGIDAV_CLIENT_BASE_URL,
  413. )
  414. )
  415. if not self.WSGIDAV_CLIENT_BASE_URL.endswith('/'):
  416. self.WSGIDAV_CLIENT_BASE_URL += '/'
  417. self.EMAIL_PROCESSING_MODE = tg.config.get(
  418. 'email.processing_mode',
  419. 'sync',
  420. ).upper()
  421. if self.EMAIL_PROCESSING_MODE not in (
  422. self.CST.ASYNC,
  423. self.CST.SYNC,
  424. ):
  425. raise Exception(
  426. 'email.processing_mode '
  427. 'can ''be "{}" or "{}", not "{}"'.format(
  428. self.CST.ASYNC,
  429. self.CST.SYNC,
  430. self.EMAIL_PROCESSING_MODE,
  431. )
  432. )
  433. self.EMAIL_SENDER_REDIS_HOST = tg.config.get(
  434. 'email.async.redis.host',
  435. 'localhost',
  436. )
  437. self.EMAIL_SENDER_REDIS_PORT = int(tg.config.get(
  438. 'email.async.redis.port',
  439. 6379,
  440. ))
  441. self.EMAIL_SENDER_REDIS_DB = int(tg.config.get(
  442. 'email.async.redis.db',
  443. 0,
  444. ))
  445. def get_tracker_js_content(self, js_tracker_file_path=None):
  446. """Get frontend analytics file."""
  447. result = ''
  448. js_tracker_file_path = tg.config.get('js_tracker_path', None)
  449. if js_tracker_file_path:
  450. info_log = 'Reading JS tracking code from file {}'
  451. logger.info(self, info_log.format(js_tracker_file_path))
  452. with open(js_tracker_file_path, 'r') as js_file:
  453. data = js_file.read()
  454. result = data
  455. return result
  456. class CST(object):
  457. ASYNC = 'ASYNC'
  458. SYNC = 'SYNC'
  459. TREEVIEW_FOLDERS = 'folders'
  460. TREEVIEW_ALL = 'all'
  461. #######
  462. #
  463. # INFO - D.A. - 2014-11-05
  464. # Allow to process asynchronous tasks
  465. # This is used for email notifications
  466. #
  467. # import tgext.asyncjob
  468. # tgext.asyncjob.plugme(base_config)
  469. #
  470. # OR
  471. #
  472. # plug(base_config, 'tgext.asyncjob', app_globals=base_config)
  473. #
  474. # OR
  475. #
  476. # Add some variable to each templates
  477. base_config.variable_provider = lambda: {
  478. 'CFG': CFG.get_instance()
  479. }