combo/combo/apps/wcs/views.py

71 lines
2.8 KiB
Python

# combo - content management system
# Copyright (C) 2014-2018 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/>.
from django.contrib import messages
from django.http import HttpResponseRedirect, HttpResponseBadRequest
from django.http import HttpResponseRedirect
from django.utils.six.moves.urllib import parse as urlparse
from django.utils.translation import ugettext_lazy as _
from django.views.decorators.csrf import csrf_exempt
from django.views.generic import View
from .models import TrackingCodeInputCell
from .utils import get_wcs_services
from combo.utils import requests
class TrackingCodeView(View):
http_method_names = ['post']
@csrf_exempt
def dispatch(self, *args, **kwargs):
# CSRF check must be disabled as the cell may be distributed to other
# sites in a skeleton.
return super(TrackingCodeView, self).dispatch(*args, **kwargs)
def post(self, request, *args, **kwargs):
try:
cell = TrackingCodeInputCell.objects.get(id=request.POST['cell'])
except (ValueError, TrackingCodeInputCell.DoesNotExist):
return HttpResponseBadRequest('Invalid cell id')
code = request.POST['code']
if cell.wcs_site:
wcs_sites = [get_wcs_services().get(cell.wcs_site)]
else:
wcs_sites = get_wcs_services().values()
for wcs_site in wcs_sites:
response = requests.get('/api/code/' + code,
remote_service=wcs_site, log_errors=False)
if response.status_code == 200 and response.json().get('err') == 0:
url = response.json().get('load_url')
return HttpResponseRedirect(url)
next_url = request.POST.get('url') or '/'
next_netloc = urlparse.urlparse(next_url).netloc
if not (next_netloc and next_netloc != urlparse.urlparse(request.build_absolute_uri()).netloc):
messages.error(self.request,
_(u'The tracking code could not been found.'))
else:
if '?' in next_url:
next_url += '&'
else:
next_url += '?'
next_url += 'unknown-tracking-code'
return HttpResponseRedirect(next_url)