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.

275 lines
11 KiB

  1. # -*- coding: utf-8 -*-
  2. ##############################################################################
  3. #
  4. # Authors: Cédric Pigeon
  5. # Copyright (c) 2014 Acsone SA/NV (http://www.acsone.eu)
  6. #
  7. # This program is free software: you can redistribute it and/or modify
  8. # it under the terms of the GNU Affero General Public License as published
  9. # by 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 Affero General Public License for more details.
  16. #
  17. # You should have received a copy of the GNU Affero General Public License
  18. # along with this program. If not, see <http://www.gnu.org/licenses/>.
  19. #
  20. ##############################################################################
  21. import logging
  22. import base64
  23. import time
  24. import copy
  25. from lxml import etree as ET
  26. from openerp import models, fields, api, exceptions
  27. from openerp.tools.translate import _
  28. _logger = logging.getLogger(__name__)
  29. PAGE_PREFIX_PARAMETER = 'help_online_page_prefix'
  30. TEMPLATE_PREFIX_PARAMETER = 'help_online_template_prefix'
  31. AUTOBACKUP_PARAMETER = 'help_online_autobackup_path'
  32. HELP_ONLINE_SNIPPET_IMAGE_PATH = '/help_online/static/src/'\
  33. 'img/snippet/snippet_thumbs.png'
  34. class ExportHelpWizard(models.TransientModel):
  35. _name = "export.help.wizard"
  36. _description = 'Export Help Online'
  37. data = fields.Binary('XML', readonly=True)
  38. export_filename = fields.Char('Export XML Filename', size=128)
  39. def _manage_images_on_page(self, page_node, data_node):
  40. """
  41. - Extract images from page and generate a xml node
  42. - Replace db id in url with xml id
  43. """
  44. def substitute_id_by_xml_id(img_elem):
  45. new_src = False
  46. attach_id = False
  47. img_src = img_elem.get('src')
  48. if 'id=' in img_src:
  49. id_pos = img_src.index('id=') + 3
  50. attach_id = img_elem.get('src')[id_pos:]
  51. new_src = img_src.replace(attach_id, xml_id)
  52. else:
  53. fragments = img_src.split('ir.attachment/')
  54. attach_id, trail = fragments[1].split('_', 1)
  55. new_src = "/website/image/ir.attachment/%s|%s" % \
  56. (xml_id, trail)
  57. return new_src, attach_id
  58. i_img = 0
  59. img_model = 'ir.attachment'
  60. for img_elem in page_node.iter('img'):
  61. if img_model in img_elem.get('src'):
  62. i_img += 1
  63. xml_id = "%s_img_%s" % \
  64. (page_node.attrib['name'], str(i_img).rjust(2, '0'))
  65. new_src, attach_id = substitute_id_by_xml_id(img_elem)
  66. if not attach_id:
  67. continue
  68. image = self.env[img_model].browse(int(attach_id))
  69. if not image:
  70. continue
  71. img_elem.attrib['src'] = new_src
  72. img_node = ET.SubElement(data_node,
  73. 'record',
  74. attrib={'id': xml_id,
  75. 'model': img_model})
  76. field_node = ET.SubElement(img_node,
  77. 'field',
  78. attrib={'name': 'datas'})
  79. field_node.text = str(image.datas)
  80. field_node = ET.SubElement(img_node,
  81. 'field',
  82. attrib={'name': 'datas_fname'})
  83. field_node.text = image.datas_fname
  84. field_node = ET.SubElement(img_node,
  85. 'field',
  86. attrib={'name': 'name'})
  87. field_node.text = image.name
  88. field_node = ET.SubElement(img_node,
  89. 'field',
  90. attrib={'name': 'res_model'})
  91. field_node.text = image.res_model
  92. field_node = ET.SubElement(img_node,
  93. 'field',
  94. attrib={'name': 'mimetype'})
  95. field_node.text = image.mimetype
  96. data_node.append(img_node)
  97. def _clean_href_urls(self, page_node, page_prefix, template_prefix):
  98. """
  99. Remove host address for href urls
  100. """
  101. for a_elem in page_node.iter('a'):
  102. if not a_elem.get('href'):
  103. continue
  104. href = a_elem.get('href')
  105. if not href.startswith('http'):
  106. continue
  107. page_url = '/page/%s' % page_prefix
  108. template_url = '/page/%s' % template_prefix
  109. if page_url not in href and template_url not in href:
  110. continue
  111. elif page_url in href and template_url not in href:
  112. pass
  113. elif page_url not in href and template_url in href:
  114. page_url = template_url
  115. else:
  116. if page_prefix in template_prefix:
  117. page_url = template_url
  118. else:
  119. pass
  120. if page_url:
  121. trail = href.split(page_url, 1)[1]
  122. a_elem.attrib['href'] = page_url + trail
  123. def _generate_snippet_from_template(self, page_node,
  124. template_id, template_prefix):
  125. """
  126. Generate a website snippet from a template
  127. """
  128. page = copy.deepcopy(page_node)
  129. snippet = ET.Element('template')
  130. snippet.attrib['id'] = template_id + '_snippet'
  131. snippet.attrib['inherit_id'] = 'website.snippets'
  132. snippet.attrib['name'] = page_node.attrib['name']
  133. xpath = ET.SubElement(snippet,
  134. 'xpath',
  135. attrib={'expr': "//div[@id='snippet_structure']",
  136. 'position': 'inside'})
  137. main_div = ET.SubElement(xpath,
  138. 'div')
  139. thumbnail = ET.SubElement(main_div,
  140. 'div',
  141. attrib={'class': 'oe_snippet_thumbnail'})
  142. ET.SubElement(thumbnail,
  143. 'img',
  144. attrib={'class': 'oe_snippet_thumbnail_img',
  145. 'src': HELP_ONLINE_SNIPPET_IMAGE_PATH})
  146. span = ET.SubElement(thumbnail,
  147. 'span',
  148. attrib={'class': 'oe_snippet_thumbnail_title'})
  149. span.text = page_node.attrib['name'].replace(template_prefix, '')
  150. body = ET.SubElement(main_div,
  151. 'section',
  152. attrib={'class': 'oe_snippet_body '
  153. 'mt_simple_snippet'})
  154. template = page.find(".//div[@id='wrap']")
  155. for node in template.getchildren():
  156. body.append(node)
  157. return snippet
  158. def _get_qweb_views_data(self):
  159. parameter_model = self.env['ir.config_parameter']
  160. page_prefix = parameter_model.get_param(PAGE_PREFIX_PARAMETER,
  161. False)
  162. template_prefix = parameter_model.get_param(TEMPLATE_PREFIX_PARAMETER,
  163. False)
  164. if not page_prefix or not template_prefix:
  165. return False
  166. domain = [('type', '=', 'qweb'),
  167. ('page', '=', True),
  168. '|',
  169. ('name', 'like', '%s%%' % page_prefix),
  170. ('name', 'like', '%s%%' % template_prefix)]
  171. view_data_list = self.env['ir.ui.view'].search_read(domain,
  172. ['arch', 'name'],
  173. order='name')
  174. xml_to_export = ET.Element('openerp')
  175. data_node = ET.SubElement(xml_to_export, 'data')
  176. for view_data in view_data_list:
  177. parser = ET.XMLParser(remove_blank_text=True)
  178. root = ET.XML(view_data['arch'], parser=parser)
  179. root.tag = 'template'
  180. template_id = root.attrib.pop('t-name')
  181. root.attrib['name'] = view_data['name'].replace('website.', '')
  182. root.attrib['id'] = template_id
  183. root.attrib['page'] = 'True'
  184. self._manage_images_on_page(root, data_node)
  185. self._clean_href_urls(root, page_prefix, template_prefix)
  186. data_node.append(root)
  187. if root.attrib['name'].startswith(template_prefix):
  188. snippet = self._generate_snippet_from_template(root,
  189. template_id,
  190. template_prefix)
  191. data_node.append(snippet)
  192. if len(view_data_list) > 0:
  193. return ET.tostring(xml_to_export, encoding='utf-8',
  194. xml_declaration=True,
  195. pretty_print=True)
  196. else:
  197. return False
  198. @api.multi
  199. def export_help(self):
  200. """
  201. Export all Qweb views related to help online in a Odoo
  202. data XML file
  203. """
  204. xml_data = self._get_qweb_views_data()
  205. if not xml_data:
  206. raise exceptions.Warning(_('No data to export !'))
  207. out = base64.encodestring(xml_data)
  208. self.write({'data': out,
  209. 'export_filename': 'help_online_data.xml'})
  210. return {
  211. 'name': _('Export Help'),
  212. 'type': 'ir.actions.act_window',
  213. 'res_model': self._name,
  214. 'view_mode': 'form',
  215. 'view_type': 'form',
  216. 'res_id': self.id,
  217. 'views': [(False, 'form')],
  218. 'target': 'new',
  219. }
  220. @api.model
  221. def auto_backup(self):
  222. """
  223. Export data to a file on home directory of user
  224. """
  225. parameter_model = self.env['ir.config_parameter']
  226. autobackup_path = parameter_model.get_param(AUTOBACKUP_PARAMETER,
  227. False)
  228. if autobackup_path:
  229. xml_data = self._get_qweb_views_data()
  230. try:
  231. timestr = time.strftime("%Y%m%d-%H%M%S")
  232. filename = '%s/help_online_backup-%s.xml' % (autobackup_path,
  233. timestr)
  234. backup_file = open(filename,
  235. 'w')
  236. backup_file.write(xml_data)
  237. backup_file.close
  238. except:
  239. _logger.warning(_('Unable to write autobackup file '
  240. 'in given directory: %s'
  241. % autobackup_path))