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.

243 lines
8.5 KiB

10 years ago
10 years ago
  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. def func(*a):
  90. return str(value)
  91. return dict.__setitem__(self, key, func)
  92. class ServerConfiguration(models.TransientModel):
  93. """Display server configuration."""
  94. _name = 'server.config'
  95. _conf_defaults = _Defaults()
  96. def __init__(self, pool, cr):
  97. """Add columns to model dynamically
  98. and init some properties
  99. """
  100. self._add_columns()
  101. super(ServerConfiguration, self).__init__(pool, cr)
  102. self.running_env = system_base_config['running_env']
  103. # Only show passwords in development
  104. self.show_passwords = self.running_env in ('dev',)
  105. self._arch = None
  106. self._build_osv()
  107. def _format_key(self, section, key):
  108. return '%s | %s' % (section, key)
  109. def _add_columns(self):
  110. """Add columns to model dynamically"""
  111. cols = chain(
  112. self._get_base_cols().items(),
  113. self._get_env_cols().items(),
  114. self._get_system_cols().items()
  115. )
  116. for col, value in cols:
  117. col_name = col.replace('.', '_')
  118. setattr(ServerConfiguration,
  119. col_name,
  120. fields.Char(string=col, readonly=True))
  121. self._conf_defaults[col_name] = value
  122. def _get_base_cols(self):
  123. """ Compute base fields"""
  124. res = {}
  125. for col, item in system_base_config.options.items():
  126. key = self._format_key('openerp', col)
  127. res[key] = item
  128. return res
  129. def _get_env_cols(self, sections=None):
  130. """ Compute base fields"""
  131. res = {}
  132. sections = sections if sections else serv_config.sections()
  133. for section in sections:
  134. for col, item in serv_config.items(section):
  135. key = self._format_key(section, col)
  136. res[key] = item
  137. return res
  138. def _get_system_cols(self):
  139. """ Compute system fields"""
  140. res = {}
  141. for col, item in get_server_environment():
  142. key = self._format_key('system', col)
  143. res[key] = item
  144. return res
  145. def _group(self, items):
  146. """Return an XML chunk which represents a group of fields."""
  147. names = []
  148. for key in sorted(items):
  149. names.append(key.replace('.', '_'))
  150. return ('<group col="2" colspan="4">' +
  151. ''.join(['<field name="%s" readonly="1"/>' %
  152. _escape(name) for name in names]) +
  153. '</group>')
  154. def _build_osv(self):
  155. """Build the view for the current configuration."""
  156. arch = ('<?xml version="1.0" encoding="utf-8"?>'
  157. '<form string="Configuration Form">'
  158. '<notebook colspan="4">')
  159. # OpenERP server configuration
  160. rcfile = system_base_config.rcfile
  161. items = self._get_base_cols()
  162. arch += '<page string="OpenERP">'
  163. arch += '<separator string="%s" colspan="4"/>' % _escape(rcfile)
  164. arch += self._group(items)
  165. arch += '<separator colspan="4"/></page>'
  166. arch += '<page string="Environment based configurations">'
  167. for section in sorted(serv_config.sections()):
  168. items = self._get_env_cols(sections=[section])
  169. arch += '<separator string="[%s]" colspan="4"/>' % _escape(section)
  170. arch += self._group(items)
  171. arch += '<separator colspan="4"/></page>'
  172. # System information
  173. arch += '<page string="System">'
  174. arch += '<separator string="Server Environment" colspan="4"/>'
  175. arch += self._group(self._get_system_cols())
  176. arch += '<separator colspan="4"/></page>'
  177. arch += '</notebook></form>'
  178. self._arch = etree.fromstring(arch)
  179. def fields_view_get(self, cr, uid, view_id=None, view_type='form',
  180. context=None, toolbar=False, submenu=False):
  181. """Overwrite the default method to render the custom view."""
  182. res = super(ServerConfiguration, self).fields_view_get(cr, uid,
  183. view_id,
  184. view_type,
  185. context,
  186. toolbar)
  187. if view_type == 'form':
  188. arch_node = self._arch
  189. xarch, xfields = self._view_look_dom_arch(cr, uid,
  190. arch_node,
  191. view_id,
  192. context=context)
  193. res['arch'] = xarch
  194. res['fields'] = xfields
  195. return res
  196. def default_get(self, cr, uid, fields_list, context=None):
  197. res = {}
  198. for key in self._conf_defaults:
  199. if 'passw' in key and not self.show_passwords:
  200. res[key] = '**********'
  201. else:
  202. res[key] = self._conf_defaults[key]()
  203. return res