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.

147 lines
7.0 KiB

  1. ###################################################################################
  2. #
  3. # Copyright (C) 2018 MuK IT GmbH
  4. #
  5. # This program is free software: you can redistribute it and/or modify
  6. # it under the terms of the GNU Affero General Public License as
  7. # published by the Free Software Foundation, either version 3 of the
  8. # License, or (at your option) any later version.
  9. #
  10. # This program is distributed in the hope that it will be useful,
  11. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. # GNU Affero General Public License for more details.
  14. #
  15. # You should have received a copy of the GNU Affero General Public License
  16. # along with this program. If not, see <http://www.gnu.org/licenses/>.
  17. #
  18. ###################################################################################
  19. import os
  20. import io
  21. import base64
  22. import shutil
  23. import urllib
  24. import logging
  25. import tempfile
  26. import mimetypes
  27. from subprocess import Popen
  28. from subprocess import PIPE
  29. from subprocess import CalledProcessError
  30. from contextlib import closing
  31. from odoo.tools import config
  32. from odoo.tools.mimetypes import guess_mimetype
  33. from odoo.addons.muk_utils.tools.file import guess_extension
  34. _logger = logging.getLogger(__name__)
  35. UNOCONV_FORMATS = [
  36. "bib", "bmp", "csv", "dbf", "dif", "doc", "doc6", "doc95", "docbook", "docx", "docx7", "emf",
  37. "eps", "fodg", "fodp", "fods", "fodt", "gif", "html", "jpg", "latex", "mediawiki", "met", "odd",
  38. "odg", "odp", "ods", "odt", "ooxml", "otg", "otp", "ots", "ott", "pbm", "pct", "pdb", "pdf", "pgm",
  39. "png", "pot", "potm", "ppm", "pps", "ppt", "pptx", "psw", "pwp", "pxl", "ras", "rtf", "sda", "sdc",
  40. "sdc3", "sdc4", "sdd", "sdd3", "sdd4", "sdw", "sdw3", "sdw4", "slk", "stc", "std", "sti", "stw",
  41. "svg", "svm", "swf", "sxc", "sxd", "sxd3", "sxd5", "sxi", "sxw", "text", "tiff", "txt", "uop", "uos",
  42. "uot", "vor", "vor3", "vor4", "vor5", "wmf", "wps", "xhtml", "xls", "xls5", "xls95", "xlsx", "xlt",
  43. "xlt5", "xlt95", "xpm""bib", "bmp", "csv", "dbf", "dif", "doc", "doc6", "doc95", "docbook", "docx",
  44. "docx7", "emf", "eps", "fodg", "fodp", "fods", "fodt", "gif", "html", "jpg", "latex", "mediawiki",
  45. "met", "odd", "odg", "odp", "ods", "odt", "ooxml", "otg", "otp", "ots", "ott", "pbm", "pct", "pdb",
  46. "pdf", "pgm", "png", "pot", "potm", "ppm", "pps", "ppt", "pptx", "psw", "pwp", "pxl", "ras", "rtf",
  47. "sda", "sdc", "sdc3", "sdc4", "sdd", "sdd3", "sdd4", "sdw", "sdw3", "sdw4", "slk", "stc", "std",
  48. "sti", "stw", "svg", "svm", "swf", "sxc", "sxd", "sxd3", "sxd5", "sxi", "sxw", "text", "tiff",
  49. "txt", "uop", "uos", "uot", "vor", "vor3", "vor4", "vor5", "wmf", "wps", "xhtml", "xls", "xls5",
  50. "xls95", "xlsx", "xlt", "xlt5", "xlt95", "xpm"
  51. ]
  52. UNOCONV_IMPORTS = [
  53. "bmp", "csv", "dbf", "dif", "doc", "docx", "dot", "emf", "eps", "epub", "fodg", "fodp", "fods",
  54. "fodt", "gif", "gnm", "gnumeric", "htm", "html", "jpeg", "jpg", "met", "mml", "odb", "odf", "odg",
  55. "odp", "ods", "odt", "pbm", "pct", "pdb", "pdf", "pgm", "png", "pot", "ppm", "pps", "ppt", "pptx",
  56. "psw", "pxl", "ras", "rtf", "sda", "sdc", "sdd", "sdp", "sdw", "sgl", "slk", "stc", "std", "sti",
  57. "stw", "svg", "svm", "swf", "sxc", "sxd", "sxi", "sxm", "sxw", "tif", "tiff", "txt", "uof", "uop",
  58. "uos", "uot", "vor", "wmf", "wri", "xls", "xlsx", "xlt", "xlw", "xml", "xpm""bmp", "csv", "dbf",
  59. "dif", "doc", "docx", "dot", "emf", "eps", "epub", "fodg", "fodp", "fods", "fodt", "gif", "gnm",
  60. "gnumeric", "htm", "html", "jpeg", "jpg", "met", "mml", "odb", "odf", "odg", "odp", "ods", "odt",
  61. "pbm", "pct", "pdb", "pdf", "pgm", "png", "pot", "ppm", "pps", "ppt", "pptx", "psw", "pxl", "ras",
  62. "rtf", "sda", "sdc", "sdd", "sdp", "sdw", "sgl", "slk", "stc", "std", "sti", "stw", "svg", "svm",
  63. "swf", "sxc", "sxd", "sxi", "sxm", "sxw", "tif", "tiff", "text", "uof", "uop", "uos", "uot", "vor",
  64. "wmf", "wri", "xls", "xlsx", "xlt", "xlw", "xml", "xpm"
  65. ]
  66. class UnoconvConverter(object):
  67. @property
  68. def formats(self):
  69. return UNOCONV_FORMATS
  70. @property
  71. def imports(self):
  72. return UNOCONV_IMPORTS
  73. def environ(self):
  74. env = os.environ.copy()
  75. uno_path = config.get('uno_path', False)
  76. if uno_path:
  77. env['UNO_PATH'] = config['uno_path']
  78. return env
  79. def convert(self, binary, mimetype=None, filename=None, export="binary", doctype="document", format="pdf"):
  80. """ Converts a binary value to the given format.
  81. :param binary: The binary value.
  82. :param mimetype: The mimetype of the binary value.
  83. :param filename: The filename of the binary value.
  84. :param export: The output format (binary, file, base64).
  85. :param doctype: Specify the document type (document, graphics, presentation, spreadsheet).
  86. :param format: Specify the output format for the document.
  87. :return: Returns the output depending on the given format.
  88. :raises ValueError: The file extension could not be determined or the format is invalid.
  89. """
  90. extension = guess_extension(filename=filename, mimetype=mimetype, binary=binary)
  91. if not extension:
  92. raise ValueError("The file extension could not be determined.")
  93. if format not in self.formats:
  94. raise ValueError("Invalid export format.")
  95. if extension not in self.imports:
  96. raise ValueError("Invalid import format.")
  97. tmp_dir = tempfile.mkdtemp()
  98. try:
  99. tmp_wpath = os.path.join(tmp_dir, "tmpfile." + extension)
  100. tmp_ppath = os.path.join(tmp_dir, "tmpfile." + format)
  101. if os.name == 'nt':
  102. tmp_wpath = tmp_wpath.replace("\\", "/")
  103. tmp_ppath = tmp_ppath.replace("\\", "/")
  104. with closing(open(tmp_wpath, 'wb')) as file:
  105. file.write(binary)
  106. shell = True if os.name in ('nt', 'os2') else False
  107. args = ['unoconv', '--format=%s' % format, '--output=%s' % tmp_ppath, tmp_wpath]
  108. process = Popen(args, stdout=PIPE, env=self.environ(), shell=shell)
  109. outs, errs = process.communicate()
  110. return_code = process.wait()
  111. if return_code:
  112. raise CalledProcessError(return_code, args, outs, errs)
  113. with closing(open(tmp_ppath, 'rb')) as file:
  114. if export == 'file':
  115. output = io.BytesIO()
  116. output.write(file.read())
  117. output.close()
  118. return output
  119. elif export == 'base64':
  120. return base64.b64encode(file.read())
  121. else:
  122. return file.read()
  123. except CalledProcessError:
  124. _logger.exception("Error while running unoconv.")
  125. raise
  126. except OSError:
  127. _logger.exception("Error while running unoconv.")
  128. raise
  129. finally:
  130. shutil.rmtree(tmp_dir)
  131. unoconv = UnoconvConverter()