calendar-social/calsocial/group.py

101 lines
3.2 KiB
Python

# Calendar.social
# Copyright (C) 2018 Gergely Polonkai
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.
"""Group related endpoints for Calendar.social
"""
from flask import Blueprint, abort, redirect, render_template, url_for
from flask_security import current_user, login_required
from calsocial.utils import RoutedMixin
class GroupBlueprint(Blueprint, RoutedMixin):
def __init__(self):
Blueprint.__init__(self, 'group', __name__)
self.app = None
RoutedMixin.register_routes(self)
def init_app(self, app, url_prefix=None):
"""Initialise the blueprint, registering it with ``app``.
"""
self.app = app
app.register_blueprint(self, url_prefix=url_prefix)
@staticmethod
@RoutedMixin.route('/')
def list_groups():
"""View to list all public groups known by this instance
"""
from calsocial.models import db, Group, GroupMembership, GroupVisibility
groups = Group.query
if current_user.is_authenticated:
groups = groups.outerjoin(GroupMembership) \
.filter(db.or_(Group.visibility == GroupVisibility.public,
GroupMembership.profile == current_user.profile))
else:
groups = groups.filter(Group.visibility == GroupVisibility.public)
return render_template('group/list.html', groups=groups)
@staticmethod
@login_required
@RoutedMixin.route('/create', methods=['GET', 'POST'])
def create():
from datetime import datetime
from .forms import GroupForm
from .models import db, Group, GroupMemberLevel, GroupMembership
form = GroupForm()
if form.validate_on_submit():
group = Group(created_by=current_user.profile)
form.populate_obj(group)
db.session.add(group)
member = GroupMembership(group=group,
profile=current_user.profile,
level=GroupMemberLevel.admin,
accepted_at=datetime.utcnow(),
accepted_by=current_user.profile)
db.session.add(member)
db.session.commit()
return redirect(url_for('group.list'))
return render_template('group/create.html', form=form)
@staticmethod
@RoutedMixin.route('/<fqn>')
def display(fqn):
from .models import Group
group = Group.get_by_fqn(fqn)
if not group.visible_to(current_user.profile):
abort(404)
return render_template('group/display.html', group=group)