Skip to content

Commit 33f3a8c

Browse files
committed
Improved utils convert function to convert files other than odt
1 parent afaddd7 commit 33f3a8c

File tree

3 files changed

+39
-57
lines changed

3 files changed

+39
-57
lines changed

src/collective/documentgenerator/browser/converter.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
# -*- coding: utf-8 -*-
2-
from collective.documentgenerator.utils import convert_and_save_odt
3-
from collective.documentgenerator.utils import convert_odt
2+
from collective.documentgenerator.utils import convert_and_save_file
3+
from collective.documentgenerator.utils import convert_file
44
from plone.namedfile.file import NamedBlobFile
55
from Products.Five import BrowserView
66

@@ -19,7 +19,7 @@ def get_params(self):
1919

2020
def __call__(self):
2121
output_name, fmt = self.get_params()
22-
converted_filename, converted_file = convert_odt(self.context.file, output_name, fmt=fmt)
22+
converted_filename, converted_file = convert_file(self.context.file, output_name, fmt=fmt)
2323

2424
# Set headers
2525
response = self.request.RESPONSE
@@ -38,6 +38,6 @@ class PersistentDocumentConvertView(DocumentConvertView):
3838

3939
def __call__(self):
4040
output_name, fmt = self.get_params()
41-
convert_and_save_odt(self.context.file, self.context.aq_parent, self.context.portal_type, output_name, fmt=fmt)
41+
convert_and_save_file(self.context.file, self.context.aq_parent, self.context.portal_type, output_name, fmt=fmt)
4242

4343
self.request.response.redirect(self.context.aq_parent.absolute_url())

src/collective/documentgenerator/tests/test_utils.py

Lines changed: 14 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
# -*- coding: utf-8 -*-
22
from collective.documentgenerator.testing import PODTemplateIntegrationTest
33
from collective.documentgenerator.utils import compute_md5
4-
from collective.documentgenerator.utils import convert_odt
4+
from collective.documentgenerator.utils import convert_file
55
from collective.documentgenerator.utils import odfsplit
66
from collective.documentgenerator.utils import temporary_file_name
77
from collective.documentgenerator.utils import update_dict_with_validation
@@ -166,7 +166,7 @@ def test_update_oo_config(self):
166166
if original_uno:
167167
os.environ['PYTHON_UNO'] = original_uno
168168

169-
def test_convert_odt(self):
169+
def test_convert_file(self):
170170
filename = u"test_file.odt"
171171
current_path = os.path.dirname(__file__)
172172
odt_file = open(os.path.join(current_path, filename), "r").read()
@@ -177,35 +177,35 @@ def test_convert_odt(self):
177177
)
178178

179179
# convert to pdf
180-
output_name, content = convert_odt(odt_blob_file, filename.replace(".odt", ".pdf"), fmt="pdf")
181-
self.assertEqual(output_name, filename.replace(".odt", ".pdf"))
180+
output_name, content = convert_file(odt_blob_file, filename.replace(".odt", ".pdf"), fmt="pdf")
181+
self.assertEqual(output_name, u"test_file.pdf")
182182
self.assertTrue(content.startswith("%PDF-"))
183183

184184
# convert to odt
185-
output_name, content = convert_odt(odt_blob_file, filename.replace(".odt", ".odt"), fmt="odt")
186-
self.assertEqual(output_name, filename.replace(".odt", ".odt"))
185+
output_name, content = convert_file(odt_blob_file, filename.replace(".odt", ".odt"), fmt="odt")
186+
self.assertEqual(output_name, u"test_file.odt")
187187
self.assertTrue(content.startswith("PK"))
188188
self.assertIn("mimetype", content) # ODT files contain 'mimetype' in the zip
189189

190190
# convert to docx
191-
output_name, content = convert_odt(odt_blob_file, filename.replace(".odt", ".docx"), fmt="docx")
192-
self.assertEqual(output_name, filename.replace(".odt", ".docx"))
191+
output_name, content = convert_file(odt_blob_file, filename.replace(".odt", ".docx"), fmt="docx")
192+
self.assertEqual(output_name, u"test_file.docx")
193193
self.assertTrue(content.startswith("PK"))
194194
self.assertIn("[Content_Types].xml", content) # DOCX files contain this file
195195

196196
# convert to rtf
197-
output_name, content = convert_odt(odt_blob_file, filename.replace(".odt", ".rtf"), fmt="rtf")
198-
self.assertEqual(output_name, filename.replace(".odt", ".rtf"))
197+
output_name, content = convert_file(odt_blob_file, filename.replace(".odt", ".rtf"), fmt="rtf")
198+
self.assertEqual(output_name, u"test_file.rtf")
199199
self.assertTrue(content.startswith("{\\rtf1"))
200200

201201
# convert to txt
202-
output_name, content = convert_odt(odt_blob_file, filename.replace(".odt", ".txt"), fmt="txt")
203-
self.assertEqual(output_name, filename.replace(".odt", ".txt"))
202+
output_name, content = convert_file(odt_blob_file, filename.replace(".odt", ".txt"), fmt="txt")
203+
self.assertEqual(output_name, u"test_file.txt")
204204
self.assertEqual(content, "Page 1\nPage 2\n")
205205

206206
# convert to html
207-
output_name, content = convert_odt(odt_blob_file, filename.replace(".odt", ".html"), fmt="html")
208-
self.assertEqual(output_name, filename.replace(".odt", ".html"))
207+
output_name, content = convert_file(odt_blob_file, filename.replace(".odt", ".html"), fmt="html")
208+
self.assertEqual(output_name, u"test_file.html")
209209
self.assertTrue(content.startswith("<!DOCTYPE html>"))
210210
self.assertIn("<html>", content)
211211
self.assertIn("<body", content)

src/collective/documentgenerator/utils.py

Lines changed: 21 additions & 39 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,7 @@
11
# -*- coding: utf-8 -*-
22
from appy.bin.odfclean import Cleaner
3-
from appy.pod.lo_pool import LoPool
4-
from appy.pod.renderer import Renderer
53
from collective.documentgenerator import _
64
from collective.documentgenerator import BLDT_DIR
7-
from collective.documentgenerator import config
85
from imio.helpers.content import uuidToObject
96
from imio.helpers.security import fplog
107
from imio.pyutils.system import runCommand
@@ -224,56 +221,42 @@ def clean_notes(pod_template):
224221
return bool(cleaned)
225222

226223

227-
def convert_odt(afile, output_name, fmt='pdf', **kwargs):
224+
def convert_file(afile, output_name, fmt='pdf'):
228225
"""
229-
Convert an odt file to another format using appy.pod.
226+
Convert a file to another libreoffice readable format using appy.pod
230227
231228
:param afile: file field content like NamedBlobFile
232229
:param output_name: output name
233230
:param fmt: output format, default to 'pdf'
234-
:param kwargs: other parameters passed to Renderer, i.e pdfOptions='ExportNotes=True;SelectPdfVersion=1'
235231
"""
236-
lo_pool = LoPool.get(
237-
python=config.get_uno_path(),
238-
server=config.get_oo_server(),
239-
port=config.get_oo_port_list(),
240-
)
241-
if not lo_pool:
242-
raise Exception("Could not find LibreOffice, check your configuration")
243-
244-
temp_file = create_temporary_file(afile, '.odt')
245-
converted_filename = None
232+
from appy.pod import converter
233+
converter_path = converter.__file__.endswith('.pyc') and converter.__file__[:-1] or converter.__file__
234+
file_ext = afile.filename.split('.')[-1].lower()
235+
temp_file = create_temporary_file(afile, base_name='.{}'.format(file_ext))
236+
converted_filename = temp_file.name.replace('.{}'.format(file_ext), '.{}'.format(fmt))
237+
converted_file = ''
246238
try:
247-
renderer = Renderer(
248-
temp_file.name,
249-
afile,
250-
temporary_file_name(suffix=".{extension}".format(extension=fmt)),
251-
**kwargs
252-
)
253-
254-
lo_pool(renderer, temp_file.name, fmt)
255-
converted_filename = temp_file.name.replace('.odt', '.{}'.format(fmt))
256-
if not os.path.exists(converted_filename):
257-
api.portal.show_message(
258-
message=_(u"Conversion failed, no converted file '{}'".format(safe_unicode(output_name))),
259-
request=getSite().REQUEST,
260-
type="error",
261-
)
262-
raise Invalid(u"Conversion failed, no converted file '{}'".format(safe_unicode(output_name)))
239+
command = "python3 {converter_path} {temp_file} {fmt}".format(converter_path=converter_path, temp_file=temp_file.name, fmt=fmt)
240+
out, err, code = runCommand(command)
241+
# This command has no output on success
242+
if code != 0 or err or not os.path.exists(converted_filename):
243+
print(code, out, err, converted_filename, os.path.exists(converted_filename))
244+
message = _(u"Conversion failed, no converted file '{}'".format(safe_unicode(output_name)))
245+
raise Invalid(message)
263246
with open(converted_filename, 'rb') as f:
264247
converted_file = f.read()
248+
except Exception as e:
249+
api.portal.show_message(message=str(e), request=getSite().REQUEST, type="error")
265250
finally:
266251
remove_tmp_file(temp_file.name)
267-
if converted_filename:
252+
if os.path.exists(converted_filename):
268253
remove_tmp_file(converted_filename)
269-
270254
return output_name, converted_file
271255

272256

273-
def convert_and_save_odt(afile, container, portal_type, output_name, fmt='pdf', from_uid=None, attributes=None,
274-
**kwargs):
257+
def convert_and_save_file(afile, container, portal_type, output_name, fmt='pdf', from_uid=None, attributes=None):
275258
"""
276-
Convert an odt file to another format using appy.pod and save it in a NamedBlobFile.
259+
Convert a file to another libreoffice readable format using appy.pod and save it in a NamedBlobFile.
277260
278261
:param afile: file field content like NamedBlobFile
279262
:param container: container object to create new file
@@ -282,9 +265,8 @@ def convert_and_save_odt(afile, container, portal_type, output_name, fmt='pdf',
282265
:param fmt: output format, default to 'pdf'
283266
:param from_uid: uid from original file object
284267
:param attributes: dict of other attributes to set on created content
285-
:param kwargs: other parameters passed to Renderer, i.e pdfOptions='ExportNotes=True;SelectPdfVersion=1'
286268
"""
287-
converted_filename, converted_file = convert_odt(afile, output_name, fmt=fmt, **kwargs)
269+
converted_filename, converted_file = convert_file(afile, output_name, fmt=fmt)
288270
file_object = NamedBlobFile(converted_file, filename=safe_unicode(converted_filename))
289271
if attributes is None:
290272
attributes = {}

0 commit comments

Comments
 (0)