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.

242 lines
8.5 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=None):
  48. """Replace the attribute with a boolean."""
  49. if _bool is None:
  50. _bool = dict(_boolean_states)
  51. res = _bool[getattr(obj, attr).lower()]
  52. setattr(obj, attr, res)
  53. return res
  54. # Borrowed from MarkupSafe
  55. def _escape(s):
  56. """Convert the characters &<>'" in string s to HTML-safe sequences."""
  57. return (str(s).replace('&', '&amp;')
  58. .replace('>', '&gt;')
  59. .replace('<', '&lt;')
  60. .replace("'", '&#39;')
  61. .replace('"', '&#34;'))
  62. def _listconf(env_path):
  63. """List configuration files in a folder."""
  64. files = [os.path.join(env_path, name)
  65. for name in sorted(os.listdir(env_path))
  66. if name.endswith('.conf')]
  67. return files
  68. def _load_config():
  69. """Load the configuration and return a ConfigParser instance."""
  70. default = os.path.join(_dir, 'default')
  71. running_env = os.path.join(_dir,
  72. system_base_config['running_env'])
  73. if os.path.isdir(default):
  74. conf_files = _listconf(default) + _listconf(running_env)
  75. else:
  76. conf_files = _listconf(running_env)
  77. config_p = ConfigParser.SafeConfigParser()
  78. # options are case-sensitive
  79. config_p.optionxform = str
  80. try:
  81. config_p.read(conf_files)
  82. except Exception as e:
  83. raise Exception('Cannot read config files "%s": %s' % (conf_files, e))
  84. return config_p
  85. serv_config = _load_config()
  86. class _Defaults(dict):
  87. __slots__ = ()
  88. def __setitem__(self, key, value):
  89. func = lambda *a: str(value)
  90. return dict.__setitem__(self, key, func)
  91. class ServerConfiguration(models.TransientModel):
  92. """Display server configuration."""
  93. _name = 'server.config'
  94. _conf_defaults = _Defaults()
  95. def __init__(self, pool, cr):
  96. """Add columns to model dynamically
  97. and init some properties
  98. """
  99. self._add_columns()
  100. super(ServerConfiguration, self).__init__(pool, cr)
  101. self.running_env = system_base_config['running_env']
  102. # Only show passwords in development
  103. self.show_passwords = self.running_env in ('dev',)
  104. self._arch = None
  105. self._build_osv()
  106. def _format_key(self, section, key):
  107. return '%s | %s' % (section, key)
  108. def _add_columns(self):
  109. """Add columns to model dynamically"""
  110. cols = chain(
  111. self._get_base_cols().items(),
  112. self._get_env_cols().items(),
  113. self._get_system_cols().items()
  114. )
  115. for col, value in cols:
  116. col_name = col.replace('.', '_')
  117. setattr(ServerConfiguration,
  118. col_name,
  119. fields.Char(string=col, readonly=True))
  120. self._conf_defaults[col_name] = value
  121. def _get_base_cols(self):
  122. """ Compute base fields"""
  123. res = {}
  124. for col, item in system_base_config.options.items():
  125. key = self._format_key('openerp', col)
  126. res[key] = item
  127. return res
  128. def _get_env_cols(self, sections=None):
  129. """ Compute base fields"""
  130. res = {}
  131. sections = sections if sections else serv_config.sections()
  132. for section in sections:
  133. for col, item in serv_config.items(section):
  134. key = self._format_key(section, col)
  135. res[key] = item
  136. return res
  137. def _get_system_cols(self):
  138. """ Compute system fields"""
  139. res = {}
  140. for col, item in get_server_environment():
  141. key = self._format_key('system', col)
  142. res[key] = item
  143. return res
  144. def _group(self, items):
  145. """Return an XML chunk which represents a group of fields."""
  146. names = []
  147. for key in sorted(items):
  148. names.append(key.replace('.', '_'))
  149. return ('<group col="2" colspan="4">' +
  150. ''.join(['<field name="%s" readonly="1"/>' %
  151. _escape(name) for name in names]) +
  152. '</group>')
  153. def _build_osv(self):
  154. """Build the view for the current configuration."""
  155. arch = ('<?xml version="1.0" encoding="utf-8"?>'
  156. '<form string="Configuration Form">'
  157. '<notebook colspan="4">')
  158. # OpenERP server configuration
  159. rcfile = system_base_config.rcfile
  160. items = self._get_base_cols()
  161. arch += '<page string="OpenERP">'
  162. arch += '<separator string="%s" colspan="4"/>' % _escape(rcfile)
  163. arch += self._group(items)
  164. arch += '<separator colspan="4"/></page>'
  165. arch += '<page string="Environment based configurations">'
  166. for section in sorted(serv_config.sections()):
  167. items = self._get_env_cols(sections=[section])
  168. arch += '<separator string="[%s]" colspan="4"/>' % _escape(section)
  169. arch += self._group(items)
  170. arch += '<separator colspan="4"/></page>'
  171. # System information
  172. arch += '<page string="System">'
  173. arch += '<separator string="Server Environment" colspan="4"/>'
  174. arch += self._group(self._get_system_cols())
  175. arch += '<separator colspan="4"/></page>'
  176. arch += '</notebook></form>'
  177. self._arch = etree.fromstring(arch)
  178. def fields_view_get(self, cr, uid, view_id=None, view_type='form',
  179. context=None, toolbar=False, submenu=False):
  180. """Overwrite the default method to render the custom view."""
  181. res = super(ServerConfiguration, self).fields_view_get(cr, uid,
  182. view_id,
  183. view_type,
  184. context,
  185. toolbar)
  186. if view_type == 'form':
  187. arch_node = self._arch
  188. xarch, xfields = self._view_look_dom_arch(cr, uid,
  189. arch_node,
  190. view_id,
  191. context=context)
  192. res['arch'] = xarch
  193. res['fields'] = xfields
  194. return res
  195. def default_get(self, cr, uid, fields_list, context=None):
  196. res = {}
  197. for key in self._conf_defaults:
  198. if 'passw' in key and not self.show_passwords:
  199. res[key] = '**********'
  200. else:
  201. res[key] = self._conf_defaults[key]()
  202. return res