combo/combo/apps/wcs/views.py

94 lines
3.3 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/>.
import re
from django.contrib import messages
from django.core.urlresolvers import reverse
from django.http import JsonResponse, HttpResponseRedirect, HttpResponseBadRequest
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)
@classmethod
def search(self, code, wcs_site=None):
if wcs_site:
wcs_sites = [get_wcs_services().get(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:
return response.json().get('load_url')
return None
def post(self, request, *args, **kwargs):
try:
cell = TrackingCodeInputCell.objects.get(id=request.POST['cell'])
except (KeyError, ValueError, TrackingCodeInputCell.DoesNotExist):
return HttpResponseBadRequest('Invalid cell id')
code = request.POST['code']
url = self.search(code, wcs_site=cell.wcs_site)
if 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)
def tracking_code_search(request):
hits = []
query = request.GET.get('q') or ''
if re.match(r'^[BCDFGHJKLMNPQRSTVWXZ]{8}$', query):
url = TrackingCodeView.search(query)
if url:
hits.append({
'text': _('Use tracking code %s') % query,
'url': url,
})
return JsonResponse({'data': hits})