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

import gzip

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

from common.decorators import render
from common.util import make_form
from paginer import PaginationList
from paginer.decorators import paginated
from dictionary.forms import AddClassificationForm, ExclusionClassForm, \
                             AddClassificationValueForm, VocabularyForm, \
                             AddExclusionClassForm, AddQualifierForm, \
                             ChangeClassForm, ExportForm, MagicQualifierForm
from dictionary.models import visible_vocabularies, PartOfSpeech, Lexeme, \
  Vocabulary, Classification, ClassificationValue, Qualifier, History, \
  QualifierExclusionClass, get_exclusion_classes
from dictionary.history import lexeme_tables
from dictionary.export import export_lexemes

@permission_required('dictionary.view_lexeme')
@render()
def lexeme_view(request):
  exclusion_classes = get_exclusion_classes()
  visible = visible_vocabularies(request.user)
  rw_vocabs = visible.filter(editors=request.user)
  vocabs = {}
  for v in rw_vocabs:
    vocabs.update(dict((str(q.pk), v.id) for q in v.qualifier_set.all()))
  qualifiers = Qualifier.objects.filter(vocabulary__in=visible)
  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()
  default_owner = request.user.usersettings.default_owner
  js_vars = {
    'ajax_get_page': reverse('get_lexemes'),
    'ajax_inflection_tables': reverse('get_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_location': reverse('get_location'),
    'ajax_find_id': reverse('find_id'),
    'ajax_sort_rules': reverse('sort_rules'),
    '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_get_ics': reverse('get_ics'),
    'ajax_save_default_owner': reverse('save_default_owner'),
    'ajax_create_lexeme': reverse('create_lexeme'),
    'ajax_classification_forms': reverse('classification_forms'),
    'ajax_homonym_count': reverse('homonym_count'),
    'visible_vocabularies': ';'.join(
      '%s:%s' % (v.pk, v.id) for v in visible),
    'vocabs': vocabs,
    'parts_of_speech': ';'.join(
      '%s:%s' % (pos.pk, pos.symbol) for pos in PartOfSpeech.objects.all()),
    'qualifier_options': ';'.join(
      '%s:%s' % (q.pk, q.label.replace(';', ',')) for q in qualifiers),
    'cv_options': ';'.join('%s:%s' % pair for pair in cv_options),
    'commonness': Classification.objects.get(name=u'pospolitość').pk,
    'exclusion_classes': exclusion_classes,
    'status_options': dict(Lexeme.STATUS_CHOICES),
    'filtering_mode': request.user.usersettings.filter_search,
    'auto_search': request.user.usersettings.incremental_search,
    'default_owner': default_owner.id if default_owner else '',
  }
  session_variables = ('filters', 'sort_rules', 'colModel', 'colNames', 'remap')
  for var in session_variables:
    if var in request.session:
      js_vars[var] = request.session[var]
  return {'js_vars': js_vars, 'editable_vocabularies': rw_vocabs}

@permission_required('dictionary.view_pattern')
@render()
def pattern_view(request):
  js_vars = {
    'ajax_get_page': reverse('get_patterns'),
    'ajax_edit_form': reverse('pattern_edit_form'),
    'ajax_update_pattern': reverse('update_pattern'),
    'ajax_find_id': reverse('patterns_find_id'),
    'ajax_location': reverse('patterns_get_location'),
    'ajax_sort_rules': reverse('sort_rules'),
    'ajax_save_columns': reverse('patterns_save_columns'),
    'ajax_new_ending_row': reverse('new_ending_row'),
    'exclusion_classes': get_exclusion_classes(),
    'filtering_mode': request.user.usersettings.filter_search,
    'auto_search' : request.user.usersettings.incremental_search,
  }
  session_variables = (
    'pattern-filters',
    'pattern-sort_rules',
    'pattern-colModel',
    'pattern-colNames',
    'pattern-remap'
  )
  for var in session_variables:
    if var in request.session:
      js_name = var.split('-', 1)[1]
      js_vars[js_name] = request.session[var]
  return {'js_vars': js_vars}

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

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

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

@permission_required('dictionary.manage_vocabulary')
@render()
def manager_view(request):
  to_return = {}
  to_return['users'] = User.objects.all()
  to_return['vocabularies'] = request.user.managed_vocabularies.all()
  to_return['js_vars'] = {
    'ajax_add_vocabulary': reverse('add_vocabulary'),
    'ajax_get_privileges': reverse('vocabulary_privileges'),
    'ajax_set_privilege': reverse('set_vocabulary_privilege'),
  }
  return to_return

@permission_required('dictionary.manage_vocabulary')
@render()
def manage_classifications(request):
  to_return = {}
  add_form = make_form(request, AddClassificationForm)
  if add_form.is_valid():
    add_form.save()
  to_return['add_form'] = add_form
  if request.POST.get('det') == 'value_form':
    add_form = AddClassificationValueForm(data=request.POST)
    if add_form.is_valid():
      add_form.save()
  if request.POST.get('det') == 'vocabulary_form':
    form = VocabularyForm(
      data=request.POST, queryset=request.user.managed_vocabularies.all())
    if form.is_valid():
      c = form.cleaned_data['classification']
      v = form.cleaned_data['vocabulary']
      c.vocabularies.add(v) #add
  if request.POST.get('det') == 'value_remove':
    pk = int(request.POST['id'])
    try:
      cv = ClassificationValue.objects.get(pk=pk)
      cv.deleted = True
      cv.save()
    except ClassificationValue.DoesNotExist:
      pass
  if request.POST.get('det') == 'value_rename':
    pk = int(request.POST['id'])
    label = request.POST['new_name']
    try:
      v = ClassificationValue.objects.get(pk=pk)
      v.label = label
      v.save()
    except ClassificationValue.DoesNotExist:
      pass
  if request.POST:
    return HttpResponseRedirect(reverse('manage_classifications'))

  classification_forms = []
  for c in Classification.objects.all():
    value_form = AddClassificationValueForm(classification=c)
    vocabs = request.user.managed_vocabularies.all()
    using = c.vocabularies.all() & vocabs
    other = vocabs.exclude(pk__in=using.values_list('pk', flat=True))
    vocab_form = VocabularyForm(classification=c, queryset=other)
    classification_forms.append((c, value_form, vocab_form, using))
  to_return['classification_forms'] = classification_forms
  return to_return

@permission_required('dictionary.manage_vocabulary')
@render()
def manage_qualifiers(request):
  det = request.POST.get('det')
  if det == 'add_exclusion_class':
    form = AddExclusionClassForm(data=request.POST)
    if form.is_valid():
      form.save()
  if det == 'remove_exclusion_class':
    form = ExclusionClassForm(data=request.POST)
    if form.is_valid():
      ec = form.cleaned_data['ec']
      ec.delete()
  if det == 'add_qualifier':
    form = AddQualifierForm(data=request.POST)
    if form.is_valid():
      form.save()
  prefix = None
  for name, _value in request.POST.iteritems():
    if name.startswith('cec'):
      prefix = name.split('-')[0]
      q = Qualifier.objects.get(pk=int(prefix[3:]))
      break
  if prefix:
    form = ChangeClassForm(data=request.POST, instance=q, prefix=prefix)
    if form.is_valid():
      form.save()
  if det == 'remove_qualifier':
    pk = int(request.POST['id'])
    try:
      q = Qualifier.objects.get(pk=pk)
      q.deleted = True
      q.save()
    except Qualifier.DoesNotExist:
      pass
  if request.POST:
    return HttpResponseRedirect(reverse('manage_qualifiers'))

  to_return = {}
  form_list = []
  for vocabulary in request.user.managed_vocabularies.all():
    add_exclusion_class_form = AddExclusionClassForm(vocabulary=vocabulary)
    empty_ec = QualifierExclusionClass.objects.filter(
      vocabulary=vocabulary).extra(where=[
        'not exists (select * from kwalifikatory '
        'where klasa = klasy_wykluczania.id)'])
    if empty_ec:
      remove_exclusion_class_form = ExclusionClassForm(queryset=empty_ec)
    else:
      remove_exclusion_class_form = None
    add_qualifier_form = AddQualifierForm(vocabulary=vocabulary)
    qualifiers = Qualifier.objects.filter(vocabulary=vocabulary, deleted=False)
    qualifier_forms = []
    for q in qualifiers:
      change_class_form = ChangeClassForm(instance=q, prefix='cec%s' % q.pk)
      qualifier_forms.append((q, change_class_form))
    form_list.append(
      (vocabulary.id, add_exclusion_class_form, remove_exclusion_class_form,
       add_qualifier_form, qualifier_forms))
  to_return['form_list'] = form_list
  return to_return

@permission_required('dictionary.view_lexeme')
@render()
@paginated
def history_view(request):
  paginer = PaginationList()
  lexeme_history = History.objects.exclude(lexeme=None).distinct().values(
    'lexeme', 'user', 'transaction_began')
  paginer.add('lexeme_items', 'lexeme_history', {
    'columns': ('lexeme',),
    'order_by': '-transaction_began',
    'filters': [('user', 'ne', u'Kuźniobot')],
    'sort_fields': (),
    'filter_fields': ('user', 'time_from', 'time_to'),
  })
  return {
    'lexeme_tables': lexeme_tables(lexeme_history),
    'show_lexemes': True,
    'paginer': paginer,
  }

@permission_required('dictionary.view_lexeme')
@render()
def export(request):
  if request.GET:
    form = ExportForm(data=request.GET)
    if form.is_valid():
      data = {}
      data['vocabs'] = [v.id for v in form.cleaned_data['vocabs']]
      data['antivocabs'] = [v.id for v in form.cleaned_data['antivocabs']]
      data['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(mimetype='application/x-gzip')
      export_gz = gzip.GzipFile(fileobj=response, mode='w')
      export_lexemes(data, export_gz)
      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.qualifier_set.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}