You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

240 lines
8.4 KiB

  1. # -*- coding: utf-8 -*-
  2. ##############################################################################
  3. #
  4. # Adapted by Nicolas Bessi. Copyright Camptocamp SA
  5. # Based on Florent Xicluna original code. Copyright Wingo SA
  6. #
  7. # This program is free software: you can redistribute it and/or modify
  8. # it under the terms of the GNU General Public License as published by
  9. # the Free Software Foundation, either version 3 of the License, or
  10. # (at your option) any later version.
  11. #
  12. # This program is distributed in the hope that it will be useful,
  13. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  15. # GNU General Public License for more details.
  16. #
  17. # You should have received a copy of the GNU General Public License
  18. # along with this program. If not, see <http://www.gnu.org/licenses/>.
  19. #
  20. ##############################################################################
  21. import os
  22. import ConfigParser
  23. from lxml import etree
  24. from itertools import chain
  25. from openerp import models, fields
  26. from openerp.tools.config import config as system_base_config
  27. from .system_info import get_server_environment
  28. from openerp.addons import server_environment_files
  29. _dir = os.path.dirname(server_environment_files.__file__)
  30. # Same dict as RawConfigParser._boolean_states
  31. _boolean_states = {'1': True, 'yes': True, 'true': True, 'on': True,
  32. '0': False, 'no': False, 'false': False, 'off': False}
  33. if not system_base_config.get('running_env', False):
  34. raise Exception(
  35. "The parameter 'running_env' has not be set neither in base config "
  36. "file option -c or in openerprc.\n"
  37. "We strongly recommend against using the rc file but instead use an "
  38. "explicit config file with this content:\n"
  39. "[options]\nrunning_env = dev"
  40. )
  41. ck_path = os.path.join(_dir, system_base_config['running_env'])
  42. if not os.path.exists(ck_path):
  43. raise Exception(
  44. "Provided server environment does not exist, "
  45. "please add a folder %s" % ck_path
  46. )
  47. def setboolean(obj, attr, _bool=_boolean_states):
  48. """Replace the attribute with a boolean."""
  49. res = _bool[getattr(obj, attr).lower()]
  50. setattr(obj, attr, res)
  51. return res
  52. # Borrowed from MarkupSafe
  53. def _escape(s):
  54. """Convert the characters &<>'" in string s to HTML-safe sequences."""
  55. return (str(s).replace('&', '&amp;')
  56. .replace('>', '&gt;')
  57. .replace('<', '&lt;')
  58. .replace("'", '&#39;')
  59. .replace('"', '&#34;'))
  60. def _listconf(env_path):
  61. """List configuration files in a folder."""
  62. files = [os.path.join(env_path, name)
  63. for name in sorted(os.listdir(env_path))
  64. if name.endswith('.conf')]
  65. return files
  66. def _load_config():
  67. """Load the configuration and return a ConfigParser instance."""
  68. default = os.path.join(_dir, 'default')
  69. running_env = os.path.join(_dir,
  70. system_base_config['running_env'])
  71. if os.path.isdir(default):
  72. conf_files = _listconf(default) + _listconf(running_env)
  73. else:
  74. conf_files = _listconf(running_env)
  75. config_p = ConfigParser.SafeConfigParser()
  76. # options are case-sensitive
  77. config_p.optionxform = str
  78. try:
  79. config_p.read(conf_files)
  80. except Exception as e:
  81. raise Exception('Cannot read config files "%s": %s' % (conf_files, e))
  82. return config_p
  83. serv_config = _load_config()
  84. class _Defaults(dict):
  85. __slots__ = ()
  86. def __setitem__(self, key, value):
  87. func = lambda *a: str(value)
  88. return dict.__setitem__(self, key, func)
  89. class ServerConfiguration(models.TransientModel):
  90. """Display server configuration."""
  91. _name = 'server.config'
  92. _conf_defaults = _Defaults()
  93. def __init__(self, pool, cr):
  94. """Add columns to model dynamically
  95. and init some properties
  96. """
  97. self._add_columns()
  98. super(ServerConfiguration, self).__init__(pool, cr)
  99. self.running_env = system_base_config['running_env']
  100. # Only show passwords in development
  101. self.show_passwords = self.running_env in ('dev',)
  102. self._arch = None
  103. self._build_osv()
  104. def _format_key(self, section, key):
  105. return '%s | %s' % (section, key)
  106. def _add_columns(self):
  107. """Add columns to model dynamically"""
  108. cols = chain(
  109. self._get_base_cols().items(),
  110. self._get_env_cols().items(),
  111. self._get_system_cols().items()
  112. )
  113. for col, value in cols:
  114. col_name = col.replace('.', '_')
  115. setattr(ServerConfiguration,
  116. col_name,
  117. fields.Char(string=col, readonly=True))
  118. self._conf_defaults[col_name] = value
  119. def _get_base_cols(self):
  120. """ Compute base fields"""
  121. res = {}
  122. for col, item in system_base_config.options.items():
  123. key = self._format_key('openerp', col)
  124. res[key] = item
  125. return res
  126. def _get_env_cols(self, sections=None):
  127. """ Compute base fields"""
  128. res = {}
  129. sections = sections if sections else serv_config.sections()
  130. for section in sections:
  131. for col, item in serv_config.items(section):
  132. key = self._format_key(section, col)
  133. res[key] = item
  134. return res
  135. def _get_system_cols(self):
  136. """ Compute system fields"""
  137. res = {}
  138. for col, item in get_server_environment():
  139. key = self._format_key('system', col)
  140. res[key] = item
  141. return res
  142. def _group(self, items):
  143. """Return an XML chunk which represents a group of fields."""
  144. names = []
  145. for key in sorted(items):
  146. names.append(key.replace('.', '_'))
  147. return ('<group col="2" colspan="4">' +
  148. ''.join(['<field name="%s" readonly="1"/>' %
  149. _escape(name) for name in names]) +
  150. '</group>')
  151. def _build_osv(self):
  152. """Build the view for the current configuration."""
  153. arch = ('<?xml version="1.0" encoding="utf-8"?>'
  154. '<form string="Configuration Form">'
  155. '<notebook colspan="4">')
  156. # OpenERP server configuration
  157. rcfile = system_base_config.rcfile
  158. items = self._get_base_cols()
  159. arch += '<page string="OpenERP">'
  160. arch += '<separator string="%s" colspan="4"/>' % _escape(rcfile)
  161. arch += self._group(items)
  162. arch += '<separator colspan="4"/></page>'
  163. arch += '<page string="Environment based configurations">'
  164. for section in sorted(serv_config.sections()):
  165. items = self._get_env_cols(sections=[section])
  166. arch += '<separator string="[%s]" colspan="4"/>' % _escape(section)
  167. arch += self._group(items)
  168. arch += '<separator colspan="4"/></page>'
  169. # System information
  170. arch += '<page string="System">'
  171. arch += '<separator string="Server Environment" colspan="4"/>'
  172. arch += self._group(self._get_system_cols())
  173. arch += '<separator colspan="4"/></page>'
  174. arch += '</notebook></form>'
  175. self._arch = etree.fromstring(arch)
  176. def fields_view_get(self, cr, uid, view_id=None, view_type='form',
  177. context=None, toolbar=False, submenu=False):
  178. """Overwrite the default method to render the custom view."""
  179. res = super(ServerConfiguration, self).fields_view_get(cr, uid,
  180. view_id,
  181. view_type,
  182. context,
  183. toolbar)
  184. if view_type == 'form':
  185. arch_node = self._arch
  186. xarch, xfields = self._view_look_dom_arch(cr, uid,
  187. arch_node,
  188. view_id,
  189. context=context)
  190. res['arch'] = xarch
  191. res['fields'] = xfields
  192. return res
  193. def default_get(self, cr, uid, fields_list, context=None):
  194. res = {}
  195. for key in self._conf_defaults:
  196. if 'passw' in key and not self.show_passwords:
  197. res[key] = '**********'
  198. else:
  199. res[key] = self._conf_defaults[key]()
  200. return res