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.

120 lines
4.5 KiB

7 years ago
7 years ago
7 years ago
7 years ago
7 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 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 Main(http.Controller):
  55. @http.route('/web/preview/converter/msoffice', auth="user", type='http')
  56. def convert_msoffice(self, url, 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, filename)
  63. return pdf
  64. def _get_response(self, url, 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. return self._make_pdf_response(pdfconv.converter.convert_binary2pdf(data, content_type, filename, format='binary'), filename or uuid.uuid4())
  82. except KeyError:
  83. return werkzeug.exceptions.UnsupportedMediaType(_("The file couldn't be converted. Unsupported mine type."))
  84. except (ImportError, IOError, WindowsError) as error:
  85. _logger.error(error)
  86. return werkzeug.exceptions.InternalServerError(_("An error occurred during the process. Please contact your system administrator."))
  87. def _get_route(self, url):
  88. url_parts = url.split('?')
  89. path = url_parts[0]
  90. query_string = url_parts[1] if len(url_parts) > 1 else None
  91. router = request.httprequest.app.get_db_router(request.db).bind('')
  92. match = router.match(path, query_args=query_string)
  93. method = router.match(path, query_args=query_string)[0]
  94. params = dict(urlparse.parse_qsl(query_string))
  95. if len(match) > 1:
  96. params.update(match[1])
  97. return method, params
  98. def _make_error_response(self, status, message):
  99. exception = werkzeug.exceptions.HTTPException()
  100. exception.code = status
  101. exception.description = message
  102. return exception
  103. def _make_pdf_response(self, file, filename):
  104. headers = [('Content-Type', 'application/pdf'),
  105. ('Content-Disposition', 'attachment;filename={};'.format(filename)),
  106. ('Content-Length', len(file))]
  107. return request.make_response(file, headers)