views.py 13.9 KB
# -*- coding: utf-8 -*-

import gzip

from django.contrib.auth.decorators import login_required, permission_required
from django.contrib.auth.models import User, AnonymousUser
from django.core.urlresolvers import reverse
from django.http import HttpResponseRedirect, HttpResponse

from common.decorators import render
from common.util import json_decode
from dictionary.ajax_lexeme_slickgrid import LexemeQuery
from dictionary.reports import report_functions
from export.forms import ExportForm, MagicQualifierForm
from dictionary.models import visible_vocabularies, PartOfSpeech, Lexeme, \
    Vocabulary, Classification, Qualifier, \
    get_exclusion_classes, editable_vocabularies, \
    CrossReferenceType, PatternType, \
    LexemeAttribute, Gender, BorrowingSource
from export.lexeme_export import LexemeExport
from dictionary.wsjp import make_data


@login_required
def main(request):
    if request.user.has_perm('dictionary.view_lexeme'):
        return HttpResponseRedirect(reverse('lexeme_view'))
    if request.user.has_perm('dictionary.view_pattern'):
        return HttpResponseRedirect(reverse('pattern_view'))
    if request.user.has_perm('dictionary.manage_vocabulary') or \
            request.user.has_perm('auth.add_user'):
        return HttpResponseRedirect(reverse('management_menu'))
    if request.user.has_perm('dictionary.export_lexemes'):
        return HttpResponseRedirect(reverse('export'))
    return HttpResponseRedirect(reverse('auth_login'))  # niezbyt prawdopodobne


@permission_required('dictionary.view_lexeme')
@render('lexeme_view.html')
def lexeme_view(request):
    exclusion_classes = get_exclusion_classes()
    visible = visible_vocabularies(request.user)
    editable_vocabs = editable_vocabularies(request.user)
    vocabs = {}
    for v in editable_vocabs:
        vocabs.update(dict((str(q.pk), v.id) for q in v.qualifiers.all()))
    qualifier_options = [(0, u'(puste)')]
    lexeme_qualifier_options = [(0, u'(puste)')]
    form_qualifier_options = [(0, u'(puste)')]
    for vocab in visible:
        qualifiers = vocab.qualifiers.all()
        if qualifiers:
            qualifier_options.append((0, u'--%s--' % vocab.id))
            lexeme_qualifier_options.append((0, u'--%s--' % vocab.id))
            form_qualifier_options.append((0, u'--%s--' % vocab.id))
            for q in vocab.qualifiers.all():
                qualifier_options.append((q.pk, q.label))
                if q.type != Qualifier.TYPE_FORM:
                    lexeme_qualifier_options.append((q.pk, q.label))
                if q.type != Qualifier.TYPE_SCOPE:
                    form_qualifier_options.append((q.pk, q.label))
    classifications = Classification.objects.filter(
        vocabularies__in=visible).distinct()
    cv_options = []
    for classification in classifications:
        cv_options.append((0, '--%s--' % classification.name))
        cv_options += classification.make_choices()
    cr_type_options = []
    for cr_type in CrossReferenceType.objects.order_by('symbol'):
        cr_type_options.append((
            cr_type.pk,
            '%s %s->%s' % (cr_type.symbol, cr_type.from_pos, cr_type.to_pos)
        ))
    default_owner = request.user.usersettings.default_owner
    if not default_owner and len(editable_vocabs) == 1:
        default_owner = editable_vocabs[0]
    extra_attrs = []
    for la in LexemeAttribute.objects.all():
        attr = {'id': la.id, 'name': la.name, 'closed': la.closed}
        if attr['closed']:
            attr['options'] = [(0, u'(puste)')] + [
                (v.id, v.value) for v in la.values.all()]
        extra_attrs.append(attr)
    user_options = list(
        User.objects.order_by('username').values_list('id', 'username'))
    js_vars = {
        'ajax_get_page': reverse('get_lexemes'),
        'ajax_inflection_tables': reverse('inflection_tables'),
        'ajax_history_table': reverse('history_table'),
        'ajax_odm_forms': reverse('odm_forms'),
        'ajax_edit_form': reverse('lexeme_edit_form'),
        'ajax_update_lexeme': reverse('update_lexeme'),
        'ajax_search_index': reverse('search_index'),
        'ajax_search_by_form': reverse('search_by_form'),
        'ajax_row_index': reverse('row_index'),
        'ajax_save_filter': reverse('save_filter'),
        'ajax_get_filters': reverse('get_filters'),
        'ajax_delete_filter': reverse('delete_filter'),
        'ajax_table_preview': reverse('table_preview'),
        'ajax_new_lip_row': reverse('new_lip_edit_row'),
        'ajax_new_cr_row': reverse('new_cross_reference_row'),
        'ajax_save_columns': reverse('save_columns'),
        'ajax_delete_lexeme': reverse('delete_lexeme'),
        'ajax_prompter_list': reverse('prompter_list'),
        'ajax_check_pos': reverse('check_pos'),
        'ajax_check_pattern': reverse('check_pattern'),
        'ajax_check_classifications': reverse('check_classifications'),
        'ajax_save_default_owner': reverse('save_default_owner'),
        'ajax_create_lexeme': reverse('create_lexeme'),
        'ajax_classification_forms': reverse('classification_forms'),
        'ajax_extra_attributes': reverse('extra_attributes'),
        'ajax_check_attributes': reverse('check_attributes'),
        'ajax_homonym_count': reverse('homonym_count'),
        'ajax_cr_homonyms': reverse('cr_homonyms'),
        'ajax_new_action_row': reverse('new_action_row'),
        'ajax_dynamic_fields': reverse('dynamic_action_fields'),
        'ajax_execute_actions': reverse('execute_group_actions'),
        'ajax_export_list': reverse('export_list'),
        'ajax_create_derivatives': reverse('create_derivatives'),
        'ajax_clone_lexeme': reverse('clone_lexeme'),
        'vocabs': vocabs,
        'visible_vocabularies': [(v.id, v.id) for v in visible],
        'parts_of_speech': [
            (pos.symbol, pos.symbol) for pos in PartOfSpeech.objects.all()],
        'lexeme_qualifier_options': lexeme_qualifier_options,
        'form_qualifier_options': form_qualifier_options,
        'qualifier_options': qualifier_options,
        'cv_options': cv_options,
        'status_options': Lexeme.STATUS_CHOICES,
        'cr_type_options': cr_type_options,
        'gender_options': [(g.id, g.symbol) for g in Gender.objects.all()],
        'pattern_type_options': PatternType.options(),
        'bs_options': [(0, u'(puste)')] + [
            (bs.id, bs.label) for bs in BorrowingSource.objects.all()],
        'user_options': [(0, u'(brak)')] + user_options,
        'commonness': Classification.objects.get(name=u'pospolitość').pk,
        'exclusion_classes': exclusion_classes,
        'auto_search': request.user.usersettings.incremental_search,
        'default_owner': default_owner.id if default_owner else '',
        'extra_attributes': extra_attrs,
        'initial_columns': LexemeQuery.default_columns,
    }
    session_variables = ('filter', 'sort_rules', 'columns')
    for var in session_variables:
        if var in request.session:
            js_vars[var] = request.session[var]
    return {'js_vars': js_vars, 'editable_vocabularies': editable_vocabs}


@render('reader_view.html')
def reader_view(request):
    visible = visible_vocabularies(AnonymousUser())
    vocabs = {}
    qualifier_options = [(0, u'(puste)')]
    lexeme_qualifier_options = [(0, u'(puste)')]
    form_qualifier_options = [(0, u'(puste)')]
    for vocab in visible:
        qualifiers = vocab.qualifiers.all()
        if qualifiers:
            qualifier_options.append((0, u'--%s--' % vocab.id))
            lexeme_qualifier_options.append((0, u'--%s--' % vocab.id))
            form_qualifier_options.append((0, u'--%s--' % vocab.id))
            for q in vocab.qualifiers.all():
                qualifier_options.append((q.pk, q.label))
                if q.type != Qualifier.TYPE_FORM:
                    lexeme_qualifier_options.append((q.pk, q.label))
                if q.type != Qualifier.TYPE_SCOPE:
                    form_qualifier_options.append((q.pk, q.label))
    classifications = Classification.objects.filter(
        vocabularies__in=visible).distinct()
    cv_options = []
    for classification in classifications:
        cv_options.append((0, '--%s--' % classification.name))
        cv_options += classification.make_choices()
    cr_type_options = []
    for cr_type in CrossReferenceType.objects.order_by('symbol'):
        cr_type_options.append((
            cr_type.pk,
            '%s %s->%s' % (cr_type.symbol, cr_type.from_pos, cr_type.to_pos)
        ))
    extra_attrs = []
    for la in LexemeAttribute.objects.all():
        attr = {'id': la.id, 'name': la.name, 'closed': la.closed}
        if attr['closed']:
            attr['options'] = [(0, u'(puste)')] + [
                (v.id, v.value) for v in la.values.all()]
        extra_attrs.append(attr)
    js_vars = {
        'ajax_get_page': reverse('get_lexemes'),
        'ajax_inflection_tables': reverse('inflection_tables'),
        'ajax_search_index': reverse('search_index'),
        'ajax_search_by_form': reverse('search_by_form'),
        'ajax_row_index': reverse('row_index'),
        'ajax_save_filter': reverse('save_filter'),
        'ajax_get_filters': reverse('get_filters'),
        'ajax_delete_filter': reverse('delete_filter'),
        'ajax_save_columns': reverse('save_columns'),
        'ajax_export_list': reverse('export_list'),
        'vocabs': vocabs,
        'visible_vocabularies': [(v.id, v.id) for v in visible],
        'parts_of_speech': [
            (pos.symbol, pos.symbol) for pos in PartOfSpeech.objects.all()],
        'lexeme_qualifier_options': lexeme_qualifier_options,
        'form_qualifier_options': form_qualifier_options,
        'qualifier_options': qualifier_options,
        'cv_options': cv_options,
        'status_options': Lexeme.STATUS_CHOICES,
        'cr_type_options': cr_type_options,
        'gender_options': [(g.id, g.symbol) for g in Gender.objects.all()],
        'pattern_type_options': PatternType.options(),
        'user_options': [],
        'commonness': Classification.objects.get(name=u'pospolitość').pk,
        'auto_search': True,
        'extra_attributes': extra_attrs,
        'initial_columns': LexemeQuery.default_columns,
    }
    session_variables = ('filter', 'sort_rules', 'columns')
    for var in session_variables:
        if var in request.session:
            js_vars[var] = request.session[var]
    return {'js_vars': js_vars}


@login_required
@render()
def tasks(request):
    return {}


@login_required
@render()
def reports(request):
    report_lists = {}
    for report_fun in report_functions:
        report_lists.update(report_fun())
    return {
        'report_lists': report_lists
    }


@permission_required('dictionary.export_lexemes')
@render()
def export(request):
    if request.GET:
        form = ExportForm(data=request.GET)
        if form.is_valid():
            data = {
                'vocabs': [v.id for v in form.cleaned_data['vocabs']],
                'antivocabs': [v.id for v in form.cleaned_data['antivocabs']],
                'variant': form.cleaned_data['variant'].id,
            }
            # data['excluding_qualifiers'] = [
            #     q.pk for q in form.cleaned_data['excluding_qualifiers']]
            magic_ids = set()
            magic_qualifiers = []
            normal_qualifiers = []
            for key in request.GET:
                split_key = key.split('-')
                if key.startswith('magic') and split_key[0] not in magic_ids:
                    i, name = split_key
                    magic_ids.add(i)
                    magic_form = MagicQualifierForm(prefix=i, data=request.GET)
                    if magic_form.is_valid():
                        regex = magic_form.cleaned_data['regex']
                        if regex:
                            magic_qualifiers.append(
                                (
                                    regex,
                                    magic_form.cleaned_data['qualifier'].pk))
                        else:
                            normal_qualifiers.append(
                                magic_form.cleaned_data['qualifier'].pk)
            data['magic_qualifiers'] = magic_qualifiers
            data['excluding_qualifiers'] = normal_qualifiers
            data['refl'] = form.cleaned_data['refl']
            data['commonness'] = form.cleaned_data['commonness']
            ###
            response = HttpResponse(content_type='application/x-gzip')
            export_gz = gzip.GzipFile(fileobj=response, mode='w')
            LexemeExport(data, export_gz).export()
            filename = 'eksport.tab.gz'
            response['Content-Disposition'] = (
                'attachment; filename=%s' % filename)
            return response
    else:
        form = ExportForm()
    vocabs = {}
    for v in Vocabulary.objects.all():
        vocabs.update(dict((str(q.pk), v.id) for q in v.qualifiers.all()))
    js_vars = {
        'vocabs': vocabs,
        'ajax_new_qualifier_row': reverse('magic_qualifier_row'),
        'ajax_save_export_data': reverse('save_export_data'),
        'ajax_get_export_data': reverse('get_export_data'),
        'ajax_delete_export_data': reverse('delete_export_data'),
    }
    return {'form': form, 'js_vars': js_vars}


@permission_required('dictionary.view_lexeme')
def export_list(request):
    filter = json_decode(request.GET['filter'])
    sort_rules = json_decode(request.GET['sort_rules'])
    columns = json_decode(request.GET['columns'])
    filename = request.GET.get('filename') or 'lista.txt'
    response = HttpResponse(content_type='text/plain')
    visible_vocabs = list(visible_vocabularies(request.user).values_list(
        'id', flat=True))
    query = LexemeQuery(
        filter=filter, sort_rules=sort_rules, visible_vocabs=visible_vocabs)
    query.export_list(columns, response)
    response['Content-Disposition'] = ('attachment; filename=%s' % filename)
    return response


def wsjp_table(request, entry):
    data = make_data(entry)
    result = '\n'.join(
        '\t'.join(['%s'] * len(data_row)) % data_row for data_row in data)
    return HttpResponse(result, content_type="text/plain; charset=utf-8")