Exemplo n.º 1
0
def distribute():
    """categorize users"""

    # TODO: provide less hacky fix
    class CategorizeHackForm(CategorizeBatchForm):
        pass
    for category, count in g.event.category_defaults:
        setattr(CategorizeHackForm, category, wtf.IntegerField(category,
            description='Number of signups to allocate to %s' % category,
            default=count))

    try:
        form = CategorizeHackForm(request.form)
        form.category.choices = choicify(['*'] + g.event.categories)
        if request.method == 'POST' and form.validate():
            signups = iter(g.event.signups_by_category(
                category=request.form['category']))
            for category in g.event.categories:
                count = int(request.form[category])
                for _ in range(count):
                    signup = next(signups)
                    signup.update(category=category).save()
            return redirect(url_for('event.home'))
        form.category.description = 'Category to pull signups from and distribute among the categories in specified amounts.'
        return render_event('event/form.html',
            title='Distribute Signups',
            form=form,
            submit='Distribute')
    except StopIteration:
        pass
    return redirect(url_for('event.home'))
Exemplo n.º 2
0
def member(user_id):
    """Displays information about member"""

    user = User.query.get(user_id)
    g.membership = Membership.query.filter_by(group_id=g.group.id,
                                              user_id=user_id).one_or_none()

    if not g.membership and user_id == current_user():
        return render_group(
            'confirm.html',
            back=url_for('group.home'),
            title='Create Profile?',
            message=
            'You have not yet joined this group. Click below to join now!',
            action='Join',
            url=url_for('group.signup'))

    checkins = Event.query.join(Checkin).filter(Checkin.user_id == user_id,
                                                Event.group_id == g.group.id)

    # naiive way of counting hours - need a query to do this!
    hours = 0.0
    for event in checkins:
        hours += (event.end - event.start).seconds / 3600.0

    return render_group('group/member.html',
                        membership=g.membership,
                        user=user,
                        total_checkins=checkins.count(),
                        total_hours=hours)
Exemplo n.º 3
0
def distribute():
    """categorize users"""

    # TODO: provide less hacky fix
    class CategorizeHackForm(CategorizeBatchForm):
        pass

    for category, count in g.event.category_defaults:
        setattr(
            CategorizeHackForm, category,
            wtf.IntegerField(
                category,
                description='Number of signups to allocate to %s' % category,
                default=count))

    try:
        form = CategorizeHackForm(request.form)
        form.category.choices = choicify(['*'] + g.event.categories)
        if request.method == 'POST' and form.validate():
            signups = iter(
                g.event.signups_by_category(category=request.form['category']))
            for category in g.event.categories:
                count = int(request.form[category])
                for _ in range(count):
                    signup = next(signups)
                    signup.update(category=category).save()
            return redirect(url_for('event.home'))
        form.category.description = 'Category to pull signups from and distribute among the categories in specified amounts.'
        return render_event('event/form.html',
                            title='Distribute Signups',
                            form=form,
                            submit='Distribute')
    except StopIteration:
        pass
    return redirect(url_for('event.home'))
Exemplo n.º 4
0
def login(home=None, login=None):
    """
    Login using Google authentication

    :param str home: URL for queue homepage
    :param str login: URL for queue login page
    """
    try:
        flow = client.flow_from_clientsecrets(
            'client_secrets.json',
            scope=
            'openid profile email https://www.googleapis.com/auth/calendar.readonly',
            redirect_uri=login or url_for('public.login', _external=True))
        if 'code' not in request.args:
            auth_uri = flow.step1_get_authorize_url()
            return redirect(auth_uri + '&prompt=select_account')
        credentials = flow.step2_exchange(request.args.get('code'))
        session['credentials'] = credentials.to_json()

        http = credentials.authorize(httplib2.Http())
        person = service.people().get(userId='me').execute(http=http)

        user = User.query.filter_by(email=person['emails'][0]['value']).first()
        if not user:
            user = User(name=person['displayName'],
                        email=person['emails'][0]['value'],
                        google_id=person['id'],
                        image_url=person['image']['url']).save()
        else:
            user.update(google_id=person['id'],
                        image_url=person['image']['url']).save()
        flask_login.login_user(user)
        return redirect(home or url_for('public.home'))
    except client.FlowExchangeError:
        return redirect(login or url_for('public.login'))
Exemplo n.º 5
0
def import_signups():
    """import signups"""
    form = ImportSignupsForm(request.form)
    if request.method == 'POST' and form.validate():
        signups = list(
            Signup.from_csv_string(request.form['csv'],
                                   request.form.get('override', 'n') == 'y'))
        for signup in signups:
            if not Membership.query.filter_by(group_id=g.group.id,
                                              user_id=signup.user_id).count():
                Membership(group_id=g.group.id,
                           user_id=signup.user_id,
                           role_id=GroupRole.query.filter_by(
                               name='Member',
                               group_id=g.group.id).one().id).save()
        return render_group('group/import_signups.html',
                            message='All %d signups created.' % len(signups),
                            url=url_for('group.events'),
                            action='Back',
                            signups=signups)
    return render_group('group/form.html',
                        title='Import Signups',
                        submit='Import',
                        form=form,
                        back=url_for('group.events'))
Exemplo n.º 6
0
def checkin_signup(signup_id):
    """checkin signup"""
    if g.group.setting('self_checkin').is_active or current_user().can('authorize'):
        try:
            signup = Signup.query.get(signup_id)
            checkin = signup.user.checkin(g.event, current_user())
            return redirect(url_for('event.home'))
        except NoResultFound:
            abort(404)
    else:
        return redirect(url_for('group.events'))
Exemplo n.º 7
0
def edit():
    """event edit"""
    form = EventForm(request.form, obj=g.event)
    if request.method == 'POST' and form.validate():
        g.event.update(**request.form).save().set_local('start', 'end').save()
        return redirect(url_for('event.home'))
    return render_event('event/form.html',
                        title='Edit Event',
                        submit='save',
                        form=form,
                        back=url_for('event.home'))
Exemplo n.º 8
0
def edit():
    """event edit"""
    form = EventForm(request.form, obj=g.event)
    if request.method == 'POST' and form.validate():
        g.event.update(**request.form).save().set_local('start', 'end').save()
        return redirect(url_for('event.home'))
    return render_event('event/form.html',
        title='Edit Event',
        submit='save',
        form=form,
        back=url_for('event.home'))
Exemplo n.º 9
0
def signup():
    """group signup"""
    message = ''
    form = GroupSignupForm(request.form)
    choose_role = g.group.setting('choose_role').is_active
    message = 'Thank you for your interest in %s! Just click "Join" to join.' % g.group.name
    whitelisted, submit = [], 'Confirm'
    for block in g.group.setting('whitelist').value.split(','):
        data = block.split('(')
        if len(data) == 2:
            whitelisted.append((data[0].strip(), data[1].strip()[:-1]))
        else:
            whitelisted.append((data[0].strip(), ''))
    emails = [s.strip() for s, _ in whitelisted]
    if current_user().email in emails:
        title = [
            title for email, title in whitelisted
            if email == current_user().email
        ][0]
        message = 'You\'ve been identified as <code>%s</code>. Hello! Click "Confirm" below, to get started.' % title
        if not GroupRole.query.filter_by(group_id=g.group.id,
                                         name=title).one_or_none():
            submit = None
            message = 'You\'ve been identified as <code>%s</code>. Hello! However, there is no such role <code>%s</code> in this group - only <code>%s</code>. Please contact your group manager.' % (
                title, title, str([r.name for r in g.group.roles()]))
    if choose_role:
        form.role_id.choices = [(r.id, r.name)
                                for r in GroupRole.query.filter_by(
                                    group_id=g.group.id, is_active=True).all()]
    else:
        del form.role_id
    if current_user() in g.group:
        return redirect(url_for('group.home', notif=5))
    if request.method == 'POST' and form.validate():
        if current_user().email in emails:
            role = {'role': title or 'Authorizer'}
        elif choose_role:
            role = {'role_id': request.form['role_id']}
        else:
            role = {'role': g.group.setting('role').value}
        membership = current_user().join(g.group, **role)
        return redirect(url_for('group.home'))
    form.group_id.default = g.group.id
    form.user_id.default = current_user().id
    form.process()
    return render_group('group/form.html',
                        form_title='Signup for %s' % g.group.name,
                        form_description='Ready to join? Click confirm below.',
                        wide_title=True,
                        submit=submit,
                        form=form,
                        message=message,
                        back=url_for('group.home'))
Exemplo n.º 10
0
def checkin_signup(signup_id):
    """checkin signup"""
    if g.group.setting('self_checkin').is_active or current_user().can(
            'authorize'):
        try:
            signup = Signup.query.get(signup_id)
            checkin = signup.user.checkin(g.event, current_user())
            return redirect(url_for('event.home'))
        except NoResultFound:
            abort(404)
    else:
        return redirect(url_for('group.events'))
Exemplo n.º 11
0
def filter_signup():
    """Filter out signups"""
    from operator import __le__, __eq__, __ge__, __lt__, __gt__
    try:
        form = FilterSignupForm(request.form)
        form.category.choices = choicify(g.event.categories)
        if request.method == 'POST' and form.validate():
            n = int(request.form['n'])
            op = {
                '<': __lt__,
                '<=': __le__,
                '=': __eq__,
                '>=': __ge__,
                '>': __gt__
            }[request.form['operator']]
            for signup in Signup.query.filter_by(
                    is_active=True,
                    event_id=g.event.id,
                    category=request.form['category']):
                if op(getattr(signup.user, request.form['value']), n):
                    signup.update(is_active=False).save()
            return redirect(url_for('event.home'))
        return render_event(
            'event/form.html',
            title='Remove Signups by Filter',
            form=form,
            message=
            'Use the following to filter out signups. Signups that MATCH this filter will be removed.',
            submit='Remove')
    except NoResultFound:
        abort(404)
Exemplo n.º 12
0
def copy(yyyymmdd):
    """copy event"""
    date = arrow.get(yyyymmdd, 'YYYYMMDD')
    candidate = g.event.get_shift_or_none(date)
    if not candidate:
        candidate = g.event.create_shift(yyyymmdd).save()
    return redirect(url_for('event.home', event_id=candidate.id))
Exemplo n.º 13
0
def filter_signup():
    """Filter out signups"""
    from operator import __le__, __eq__, __ge__, __lt__, __gt__
    try:
        form = FilterSignupForm(request.form)
        form.category.choices = choicify(g.event.categories)
        if request.method == 'POST' and form.validate():
            n = int(request.form['n'])
            op = {
                '<': __lt__,
                '<=': __le__,
                '=': __eq__,
                '>=': __ge__,
                '>': __gt__
            }[request.form['operator']]
            for signup in Signup.query.filter_by(
                is_active=True,
                event_id=g.event.id,
                category=request.form['category']):
                if op(getattr(signup.user, request.form['value']), n):
                        signup.update(is_active=False).save()
            return redirect(url_for('event.home'))
        return render_event('event/form.html',
            title='Remove Signups by Filter',
            form=form,
            message='Use the following to filter out signups. Signups that MATCH this filter will be removed.',
            submit='Remove')
    except NoResultFound:
        abort(404)
Exemplo n.º 14
0
def copy(yyyymmdd):
    """copy event"""
    date = arrow.get(yyyymmdd, 'YYYYMMDD')
    candidate = g.event.get_shift_or_none(date)
    if not candidate:
        candidate = g.event.create_shift(yyyymmdd).save()
    return redirect(url_for('event.home', event_id=candidate.id))
Exemplo n.º 15
0
def logout(home=None):
    """
    Logs out current session and redirects to home

    :param str home: URL to redirect to after logout success
    """
    flask_login.logout_user()
    return redirect(request.args.get("redirect", home or url_for("public.home")))
Exemplo n.º 16
0
def logout(home=None):
    """
    Logs out current session and redirects to home

    :param str home: URL to redirect to after logout success
    """
    flask_login.logout_user()
    return redirect(
        request.args.get('redirect', home or url_for('public.home')))
Exemplo n.º 17
0
def leave():
    """group leave"""
    Membership.query.filter_by(group_id=g.group.id,
                               user_id=current_user().id,
                               is_active=True).one().deactivate()
    # raise UserWarning(Membership.query.filter_by(
    #     group_id=g.group.id,
    #     user_id=current_user().id).one().is_active)
    return redirect(url_for('group.home'))
Exemplo n.º 18
0
def process():
    """process whitelists"""
    form = ProcessWaitlistsForm(request.form)
    if request.method == 'POST' and form.validate():
        pass
    return render_group('group/form.html',
                        title='Process Waitlists',
                        submit='Process',
                        form=form,
                        back=url_for('group.events'))
Exemplo n.º 19
0
def deactivate_signup(signup_id):
    """Deactivate signup"""
    try:
        signup = Signup.query.get(signup_id)
        if not signup.user.id == current_user().id and not current_user().can('authorize'):
            raise UserWarning('Not allowed to delete other signups.')
        signup.update(is_active=False).save()
        return redirect(url_for('event.home'))
    except NoResultFound:
        abort(404)
Exemplo n.º 20
0
def delete_events():
    """delete events en masse"""
    form = DeleteEventsEnMasse(request.form)
    if request.method == 'POST' and form.validate():
        start_id = request.form['start_id']
        end_id = request.form['end_id']
        events = Event.__table__
        db.session.execute(
            update(events).where(
                and_(events.c.id <= end_id, events.c.id >= start_id,
                     events.c.group_id == g.group.id)).values(is_active=False))
        db.session.commit()
        return redirect(url_for('group.events'))
    return render_group('group/form.html',
                        title='Delete Events En Masse',
                        message='Be careful! This en masse is not undo-able.',
                        submit='Delete',
                        form=form,
                        back=url_for('group.events'))
Exemplo n.º 21
0
def edit():
    """group edit"""
    form = GroupForm(request.form, obj=g.group)
    if request.method == 'POST' and form.validate():
        g.group.update(**request.form).save()
        return redirect(url_for('group.home'))
    return render_group('group/form.html',
                        title='Edit Group',
                        submit='Save',
                        form=form)
Exemplo n.º 22
0
def deactivate_signup(signup_id):
    """Deactivate signup"""
    try:
        signup = Signup.query.get(signup_id)
        if not signup.user.id == current_user().id and not current_user().can(
                'authorize'):
            raise UserWarning('Not allowed to delete other signups.')
        signup.update(is_active=False).save()
        return redirect(url_for('event.home'))
    except NoResultFound:
        abort(404)
Exemplo n.º 23
0
def create_event():
    """create event"""
    form = EventForm(request.form)
    if request.method == 'POST' and form.validate():
        event = Event.from_request().save().load_roles(
            default_event_roles[g.group.category]).set_local(
                'start', 'end', 'until').save()
        return redirect(
            url_for('event.home',
                    event_id=current_user().signup(
                        event, 'Owner', category='Accepted').event_id))
    form.group_id.default = g.group.id
    form.start.default = arrow.now().floor('hour').to('local')
    form.end.default = form.start.default.replace(hours=1)
    form.until.default = form.end.default
    form.process()
    return render_group('group/form.html',
                        title='Create Event',
                        submit='Create',
                        form=form,
                        back=url_for('group.events'))
Exemplo n.º 24
0
def shift(yyyymmdd):
    """Event shift page.

    :param yyyymmdd: date formatted as YYYYMMDD
    """
    date = arrow.get(yyyymmdd, 'YYYYMMDD')
    candidate = g.event.get_shift_or_none(date)
    action = {}
    if candidate:
        return redirect(url_for('event.home', event_id=candidate.id))
    if current_user().can('create_event'):
        action = dict(url=url_for('event.copy', yyyymmdd=yyyymmdd),
                      action='Activate')
    return render_event(
        'confirm.html',
        title='Pending "{name}"'.format(name=event.name),
        message='This shift for the recurring event "{name}" on {date} has not'
        ' yet been activated.'.format(name=event.name,
                                      date=date.format('MMMM D, YYYY')),
        back=url_for('group.events'),
        **action)
Exemplo n.º 25
0
def signup():
    """event signup"""
    form = EventSignupForm(request.form)
    message = ''
    choose_role = g.event.setting('choose_role').is_active
    whitelisted = []
    for block in g.group.setting('whitelist').value.split(','):
        data = block.split('(')
        if len(data) == 2:
            whitelisted.append((data[0].strip(), data[1].strip()[:-1]))
        else:
            whitelisted.append((data[0].strip(), ''))
    emails = [s.strip() for s, _ in whitelisted]
    if current_user().email in emails:
        title = [
            title for email, title in whitelisted
            if email == current_user().email
        ][0]
        message = 'You\'ve been identified as "%s". Hello! Click "Confirm" below, to get started.' % title
    roles = EventRole.query.filter_by(event_id=g.event.id,
                                      is_active=True).all()
    if choose_role:
        form.role_id.choices = [(r.id, r.name) for r in roles]
    else:
        del form.role_id
    if current_user() in g.event:
        return redirect(url_for('event.home', notif=7))
    # if request.method == 'POST' and form.validate():
    data = {'category': g.event.setting('default_category').value}
    if current_user().email in emails:
        if title not in [r.name for r in roles]:
            title = 'Authorizer'
        data['role'] = title or 'Authorizer'
    elif choose_role:
        data['role_id'] = request.form['role_id']
    else:
        data['role'] = g.event.setting('role').value
    signup = current_user().signup(g.event, **data)
    return redirect(url_for('event.home'))
Exemplo n.º 26
0
def create_group():
    """create group form"""
    form = GroupForm(request.form)
    if request.method == 'POST' and form.validate():
        group = Group.from_request().save().load_roles(
            default_group_roles[request.form['category']]).save()
        current_user().join(group, role='Owner')
        group.load_settings('whitelist')
        return redirect(url_for('group.home', group_url=group.url))
    return render_dashboard('public/form.html',
        title='Create Group',
        submit='create',
        form=form)
Exemplo n.º 27
0
def create_group():
    """create group form"""
    form = GroupForm(request.form)
    if request.method == 'POST' and form.validate():
        group = Group.from_request().save().load_roles(
            default_group_roles[request.form['category']]).save()
        current_user().join(group, role='Owner')
        group.load_settings('whitelist')
        return redirect(url_for('group.home', group_url=group.url))
    return render_dashboard('public/form.html',
                            title='Create Group',
                            submit='create',
                            form=form)
Exemplo n.º 28
0
def shift(yyyymmdd):
    """Event shift page.

    :param yyyymmdd: date formatted as YYYYMMDD
    """
    date = arrow.get(yyyymmdd, 'YYYYMMDD')
    candidate = g.event.get_shift_or_none(date)
    action = {}
    if candidate:
        return redirect(url_for('event.home', event_id=candidate.id))
    if current_user().can('create_event'):
        action = dict(
            url=url_for('event.copy', yyyymmdd=yyyymmdd),
            action='Activate')
    return render_event(
        'confirm.html',
        title='Pending "{name}"'.format(name=event.name),
        message='This shift for the recurring event "{name}" on {date} has not'
        ' yet been activated.'.format(
            name=event.name,
            date=date.format('MMMM D, YYYY')),
        back=url_for('group.events'),
        **action)
Exemplo n.º 29
0
def signup():
    """event signup"""
    form = EventSignupForm(request.form)
    message = ''
    choose_role = g.event.setting('choose_role').is_active
    whitelisted = []
    for block in g.group.setting('whitelist').value.split(','):
        data = block.split('(')
        if len(data) == 2:
            whitelisted.append((data[0].strip(), data[1].strip()[:-1]))
        else:
            whitelisted.append((data[0].strip(), ''))
    emails = [s.strip() for s, _ in whitelisted]
    if current_user().email in emails:
        title = [title for email, title in whitelisted if email == current_user().email][0]
        message = 'You\'ve been identified as "%s". Hello! Click "Confirm" below, to get started.' % title
    roles = EventRole.query.filter_by(
        event_id=g.event.id,
        is_active=True).all()
    if choose_role:
        form.role_id.choices = [(r.id, r.name) for r in roles]
    else:
        del form.role_id
    if current_user() in g.event:
        return redirect(url_for('event.home', notif=7))
    # if request.method == 'POST' and form.validate():
    data = {'category': g.event.setting('default_category').value }
    if current_user().email in emails:
        if title not in [r.name for r in roles]:
            title = 'Authorizer'
        data['role'] = title or 'Authorizer'
    elif choose_role:
        data['role_id'] = request.form['role_id']
    else:
        data['role'] = g.event.setting('role').value
    signup = current_user().signup(g.event, **data)
    return redirect(url_for('event.home'))
Exemplo n.º 30
0
def login(home=None, login=None):
    """
    Login using Google authentication

    :param str home: URL for queue homepage
    :param str login: URL for queue login page
    """
    try:
        flow = client.flow_from_clientsecrets(
            "client_secrets.json",
            scope="openid profile email https://www.googleapis.com/auth/calendar.readonly",
            redirect_uri=login or url_for("public.login", _external=True),
        )
        if "code" not in request.args:
            auth_uri = flow.step1_get_authorize_url()
            return redirect(auth_uri + "&prompt=select_account")
        credentials = flow.step2_exchange(request.args.get("code"))
        session["credentials"] = credentials.to_json()

        http = credentials.authorize(httplib2.Http())
        person = service.people().get(userId="me").execute(http=http)

        user = User.query.filter_by(email=person["emails"][0]["value"]).first()
        if not user:
            user = User(
                name=person["displayName"],
                email=person["emails"][0]["value"],
                google_id=person["id"],
                image_url=person["image"]["url"],
            ).save()
        else:
            user.update(google_id=person["id"], image_url=person["image"]["url"]).save()
        flask_login.login_user(user)
        return redirect(home or url_for("public.home"))
    except client.FlowExchangeError:
        return redirect(login or url_for("public.login"))
Exemplo n.º 31
0
def settings():
    """edit settings"""
    g.event.load_settings()
    settings = EventSetting.query.filter_by(event_id=g.event.id).all()
    if request.method == 'POST':
        _id = request.form['id']
        value = request.form.get('value', None)
        is_active = request.form.get('is_active', None)
        setting = EventSetting.query.get(int(_id))
        if value is not None:
            setting.update(value=value).save()
        if is_active is not None:
            setting.update(is_active=is_active == 'y').save()
    return render_event('event/settings.html', settings=settings,
        back=url_for('event.home'))
Exemplo n.º 32
0
def settings():
    """edit settings"""
    g.event.load_settings()
    settings = EventSetting.query.filter_by(event_id=g.event.id).all()
    if request.method == 'POST':
        _id = request.form['id']
        value = request.form.get('value', None)
        is_active = request.form.get('is_active', None)
        setting = EventSetting.query.get(int(_id))
        if value is not None:
            setting.update(value=value).save()
        if is_active is not None:
            setting.update(is_active=is_active == 'y').save()
    return render_event('event/settings.html',
                        settings=settings,
                        back=url_for('event.home'))
Exemplo n.º 33
0
def authorize():
    """event authorization (for checkin)"""
    form = EventGenerateCodeForm(request.form)
    setting = current_user().setting('authorize_code')
    n = 25
    if (request.method == 'POST' and form.validate()) or setting.value == default_user_settings['authorize_code']['value'] or UserSetting.query.filter_by(value=setting.value).count() > 1:
        setting.value = Base.hash(request.form.get('value', str(arrow.now()))
            )[n:n+int(request.form.get('length', 5))]
        setting.save()
    message = 'Current code: %s' % setting.value
    return render_event('event/form.html',
        title='Authorization Code for %s' % event.name,
        message=message,
        submit='Regenerate',
        form=form,
        back=url_for('event.home'))
Exemplo n.º 34
0
def settings():
    """edit settings"""
    g.group.load_settings()
    g.group.access_token
    if request.method == 'POST':
        id = request.form['id']
        value = request.form.get('value', None)
        is_active = request.form.get('is_active', None)
        setting = GroupSetting.query.get(id)
        if value:
            setting.value = value
        if is_active is not None:
            setting.is_active = is_active
        setting.save()
    settings = GroupSetting.query.filter_by(group_id=g.group.id).all()
    return render_group('group/settings.html',
                        settings=settings,
                        back=url_for('group.home'))
Exemplo n.º 35
0
def categorize(signup_id='all', category=None):
    """Categorize signup"""
    try:
        form = CategorizeForm(request.form)
        form.category.choices = choicify(g.event.categories)
        if request.method == 'POST' and form.validate() or category:
            if signup_id == 'all':
                for signup in Signup.query.filter_by(event_id=g.event.id, is_active=True).all():
                    signup.update(category=request.form.get('category', category)).save()
            else:
                Signup.query.get(signup_id).update(category=request.form.get('category', category)).save()
            return redirect(url_for('event.home'))
        return render_event('event/form.html',
            title='Categorize',
            form=form,
            submit='Categorize %s' % (signup.user.name if signup_id != 'all' else 'all'))
    except NoResultFound:
        abort(404)
Exemplo n.º 36
0
def authorize():
    """event authorization (for checkin)"""
    form = EventGenerateCodeForm(request.form)
    setting = current_user().setting('authorize_code')
    n = 25
    if (request.method == 'POST'
            and form.validate()) or setting.value == default_user_settings[
                'authorize_code']['value'] or UserSetting.query.filter_by(
                    value=setting.value).count() > 1:
        setting.value = Base.hash(request.form.get('value', str(
            arrow.now())))[n:n + int(request.form.get('length', 5))]
        setting.save()
    message = 'Current code: %s' % setting.value
    return render_event('event/form.html',
                        title='Authorization Code for %s' % event.name,
                        message=message,
                        submit='Regenerate',
                        form=form,
                        back=url_for('event.home'))
Exemplo n.º 37
0
def recategorize_signup(signup_id):
    """Deactivate signup"""
    try:
        signup = Signup.query.get(signup_id)
        form = CategorizeForm(request.form)
        add_count = lambda c: c + ' (%d signup)' % Signup.query.filter_by(
            event_id=g.event.id, category=c, is_active=True).count()
        form.category.choices = choicify([add_count(c) for c in
            g.event.categories])
        if request.method == 'POST' and form.validate():
            category = request.form['category'].split('(')[0]
            signup.update(category=category).save()
            return redirect(url_for('event.home'))
        return render_event('event/form.html',
            title='Recategorize Signup',
            form=form,
            message='Assign the signup to a new category',
            submit='Recategorize')
    except NoResultFound:
        abort(404)
Exemplo n.º 38
0
def recategorize_signup(signup_id):
    """Deactivate signup"""
    try:
        signup = Signup.query.get(signup_id)
        form = CategorizeForm(request.form)
        add_count = lambda c: c + ' (%d signup)' % Signup.query.filter_by(
            event_id=g.event.id, category=c, is_active=True).count()
        form.category.choices = choicify(
            [add_count(c) for c in g.event.categories])
        if request.method == 'POST' and form.validate():
            category = request.form['category'].split('(')[0]
            signup.update(category=category).save()
            return redirect(url_for('event.home'))
        return render_event('event/form.html',
                            title='Recategorize Signup',
                            form=form,
                            message='Assign the signup to a new category',
                            submit='Recategorize')
    except NoResultFound:
        abort(404)
Exemplo n.º 39
0
def checkin():
    """event checkin"""
    message = ''
    form = EventCheckinForm(request.form)
    if request.method == 'POST' and form.validate():
        setting = UserSetting.query.filter_by(
            name='authorize_code',
            value=request.form['code'].strip(),
            is_active=True).one_or_none()
        if setting:
            checkin = current_user().checkin(g.event, setting.user)
            return redirect(url_for('event.home', notif=8))
        message = 'Authorization failed.'
    form.event_id.default = g.event.id
    form.user_id.default = current_user().id
    form.process()
    return render_event('event/form.html',
                        title='Checkin for %s' % event.name,
                        message=message,
                        submit='Checkin',
                        form=form)
Exemplo n.º 40
0
def checkin():
    """event checkin"""
    message = ''
    form = EventCheckinForm(request.form)
    if request.method == 'POST' and form.validate():
        setting = UserSetting.query.filter_by(
            name='authorize_code',
            value=request.form['code'].strip(),
            is_active=True).one_or_none()
        if setting:
            checkin = current_user().checkin(g.event, setting.user)
            return redirect(url_for('event.home', notif=8))
        message = 'Authorization failed.'
    form.event_id.default = g.event.id
    form.user_id.default = current_user().id
    form.process()
    return render_event('event/form.html',
        title='Checkin for %s' % event.name,
        message=message,
        submit='Checkin',
        form=form)
Exemplo n.º 41
0
def categorize(signup_id='all', category=None):
    """Categorize signup"""
    try:
        form = CategorizeForm(request.form)
        form.category.choices = choicify(g.event.categories)
        if request.method == 'POST' and form.validate() or category:
            if signup_id == 'all':
                for signup in Signup.query.filter_by(event_id=g.event.id,
                                                     is_active=True).all():
                    signup.update(category=request.form.get(
                        'category', category)).save()
            else:
                Signup.query.get(signup_id).update(
                    category=request.form.get('category', category)).save()
            return redirect(url_for('event.home'))
        return render_event(
            'event/form.html',
            title='Categorize',
            form=form,
            submit='Categorize %s' %
            (signup.user.name if signup_id != 'all' else 'all'))
    except NoResultFound:
        abort(404)
Exemplo n.º 42
0
def restore():
    """restore deleted event"""
    g.event.activate()
    return redirect(url_for('group.events'))
Exemplo n.º 43
0
def delete():
    """delete event"""
    g.event.deactivate()
    return redirect(url_for('group.events'))
Exemplo n.º 44
0
def unauthorized_handler():
    return redirect(url_for("public.login"))
Exemplo n.º 45
0
def logout():
    """Logout using globally defined logout procedure"""
    from piipod.public.views import logout
    return logout(home=url_for('group.home', _external=True))
Exemplo n.º 46
0
def login():
    """Login using globally defined login procedure"""
    from piipod.public.views import login
    return login(home=url_for('group.home', _external=True),
                 login=url_for('group.login', _external=True))
Exemplo n.º 47
0
def restore():
    """restore deleted event"""
    g.event.activate()
    return redirect(url_for('group.events'))
Exemplo n.º 48
0
def sync(service):
    """sync events with service"""
    try:
        form, message = SyncForm(
            request.form), 'See fields below for instructions.'
        setting = g.group.setting(service)
        calendars = setting.value.split(',') if setting.value else []
        form.calendar.choices = choicify(calendars)
        form.recurrence_start.default = arrow.now().to('local')
        form.recurrence_end.default = arrow.now().to('local').replace(weeks=1)
        if not calendars:
            message = 'You have no %s to select from! Access the <a href="%s#%s">settings</a> window to add %s IDs.' % (
                setting.label, url_for('group.settings'), setting.name,
                setting.label)
            form = None
        if (request.method == 'POST' and form.validate()
                and calendars) or 'confirm' in request.form:

            calendarId = request.form['calendar']

            pattern = request.form.get('pattern', '*')
            if pattern != '*':
                pattern = re.compile(request.form['pattern'])

            # TODO: combine with regular login
            if 'credentials' not in session:
                session['redirect'] = current_url()
                return redirect(url_for('public.login'))
            credentials = client.OAuth2Credentials.from_json(
                session['credentials'])
            if credentials.access_token_expired:
                session['redirect'] = current_url()
                return redirect(url_for('public.login'))
            http_auth = credentials.authorize(httplib2.Http())
            service = discovery.build('calendar', 'v3', http=http_auth)

            all_events = []
            page_token = None
            while True:
                events = service.events().list(calendarId=calendarId.strip(),
                                               pageToken=page_token).execute()
                for event in events['items']:
                    all_events.append(event)
                page_token = events.get('nextPageToken')
                if not page_token:
                    break

            all_events = [
                e for e in all_events
                if (pattern == '*' or pattern.match(e.get('summary', 'None')))
                and 'start' in e
            ]

            # hacky fix for daylight savings below
            events = [
                dict(name=e.get('summary', '')[:50],
                     description=e.get('summary', ''),
                     start=arrow.get(e['start'].get(
                         'dateTime',
                         e['start'].get('date',
                                        None))).to('local').replace(hours=-1),
                     end=arrow.get(e['end'].get('dateTime', e['start'].get(
                         'date', None))).to('local').replace(hours=-1),
                     google_id=e['id'],
                     group_id=g.group.id,
                     recurrence=e.get('recurrence', [])) for e in all_events
            ]

            if 'confirm' not in request.form:
                form = ConfirmSyncForm(request.form)
                message = 'Are you sure? %d events will be synced:<br><br> %s' % (
                    len(all_events), '<br>'.join(
                        '{name} <span class="subtext">({start} to {end})</span>'
                        .format(name=e['name'],
                                start=e['start'].format('MMM D h:mm a'),
                                end=e['end'].format('MMM D h:mm a'))
                        for e in events))
                return render_group('group/form.html',
                                    wide_title=True,
                                    form_title='Confirm Sync',
                                    form_message=message,
                                    submit='Sync',
                                    form=form,
                                    back=url_for('group.events'))

            for event_data in events:

                query = Event.query.filter_by(
                    google_id=event_data['google_id'])
                raw_recurrence = event_data.pop('recurrence')
                if raw_recurrence:
                    recurrence = dict(
                        item.split('=')
                        for item in raw_recurrence[0].split(':')[1].split(';'))
                    event_data.update({
                        'frequency':
                        recurrence.get('FREQ', ''),
                        'until':
                        arrow.get(recurrence.get('UNTIL', ''), 'YYYYMMDD'),
                        # 'byday': recurrence.get('BYDAY', '') # TODO: properly implement byday
                    })

                if not query.count():
                    Event(**event_data).save()
                else:
                    query.first().update(**event_data).save()

            return redirect(url_for('group.events'))
        if form:
            form.process()
        return render_group('group/form.html',
                            wide_title=True,
                            form_title='Sync with %s' % setting.label,
                            form_description=message,
                            submit='Sync',
                            form=form,
                            back=url_for('group.events'))
    except AssertionError:
        abort(404)
    except googleapiclient.errors.HttpError:
        form.errors.setdefault(
            'calendar',
            []).append('Google Calendar failed to load. Wrong link perhaps?')
        return render_group('group/form.html',
                            title='Sync with %s' % setting.label,
                            message=message,
                            submit='Sync',
                            form=form,
                            back=url_for('group.events'))
Exemplo n.º 49
0
def leave():
    """leave event"""
    current_user().leave(g.event)
    return redirect(url_for('group.events'))
Exemplo n.º 50
0
def unauthorized_handler():
    return redirect(url_for('public.login'))