Ejemplo n.º 1
0
def newsletter(request):
    remove = request.GET.get('remove')

    languages = Language.objects.all()
    newsletter, created = Newsletter.objects.get_or_create(user=request.user)
    if not newsletter.user.email:
        messages.error(request, _('Without specifying an email-address, you can not receive a newsletter.'))

    if remove:
        newsletter.words.remove(get_object_or_404(Word, id=remove))
        newsletter.save()
        messages.success(request, _('You removed %(word)s successfully from your newsletter.') % {'word': get_object_or_404(Word, id=remove)})

    if request.method == 'POST':
        form = NewsletterForm(request.POST)
        if form.is_valid():
            for word in form.cleaned_data['words']:
                newsletter.words.add(word)
            newsletter.save()
            messages.success(request, ungettext('Added %(words)s to your newsletter.', 'Added %(words)s to your newsletter.', len(form.cleaned_data['words'])) % {'words': ', '.join(['%s (%s)' % (word, word.language) for word in form.cleaned_data['words']])})
            form = NewsletterForm()
    else:
        form = NewsletterForm()

    track(request, 'Newsletter | Profile | TIMA')
    return render(request, 'tima/app/profile/newsletter.html', locals())
Ejemplo n.º 2
0
def next(request):
    """Handels a POST/GET request for the next word.

    GET/POST parameters:
    language --- language of the word
    username --- username of a user (optinal)
    excludes --- list of words that should be exclude from the result (optinal)
    """

    track(request, 'next | words | API | TIMA')
    params = request.POST.copy() if request.method == 'POST' else request.GET.copy()

    language = None
    if 'language' in params:
        try:
            language = Language.objects.get(code=params.pop('language')[-1])
        except Language.DoesNotExist:
            return HttpResponseNotFound('Language with "language" not found.')
    else:
        return HttpResponseBadRequest('Required parameter "language" is missing.')

    user = None
    if 'username' in params:
        try:
            user = get_user_model().objects.get(username=params.pop('username')[-1])
        except get_user_model().DoesNotExist:
            return HttpResponseNotFound('User with "username" not found.')
    excludes = []
    if 'excludes' in params:
        excludes = Word.objects.filter(name__in=params.pop('excludes'))

    word = get_next_word(language, user, excludes)
    data = {'response_date':timezone.now().strftime('%Y-%m-%dT%H:%M:%S:%f%z'), 'word': word.name}
    return HttpResponse(dumps(data), 'application/json')
Ejemplo n.º 3
0
def graph(request):
    """Handels GET/POST request to get graph data for the given word.

    GET/POST parameters:
    word --- word
    language --- language of the word
    depth --- depth of associations (defailt 2)
    """
    track(request, 'graph | words | API | TIMA')
    params = request.POST.copy() if request.method == 'POST' else request.GET.copy()

    word = None
    if 'word' in params and 'language' in params:
        try:
            word = Word.objects.get(name=params.pop('word')[-1], language__code=params.pop('language')[-1])
        except Word.DoesNotExist:
            return HttpResponseNotFound('Word with "word" and "language" not found.')
    else:
        return HttpResponseBadRequest('Required parameter "language" or "word" is missing.')

    depth = 2
    if 'depth' in params:
        depth = int(params.pop('depth')[-1])

    nodes, links = build_graph(word, depth)
    data = {'response_date':timezone.now().strftime('%Y-%m-%dT%H:%M:%S:%f%z'), 'nodes':nodes, 'links':links}
    return HttpResponse(dumps(data), 'application/json')
Ejemplo n.º 4
0
def signin(request):
    gnext = request.GET.get('next')
    track(request, 'Sign in | TIMA')
    if request.method == 'POST':
        username = request.POST['username']
        password = request.POST['password']
        user = authenticate(username=username, password=password)

        if user is not None:
            if user.is_active:
                login(request, user)
                messages.add_message(request, messages.SUCCESS, 'You have successfully logged in.')

                try:
                    Profile.objects.get(user=user)
                except Profile.DoesNotExist:
                    Profile.objects.create(user=user)

                return redirect(gnext) if gnext else redirect('home')
            else:
                messages.add_message(request, messages.ERROR, 'Your account is disabled.')
            return redirect(request.META.get('HTTP_REFERER'))
        else:
            messages.add_message(request, messages.ERROR, 'Please enter a correct username and password to log in. Note that both fields may be case-sensitive.')
            return redirect(request.META.get('HTTP_REFERER'))
    else:
        form = AuthenticationForm(request)
        return render(request, 'registration/login.html', locals())
Ejemplo n.º 5
0
def isA(request):
    """Handels a GET/POST request to check if a given word is a word.

    GET/POST parameters:
    language --- language of the word
    word --- word to check
    """
    track(request, 'isA | words | API | TIMA')
    params = request.POST.copy() if request.method == 'POST' else request.GET.copy()

    language = None
    if 'language' in params and 'word' in params:
        l = params.pop('language')[-1]
        try:
            language = Language.objects.get(code=l)
        except Language.DoesNotExist:
            return HttpResponseNotFound('Language with "%s" not found.' % l)

        w = params.pop('word')[-1]
        try:
            word = Word.objects.get(name=w, language=language)
        except Word.DoesNotExist:
            if not exists(language.code.lower(), w):
                return HttpResponseNotFound('Word with "%s" not found.' % w)
    else:
        return HttpResponseBadRequest('Required parameter "language" or "word" is missing.')
    return HttpResponse(dumps({'response_date':timezone.now().strftime('%Y-%m-%dT%H:%M:%S:%f%z')}), 'application/json')
Ejemplo n.º 6
0
def request(request):
    """Handels a POST/GET request to want to auth.

    GET/POST parameters:
    username --- username
    client_id --- client_id of the application
    """
    track(request, 'request | auth | applications | API | TIMA')
    params = request.POST.copy() if request.method == 'POST' else request.GET.copy()
    user = None
    if 'username' in params:
        try:
            user = get_user_model().objects.get(username=params.pop('username')[-1])
        except get_user_model().DoesNotExist:
            return HttpResponseNotFound('User with "username" not found.')
    else:
        return HttpResponseBadRequest('Required parameter "username" is missing.')

    application = None
    if 'client_id' in params:
        try:
            application = Application.objects.get(client_id=params.pop('client_id')[-1])
        except Application.DoesNotExist:
            return HttpResponseNotFound('Apllication with "client_id" not found.')
    else:
        return HttpResponseBadRequest('Required parameter "client_id" is missing.')

    authrequest, created = AuthRequest.objects.update_or_create(user=user, defaults={'timestamp':timezone.now()})
    data = {'timestamp': authrequest.timestamp.strftime('%Y-%m-%dT%H:%M:%S:%f%z')}
    return HttpResponse(dumps(data), 'application/json')
Ejemplo n.º 7
0
def add(request):
    """Handels GET/POST adds the given word to the list of exclude list of the user.

    GET/POST parameters:
    u --- int
    token --- hash of user token and n
    word --- word to add to exclude list
    language --- language of the word
    """
    track(request, 'add | excludeword | profile | API | TIMA')
    params = request.POST.copy() if request.method == 'POST' else request.GET.copy()

    autheduser = check_authed_user(params)
    if isinstance(autheduser, HttpResponse):
        return autheduser

    word = None
    if 'language' in params and 'word' in params:
        language_code = params.pop('language')[-1]
        try:
            language = Language.objects.get(code=language_code)
        except Language.DoesNotExist:
            return HttpResponseNotFound('Language with "%s" not found.' % language_code)

        word_name = params.pop('word')[-1]
        try:
            word = Word.objects.get(name=word_name, language=language)
        except Word.DoesNotExist:
            return HttpResponseNotFound('Word with "%s" not found.' % word_name)
    else:
        return HttpResponseBadRequest('Required parameter "language" or "word" is missing.')

    excludeword, created = ExcludeWord.objects.get_or_create(word=word, user=autheduser.user)
    data = {'response_date':timezone.now().strftime('%Y-%m-%dT%H:%M:%S:%f%z'), 'created':created}
    return HttpResponse(dumps(data), 'application/json')
Ejemplo n.º 8
0
def list(request):
    """Handels a POST or GET request to list all languages.
    """
    track(request, 'list | languages | API | TIMA')
    data = {'response_date':timezone.now().strftime('%Y-%m-%dT%H:%M:%SZ'),
            'languages': [{
            'name':language.name,
            'code':language.code} for language in Language.objects.all()]}
    return HttpResponse(dumps(data), 'application/json')
Ejemplo n.º 9
0
def user(request):
    """Handels a POST/GET request to auth a user.

    GET/POST parameters:
    username --- username
    password --- password
    timestamp --- timestamp send by auth/request request
    client_id --- client_id of the application
    token --- hash of application secret and n
    """
    track(request, 'user | auth | applications | API | TIMA')
    params = request.POST.copy() if request.method == 'POST' else request.GET.copy()

    user = None
    if 'username' in params and 'password' in params:
        user = authenticate(username=params.pop('username')[-1], password=params.pop('password')[-1])
        if not user or not user.is_active:
            return HttpResponseForbidden('User authentication fail or user is deactivated.')
    else:
        return HttpResponseBadRequest('Required parameter "username" or "password" are missing.')

    application = None
    if 'client_id' in params:
        try:
            application = Application.objects.get(client_id=params.pop('client_id')[-1])
        except Application.DoesNotExist:
            return HttpResponseNotFound('Application with "client_id" not found.')
    else:
        return HttpResponseBadRequest('Required parameter "client_id" is missing.')

    authrequest = None
    if 'timestamp' in params and user:
        try:
            timestamp = datetime.strptime(params.pop('timestamp')[-1], '%Y-%m-%dT%H:%M:%S:%f%z')
            try:
                authrequest = AuthRequest.objects.get(user=user, timestamp=timestamp)
            except AuthRequest.DoesNotExist:
                return HttpResponseNotFound('AuthRequest with "timestamp" not found.')
        except Exception as e:
            return HttpResponseBadRequest('Required parameter "timestamp" has wrong format.')
    else:
        return HttpResponseBadRequest('Required parameter "timestamp" is missing.')

    if 'token' in params and application and authrequest:
        if sha512(('%s%s' % (application.secret, authrequest.timestamp.strftime('%Y-%m-%dT%H:%M:%S:%f%z'))).encode('utf-8')).hexdigest() != params.pop('token')[-1]:
            return HttpResponseForbidden('Wrong "token" given.')
    else:
        return HttpResponseBadRequest('Required parameter "token" is missing.')

    autheduser, created = AuthedUser.objects.update_or_create(user=user)
    authrequest.delete()
    data = {'n':autheduser.n, 'u':user.id, 'token':autheduser.token}
    return HttpResponse(dumps(data), 'application/json')
Ejemplo n.º 10
0
def statistics(request):
    """Handels GET/POST request to export statistics.
    """
    track(request, 'statistics | API | TIMA')
    languages = Language.objects.all()
    user_count = Profile.objects.all().count()
    data = {'response_date':timezone.now().strftime('%Y-%m-%dT%H:%M:%SZ'),
            'statistics': [{'citizen_scientists': user_count,
                    'languages': [{'language': language.code,
                        'words': language.words.count(),
                        'associations': Association.objects.filter(word__language=language).count()
                    } for language in languages]}]}
    return HttpResponse(dumps(data), 'application/json')
Ejemplo n.º 11
0
def leaderboard(request):
    profile_list = Profile.objects.all().order_by('-points')

    paginator = Paginator(profile_list, 50)
    page = request.GET.get('page')
    try:
        profiles = paginator.page(page)
    except PageNotAnInteger:
        profiles = paginator.page(1)
    except EmptyPage:
        profiles = paginator.page(paginator.num_pages)

    track(request, 'Leaderboard | TIMA')
    return render(request, 'tima/app/leaderboard.html', locals())
Ejemplo n.º 12
0
def revoke(request):
    """Handels a POST/GET request to auth a user.

    GET/POST parameters:
    u --- int
    token --- hash of user token and n
    """
    track(request, 'revoke | auth | applications | API | TIMA')
    params = request.POST.copy() if request.method == 'POST' else request.GET.copy()
    autheduser = check_authed_user(params)
    if isinstance(autheduser, HttpResponse):
        return autheduser
    else:
        autheduser.delete()
        return HttpResponse(dumps({'response_date':timezone.now().strftime('%Y-%m-%dT%H:%M:%S:%f%z')}), 'application/json')
Ejemplo n.º 13
0
def signup(request):
    track(request, 'Sign up | TIMA')
    if request.method == 'POST':
        form = UserCreationForm(request.POST)
        if form.is_valid():
            new_user = form.save()
            Profile.objects.create(user=new_user)
            messages.info(request, 'Thanks for signing up. You are now logged in.')
            new_user = authenticate(username=request.POST['username'], password=request.POST['password1'])
            login(request, new_user)
            return redirect(reverse('profile'))
        else:
            return render(request, 'registration/signup.html', locals())
    else:
        form = UserCreationForm()
        return render(request, 'registration/signup.html', locals())
Ejemplo n.º 14
0
def edit(request):
    if request.method == 'POST':
        form = UserChangeForm(instance=request.user, data=request.POST)
        if form.is_valid():
            user = form.save()

            if form.cleaned_data['cultural_background']:
                profile = get_object_or_404(Profile, user=user)
                profile.cultural_background = form.cleaned_data['cultural_background']
                profile.save()
            messages.success(request, _('Your profile has been successfully updated.'))
    else:
        profile = get_object_or_404(Profile, user=request.user)
        form = UserChangeForm(instance=request.user, initial={'cultural_background': profile.cultural_background})

    track(request, 'edit | Profile | TIMA')
    return render(request, 'tima/app/profile/form.html', locals())
Ejemplo n.º 15
0
def association(request):
    """Handels a POST or GET request to save a association.

    GET/POST parameters:
    language --- language of the word and association
    word --- word
    association --- association
    u --- int
    token --- hash of user token and n
    """
    track(request, 'association | API | TIMA')
    params = request.POST.copy() if request.method == 'POST' else request.GET.copy()

    autheduser = check_authed_user(params)
    if isinstance(autheduser, HttpResponse):
        return autheduser

    language = None
    if 'language' in params:
        try:
            language = Language.objects.get(code=params.pop('language')[-1])
        except Language.DoesNotExist:
            return HttpResponseNotFound('Language with "language" not found.')
    else:
        return HttpResponseBadRequest('Required parameter "language" is missing.')

    word = None
    if 'word' in params:
        try:
            word = Word.objects.get(name=params.pop('word')[-1], language=language)
        except Word.DoesNotExist:
            return HttpResponseNotFound('Word with "word" and "language" not found.')
    else:
        return HttpResponseBadRequest('Required parameter "word" is missing.')

    word1 = None
    points = 0
    if 'association' in params:
        word1, created = Word.objects.get_or_create(name=params.pop('association')[-1], language=language)
        association, created = Association.objects.update_or_create(word=word, association=word1)
        points = calculate_points(autheduser.user, association)
    else:
        return HttpResponseBadRequest('Required parameter "association" is missing.')

    data = {'response_date':timezone.now().strftime('%Y-%m-%dT%H:%M:%S:%f%z'), 'points':points}
    return HttpResponse(dumps(data), 'application/json')
Ejemplo n.º 16
0
def export(request):
    """Handels GET/POST request to export word(s) with their associations.

    GET/POST parameters:
    language --- language of the word(s) (optinal)
    word --- list of word ids to include (optinal)
    limit --- limit the number of associations per word (optinal)
    """
    track(request, 'words | API | TIMA')
    params = request.POST.copy() if request.method == 'POST' else request.GET.copy()
    words = Word.objects.all().order_by(Lower('name'))
    if 'word' in params:
        words = words.filter(id__in=params.pop('word'))
    if 'language' in params:
        words = words.filter(language__code=params.pop('language')[-1])
    data = {'response_date':timezone.now().strftime('%Y-%m-%dT%H:%M:%S:%f%z'),
            'words': [word.to_json(request, limit=params.get('limit')) for word in words]}
    return HttpResponse(dumps(data), 'application/json')
Ejemplo n.º 17
0
def lists(request):
    """Handels GET/POST lists all excluded words of the user.

    GET/POST parameters:
    u --- int
    token --- hash of user token and n
    """
    track(request, 'lists | excludeword | profile | API | TIMA')
    params = request.POST.copy() if request.method == 'POST' else request.GET.copy()

    autheduser = check_authed_user(params)
    if isinstance(autheduser, HttpResponse):
        return autheduser

    excluded_words = ExcludeWord.objects.filter(user=autheduser.user)
    data = {'response_date':timezone.now().strftime('%Y-%m-%dT%H:%M:%S:%f%z'),
            'excluded_words':[excluded_word.word.to_json(request, limit=0) for excluded_word in excluded_words]}
    return HttpResponse(dumps(data), 'application/json')
Ejemplo n.º 18
0
def associationhistory(request):
    """Handels GET/POST request to export the association history of the authed user.

    GET/POST parameters:
    u --- int
    token --- hash of user token and n
    """
    track(request, 'associationhistory | profile | API | TIMA')
    params = request.POST.copy() if request.method == 'POST' else request.GET.copy()

    autheduser = check_authed_user(params)
    if isinstance(autheduser, HttpResponse):
        return autheduser

    association_histories = AssociationHistory.objects.filter(user=autheduser.user)
    data = {'response_date':timezone.now().strftime('%Y-%m-%dT%H:%M:%S:%f%z'),
        'association_history':[{'association':association_history.association.to_json(request), 'points':association_history.points} for association_history in association_histories]}
    return HttpResponse(dumps(data), 'application/json')
Ejemplo n.º 19
0
def leaderboard(request):
    """Handels GET/POST request to export the leaderboard.
    """
    track(request, "leaderboard | API | TIMA")
    profiles = Profile.objects.all().order_by("-points")
    data = {
        "response_date": timezone.now().strftime("%Y-%m-%dT%H:%M:%SZ"),
        "leaderboard": [
            {
                "citizen_scientist": profile.user.username,
                "points": profile.points,
                "languages": [{"language": language.code} for language in profile.languages.all()],
                "cultural_background": profile.cultural_background,
            }
            for profile in profiles
        ],
    }
    return HttpResponse(dumps(data), "application/json")
Ejemplo n.º 20
0
def association(request, slug):
    language = get_object_or_404(Language, slug=slug)

    excludes = []
    if 'excludes' in request.GET:
        for exclude in request.GET.getlist('excludes'):
            word = get_object_or_404(Word, name=exclude, language=language)
            excludes.append(word)
            if not request.user.is_anonymous():
                ExcludeWord.objects.get_or_create(user=request.user, word=word)

    if request.method == 'POST':
        form = AssociationForm(request.POST)
        if form.is_valid():
            if not request.user.is_anonymous():
                language.users.add(get_object_or_404(Profile, user=request.user))
                language.save()

            if form.cleaned_data['word'] == form.cleaned_data['association']:
                word = Word.objects.get(name=form.cleaned_data['word'], language=language)
                return render(request, 'tima/association/association.html', locals())

            word = get_object_or_404(Word, name=form.cleaned_data['word'], language=language)
            word1, created = Word.objects.get_or_create(name=form.cleaned_data['association'], language=language)

            association, created = Association.objects.update_or_create(word=word, association=word1)
            excludes.append(word)
            excludes.append(word1)
            points = calculate_points(request.user if not request.user.is_anonymous() else None, association)
            if not request.user.is_anonymous():
                messages.add_message(request, messages.INFO, _('You received %(points)s points for your association of %(association)s.') % {'points': points, 'association': association})
            else:
                messages.add_message(request, messages.INFO, _('Your association %(association)s has been saved. If you had been signed in you would have received %(points)s points.') % {'association': association, 'points':points})
        else:
            word = Word.objects.get(name=form.cleaned_data['word'], language=language)
            association1 = form.cleaned_data['association1']
            return render(request, 'tima/association/association.html', locals())

    word = get_next_word(language=language, user=request.user, excludes=excludes)
    association1 = ''
    form = AssociationForm(initial={'word':word.name, 'language':language.code})
    track(request, 'Association | TIMA')
    return render(request, 'tima/association/association.html', locals())
Ejemplo n.º 21
0
def leaderboard(request):
    search = request.GET.get('search')
    profile_list = Profile.objects.extra(select={'rank':'RANK() OVER (ORDER BY points DESC)'}).all().order_by('rank')
    if search:
        profile_list = profile_list.filter(user__username__icontains=search)

    paginator = Paginator(profile_list, 50)
    page = request.GET.get('page')
    try:
        profiles = paginator.page(page)
    except PageNotAnInteger:
        if request.user.is_authenticated() and not search:
            profiles = paginator.page(min(Profile.objects.filter(points__gt=Profile.objects.get(user=request.user).points).count() / 3 + 1, paginator.num_pages))
        else:
            profiles = paginator.page(1)
    except EmptyPage:
        profiles = paginator.page(paginator.num_pages)

    track(request, 'Leaderboard | TIMA')
    return render(request, 'tima/app/leaderboard.html', locals())
Ejemplo n.º 22
0
def association_history(request):
    word = request.GET.get('word')
    l = request.GET.get('l')
    association_histories_list = AssociationHistory.objects.filter(user=request.user).order_by('-updated_at')
    if word:
        word = int(word)
        association_histories_list = association_histories_list.filter(Q(association__word__id=word) | Q(association__association__id=word))
    if l:
        association_histories_list = association_histories_list.filter(association__word__language__code=l)

    paginator = Paginator(association_histories_list, 50)
    page = request.GET.get('page')
    try:
        association_histories = paginator.page(page)
    except PageNotAnInteger:
        association_histories = paginator.page(1)
    except EmptyPage:
        association_histories = paginator.page(paginator.num_pages)

    track(request, 'Association history | Profile | TIMA')
    return render(request, 'tima/app/profile/association_history.html', locals())
Ejemplo n.º 23
0
def words(request):
    o = request.GET.get('o') if 'o' in request.GET else 'name'
    l = request.GET.get('l')
    r = request.GET.get('r')
    a = request.GET.get('a')
    search = request.GET.get('search')

    if o not in ['name', 'language', 'c', 'a']:
        o = 'name'

    if request.user.is_authenticated():
        newsletter, created = Newsletter.objects.get_or_create(user=request.user)
        if r:
            newsletter.words.remove(get_object_or_404(Word, id=r))
            newsletter.save()
            messages.success(request, _('You removed %(word)s successfully from your newsletter.') % {'word': get_object_or_404(Word, id=r)})
        if a:
            newsletter.words.add(get_object_or_404(Word, id=a))
            newsletter.save()
            messages.success(request, _('You added %(word)s successfully to your newsletter.') % {'word': get_object_or_404(Word, id=a)})

    word_list = Word.objects.all().annotate(c=Count('word', distinct=True),
            a=Count('association', distinct=True)).order_by(Lower(o) if o == 'name' else o, Lower('name'))
    if l:
        lang = get_object_or_404(Language, code=l)
        word_list = word_list.filter(language=lang)
    if search:
        word_list = word_list.filter(name__icontains=search)

    paginator = Paginator(word_list, 100)
    page = request.GET.get('page')
    try:
        words = paginator.page(page)
    except PageNotAnInteger:
        words = paginator.page(1)
    except EmptyPage:
        words = paginator.page(paginator.num_pages)

    track(request, 'Words | TIMA')
    return render(request, 'tima/association/word/words.html', locals())
Ejemplo n.º 24
0
def profile(request):
    """Handels GET/POST request to export a profile of the authed user.

    GET/POST parameters:
    u --- int
    token --- hash of user token and n
    """
    track(request, 'profile | API | TIMA')
    params = request.POST.copy() if request.method == 'POST' else request.GET.copy()

    autheduser = check_authed_user(params)
    if isinstance(autheduser, HttpResponse):
        return autheduser

    profile = Profile.objects.get(user=autheduser.user)
    data = {'response_date':timezone.now().strftime('%Y-%m-%dT%H:%M:%S:%f%z'),
                'profile':{'username':profile.user.username,
                            'points':profile.points,
                            'cultural_background': profile.cultural_background,
                            'first_name': profile.user.first_name,
                            'last_name': profile.user.last_name,
                            'email': profile.user.email,}}
    return HttpResponse(dumps(data), 'application/json')
Ejemplo n.º 25
0
def faq(request):
    track(request, 'FAQ | TIMA')
    return render(request, 'tima/pages/faq.html', locals())
Ejemplo n.º 26
0
def page(request, slug):
    page = get_object_or_404(Page, slug=slug)
    track(request, '%s | TIMA' % page.title)
    return render(request, 'tima/pages/page.html', locals())
Ejemplo n.º 27
0
def oai2(request):
    """
    Handels all OAI-PMH v2 requets. For details see
    https://www.openarchives.org/OAI/openarchivesprotocol.html
    """
    global PER_PAGE

    errors = []
    verb = None
    identifier = None
    metadata_prefix = None
    set_spec = None
    from_timestamp = None
    until_timestamp = None
    resumption_token = None
    params = request.POST.copy() if request.method == 'POST' else request.GET.copy()

    if 'verb' in params:
        verb = params.pop('verb')[-1]
        if verb == 'GetRecord':
            template = 'tima/oai_pmh/getrecord.xml'

            if 'metadataPrefix' in params:
                metadata_prefix = params.pop('metadataPrefix')
                if len(metadata_prefix) == 1:
                    metadata_prefix = metadata_prefix[0]
                    if not MetadataFormat.objects.filter(prefix=metadata_prefix).exists():
                        errors.append({'code':'cannotDisseminateFormat', 'msg':'The value of the metadataPrefix argument "%s" is not supported.' % metadata_prefix})
                    if 'identifier' in params:
                        identifier = params.pop('identifier')[-1]
                        try:
                            header = Header.objects.get(identifier=identifier)
                        except Header.DoesNotExist:
                            errors.append({'code':'idDoesNotExist', 'msg':'A record with the identifier "%s" does not exist.' % identifier})
                    else:
                        errors.append({'code':'badArgument', 'msg':'The required argument "identifier" is missing in the request.'})
                else:
                    errors.append({'code':'badArgument', 'msg':'Only a single metadataPrefix argument is allowed, got "%s".' % ';'.join(metadata_prefix)})
                    metadata_prefix = None
            else:
                errors.append({'code':'badArgument', 'msg':'The required argument "metadataPrefix" is missing in the request.'})
            check_bad_arguments(params, errors)
        elif verb == 'Identify':
            template = 'tima/oai_pmh/identify.xml'
            check_bad_arguments(params, errors)
        elif verb == 'ListIdentifiers':
            template = 'tima/oai_pmh/listidentifiers.xml'

            if 'resumptionToken' in params:
                header_list = Header.objects.all()
                paginator, headers, resumption_token, set_spec, metadata_prefix, from_timestamp, until_timestamp = do_resumption_token(params, errors, header_list)
            elif 'metadataPrefix' in params:
                metadata_prefix = params.pop('metadataPrefix')
                if len(metadata_prefix) == 1:
                    metadata_prefix = metadata_prefix[0]
                    if not MetadataFormat.objects.filter(prefix=metadata_prefix).exists():
                        errors.append({'code':'cannotDisseminateFormat', 'msg':'The value of the metadataPrefix argument "%s" is not supported.' % metadata_prefix})
                    else:
                        header_list = Header.objects.filter(metadata_formats__prefix=metadata_prefix)

                        if 'set' in params:
                            if Set.objects.all().count() == 0:
                                errors.append({'code':'noSetHierarchy', 'msg':'This repository does not support sets.'})
                            else:
                                set_spec = params.pop('set')[-1]
                                header_list = header_list.filter(sets__spec=set_spec)

                        from_timestamp, until_timestamp = check_timestamps(params, errors)
                        if from_timestamp:
                            header_list = header_list.filter(timestamp__gte=from_timestamp)
                        if until_timestamp:
                            header_list = header_list.filter(timestamp__lte=until_timestamp)

                        if header_list.count() == 0 and not errors:
                            errors.append({'code':'noRecordsMatch', 'msg':'The combination of the values of the from, until, and set arguments results in an empty list.'})
                        else:
                            paginator = Paginator(header_list, PER_PAGE)
                            headers = paginator.page(1)
                else:
                    errors.append({'code':'badArgument', 'msg':'Only a single metadataPrefix argument is allowed, got "%s".' % ';'.join(metadata_prefix)})
                    metadata_prefix = None
            else:
                errors.append({'code':'badArgument', 'msg':'The required argument "metadataPrefix" is missing in the request.'})
            check_bad_arguments(params, errors)
        elif verb == 'ListMetadataFormats':
            template = 'tima/oai_pmh/listmetadataformats.xml'
            metadataformats = MetadataFormat.objects.all()

            if 'identifier' in params:
                identifier = params.pop('identifier')[-1]
                if Header.objects.filter(identifier=identifier).exists():
                    metadataformats = metadataformats.filter(identifiers__identifier=identifier)
                else:
                    errors.append({'code':'idDoesNotExist', 'msg':'A record with the identifier "%s" does not exist.' % identifier})
            if metadataformats.count() == 0:
                errors.append({'code':'noMetadataFormats', 'msg':'There are no metadata formats available for the record with identifier "%s".' % identifier})
            check_bad_arguments(params, errors)
        elif verb == 'ListRecords':
            template = 'tima/oai_pmh/listrecords.xml'

            if 'resumptionToken' in params:
                header_list = Header.objects.all()
                paginator, headers, resumption_token, set_spec, metadata_prefix, from_timestamp, until_timestamp = do_resumption_token(params, errors, header_list)
            elif 'metadataPrefix' in params:
                metadata_prefix = params.pop('metadataPrefix')
                if len(metadata_prefix) == 1:
                    metadata_prefix = metadata_prefix[0]
                    if not MetadataFormat.objects.filter(prefix=metadata_prefix).exists():
                        errors.append({'code':'cannotDisseminateFormat', 'msg':'The value of the metadataPrefix argument "%s" is not supported.' % metadata_prefix})
                    else:
                        header_list = Header.objects.filter(metadata_formats__prefix=metadata_prefix)

                        if 'set' in params:
                            if Set.objects.all().count() == 0:
                                errors.append({'code':'noSetHierarchy', 'msg':'This repository does not support sets.'})
                            else:
                                set_spec = params.pop('set')[-1]
                                header_list = header_list.filter(sets__spec=set_spec)
                        from_timestamp, until_timestamp = check_timestamps(params, errors)
                        if from_timestamp:
                            header_list = header_list.filter(timestamp__gte=from_timestamp)
                        if until_timestamp:
                            header_list = header_list.filter(timestamp__lte=until_timestamp)

                        if header_list.count() == 0 and not errors:
                            errors.append({'code':'noRecordsMatch', 'msg':'The combination of the values of the from, until, and set arguments results in an empty list.'})
                        else:
                            paginator = Paginator(header_list, PER_PAGE)
                            headers = paginator.page(1)
                else:
                    errors.append({'code':'badArgument', 'msg':'Only a single metadataPrefix argument is allowed, got "%s".' % ';'.join(metadata_prefix)})
                    metadata_prefix = None
            else:
                errors.append({'code':'badArgument', 'msg':'The required argument "metadataPrefix" is missing in the request.'})
        elif verb == 'ListSets':
            template = 'tima/oai_pmh/listsets.xml'

            if not Set.objects.all().exists():
                errors.append({'code':'noSetHierarchy', 'msg':'This repository does not support sets.'})
            else:
                paginator, sets, resumption_token, set_spec, metadata_prefix, from_timestamp, until_timestamp = do_resumption_token(params, errors, Set.objects.all())
            check_bad_arguments(params, errors)
        else:
            errors.append({'code':'badVerb', 'msg':'The verb "%s" provided in the request is illegal.' % verb})
    else:
        errors.append({'code':'badVerb', 'msg':'The request does not provide any verb.'})
    track(request, 'OAI-PMH')
    return render(request, template if not errors else 'tima/oai_pmh/error.xml', locals(), content_type='text/xml')
Ejemplo n.º 28
0
def statistics(request):
    languages = Language.objects.all();
    user_count = Profile.objects.all().count()
    track(request, 'Statistics | TIMA')
    return render(request, 'tima/app/statistics.html', locals())
Ejemplo n.º 29
0
def home(request):
    languages = Language.objects.all()
    track(request, 'TIMA')
    return render(request, 'tima/association/home.html', locals())
Ejemplo n.º 30
0
def profile(request):
    profile = get_object_or_404(Profile, user=request.user)
    track(request, 'Profile | TIMA')
    return render(request, 'tima/app/profile/profile.html', locals())