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

8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
7 years ago
8 years ago
8 years ago
8 years ago
8 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 urllib2
  27. import logging
  28. import tempfile
  29. import urlparse
  30. import cStringIO
  31. import mimetypes
  32. import collections
  33. import werkzeug.exceptions
  34. from contextlib import closing
  35. from odoo import _
  36. from odoo import tools
  37. from odoo import http
  38. from odoo.http import request
  39. from odoo.http import Response
  40. _logger = logging.getLogger(__name__)
  41. try:
  42. import requests
  43. except ImportError:
  44. _logger.warn('Cannot `import requests`.')
  45. try:
  46. from cachetools import TTLCache
  47. pdf_cache = TTLCache(maxsize=25, ttl=1200)
  48. except ImportError:
  49. _logger.warn('Cannot `import cachetools`.')
  50. try:
  51. import pdfconv
  52. except ImportError:
  53. _logger.warn('Cannot `import pdfconv`.')
  54. class MSOfficeParserController(http.Controller):
  55. @http.route('/web/preview/converter/msoffice', auth="user", type='http')
  56. def convert_msoffice(self, url, export_filename=None, force_compute=False, **kw):
  57. try:
  58. response = pdf_cache[url] if pdf_cache and not force_compute else None
  59. except KeyError:
  60. response = None
  61. if not response:
  62. return self._get_response(url, export_filename)
  63. return response
  64. def _get_response(self, url, export_filename):
  65. if not bool(urlparse.urlparse(url).netloc):
  66. method, params = self._get_route(url)
  67. response = method(**params)
  68. if not response.status_code == 200:
  69. return self._make_error_response(response.status_code,response.description if hasattr(response, 'description') else _("Unknown Error"))
  70. else:
  71. content_type = response.headers['content-type']
  72. data = response.data
  73. else:
  74. try:
  75. response = requests.get(url)
  76. content_type = response.headers['content-type']
  77. data = response.content
  78. except requests.exceptions.RequestException as exception:
  79. return self._make_error_response(exception.response.status_code, exception.response.reason or _("Unknown Error"))
  80. try:
  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(urlparse.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)