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.

155 lines
7.4 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
7 years ago
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. ###################################################################################
  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 import utils_os
  34. _logger = logging.getLogger(__name__)
  35. 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. 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. def formats():
  67. return FORMATS
  68. def imports():
  69. return IMPORTS
  70. def unoconv_environ():
  71. env = os.environ.copy()
  72. uno_path = config.get('uno_path', False)
  73. if uno_path:
  74. env['UNO_PATH'] = config['uno_path']
  75. return env
  76. def convert(input_path, output_path, doctype="document", format="pdf"):
  77. """
  78. Convert a file to the given format.
  79. :param input_path: The path of the file to convert.
  80. :param output_path: The path of the output where the converted file is to be saved.
  81. :param doctype: Specify the document type (document, graphics, presentation, spreadsheet).
  82. :param format: Specify the output format for the document.
  83. :raises CalledProcessError: The command returned non-zero exit status 1.
  84. :raises OSError: This exception is raised when a system function returns a system-related error.
  85. """
  86. try:
  87. env = unoconv_environ()
  88. shell = True if os.name in ('nt', 'os2') else False
  89. args = ['unoconv', '--format=%s' % format, '--output=%s' % output_path, input_path]
  90. process = Popen(args, stdout=PIPE, env=env, shell=shell)
  91. outs, errs = process.communicate()
  92. return_code = process.wait()
  93. if return_code:
  94. raise CalledProcessError(return_code, args, outs, errs)
  95. except CalledProcessError:
  96. _logger.exception("Error while running unoconv.")
  97. raise
  98. except OSError:
  99. _logger.exception("Error while running unoconv.")
  100. raise
  101. def convert_binary(binary, mimetype=None, filename=None, export="binary", doctype="document", format="pdf"):
  102. """
  103. Converts a binary value to the given format.
  104. :param binary: The binary value.
  105. :param mimetype: The mimetype of the binary value.
  106. :param filename: The filename of the binary value.
  107. :param export: The output format (binary, file, base64).
  108. :param doctype: Specify the document type (document, graphics, presentation, spreadsheet).
  109. :param format: Specify the output format for the document.
  110. :return: Returns the output depending on the given format.
  111. :raises ValueError: The file extension could not be determined or the format is invalid.
  112. """
  113. extension = utils_os.get_extension(binary, filename, mimetype)
  114. if not extension:
  115. raise ValueError("The file extension could not be determined.")
  116. if format not in FORMATS:
  117. raise ValueError("Invalid export format.")
  118. if extension not in IMPORTS:
  119. raise ValueError("Invalid import format.")
  120. tmp_dir = tempfile.mkdtemp()
  121. try:
  122. tmp_wpath = os.path.join(tmp_dir, "tmpfile." + extension)
  123. tmp_ppath = os.path.join(tmp_dir, "tmpfile." + format)
  124. if os.name == 'nt':
  125. tmp_wpath = tmp_wpath.replace("\\", "/")
  126. tmp_ppath = tmp_ppath.replace("\\", "/")
  127. with closing(open(tmp_wpath, 'wb')) as file:
  128. file.write(binary)
  129. convert(tmp_wpath, tmp_ppath, doctype, format)
  130. with closing(open(tmp_ppath, 'rb')) as file:
  131. if export == 'file':
  132. output = io.BytesIO()
  133. output.write(file.read())
  134. output.close()
  135. return output
  136. elif export == 'base64':
  137. return base64.b64encode(file.read())
  138. else:
  139. return file.read()
  140. finally:
  141. shutil.rmtree(tmp_dir)