This repository has been archived on 2023-02-21. You can view files and clone it, but cannot push or open issues or pull requests.
passerelle-maarch/passerelle_maarch/views.py

194 lines
7.1 KiB
Python

# passerelle-maarch
# 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 json
import urlparse
import requests
from suds.client import Client
from django.core.urlresolvers import reverse
from django.views.generic import DetailView
from django.views.generic.edit import CreateView, UpdateView, DeleteView
from django.core.cache import cache
from django.utils.decorators import method_decorator
from django.views.decorators.csrf import csrf_exempt
from passerelle import utils
from .soap import get_client, client_to_jsondict, recursive_asdict
from .models import MaarchManagement
from .forms import MaarchManagementForm, MaarchManagementUpdateForm
class MaarchManagementDetailView(DetailView):
model = MaarchManagement
template_name = 'passerelle_maarch/detail.html'
class MaarchManagementCreateView(CreateView):
model = MaarchManagement
form_class = MaarchManagementForm
template_name = 'passerelle/manage/service_form.html'
class MaarchManagementUpdateView(UpdateView):
model = MaarchManagement
form_class = MaarchManagementUpdateForm
template_name = 'passerelle/manage/service_form.html'
class MaarchManagementDeleteView(DeleteView):
model = MaarchManagement
template_name = 'passerelle/manage/service_confirm_delete.html'
def get_success_url(self):
return reverse('manage-home')
class MaarchDetailView(DetailView):
model = MaarchManagement
def get_client(self):
return get_client(maarch=self.get_object())
def get_data(self, request, *args, **kwargs):
raise NotImplementedError
@utils.protected_api('can_access')
def get(self, request, *args, **kwargs):
data = self.get_data(request, *args, **kwargs)
return utils.response_for_json(request, data)
class MaarchPingView(MaarchDetailView):
def get_data(self, request, *args, **kwargs):
client = self.get_client()
res = {'ping': 'pong'}
if 'debug' in request.GET:
res['client'] = client_to_jsondict(client)
return res
class MaarchResourceView(MaarchDetailView):
@method_decorator(csrf_exempt)
def dispatch(self, *args, **kwargs):
return super(MaarchResourceView, self).dispatch(*args, **kwargs)
def get_data(self, request, resource_id=None, table_name=None, adr_table_name=None, *args, **kwargs):
client = self.get_client()
if resource_id:
if not adr_table_name:
adr_table_name = 'adr_x'
results = client.service.viewResource(int(resource_id),
table_name, adr_table_name, True)
else:
if 'where' in request.GET:
searchParams = client.factory.create('searchParams')
searchParams.whereClause = request.GET.get('where')
else:
searchParams = ''
results = client.service.Demo_searchResources(searchParams)
return recursive_asdict(results)
@utils.protected_api('can_access')
def post(self, request, *args, **kwargs):
client = self.get_client()
formdata = json.loads(request.body)
url = formdata['url']
# get formdef schema
p = urlparse.urlsplit(url)
scheme, netloc, path, query, fragment = \
p.scheme, p.netloc, p.path, p.query, p.fragment
schema_path = path.rsplit('/', 2)[0] + '/schema'
schema_url = urlparse.urlunsplit((scheme, netloc, schema_path, query, fragment))
schema = requests.get(schema_url).json()
# build document
attachments = []
document = u'<html>'
document += u'<h1>%s</h1>' % schema['name']
for field in schema['fields']:
part = ''
if field['type'] == 'page':
part = u'<hr /><h2>%s</h2>' % field['label']
elif field['type'] == 'title':
part = u'<h3>%s</h3>' % field['label']
elif 'varname' in field:
part = u'<dl>'
part += u'<dt>%s</dt>' % field['label']
value = formdata['fields'].get(field['varname'], '')
if value and field['type'] == 'file':
attachments.append(value)
value = '%s' % value['filename']
if value is None:
value = '---'
part += u'<dd>%s</dd>' % value
part += u'</dl>'
document += part
document += '</html>'
encodedFile = document.encode('utf-8').encode('base64')
fileFormat = 'html'
# Maarch metadata
options = schema.get('options', {})
status = options.get('status') or 'ATT' # ATT->QualificationBasket
subject = client.factory.create('arrayOfDataContent')
subject.column = 'subject'
subject.value = formdata['display_name']
subject.type = 'string'
maarch_meta = [subject]
for meta in ('initiator', 'type_id', 'destination', 'priority', 'dest_user', 'typist'):
if meta in options:
soapmeta = client.factory.create('arrayOfDataContent')
soapmeta.column = meta
soapmeta.value = options[meta]
soapmeta.type = 'string'
maarch_meta.append(soapmeta)
metadata = client.factory.create('arrayOfData')
metadata.value = maarch_meta
# Maarch target is letterbox
collId = 'letterbox_coll'
table = 'res_letterbox'
# store resource
results = client.service.storeResource(encodedFile, metadata, collId,
table, fileFormat, status)
data = recursive_asdict(results)
resId = data['resId']
# if resId exists, store attachments
if resId:
for attachment in attachments:
fileFormat = attachment['content_type'].split('/')[1] # FIXME (how ?)
client.service.storeAttachmentResource(resId, collId, attachment['content'],
fileFormat, attachment['filename'])
return utils.response_for_json(request, data)
class MaarchContactView(MaarchDetailView):
def get_data(self, request, contact_id=None, *args, **kwargs):
client = self.get_client()
if contact_id:
searchParams = {'whereClause': "contact_id = '%s'" % contact_id}
elif 'where' in request.GET:
searchParams = {'whereClause': request.GET.get('where')}
else:
searchParams = ''
results = client.service.listContacts(searchParams)
return recursive_asdict(results)