268 lines
10 KiB
Python
268 lines
10 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.encoding import force_text
|
|
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, XMLSyntaxError
|
|
try:
|
|
from zeep import Settings # zeep version >= 3.x
|
|
except ImportError:
|
|
Settings = None
|
|
|
|
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-04/schema#',
|
|
'title': 'Iparapheur create file',
|
|
'type': 'object',
|
|
'required': ['file', 'title', 'type', 'subtype', 'visibility'],
|
|
'properties': {
|
|
'file': {
|
|
'type': 'object',
|
|
'required': ['content', 'content_type'],
|
|
'properties': {
|
|
'content': {
|
|
'type': 'string',
|
|
},
|
|
'content_type': {
|
|
'type': 'string',
|
|
}
|
|
}
|
|
},
|
|
'title': {
|
|
'type': 'string',
|
|
},
|
|
'type': {
|
|
'type': 'string',
|
|
},
|
|
'subtype': {
|
|
'type': 'string',
|
|
},
|
|
'email': {
|
|
'type': 'string',
|
|
},
|
|
'visibility': {
|
|
'type': 'string',
|
|
}
|
|
}
|
|
}
|
|
|
|
|
|
def format_type(t):
|
|
return {'id': force_text(t), 'text': force_text(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 get_client(self, **kwargs):
|
|
try:
|
|
soap_client = self.soap_client(**kwargs)
|
|
|
|
# overrides the service port address URL defined in the WSDL.
|
|
if self.wsdl_endpoint_location:
|
|
soap_client.overridden_service = soap_client.create_service(
|
|
# picks the first binding in the WSDL as the default
|
|
list(soap_client.wsdl.bindings.keys())[0],
|
|
self.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 call(self, service_name, *args, **kwargs):
|
|
strict_mode = kwargs.pop('strict_mode', True)
|
|
if Settings is not None: # zeep version >= 3.x:
|
|
client = self.get_client(settings=Settings(strict=strict_mode))
|
|
else:
|
|
client = self.get_client(strict=strict_mode)
|
|
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)
|
|
except XMLSyntaxError as exc:
|
|
raise APIError('XMLSyntax 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 = self.get_client()
|
|
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)
|
|
generated_dossier_id = slugify(post_data['title'])
|
|
parameters = {'TypeTechnique': post_data['type'],
|
|
'DossierID': generated_dossier_id,
|
|
'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)
|
|
|
|
dossier_id = resp.DossierID
|
|
if not dossier_id:
|
|
dossier_id = generated_dossier_id
|
|
return {'data': {'dossier_id': dossier_id, '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):
|
|
# We need to disable strict mode since the response
|
|
# can be non compliant with the xsd
|
|
resp = self.call('GetDossier', file_id, strict_mode=False)
|
|
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
|
|
}}
|