ir_module.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287
  1. # -*- coding: utf-8 -*-
  2. import ast
  3. import base64
  4. import logging
  5. import lxml
  6. import os
  7. import sys
  8. import tempfile
  9. import zipfile
  10. from collections import defaultdict
  11. from os.path import join as opj
  12. from odoo import api, fields, models, _
  13. from odoo.exceptions import UserError
  14. from odoo.modules.module import MANIFEST_NAMES
  15. from odoo.tools import convert_csv_import, convert_sql_import, convert_xml_import, exception_to_unicode
  16. from odoo.tools import file_open, file_open_temporary_directory
  17. _logger = logging.getLogger(__name__)
  18. MAX_FILE_SIZE = 100 * 1024 * 1024 # in megabytes
  19. class IrModule(models.Model):
  20. _inherit = "ir.module.module"
  21. imported = fields.Boolean(string="Imported Module")
  22. def _get_modules_to_load_domain(self):
  23. # imported modules are not expected to be loaded as regular modules
  24. return super()._get_modules_to_load_domain() + [('imported', '=', False)]
  25. @api.depends('name')
  26. def _get_latest_version(self):
  27. imported_modules = self.filtered(lambda m: m.imported and m.latest_version)
  28. for module in imported_modules:
  29. module.installed_version = module.latest_version
  30. super(IrModule, self - imported_modules)._get_latest_version()
  31. def _import_module(self, module, path, force=False):
  32. known_mods = self.search([])
  33. known_mods_names = {m.name: m for m in known_mods}
  34. installed_mods = [m.name for m in known_mods if m.state == 'installed']
  35. terp = {}
  36. manifest_path = next((opj(path, name) for name in MANIFEST_NAMES if os.path.exists(opj(path, name))), None)
  37. if manifest_path:
  38. with file_open(manifest_path, 'rb', env=self.env) as f:
  39. terp.update(ast.literal_eval(f.read().decode()))
  40. if not terp:
  41. return False
  42. if not terp.get('icon'):
  43. icon_path = 'static/description/icon.png'
  44. module_icon = module if os.path.exists(opj(path, icon_path)) else 'base'
  45. terp['icon'] = opj('/', module_icon, icon_path)
  46. values = self.get_values_from_terp(terp)
  47. if 'version' in terp:
  48. values['latest_version'] = terp['version']
  49. unmet_dependencies = set(terp.get('depends', [])).difference(installed_mods)
  50. if unmet_dependencies:
  51. if (unmet_dependencies == set(['web_studio']) and
  52. _is_studio_custom(path)):
  53. err = _("Studio customizations require Studio")
  54. else:
  55. err = _("Unmet module dependencies: \n\n - %s") % '\n - '.join(
  56. known_mods.filtered(lambda mod: mod.name in unmet_dependencies).mapped('shortdesc')
  57. )
  58. raise UserError(err)
  59. elif 'web_studio' not in installed_mods and _is_studio_custom(path):
  60. raise UserError(_("Studio customizations require the Odoo Studio app."))
  61. mod = known_mods_names.get(module)
  62. if mod:
  63. mod.write(dict(state='installed', **values))
  64. mode = 'update' if not force else 'init'
  65. else:
  66. assert terp.get('installable', True), "Module not installable"
  67. self.create(dict(name=module, state='installed', imported=True, **values))
  68. mode = 'init'
  69. for kind in ['data', 'init_xml', 'update_xml']:
  70. for filename in terp.get(kind, []):
  71. ext = os.path.splitext(filename)[1].lower()
  72. if ext not in ('.xml', '.csv', '.sql'):
  73. _logger.info("module %s: skip unsupported file %s", module, filename)
  74. continue
  75. _logger.info("module %s: loading %s", module, filename)
  76. noupdate = False
  77. if ext == '.csv' and kind in ('init', 'init_xml'):
  78. noupdate = True
  79. pathname = opj(path, filename)
  80. idref = {}
  81. with file_open(pathname, 'rb', env=self.env) as fp:
  82. if ext == '.csv':
  83. convert_csv_import(self.env.cr, module, pathname, fp.read(), idref, mode, noupdate)
  84. elif ext == '.sql':
  85. convert_sql_import(self.env.cr, fp)
  86. elif ext == '.xml':
  87. convert_xml_import(self.env.cr, module, fp, idref, mode, noupdate)
  88. path_static = opj(path, 'static')
  89. IrAttachment = self.env['ir.attachment']
  90. if os.path.isdir(path_static):
  91. for root, dirs, files in os.walk(path_static):
  92. for static_file in files:
  93. full_path = opj(root, static_file)
  94. with file_open(full_path, 'rb', env=self.env) as fp:
  95. data = base64.b64encode(fp.read())
  96. url_path = '/{}{}'.format(module, full_path.split(path)[1].replace(os.path.sep, '/'))
  97. if not isinstance(url_path, str):
  98. url_path = url_path.decode(sys.getfilesystemencoding())
  99. filename = os.path.split(url_path)[1]
  100. values = dict(
  101. name=filename,
  102. url=url_path,
  103. res_model='ir.ui.view',
  104. type='binary',
  105. datas=data,
  106. )
  107. attachment = IrAttachment.sudo().search([('url', '=', url_path), ('type', '=', 'binary'), ('res_model', '=', 'ir.ui.view')])
  108. if attachment:
  109. attachment.write(values)
  110. else:
  111. attachment = IrAttachment.create(values)
  112. self.env['ir.model.data'].create({
  113. 'name': f"attachment_{url_path}".replace('.', '_'),
  114. 'model': 'ir.attachment',
  115. 'module': module,
  116. 'res_id': attachment.id,
  117. })
  118. IrAsset = self.env['ir.asset']
  119. assets_vals = []
  120. # Generate 'ir.asset' record values for each asset delared in the manifest
  121. for bundle, commands in terp.get('assets', {}).items():
  122. for command in commands:
  123. directive, target, path = IrAsset._process_command(command)
  124. path = path if path.startswith('/') else '/' + path # Ensures a '/' at the start
  125. assets_vals.append({
  126. 'name': f'{module}.{bundle}.{path}',
  127. 'directive': directive,
  128. 'target': target,
  129. 'path': path,
  130. 'bundle': bundle,
  131. })
  132. # Look for existing assets
  133. existing_assets = {
  134. asset.name: asset
  135. for asset in IrAsset.search([('name', 'in', [vals['name'] for vals in assets_vals])])
  136. }
  137. assets_to_create = []
  138. # Update existing assets and generate the list of new assets values
  139. for values in assets_vals:
  140. if values['name'] in existing_assets:
  141. existing_assets[values['name']].write(values)
  142. else:
  143. assets_to_create.append(values)
  144. # Create new assets and attach 'ir.model.data' records to them
  145. created_assets = IrAsset.create(assets_to_create)
  146. self.env['ir.model.data'].create([{
  147. 'name': f"{asset['bundle']}_{asset['path']}".replace(".", "_"),
  148. 'model': 'ir.asset',
  149. 'module': module,
  150. 'res_id': asset.id,
  151. } for asset in created_assets])
  152. return True
  153. @api.model
  154. def import_zipfile(self, module_file, force=False):
  155. if not module_file:
  156. raise Exception(_("No file sent."))
  157. if not zipfile.is_zipfile(module_file):
  158. raise UserError(_('Only zip files are supported.'))
  159. success = []
  160. errors = dict()
  161. module_names = []
  162. with zipfile.ZipFile(module_file, "r") as z:
  163. for zf in z.filelist:
  164. if zf.file_size > MAX_FILE_SIZE:
  165. raise UserError(_("File '%s' exceed maximum allowed file size", zf.filename))
  166. with file_open_temporary_directory(self.env) as module_dir:
  167. manifest_files = [
  168. file
  169. for file in z.filelist
  170. if file.filename.count('/') == 1
  171. and file.filename.split('/')[1] in MANIFEST_NAMES
  172. ]
  173. module_data_files = defaultdict(list)
  174. for manifest in manifest_files:
  175. manifest_path = z.extract(manifest, module_dir)
  176. mod_name = manifest.filename.split('/')[0]
  177. try:
  178. with file_open(manifest_path, 'rb', env=self.env) as f:
  179. terp = ast.literal_eval(f.read().decode())
  180. except Exception:
  181. continue
  182. for filename in terp.get('data', []) + terp.get('init_xml', []) + terp.get('update_xml', []):
  183. if os.path.splitext(filename)[1].lower() not in ('.xml', '.csv', '.sql'):
  184. continue
  185. module_data_files[mod_name].append('%s/%s' % (mod_name, filename))
  186. for file in z.filelist:
  187. filename = file.filename
  188. mod_name = filename.split('/')[0]
  189. is_data_file = filename in module_data_files[mod_name]
  190. is_static = filename.startswith('%s/static' % mod_name)
  191. if is_data_file or is_static:
  192. z.extract(file, module_dir)
  193. dirs = [d for d in os.listdir(module_dir) if os.path.isdir(opj(module_dir, d))]
  194. for mod_name in dirs:
  195. module_names.append(mod_name)
  196. try:
  197. # assert mod_name.startswith('theme_')
  198. path = opj(module_dir, mod_name)
  199. if self._import_module(mod_name, path, force=force):
  200. success.append(mod_name)
  201. except Exception as e:
  202. _logger.exception('Error while importing module')
  203. errors[mod_name] = exception_to_unicode(e)
  204. r = ["Successfully imported module '%s'" % mod for mod in success]
  205. for mod, error in errors.items():
  206. r.append("Error while importing module '%s'.\n\n %s \n Make sure those modules are installed and try again." % (mod, error))
  207. return '\n'.join(r), module_names
  208. def module_uninstall(self):
  209. # Delete an ir_module_module record completely if it was an imported
  210. # one. The rationale behind this is that an imported module *cannot* be
  211. # reinstalled anyway, as it requires the data files. Any attempt to
  212. # install it again will simply fail without trace.
  213. # /!\ modules_to_delete must be calculated before calling super().module_uninstall(),
  214. # because when uninstalling `base_import_module` the `imported` column will no longer be
  215. # in the database but we'll still have an old registry that runs this code.
  216. modules_to_delete = self.filtered('imported')
  217. res = super().module_uninstall()
  218. if modules_to_delete:
  219. deleted_modules_names = modules_to_delete.mapped('name')
  220. assets_data = self.env['ir.model.data'].search([
  221. ('model', '=', 'ir.asset'),
  222. ('module', 'in', deleted_modules_names),
  223. ])
  224. assets = self.env['ir.asset'].search([('id', 'in', assets_data.mapped('res_id'))])
  225. assets.unlink()
  226. _logger.info("deleting imported modules upon uninstallation: %s",
  227. ", ".join(deleted_modules_names))
  228. modules_to_delete.unlink()
  229. return res
  230. def _is_studio_custom(path):
  231. """
  232. Checks the to-be-imported records to see if there are any references to
  233. studio, which would mean that the module was created using studio
  234. Returns True if any of the records contains a context with the key
  235. studio in it, False if none of the records do
  236. """
  237. filepaths = []
  238. for level in os.walk(path):
  239. filepaths += [os.path.join(level[0], fn) for fn in level[2]]
  240. filepaths = [fp for fp in filepaths if fp.lower().endswith('.xml')]
  241. for fp in filepaths:
  242. root = lxml.etree.parse(fp).getroot()
  243. for record in root:
  244. # there might not be a context if it's a non-studio module
  245. try:
  246. # ast.literal_eval is like eval(), but safer
  247. # context is a string representing a python dict
  248. ctx = ast.literal_eval(record.get('context'))
  249. # there are no cases in which studio is false
  250. # so just checking for its existence is enough
  251. if ctx and ctx.get('studio'):
  252. return True
  253. except Exception:
  254. continue
  255. return False