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.

122 lines
4.6 KiB

7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
6 years ago
7 years ago
7 years ago
7 years ago
  1. # -*- coding: utf-8 -*-
  2. ###################################################################################
  3. #
  4. # Copyright (C) 2017 MuK IT GmbH
  5. #
  6. # This program is free software: you can redistribute it and/or modify
  7. # it under the terms of the GNU Affero General Public License as
  8. # published by the Free Software Foundation, either version 3 of the
  9. # License, or (at your option) any later version.
  10. #
  11. # This program is distributed in the hope that it will be useful,
  12. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. # GNU Affero General Public License for more details.
  15. #
  16. # You should have received a copy of the GNU Affero General Public License
  17. # along with this program. If not, see <http://www.gnu.org/licenses/>.
  18. #
  19. ###################################################################################
  20. import os
  21. import sys
  22. import json
  23. import uuid
  24. import base64
  25. import urllib
  26. import logging
  27. import tempfile
  28. import mimetypes
  29. import collections
  30. import werkzeug.exceptions
  31. from contextlib import closing
  32. from urllib.parse import urlparse
  33. from urllib.parse import parse_qsl
  34. from odoo import _
  35. from odoo import tools
  36. from odoo import http
  37. from odoo.http import request
  38. from odoo.http import Response
  39. _logger = logging.getLogger(__name__)
  40. try:
  41. import requests
  42. except ImportError:
  43. _logger.warn('Cannot `import requests`.')
  44. try:
  45. from cachetools import TTLCache
  46. pdf_cache = TTLCache(maxsize=25, ttl=1200)
  47. except ImportError:
  48. _logger.warn('Cannot `import cachetools`.')
  49. try:
  50. import pdfconv
  51. except ImportError:
  52. _logger.warn('Cannot `import pdfconv`.')
  53. class MSOfficeParserController(http.Controller):
  54. @http.route('/web/preview/converter/msoffice', auth="user", type='http')
  55. def convert_msoffice(self, url, export_filename=None, force_compute=False, **kw):
  56. try:
  57. response = pdf_cache[url] if pdf_cache and not force_compute else None
  58. except KeyError:
  59. response = None
  60. if not response:
  61. return self._get_response(url, export_filename)
  62. return response
  63. def _get_response(self, url, export_filename):
  64. if not bool(urlparse(url).netloc):
  65. method, params = self._get_route(url)
  66. response = method(**params)
  67. if not response.status_code == 200:
  68. return self._make_error_response(response.status_code,response.description if hasattr(response, 'description') else _("Unknown Error"))
  69. else:
  70. content_type = response.headers['content-type']
  71. data = response.data
  72. else:
  73. try:
  74. response = requests.get(url)
  75. content_type = response.headers['content-type']
  76. data = response.content
  77. except requests.exceptions.RequestException as exception:
  78. return self._make_error_response(exception.response.status_code, exception.response.reason or _("Unknown Error"))
  79. try:
  80. _logger.info(content_type)
  81. response = self._make_pdf_response(pdfconv.converter.convert_binary2pdf(data, content_type, None, format='binary'), export_filename or uuid.uuid4())
  82. pdf_cache[url] = response
  83. return response
  84. except KeyError:
  85. return werkzeug.exceptions.UnsupportedMediaType(_("The file couldn't be converted. Unsupported mine type."))
  86. except (ImportError, IOError, OSError) as error:
  87. _logger.error(error)
  88. return werkzeug.exceptions.InternalServerError(_("An error occurred during the process. Please contact your system administrator."))
  89. def _get_route(self, url):
  90. url_parts = url.split('?')
  91. path = url_parts[0]
  92. query_string = url_parts[1] if len(url_parts) > 1 else None
  93. router = request.httprequest.app.get_db_router(request.db).bind('')
  94. match = router.match(path, query_args=query_string)
  95. method = router.match(path, query_args=query_string)[0]
  96. params = dict(parse_qsl(query_string))
  97. if len(match) > 1:
  98. params.update(match[1])
  99. return method, params
  100. def _make_error_response(self, status, message):
  101. exception = werkzeug.exceptions.HTTPException()
  102. exception.code = status
  103. exception.description = message
  104. return exception
  105. def _make_pdf_response(self, file, filename):
  106. headers = [('Content-Type', 'application/pdf'),
  107. ('Content-Disposition', 'attachment;filename="{}";'.format(filename)),
  108. ('Content-Length', len(file))]
  109. return request.make_response(file, headers)