Commit 4b1f48f8 authored by Tristan Cavelier's avatar Tristan Cavelier Committed by Cédric Le Ninivin

implement getAllowedConversionFormat

parent c0752dba
...@@ -123,3 +123,16 @@ class Handler(object): ...@@ -123,3 +123,16 @@ class Handler(object):
return self.input.getContent() return self.input.getContent()
finally: finally:
self.input.trash() self.input.trash()
@staticmethod
def getAllowedConversionFormatList(source_mimetype):
"""Returns a list content_type and their titles which are supported
by enabled handlers.
[('audio/ogg;codecs=opus', 'Opus Audio File Format'),
('video/webm', 'Webm Video File Format'),
...
]
"""
# XXX NotImplemented
return []
...@@ -91,3 +91,16 @@ class Handler(object): ...@@ -91,3 +91,16 @@ class Handler(object):
metadata -- expected an dictionary with metadata. metadata -- expected an dictionary with metadata.
""" """
raise NotImplementedError raise NotImplementedError
@staticmethod
def getAllowedConversionFormatList(source_mimetype):
"""Returns a list content_type and their titles which are supported
by enabled handlers.
[('image/jpeg', 'Jpeg Image File Format'),
('image/png', 'Png Image File Format'),
...
]
"""
# XXX NotImplemented
return []
...@@ -29,6 +29,7 @@ ...@@ -29,6 +29,7 @@
import json import json
import re import re
import pkg_resources import pkg_resources
import mimetypes
from base64 import decodestring, encodestring from base64 import decodestring, encodestring
from os import environ, path from os import environ, path
from subprocess import Popen, PIPE from subprocess import Popen, PIPE
...@@ -39,7 +40,7 @@ from cloudooo.handler.ooo.mimemapper import mimemapper ...@@ -39,7 +40,7 @@ from cloudooo.handler.ooo.mimemapper import mimemapper
from cloudooo.handler.ooo.document import FileSystemDocument from cloudooo.handler.ooo.document import FileSystemDocument
from cloudooo.handler.ooo.monitor.timeout import MonitorTimeout from cloudooo.handler.ooo.monitor.timeout import MonitorTimeout
from cloudooo.handler.ooo.monitor import monitor_sleeping_time from cloudooo.handler.ooo.monitor import monitor_sleeping_time
from cloudooo.util import logger from cloudooo.util import logger, parseContentType
from psutil import pid_exists from psutil import pid_exists
...@@ -213,6 +214,37 @@ class Handler(object): ...@@ -213,6 +214,37 @@ class Handler(object):
self.document.trash() self.document.trash()
return doc_loaded return doc_loaded
@staticmethod
def getAllowedConversionFormatList(source_mimetype):
"""Returns a list content_type and their titles which are supported
by enabled handlers.
[('application/vnd.oasis.opendocument.text', 'ODF Text Document'),
('application/pdf', 'PDF - Portable Document Format'),
...
]
"""
# XXX please never guess extension from mimetype
output_set = set()
if "/" in source_mimetype:
parsed_mimetype_type = parseContentType(source_mimetype).gettype()
# here `guess_all_extensions` never handles mimetype parameters
# (even for `text/plain;charset=UTF-8` which is standard)
extension_list = mimetypes.guess_all_extensions(parsed_mimetype_type) # XXX never guess
else:
extension_list = [source_mimetype]
for ext in extension_list:
for ext, title in mimemapper.getAllowedExtensionList(extension=ext.replace(".", "")):
if ext in ("fodt", ".fodt"): # BBB
output_set.add(("application/vnd.oasis.opendocument.text-flat-xml", title))
continue
if ext:
mimetype, _ = mimetypes.guess_type("a." + ext) # XXX never guess
if mimetype and mimetype != parsed_mimetype_type:
output_set.add((mimetype, title))
return list(output_set)
def bootstrapHandler(configuration_dict): def bootstrapHandler(configuration_dict):
# Bootstrap handler # Bootstrap handler
from signal import signal, SIGINT, SIGQUIT, SIGHUP from signal import signal, SIGINT, SIGQUIT, SIGHUP
......
...@@ -29,7 +29,7 @@ ...@@ -29,7 +29,7 @@
from zope.interface import implements from zope.interface import implements
from cloudooo.interfaces.handler import IHandler from cloudooo.interfaces.handler import IHandler
from cloudooo.file import File from cloudooo.file import File
from cloudooo.util import logger from cloudooo.util import logger, parseContentType
from subprocess import Popen, PIPE from subprocess import Popen, PIPE
from tempfile import mktemp from tempfile import mktemp
...@@ -115,3 +115,17 @@ class Handler(object): ...@@ -115,3 +115,17 @@ class Handler(object):
return self.document.getContent() return self.document.getContent()
finally: finally:
self.document.trash() self.document.trash()
@staticmethod
def getAllowedConversionFormatList(source_mimetype):
"""Returns a list content_type and their titles which are supported
by enabled handlers.
[('text/plain', 'Plain Text'),
...
]
"""
source_mimetype = parseContentType(source_mimetype).gettype()
if source_mimetype in ("application/pdf", "pdf"):
return [("text/plain", "Plain Text")]
return []
...@@ -28,7 +28,7 @@ ...@@ -28,7 +28,7 @@
from zope.interface import implements from zope.interface import implements
from cloudooo.interfaces.handler import IHandler from cloudooo.interfaces.handler import IHandler
from cloudooo.file import File from cloudooo.file import File
from cloudooo.util import logger from cloudooo.util import logger, parseContentType
from subprocess import Popen, PIPE from subprocess import Popen, PIPE
from tempfile import mktemp from tempfile import mktemp
from os.path import basename from os.path import basename
...@@ -96,6 +96,20 @@ class Handler(object): ...@@ -96,6 +96,20 @@ class Handler(object):
""" """
raise NotImplementedError raise NotImplementedError
@staticmethod
def getAllowedConversionFormatList(source_mimetype):
"""Returns a list content_type and their titles which are supported
by enabled handlers.
[('application/pdf', 'PDF - Portable Document Format'),
...
]
"""
source_mimetype = parseContentType(source_mimetype).gettype()
if source_mimetype in ("text/html", "htm", "html"):
return [("application/pdf", "PDF - Portable Document Format")]
return []
def makeSwitchOptionList(self, allowed_option_list, option_dict): def makeSwitchOptionList(self, allowed_option_list, option_dict):
""" """
A switch option is enable if it exists. A switch option is enable if it exists.
......
...@@ -35,7 +35,7 @@ from zope.interface import implements ...@@ -35,7 +35,7 @@ from zope.interface import implements
from cloudooo.interfaces.handler import IHandler from cloudooo.interfaces.handler import IHandler
from cloudooo.file import File from cloudooo.file import File
from cloudooo.util import logger, zipTree, unzip from cloudooo.util import logger, zipTree, unzip, parseContentType
AVS_OFFICESTUDIO_FILE_UNKNOWN = "0" AVS_OFFICESTUDIO_FILE_UNKNOWN = "0"
AVS_OFFICESTUDIO_FILE_DOCUMENT_DOCX = "65" AVS_OFFICESTUDIO_FILE_DOCUMENT_DOCX = "65"
...@@ -168,3 +168,27 @@ class Handler(object): ...@@ -168,3 +168,27 @@ class Handler(object):
metadata -- expected an dictionary with metadata. metadata -- expected an dictionary with metadata.
""" """
raise NotImplementedError raise NotImplementedError
@staticmethod
def getAllowedConversionFormatList(source_mimetype):
"""Returns a list content_type and their titles which are supported
by enabled handlers.
[('application/x-asc-text', 'OnlyOffice Text Document'),
...
]
"""
source_mimetype = parseContentType(source_mimetype).gettype()
if source_mimetype in ("docx", "application/vnd.openxmlformats-officedocument.wordprocessingml.document"):
return [("application/x-asc-text", "OnlyOffice Text Document")]
if source_mimetype in ("docy", "application/x-asc-text"):
return [("application/vnd.openxmlformats-officedocument.wordprocessingml.document", "Word 2007 Document")]
if source_mimetype in ("xlsx", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"):
return [("application/x-asc-spreadsheet", "OnlyOffice Spreadsheet")]
if source_mimetype in ("xlsy", "application/x-asc-spreadsheet"):
return [("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "Excel 2007 Spreadsheet")]
if source_mimetype in ("pptx", "application/vnd.openxmlformats-officedocument.presentationml.presentation"):
return [("application/x-asc-presentation", "OnlyOffice Presentation")]
if source_mimetype in ("ppty", "application/x-asc-presentation"):
return [("application/vnd.openxmlformats-officedocument.presentationml.presentation", "PowerPoint 2007 Presentation")]
return []
...@@ -87,7 +87,7 @@ class IManager(Interface): ...@@ -87,7 +87,7 @@ class IManager(Interface):
metadata_dict : Metadatas to include in content metadata_dict : Metadatas to include in content
""" """
def getAllowedConversionFormatList(source_mimetype): def getAllowedConversionFormatList(self, source_mimetype):
"""Returns a list content_type and their titles which are supported """Returns a list content_type and their titles which are supported
by enabled handlers. by enabled handlers.
......
...@@ -173,6 +173,42 @@ class Manager(object): ...@@ -173,6 +173,42 @@ class Manager(object):
else: else:
return [('', '')] return [('', '')]
def getAllowedConversionFormatList(self, source_mimetype):
r"""Returns a list content_type and their titles which are supported
by enabled handlers.
[('application/vnd.oasis.opendocument.text', 'ODF Text Document'),
('application/pdf', 'PDF - Portable Document Format'),
...
]
This methods gets handler conversion mimetype availability according
to Cloudooo's mimetype registry.
/!\ unlike `self.getAllowedExtensionList`, it may return empty list
instead of `[('', '')]`.
/!\ the returned list may have the same mimetype twice with different title.
"""
handler_dict = {} # handler_dict["ooo"] = ["text/*", "application/*"]
for entry in self.mimetype_registry:
split_entry = entry.split()
if fnmatch(source_mimetype, split_entry[0]):
if split_entry[2] in handler_dict:
handler_dict[split_entry[2]].append(split_entry[1])
else:
handler_dict[split_entry[2]] = [split_entry[1]]
output_mimetype_set = set()
for handler, mimetype_filter_list in handler_dict.items():
for output_mimetype in self.handler_dict[handler].getAllowedConversionFormatList(source_mimetype):
for mimetype_filter in mimetype_filter_list:
if fnmatch(output_mimetype[0], mimetype_filter):
output_mimetype_set.add(output_mimetype)
break
return list(output_mimetype_set)
def run_convert(self, filename='', data=None, meta=None, extension=None, def run_convert(self, filename='', data=None, meta=None, extension=None,
orig_format=None): orig_format=None):
"""Method to support the old API. Wrapper getFileMetadataItemList but """Method to support the old API. Wrapper getFileMetadataItemList but
......
...@@ -30,6 +30,8 @@ import logging ...@@ -30,6 +30,8 @@ import logging
import mimetypes import mimetypes
import pkg_resources import pkg_resources
import os import os
import mimetools
import cStringIO
from zipfile import ZipFile, ZIP_DEFLATED from zipfile import ZipFile, ZIP_DEFLATED
logger = logging.getLogger('Cloudooo') logger = logging.getLogger('Cloudooo')
...@@ -133,3 +135,18 @@ def unzip(source, destination): ...@@ -133,3 +135,18 @@ def unzip(source, destination):
zipfile = ZipFile(source) zipfile = ZipFile(source)
zipfile.extractall(destination) zipfile.extractall(destination)
zipfile.close() zipfile.close()
def parseContentType(content_type):
"""Parses `text/plain;charset="utf-8"` to a mimetools.Message object.
Note: Content type or MIME type are built like `maintype/subtype[;params]`.
parsed_content_type = parseContentType('text/plain;charset="utf-8"')
parsed_content_type.gettype() -> 'text/plain'
parsed_content_type.getmaintype() -> 'text'
parsed_content_type.getsubtype() -> 'plain'
parsed_content_type.getplist() -> 'charset="utf-8"'
parsed_content_type.getparam('charset') -> 'utf-8'
parsed_content_type.typeheader -> 'text/plain;charset="utf-8"'
"""
return mimetools.Message(cStringIO.StringIO("Content-Type:" + content_type.replace("\r\n", "\r\n\t")))
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment