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.

338 lines
14 KiB

10 years ago
  1. # Copyright 2014 ACSONE SA/NV (<http://acsone.eu>)
  2. # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
  3. import logging
  4. import base64
  5. import time
  6. import copy
  7. from urllib.parse import urlparse
  8. from werkzeug.routing import Map, Rule
  9. from lxml import etree as ET
  10. from odoo import models, fields, api, exceptions
  11. from odoo.tools.translate import _
  12. from odoo.addons.web.controllers.main import Binary
  13. from odoo.addons.website.controllers.main import WebsiteBinary
  14. _logger = logging.getLogger(__name__)
  15. PAGE_PREFIX_PARAMETER = 'help_online_page_prefix'
  16. TEMPLATE_PREFIX_PARAMETER = 'help_online_template_prefix'
  17. AUTOBACKUP_PARAMETER = 'help_online_autobackup_path'
  18. HELP_ONLINE_SNIPPET_IMAGE_PATH = '/help_online/static/src/'\
  19. 'img/snippet/snippet_thumbs.png'
  20. class ExportHelpWizard(models.TransientModel):
  21. _name = "export.help.wizard"
  22. _description = 'Export Help Online'
  23. data = fields.Binary('XML', readonly=True)
  24. export_filename = fields.Char('Export XML Filename', size=128)
  25. binary = Binary()
  26. websiteBinary = WebsiteBinary()
  27. img_url_map = Map([
  28. Rule('/web/image'),
  29. Rule('/web/image/<string:xmlid>'),
  30. Rule('/web/image/<string:xmlid>/<string:filename>'),
  31. Rule('/web/image/<string:xmlid>/<int:width>x<int:height>'),
  32. Rule('/web/image/<string:xmlid>/<int:width>x<int:height>/'
  33. '<string:filename>'),
  34. Rule('/web/image/<string:model>/<int:id>/<string:field>'),
  35. Rule('/web/image/<string:model>/<int:id>/<string:field>/'
  36. '<string:filename>'),
  37. Rule('/web/image/<string:model>/<int:id>/<string:field>/'
  38. '<int:width>x<int:height>'),
  39. Rule('/web/image/<string:model>/<int:id>/<string:field>/'
  40. '<int:width>x<int:height>/<string:filename>'),
  41. Rule('/web/image/<int:id>'),
  42. Rule('/web/image/<int:id>/<string:filename>'),
  43. Rule('/web/image/<int:id>/<int:width>x<int:height>'),
  44. Rule('/web/image/<int:id>/<int:width>x<int:height>/<string:filename>'),
  45. Rule('/web/image/<int:id>-<string:unique>'),
  46. Rule('/web/image/<int:id>-<string:unique>/<string:filename>'),
  47. Rule('/web/image/<int:id>-<string:unique>/<int:width>x<int:height>'),
  48. Rule('/web/image/<int:id>-<string:unique>/<int:width>x<int:height>'
  49. '/<string:filename>'),
  50. Rule('/website/image'),
  51. Rule('/website/image/<xmlid>'),
  52. Rule('/website/image/<xmlid>/<int:width>x<int:height>'),
  53. Rule('/website/image/<xmlid>/<field>'),
  54. Rule('/website/image/<xmlid>/<field>/<int:width>x<int:height>'),
  55. Rule('/website/image/<model>/<id>/<field>'),
  56. Rule('/website/image/<model>/<id>/<field>/<int:width>x<int:height>')
  57. ])
  58. def _manage_images_on_page(self, page_node, data_node, exported_resources):
  59. """
  60. - Extract images from page and generate an xml node
  61. - Replace db id in url with xml id
  62. """
  63. img_model = 'ir.attachment'
  64. urls = self.img_url_map.bind("dummy.org", "/")
  65. for img_elem in page_node.iter('img'):
  66. img_src = img_elem.get('src')
  67. parse_result = urlparse.urlparse(img_src)
  68. path = parse_result.path
  69. query_args = parse_result.query
  70. if urls.test(parse_result.path, "GET"):
  71. endpoint, kwargs = urls.match(path, "GET",
  72. query_args=query_args)
  73. kwargs.update(dict(urlparse.parse_qsl(query_args)))
  74. image = None
  75. # get the binary object
  76. xml_id = kwargs.get('xmlid')
  77. if xml_id:
  78. image = self.env.ref(xml_id, False)
  79. else:
  80. _id = kwargs.get('id')
  81. model = kwargs.get('model', 'ir.attachment')
  82. if _id and model:
  83. _id, _, unique = str(_id).partition('_')
  84. image = self.env[model].browse(int(_id))
  85. if (not image or
  86. not image.exists() or
  87. image._name != img_model):
  88. raise exceptions.UserError(
  89. _('Only images from ir.attachment are supported when '
  90. 'exporting help pages'))
  91. exported_data = image.export_data(
  92. ['id',
  93. 'datas',
  94. 'datas_fname',
  95. 'name',
  96. 'res_model',
  97. 'mimetype'],
  98. raw_data=False)['datas'][0]
  99. xml_id = exported_data[0]
  100. new_src = '/web/image/%s' % xml_id
  101. img_elem.attrib['src'] = new_src
  102. if xml_id in exported_resources:
  103. continue
  104. img_node = ET.SubElement(
  105. data_node,
  106. 'record',
  107. attrib={'id': xml_id,
  108. 'model': image._name})
  109. field_node = ET.SubElement(img_node,
  110. 'field',
  111. attrib={'name': 'datas'})
  112. field_node.text = str(exported_data[1])
  113. field_node = ET.SubElement(img_node,
  114. 'field',
  115. attrib={'name': 'datas_fname'})
  116. field_node.text = exported_data[2]
  117. field_node = ET.SubElement(img_node,
  118. 'field',
  119. attrib={'name': 'name'})
  120. field_node.text = exported_data[3]
  121. field_node = ET.SubElement(img_node,
  122. 'field',
  123. attrib={'name': 'res_model'})
  124. field_node.text = exported_data[4]
  125. field_node = ET.SubElement(img_node,
  126. 'field',
  127. attrib={'name': 'mimetype'})
  128. field_node.text = exported_data[5]
  129. data_node.append(img_node)
  130. exported_resources.add(xml_id)
  131. def _clean_href_urls(self, page_node, page_prefix, template_prefix):
  132. """
  133. Remove host address for href urls
  134. """
  135. for a_elem in page_node.iter('a'):
  136. if not a_elem.get('href'):
  137. continue
  138. href = a_elem.get('href')
  139. if not href.startswith('http'):
  140. continue
  141. page_url = '/page/%s' % page_prefix
  142. template_url = '/page/%s' % template_prefix
  143. if page_url not in href and template_url not in href:
  144. continue
  145. elif page_url in href and template_url not in href:
  146. pass
  147. elif page_url not in href and template_url in href:
  148. page_url = template_url
  149. else:
  150. if page_prefix in template_prefix:
  151. page_url = template_url
  152. else:
  153. pass
  154. if page_url:
  155. trail = href.split(page_url, 1)[1]
  156. a_elem.attrib['href'] = page_url + trail
  157. def _generate_snippet_from_template(self, page_node,
  158. template_id, template_prefix):
  159. """
  160. Generate a website snippet from a template
  161. """
  162. page = copy.deepcopy(page_node)
  163. snippet = ET.Element('template')
  164. snippet.attrib['id'] = template_id + '_snippet'
  165. snippet.attrib['inherit_id'] = 'website.snippets'
  166. snippet.attrib['name'] = page_node.attrib['name']
  167. xpath = ET.SubElement(snippet,
  168. 'xpath',
  169. attrib={'expr': "//div[@id='snippet_structure']",
  170. 'position': 'inside'})
  171. main_div = ET.SubElement(xpath,
  172. 'div')
  173. thumbnail = ET.SubElement(main_div,
  174. 'div',
  175. attrib={'class': 'oe_snippet_thumbnail'})
  176. ET.SubElement(thumbnail,
  177. 'img',
  178. attrib={'class': 'oe_snippet_thumbnail_img',
  179. 'src': HELP_ONLINE_SNIPPET_IMAGE_PATH})
  180. span = ET.SubElement(thumbnail,
  181. 'span',
  182. attrib={'class': 'oe_snippet_thumbnail_title'})
  183. span.text = page_node.attrib['name'].replace(template_prefix, '')
  184. body = ET.SubElement(main_div,
  185. 'section',
  186. attrib={'class': 'oe_snippet_body '
  187. 'mt_simple_snippet'})
  188. template = page.find(".//div[@id='wrap']")
  189. for node in template.getchildren():
  190. body.append(node)
  191. return snippet
  192. def _get_qweb_views_data(self):
  193. parameter_model = self.env['ir.config_parameter']
  194. page_prefix = parameter_model.get_param(PAGE_PREFIX_PARAMETER,
  195. False)
  196. template_prefix = parameter_model.get_param(TEMPLATE_PREFIX_PARAMETER,
  197. False)
  198. if not page_prefix or not template_prefix:
  199. return False
  200. domain = [('type', '=', 'qweb'),
  201. ('page', '=', True),
  202. '|',
  203. ('name', 'like', '%s%%' % page_prefix),
  204. ('name', 'like', '%s%%' % template_prefix)]
  205. ir_ui_views = self.env['ir.ui.view'].search(domain, order='name')
  206. xml_to_export = ET.Element('odoo')
  207. data_node = ET.SubElement(xml_to_export, 'data')
  208. exported_resources = set()
  209. for ir_ui_view in ir_ui_views:
  210. parser = ET.XMLParser(remove_blank_text=True)
  211. root = ET.XML(ir_ui_view.arch, parser=parser)
  212. root.tag = 'template'
  213. xml_id = self._get_ir_ui_view_xml_id(
  214. ir_ui_view, root.attrib.pop('t-name'))
  215. root.attrib['name'] = ir_ui_view.name.replace('website.', '')
  216. root.attrib['id'] = xml_id
  217. root.attrib['page'] = 'True'
  218. root.attrib['key'] = ir_ui_view.key
  219. self._manage_images_on_page(root, data_node, exported_resources)
  220. self._clean_href_urls(root, page_prefix, template_prefix)
  221. data_node.append(root)
  222. if root.attrib['name'].startswith(template_prefix):
  223. snippet = self._generate_snippet_from_template(root,
  224. xml_id,
  225. template_prefix)
  226. data_node.append(snippet)
  227. if len(ir_ui_views) > 0:
  228. return ET.tostring(xml_to_export, encoding='utf-8',
  229. xml_declaration=True,
  230. pretty_print=True)
  231. else:
  232. return False
  233. @api.model
  234. def _get_ir_ui_view_xml_id(self, ir_ui_view, template_name):
  235. """This method check if an xml_id exists for the given ir.ui.view
  236. If no xml_id exists, a new one is created with template name as
  237. value to ensure that the import of the generated file will update
  238. the existing view in place of creating new copies.
  239. """
  240. ir_model_data = self.sudo().env['ir.model.data']
  241. data = ir_model_data.search([('model', '=', ir_ui_view._name),
  242. ('res_id', '=', ir_ui_view.id)])
  243. if data:
  244. if data[0].module:
  245. return '%s.%s' % (data[0].module, data[0].name)
  246. else:
  247. return data[0].name
  248. else:
  249. module, name = template_name.split('.')
  250. # always use __export__ as module by convention to
  251. # avoid the removal by odoo of the exported pages on system
  252. # update (-u )
  253. module = "__export__"
  254. postfix = ir_model_data.search_count(
  255. [('module', '=', module),
  256. ('name', 'like', name)])
  257. if postfix:
  258. name = '%s_%s' % (name, postfix)
  259. ir_model_data.create({
  260. 'model': ir_ui_view._name,
  261. 'res_id': ir_ui_view.id,
  262. 'module': module,
  263. 'name': name,
  264. })
  265. return module + '.' + name
  266. @api.multi
  267. def export_help(self):
  268. """
  269. Export all Qweb views related to help online in a Odoo
  270. data XML file
  271. """
  272. xml_data = self._get_qweb_views_data()
  273. if not xml_data:
  274. raise exceptions.Warning(_('No data to export !'))
  275. out = base64.encodestring(xml_data)
  276. self.write({'data': out,
  277. 'export_filename': 'help_online_data.xml'})
  278. return {
  279. 'name': _('Export Help'),
  280. 'type': 'ir.actions.act_window',
  281. 'res_model': self._name,
  282. 'view_mode': 'form',
  283. 'view_type': 'form',
  284. 'res_id': self.id,
  285. 'views': [(False, 'form')],
  286. 'target': 'new',
  287. }
  288. @api.model
  289. def auto_backup(self):
  290. """
  291. Export data to a file on home directory of user
  292. """
  293. parameter_model = self.env['ir.config_parameter']
  294. autobackup_path = parameter_model.get_param(AUTOBACKUP_PARAMETER,
  295. False)
  296. if autobackup_path:
  297. xml_data = self._get_qweb_views_data()
  298. try:
  299. timestr = time.strftime("%Y%m%d-%H%M%S")
  300. filename = '%s/help_online_backup-%s.xml' % (autobackup_path,
  301. timestr)
  302. backup_file = open(filename,
  303. 'w')
  304. backup_file.write(xml_data)
  305. backup_file.close()
  306. except:
  307. _logger.warning(_('Unable to write autobackup file '
  308. 'in given directory: %s'
  309. % autobackup_path))