Commit 065de041 authored by Gabriel Monnerat's avatar Gabriel Monnerat

revert part of r41929. Interfaces must remain in cloudooo

git-svn-id: https://svn.erp5.org/repos/public/erp5/trunk/utils@41937 20353a03-c40f-0410-a6d1-a30d3c3de9de
parent 375d7f46
##############################################################################
#
# Copyright (c) 2009-2010 Nexedi SA and Contributors. All Rights Reserved.
# Gabriel M. Monnerat <gabriel@tiolive.com>
#
# WARNING: This program as such is intended to be used by professional
# programmers who take the whole responsibility of assessing all potential
# consequences resulting from its eventual inadequacies and bugs
# End users who are looking for a ready-to-use solution with commercial
# guarantees and support are strongly adviced to contract a Free Software
# Service Company
#
# This program is Free Software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
#
##############################################################################
import json
import re
import pkg_resources
from base64 import decodestring, encodestring
from os import environ, path
from subprocess import Popen, PIPE
from cloudooo.application.openoffice import openoffice
from cloudooo.application.xvfb import xvfb
from zope.interface import implements
from cloudooo.interfaces.handler import IHandler
from cloudooo.mimemapper import mimemapper
from cloudooo.document import FileSystemDocument
from cloudooo.monitor.timeout import MonitorTimeout
from cloudooo.utils import logger
from psutil import pid_exists
class OOHandler:
"""OOHandler is used to access the one Document and OpenOffice.
For each Document inputed is created on instance of this class to manipulate
the document. This Document must be able to create and remove a temporary
document at FS, load and export.
"""
implements(IHandler)
def __init__(self, base_folder_url, data, source_format, **kw):
"""Creates document in file system and loads it in OOo."""
self.document = FileSystemDocument(base_folder_url,
data,
source_format)
self.zip = kw.get('zip', False)
self.uno_path = kw.get("uno_path", None)
self.office_binary_path = kw.get("office_binary_path", None)
self.timeout = kw.get("timeout", 600)
self.refresh = kw.get('refresh', False)
self.source_format = source_format
if not self.uno_path:
self.uno_path = environ.get("uno_path")
if not self.office_binary_path:
self.office_binary_path = environ.get("office_binary_path")
def _getCommand(self, *args, **kw):
"""Transforms all parameters passed in a command"""
hostname, port = openoffice.getAddress()
kw['hostname'] = hostname
kw['port'] = port
python = path.join(self.office_binary_path, "python")
command_list = [path.exists(python) and python or "python",
pkg_resources.resource_filename("cloudooo",
path.join("helper", "unoconverter.py")),
"--uno_path='%s'" % self.uno_path,
"--office_binary_path='%s'" % self.office_binary_path,
"--document_url='%s'" % self.document.getUrl()]
for arg in args:
command_list.insert(3, "--%s" % arg)
for k, v in kw.iteritems():
command_list.append("--%s='%s'" % (k, v))
return ' '.join(command_list)
def _startTimeout(self):
"""start the Monitor"""
self.monitor = MonitorTimeout(openoffice, self.timeout)
self.monitor.start()
def _stopTimeout(self):
"""stop the Monitor"""
self.monitor.terminate()
def _subprocess(self, command):
"""Run one procedure"""
try:
self._startTimeout()
process = Popen(command,
shell=True,
stdout=PIPE,
stderr=PIPE,
close_fds=True)
stdout, stderr = process.communicate()
except OSError, e:
self.monitor = process = None
stdout, stderr = "", "OSError: %s" % e
finally:
if self.monitor is not None and process is not None:
self._stopTimeout()
if pid_exists(process.pid):
process.terminate()
return stdout, stderr
def _callUnoConverter(self, *feature_list, **kw):
""" """
if not openoffice.status():
xvfb.restart()
openoffice.start()
command = self._getCommand(*feature_list, **kw)
stdout, stderr = self._subprocess(command)
if not stdout and len(re.findall("\w*Exception|\w*Error", stderr)) >= 1:
logger.debug(stderr)
self.document.restoreOriginal()
openoffice.restart()
kw['document_url'] = self.document.getUrl()
command = self._getCommand(*feature_list, **kw)
stdout, stderr = self._subprocess(command)
if stderr != "":
raise Exception, stderr
return stdout, stderr
def _serializeMimemapper(self, extension=None):
"""Serialize parts of mimemapper"""
if extension is None:
return json.dumps(dict(mimetype_by_filter_type=mimemapper._mimetype_by_filter_type))
filter_list = []
for service_type in mimemapper._doc_type_list_by_extension[extension]:
for extension in mimemapper.extension_list_by_doc_type[service_type]:
filter_list.append((extension,
service_type,
mimemapper.getFilterName(extension,
service_type)))
return json.dumps(dict(doc_type_list_by_extension=mimemapper._doc_type_list_by_extension,
filter_list=filter_list,
mimetype_by_filter_type=mimemapper._mimetype_by_filter_type))
def convert(self, destination_format=None, **kw):
"""Convert a document to another format supported by the OpenOffice
Keyword Arguments:
destination_format -- extension of document as String
"""
logger.debug("Convert: %s > %s" % (self.source_format, destination_format))
openoffice.acquire()
kw['source_format'] = self.source_format
if destination_format:
kw['destination_format'] = destination_format
kw['mimemapper'] = self._serializeMimemapper(destination_format)
kw['refresh'] = json.dumps(self.refresh)
try:
stdout, stderr = self._callUnoConverter(*['convert'], **kw)
finally:
openoffice.release()
if self.monitor.is_alive():
self._stopTimeout()
url = stdout.replace('\n', '')
self.document.reload(url)
content = self.document.getContent(self.zip)
self.document.trash()
return content
def getMetadata(self, base_document=False):
"""Returns a dictionary with all metadata of document.
Keywords Arguments:
base_document -- Boolean variable. if true, the document is also returned
along with the metadata."""
openoffice.acquire()
logger.debug("getMetadata")
kw = dict(mimemapper=self._serializeMimemapper())
if base_document:
feature_list = ['getmetadata', 'convert']
else:
feature_list = ['getmetadata']
try:
stdout, stderr = self._callUnoConverter(*feature_list, **kw)
finally:
openoffice.release()
if self.monitor.is_alive():
self._stopTimeout()
metadata = json.loads(decodestring(stdout))
if metadata.get("Data"):
self.document.reload(metadata['Data'])
metadata['Data'] = self.document.getContent()
else:
metadata['Data'] = ''
self.document.trash()
return metadata
def setMetadata(self, metadata):
"""Returns a document with new metadata.
Keyword arguments:
metadata -- expected an dictionary with metadata.
"""
openoffice.acquire()
metadata_pickled = json.dumps(metadata)
logger.debug("setMetadata")
kw = dict(metadata=encodestring(metadata_pickled))
try:
stdout, stderr = self._callUnoConverter(*['setmetadata'], **kw)
finally:
openoffice.release()
if self.monitor.is_alive():
self._stopTimeout()
doc_loaded = self.document.getContent()
self.document.trash()
return doc_loaded
...@@ -27,7 +27,7 @@ ...@@ -27,7 +27,7 @@
############################################################################## ##############################################################################
from zope.interface import implements from zope.interface import implements
from cloudooo.handler.ooo.interfaces.application import IApplication from cloudooo.interfaces.application import IApplication
from cloudooo.handler.ooo.utils import logger, socketStatus, waitStopDaemon from cloudooo.handler.ooo.utils import logger, socketStatus, waitStopDaemon
from psutil import pid_exists, Process from psutil import pid_exists, Process
......
...@@ -35,7 +35,7 @@ from threading import Lock ...@@ -35,7 +35,7 @@ from threading import Lock
from zope.interface import implements from zope.interface import implements
from application import Application from application import Application
from xvfb import xvfb from xvfb import xvfb
from cloudooo.handler.ooo.interfaces.lockable import ILockable from cloudooo.interfaces.lockable import ILockable
from cloudooo.handler.ooo.utils import logger, waitStartDaemon, \ from cloudooo.handler.ooo.utils import logger, waitStartDaemon, \
removeDirectory, waitStopDaemon, \ removeDirectory, waitStopDaemon, \
convertStringToBool, socketStatus convertStringToBool, socketStatus
......
...@@ -30,7 +30,7 @@ from subprocess import Popen, PIPE ...@@ -30,7 +30,7 @@ from subprocess import Popen, PIPE
from cloudooo.handler.ooo.utils import logger, waitStartDaemon, remove_file from cloudooo.handler.ooo.utils import logger, waitStartDaemon, remove_file
from zope.interface import implements from zope.interface import implements
from application import Application from application import Application
from cloudooo.handler.ooo.interfaces.application import IApplication from cloudooo.interfaces.application import IApplication
from os.path import exists from os.path import exists
......
...@@ -35,7 +35,7 @@ from zipfile import ZipFile, is_zipfile ...@@ -35,7 +35,7 @@ from zipfile import ZipFile, is_zipfile
from shutil import rmtree from shutil import rmtree
from StringIO import StringIO from StringIO import StringIO
from lxml import etree from lxml import etree
from interfaces.document import IDocument, IOdfDocument from cloudooo.interfaces.document import IDocument, IOdfDocument
class FileSystemDocument(object): class FileSystemDocument(object):
......
...@@ -27,7 +27,7 @@ ...@@ -27,7 +27,7 @@
############################################################################## ##############################################################################
from zope.interface import implements from zope.interface import implements
from interfaces.filter import IFilter from cloudooo.interfaces.filter import IFilter
class Filter(object): class Filter(object):
......
...@@ -33,7 +33,7 @@ from lxml import etree ...@@ -33,7 +33,7 @@ from lxml import etree
from os import path from os import path
from cloudooo.handler.ooo.utils import logger from cloudooo.handler.ooo.utils import logger
from cloudooo.handler.ooo.document import OdfDocument from cloudooo.handler.ooo.document import OdfDocument
from cloudooo.handler.ooo.interfaces.granulate import ITableGranulator, \ from cloudooo.interfaces.granulate import ITableGranulator, \
IImageGranulator, \ IImageGranulator, \
ITextGranulator ITextGranulator
......
...@@ -35,7 +35,7 @@ from subprocess import Popen, PIPE ...@@ -35,7 +35,7 @@ from subprocess import Popen, PIPE
from cloudooo.handler.ooo.application.openoffice import openoffice from cloudooo.handler.ooo.application.openoffice import openoffice
from cloudooo.handler.ooo.application.xvfb import xvfb from cloudooo.handler.ooo.application.xvfb import xvfb
from zope.interface import implements from zope.interface import implements
from cloudooo.handler.ooo.interfaces.handler import IHandler from cloudooo.interfaces.handler import IHandler
from cloudooo.handler.ooo.mimemapper import mimemapper 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
......
...@@ -32,7 +32,7 @@ from subprocess import Popen, PIPE ...@@ -32,7 +32,7 @@ from subprocess import Popen, PIPE
from zope.interface import implements from zope.interface import implements
from filter import Filter from filter import Filter
from os import environ, path from os import environ, path
from interfaces.mimemapper import IMimemapper from cloudooo.interfaces.mimemapper import IMimemapper
from types import InstanceType from types import InstanceType
from utils import getCleanPythonEnvironment from utils import getCleanPythonEnvironment
import json import json
......
...@@ -27,7 +27,7 @@ ...@@ -27,7 +27,7 @@
############################################################################## ##############################################################################
from zope.interface import implements from zope.interface import implements
from cloudooo.handler.ooo.interfaces.monitor import IMonitor from cloudooo.interfaces.monitor import IMonitor
class Monitor(object): class Monitor(object):
......
...@@ -30,7 +30,7 @@ ...@@ -30,7 +30,7 @@
from mimetypes import guess_all_extensions, guess_extension from mimetypes import guess_all_extensions, guess_extension
from base64 import encodestring, decodestring from base64 import encodestring, decodestring
from zope.interface import implements from zope.interface import implements
from handler.ooo.interfaces.manager import IManager, IERP5Compatibility from interfaces.manager import IManager, IERP5Compatibility
from handler.ooo.handler import OOHandler from handler.ooo.handler import OOHandler
from handler.ooo.mimemapper import mimemapper from handler.ooo.mimemapper import mimemapper
from handler.ooo.utils import logger from handler.ooo.utils import logger
......
...@@ -36,15 +36,15 @@ from cloudooo.handler.ooo.filter import Filter ...@@ -36,15 +36,15 @@ from cloudooo.handler.ooo.filter import Filter
from cloudooo.handler.ooo.application.xvfb import Xvfb from cloudooo.handler.ooo.application.xvfb import Xvfb
from cloudooo.handler.ooo.monitor.request import MonitorRequest from cloudooo.handler.ooo.monitor.request import MonitorRequest
from cloudooo.handler.ooo.granulator import OOGranulator from cloudooo.handler.ooo.granulator import OOGranulator
from cloudooo.handler.ooo.interfaces.document import IDocument, IOdfDocument from cloudooo.interfaces.document import IDocument, IOdfDocument
from cloudooo.handler.ooo.interfaces.lockable import ILockable from cloudooo.interfaces.lockable import ILockable
from cloudooo.handler.ooo.interfaces.manager import IManager from cloudooo.interfaces.manager import IManager
from cloudooo.handler.ooo.interfaces.application import IApplication from cloudooo.interfaces.application import IApplication
from cloudooo.handler.ooo.interfaces.filter import IFilter from cloudooo.interfaces.filter import IFilter
from cloudooo.handler.ooo.interfaces.mimemapper import IMimemapper from cloudooo.interfaces.mimemapper import IMimemapper
from cloudooo.handler.ooo.interfaces.handler import IHandler from cloudooo.interfaces.handler import IHandler
from cloudooo.handler.ooo.interfaces.monitor import IMonitor from cloudooo.interfaces.monitor import IMonitor
from cloudooo.handler.ooo.interfaces.granulate import ITableGranulator, \ from cloudooo.interfaces.granulate import ITableGranulator, \
IImageGranulator, \ IImageGranulator, \
ITextGranulator ITextGranulator
from cloudoooTestCase import make_suite from cloudoooTestCase import make_suite
......
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