<commit_before># -*- coding: utf-8 -*-
# Copyright (c) 2012 The Pycroft Authors. See the AUTHORS file.
# This file is part of the Pycroft project and licensed under the terms of
# the Apache License, Version 2.0. See the LICENSE file for details.
"""
    web.blueprints.user
    ~~~~~~~~~~~~~~

    This module defines view functions for /user

    :copyright: (c) 2012 by AG DSN.
"""

from flask import Blueprint, render_template, flash, redirect, url_for,\
    request, jsonify, abort
from pycroft import lib
from pycroft.helpers import host_helper
from pycroft.model.dormitory import Room
from pycroft.model.hosts import Host, NetDevice, Ip
from pycroft.model.logging import UserLogEntry
from pycroft.model.session import session
from pycroft.model.user import User
from pycroft.model.properties import Membership
from pycroft.model.accounting import TrafficVolume
from sqlalchemy.sql.expression import or_
from web.blueprints.navigation import BlueprintNavigation
from web.blueprints.user.forms import UserSearchForm, UserCreateForm,\
    hostCreateForm, userLogEntry, UserAddGroupMembership, UserMoveForm,\
    UserEditNameForm
from web.blueprints.access import login_required, BlueprintAccess
from datetime import datetime, timedelta, time
from flask.ext.login import current_user

bp = Blueprint('user', __name__, )
nav = BlueprintNavigation(bp, "Nutzer")
access = BlueprintAccess(bp)


@bp.errorhandler(404)
def error_404(e):
    return render_template('errorpages/404.html', ref=request.referrer)


@bp.route('/')
@nav.navigate(u"Übersicht")
def overview():
    return redirect(url_for("dormitories.overview"))


@bp.route('/show/<user_id>', methods=['GET', 'POST'])
@access.login_required
def user_show(user_id):

    user = User.q.get(user_id)
    if user is None:
        flash(u"Nutzer mit ID %s existiert nicht!" % (user_id,), 'error')
        abort(404)

    room = Room.q.get(user.room_id)
    form = userLogEntry()

    if form.validate_on_submit():
        newUserLogEntry = UserLogEntry(message=form.message.data,
            timestamp=datetime.now(),
            author_id=current_user.id, user_id=user_id)
        session.add(newUserLogEntry)
        session.commit()
        flash(u'Kommentar hinzugefügt', 'success')

    user_log_list = user.user_log_entries[::-1]

    memberships = Membership.q.filter(Membership.user_id == user.id)
    memberships_active = memberships.filter(
        # it is important to use == here, "is" does NOT work
        or_(Membership.start_date == None,
            Membership.start_date <= datetime.now())
    ).filter(
        # it is important to use == here, "is" does NOT work
        or_(Membership.end_date == None,
            Membership.end_date > datetime.now())
    )

    return render_template('user/user_show.html',
        user=user, user_logs=user_log_list, room=room, form=form,
        memberships=memberships.all(),
        memberships_active=memberships_active.all())


@bp.route('/add_membership/<int:user_id>/', methods=['GET', 'Post'])
def add_membership(user_id):

    user = User.q.get(user_id)
    if user is None:
        flash(u"Nutzer mit ID %s existiert nicht!" % (user_id,), 'error')
        abort(404)

    form = UserAddGroupMembership()
    if form.validate_on_submit():
        newMembership = Membership(user=user, group=form.group_id.data,
            start_date=datetime.combine(form.begin_date.data,time(0)), end_date=datetime.combine(form.end_date.data,time(0)))
        newUserLogEntry = UserLogEntry(author_id=current_user.id,
            message=u"hat Nutzer zur Gruppe '%s' hinzugefügt." %
                    form.group_id.data.name,
            timestamp=datetime.now(), user_id=user_id)

        session.add(newMembership)
        session.add(newUserLogEntry)
        session.commit()
        flash(u'Nutzer wurde der Gruppe hinzugefügt.', 'success')

        return redirect(url_for(".user_show", user_id=user_id))

    return render_template('user/add_membership.html',
        page_title=u"Neue Gruppenmitgliedschaft für Nutzer %s" % user_id,
        user_id=user_id, form=form)


@bp.route('/delete_membership/<int:membership_id>')
def end_membership(membership_id):
    membership = Membership.q.get(membership_id)
    membership.disable()

    # ToDo: Make the log messages not Frontend specific (a helper?)
    newUserLogEntry = UserLogEntry(author_id=current_user.id,
        message=u"hat die Mitgliedschaft des Nutzers"
                u" in der Gruppe '%s' beendet." %
                membership.group.name,
        timestamp=datetime.now(), user_id=membership.user_id)

    session.add(newUserLogEntry)
    session.commit()
    flash(u'Mitgliedschaft in Gruppe beendet', 'success')
    return redirect(url_for(".user_show", user_id=membership.user_id))


@bp.route('/json/levels')
def json_levels():
    if not request.is_xhr:
        abort(404)
    dormitory_id = request.args.get('dormitory', 0, type=int)
    levels = session.query(Room.level.label('level')).filter_by(
        dormitory_id=dormitory_id).order_by(Room.level).distinct()
    return jsonify(dict(items=[entry.level for entry in levels]))


@bp.route('/json/rooms')
def json_rooms():
    if not request.is_xhr:
        abort(404)
    dormitory_id = request.args.get('dormitory', 0, type=int)
    level = request.args.get('level', 0, type=int)
    rooms = session.query(
        Room.number.label("room_num")).filter_by(
        dormitory_id=dormitory_id, level=level).order_by(
        Room.number).distinct()
    return jsonify(dict(items=[entry.room_num for entry in rooms]))


@bp.route('/json/traffic/<int:user_id>')
def json_trafficdata(user_id):
    traffic_timespan = datetime.now() - timedelta(days=7)

    trafficvolumes = session.query(
        TrafficVolume
    ).join(
        TrafficVolume.ips
    ).join(
        Ip.host
    ).filter(<commit_msg>renamed traffic_volume.ips in traffic_volume.ip<commit_after># -*- coding: utf-8 -*-
# Copyright (c) 2012 The Pycroft Authors. See the AUTHORS file.
# This file is part of the Pycroft project and licensed under the terms of
# the Apache License, Version 2.0. See the LICENSE file for details.
"""
    web.blueprints.user
    ~~~~~~~~~~~~~~

    This module defines view functions for /user

    :copyright: (c) 2012 by AG DSN.
"""

from flask import Blueprint, render_template, flash, redirect, url_for,\
    request, jsonify, abort
from pycroft import lib
from pycroft.helpers import host_helper
from pycroft.model.dormitory import Room
from pycroft.model.hosts import Host, NetDevice, Ip
from pycroft.model.logging import UserLogEntry
from pycroft.model.session import session
from pycroft.model.user import User
from pycroft.model.properties import Membership
from pycroft.model.accounting import TrafficVolume
from sqlalchemy.sql.expression import or_
from web.blueprints.navigation import BlueprintNavigation
from web.blueprints.user.forms import UserSearchForm, UserCreateForm,\
    hostCreateForm, userLogEntry, UserAddGroupMembership, UserMoveForm,\
    UserEditNameForm
from web.blueprints.access import login_required, BlueprintAccess
from datetime import datetime, timedelta, time
from flask.ext.login import current_user

bp = Blueprint('user', __name__, )
nav = BlueprintNavigation(bp, "Nutzer")
access = BlueprintAccess(bp)


@bp.errorhandler(404)
def error_404(e):
    return render_template('errorpages/404.html', ref=request.referrer)


@bp.route('/')
@nav.navigate(u"Übersicht")
def overview():
    return redirect(url_for("dormitories.overview"))


@bp.route('/show/<user_id>', methods=['GET', 'POST'])
@access.login_required
def user_show(user_id):

    user = User.q.get(user_id)
    if user is None:
        flash(u"Nutzer mit ID %s existiert nicht!" % (user_id,), 'error')
        abort(404)

    room = Room.q.get(user.room_id)
    form = userLogEntry()

    if form.validate_on_submit():
        newUserLogEntry = UserLogEntry(message=form.message.data,
            timestamp=datetime.now(),
            author_id=current_user.id, user_id=user_id)
        session.add(newUserLogEntry)
        session.commit()
        flash(u'Kommentar hinzugefügt', 'success')

    user_log_list = user.user_log_entries[::-1]

    memberships = Membership.q.filter(Membership.user_id == user.id)
    memberships_active = memberships.filter(
        # it is important to use == here, "is" does NOT work
        or_(Membership.start_date == None,
            Membership.start_date <= datetime.now())
    ).filter(
        # it is important to use == here, "is" does NOT work
        or_(Membership.end_date == None,
            Membership.end_date > datetime.now())
    )

    return render_template('user/user_show.html',
        user=user, user_logs=user_log_list, room=room, form=form,
        memberships=memberships.all(),
        memberships_active=memberships_active.all())


@bp.route('/add_membership/<int:user_id>/', methods=['GET', 'Post'])
def add_membership(user_id):

    user = User.q.get(user_id)
    if user is None:
        flash(u"Nutzer mit ID %s existiert nicht!" % (user_id,), 'error')
        abort(404)

    form = UserAddGroupMembership()
    if form.validate_on_submit():
        newMembership = Membership(user=user, group=form.group_id.data,
            start_date=datetime.combine(form.begin_date.data,time(0)), end_date=datetime.combine(form.end_date.data,time(0)))
        newUserLogEntry = UserLogEntry(author_id=current_user.id,
            message=u"hat Nutzer zur Gruppe '%s' hinzugefügt." %
                    form.group_id.data.name,
            timestamp=datetime.now(), user_id=user_id)

        session.add(newMembership)
        session.add(newUserLogEntry)
        session.commit()
        flash(u'Nutzer wurde der Gruppe hinzugefügt.', 'success')

        return redirect(url_for(".user_show", user_id=user_id))

    return render_template('user/add_membership.html',
        page_title=u"Neue Gruppenmitgliedschaft für Nutzer %s" % user_id,
        user_id=user_id, form=form)


@bp.route('/delete_membership/<int:membership_id>')
def end_membership(membership_id):
    membership = Membership.q.get(membership_id)
    membership.disable()

    # ToDo: Make the log messages not Frontend specific (a helper?)
    newUserLogEntry = UserLogEntry(author_id=current_user.id,
        message=u"hat die Mitgliedschaft des Nutzers"
                u" in der Gruppe '%s' beendet." %
                membership.group.name,
        timestamp=datetime.now(), user_id=membership.user_id)

    session.add(newUserLogEntry)
    session.commit()
    flash(u'Mitgliedschaft in Gruppe beendet', 'success')
    return redirect(url_for(".user_show", user_id=membership.user_id))


@bp.route('/json/levels')
def json_levels():
    if not request.is_xhr:
        abort(404)
    dormitory_id = request.args.get('dormitory', 0, type=int)
    levels = session.query(Room.level.label('level')).filter_by(
        dormitory_id=dormitory_id).order_by(Room.level).distinct()
    return jsonify(dict(items=[entry.level for entry in levels]))


@bp.route('/json/rooms')
def json_rooms():
    if not request.is_xhr:
        abort(404)
    dormitory_id = request.args.get('dormitory', 0, type=int)
    level = request.args.get('level', 0, type=int)
    rooms = session.query(
        Room.number.label("room_num")).filter_by(
        dormitory_id=dormitory_id, level=level).order_by(
        Room.number).distinct()
    return jsonify(dict(items=[entry.room_num for entry in rooms]))


@bp.route('/json/traffic/<int:user_id>')
def json_trafficdata(user_id):
    traffic_timespan = datetime.now() - timedelta(days=7)

    trafficvolumes = session.query(
        TrafficVolume
    ).join(
        TrafficVolume.ip
    ).join(
        Ip.host
    ).filter(
{'fraction_non_alphanumeric': 0.11986681465038845, 'fraction_numerical': 0.006659267480577136, 'mean_word_length': 3.6484126984126983, 'pattern_counts': {'":': 0, '<': 13, '<?xml version=': 0, '>': 13, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '7534970', 'n_tokens_mistral': 3837, 'n_tokens_neox': 3741, 'n_words': 802}