passerelle/passerelle/contrib/iparapheur/models.py

261 lines
9.4 KiB
Python

# Passerelle - uniform access to data and services
# Copyright (C) 2015 Entr'ouvert
#
# This program is free software: you can redistribute it and/or modify it
# under the terms of the GNU Affero General Public License as published
# by the Free Software Foundation, either version 3 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 Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import base64
import urllib
from requests.exceptions import ConnectionError
from django.db import models
from django.utils.text import slugify
from django.utils.translation import ugettext_lazy as _
from django.http import HttpResponse, Http404
from zeep.exceptions import Fault as WebFault, TransportError
from passerelle.base.models import BaseResource, HTTPResource
from passerelle.utils.api import endpoint
from passerelle.utils.jsonresponse import APIError
CREATE_FILE_SCHEMA = {
'$schema': 'http://json-schema.org/draft-03/schema#',
'title': 'Iparapheur create file',
'definitions': {
'file': {
'type': 'object',
'properties': {
'content': {
'type': 'string',
'required': True
},
'content_type': {
'type': 'string',
'required': True
}
},
'required': True
}
},
'type': 'object',
'properties': {
'file': {
'$ref': '#/definitions/file'
},
'title': {
'type': 'string',
'required': True
},
'type': {
'type': 'string',
'required': True
},
'subtype': {
'type': 'string',
'required': True
},
'email': {
'type': 'string',
},
'visibility': {
'type': 'string',
'required': True
}
}
}
def get_client(model):
try:
soap_client = model.soap_client()
# overrides the service port address URL defined in the WSDL.
if model.wsdl_endpoint_location:
soap_client.overridden_service = soap_client.create_service(
# picks the first binding in the WSDL as the default
soap_client.wsdl.bindings.keys()[0],
model.wsdl_endpoint_location)
else:
soap_client.overridden_service = soap_client.service
return soap_client
except ConnectionError as exc:
raise APIError('i-Parapheur error: %s' % exc)
def format_type(t):
return {'id': unicode(t), 'text': unicode(t)}
def format_file(f):
return {'status': f.status, 'id': f.nom, 'timestamp': f.timestamp}
class FileError(Exception):
pass
class FileNotFoundError(Exception):
http_status = 404
class IParapheur(BaseResource, HTTPResource):
wsdl_url = models.CharField(max_length=128, blank=False,
verbose_name=_('WSDL URL'),
help_text=_('WSDL URL'))
wsdl_endpoint_location = models.CharField(max_length=256, blank=True,
verbose_name=_('WSDL endpoint location'),
help_text=_('override WSDL endpoint location'))
category = _('Business Process Connectors')
class Meta:
verbose_name = _('i-Parapheur')
@classmethod
def get_verbose_name(cls):
return cls._meta.verbose_name
def call(self, service_name, *args, **kwargs):
client = get_client(self)
try:
result = getattr(client.overridden_service, service_name)(*args, **kwargs)
except WebFault as exc:
# Remote Service Error: <SOAP-ENV:Fault> in response
raise APIError('ServiceError: %s' % exc)
except TransportError as exc:
raise APIError('Transport Error: %s' % exc)
except TypeError as exc:
raise APIError('Type Error: %s' % exc)
return result
@endpoint(perm='can_access')
def types(self, request):
return {'data': [format_type(t) for t in self.call('GetListeTypes')]}
@endpoint(perm='can_access')
def ping(self, request):
return {'data': self.call('echo', 'ping')}
@endpoint()
def wsdl(self, request):
try:
response = self.requests.get(self.wsdl_url)
except Exception as exc:
raise APIError('i-Parapheur WSDL error: %s' % exc)
return HttpResponse(response.content, content_type='text/xml')
@endpoint(perm='can_access')
def subtypes(self, request, type=None):
if type:
return {'data': [format_type(t) for t in self.call('GetListeSousTypes', type)]}
return {'data': [format_type(t) for t in self.call('GetListeSousTypes')]}
@endpoint(perm='can_access')
def files(self, request, status=None):
if status:
return {'data': [format_file(f) for f in self.call('RechercherDossiers', Status=status)]}
return {'data': [format_file(f) for f in self.call('RechercherDossiers')]}
@endpoint(
perm='can_access', name='create-file',
post={
'description': _('Create file'),
'request_body': {
'schema': {
'application/json': CREATE_FILE_SCHEMA
}
}
}
)
def create_file(self, request, post_data):
try:
content = base64.b64decode(post_data['file']['content'])
except TypeError:
raise APIError('Invalid base64 string')
content_type = post_data['file']['content_type']
soap_client = get_client(self)
if post_data['visibility'] not in ['PUBLIC', 'SERVICE', 'CONFIDENTIEL']:
raise FileError('Unknown value for "visibility". Should be "PUBLIC", "SERVICE" or "CONFIDENTIEL"')
doc_type = soap_client.get_type('ns0:TypeDoc')
doc = doc_type(content, content_type)
parameters = {'TypeTechnique': post_data['type'],
'DossierID': slugify(post_data['title']),
'DossierTitre': post_data['title'],
'SousType': post_data['subtype'],
'Visibilite': post_data['visibility'],
'DocumentPrincipal': doc,
}
if 'email' in post_data:
parameters['EmailEmetteur'] = post_data['email']
resp = soap_client.overridden_service.CreerDossier(**parameters)
if not resp or not resp.MessageRetour:
raise FileError('unknown error, no response')
if resp.MessageRetour.codeRetour == 'KO':
raise FileError(resp.MessageRetour.message)
return {'data': {'RecordId': resp.DossierID, 'message': resp.MessageRetour.message}}
@endpoint(perm='can_access', name='get-file', pattern='(?P<file_id>[\w-]+)')
def get_file(self, request, file_id, appendix=None):
resp = self.call('GetDossier', file_id)
filename = None
if not resp or not resp.MessageRetour:
raise FileError('unknown error, no response')
if resp.MessageRetour.codeRetour == 'KO':
if 'inconnu' in resp.MessageRetour.message:
raise Http404(resp.MessageRetour.message)
raise FileError(resp.MessageRetour.message)
if appendix is not None:
try:
appendix = int(appendix)
except ValueError:
raise Http404('invalid appendix index')
try:
document = resp.DocumentsAnnexes.DocAnnexe[appendix].fichier
filename = resp.DocumentsAnnexes.DocAnnexe[appendix].nom
except IndexError:
raise Http404('unknown appendix')
else:
document = resp.DocPrincipal
for metadata in resp.MetaDonnees.MetaDonnee:
if metadata['nom'] == 'ph:dossierTitre':
filename = metadata['valeur']
if document['contentType'] == 'application/pdf':
filename += '.pdf'
break
if not filename:
raise FileError('File title not found.')
response = HttpResponse(document['_value_1'],
content_type=document['contentType'])
ascii_filename = filename.encode('ascii', 'replace')
encoded_filename = urllib.quote(filename.encode('utf-8'), safe='')
response['Content-Disposition'] = 'inline; filename=%s; filename*=UTF-8\'\'%s' % (ascii_filename, encoded_filename)
return response
@endpoint(perm='can_access', name='get-file-status', pattern='(?P<file_id>[\w-]+)')
def get_file_status(self, request, file_id):
resp = self.call('GetHistoDossier', file_id)
if not resp or not resp.MessageRetour:
raise FileError('unknown error, no response')
if resp.MessageRetour.codeRetour == 'KO':
if 'inconnu' in resp.MessageRetour.message:
raise Http404(resp.MessageRetour.message)
raise FileError(resp.MessageRetour.message)
last = resp.LogDossier[-1]
return {'data': {
'annotation': last.annotation, 'nom': last.nom,
'status': last.status, 'timestamp': last.timestamp
}}