示例#1
0
def register_route():
    if request.method == 'GET':
        form = RegistrationForm()
        return render_template("register.html",
                               title="Register Page",
                               form=form)
    elif request.method == 'POST':
        form = RegistrationForm()
        if form.validate_on_submit():
            username = form.username.data
            password = crypto.hash_password(form.password.data)
            email = form.email.data
            register_time = timestamp(),
            last_login = register_time
            user = User(username=username,
                        password=password,
                        email=email,
                        register_time=register_time,
                        last_login=last_login,
                        last_login_ip=request.remote_addr,
                        city=form.city.data)
            db.session.add(user)
            db.session.commit()
            login_user(user, force=True)
            flash(
                gettext(
                    'Account created! Please fill additional information.'),
                'success')
            return redirect(url_for('profile_route', action='edit'))
        else:
            return render_template("register.html",
                                   title="Register Page",
                                   form=form)
    else:
        abort(403)
 def get_recipient(self):
     from libs.models.User import User
     from libs.models.Group import Group
     from libs.models.Event import Event
     if self.type == InvitationType.FRIEND or \
             self.type == InvitationType.FROM_EVENT or \
             self.type == InvitationType.FROM_GROUP:
         return User.get_or_404(self.recipient_id)
     elif self.type == InvitationType.TO_GROUP:
         return Group.get_or_404(self.recipient_id)
     elif self.type == InvitationType.TO_EVENT:
         return Event.get_or_404(self.recipient_id)
 def get_referrer(self):
     from libs.models.User import User
     from libs.models.Group import Group
     from libs.models.Event import Event
     if self.type in EVENTS_FROM_USER:
         return User.get_or_404(self.referrer_id)
     elif self.type == InvitationType.FROM_GROUP:
         return Group.get_or_404(self.referrer_id)
     elif self.type == InvitationType.FROM_EVENT:
         return Event.get_or_404(self.referrer_id)
     else:
         return None
示例#4
0
def handle_msg(msg):
    text = msg.get('text')
    # current_user - от кого пришло сообщение
    try:
        user_id = int(msg.get('user_id'))
        chat_id = int(msg.get('chat_id'))
    except TypeError as e:
        logging.error(e)
        return
    # TODO добавить контент
    message = Message(id=get_rand(), chat_id=chat_id, user_id=user_id,
                      time=timestamp(), text=text)
    members = Chat.get_or_404(chat_id).get_members()
    for i in members:
        if i.id != user_id:
            ChatNotification.add(chat_id=chat_id, user_id=i.id)
    db.session.add(message)
    db.session.commit()
    chat = Chat.get_or_404(chat_id)
    if chat is not None and not chat.deleted:
        members = chat.get_members()
        chat.update_last_msg(message)
        for user in members:
            if user.id != user_id:
                session = sessions.get_or_404(user.id)
                if session:
                    emit(
                        'message',
                        json.dumps({
                            'text': text,
                            'message_id': message.id,
                            'username': User.get_or_404(user_id).username,
                            'chat_id': chat_id, 'user_id': user_id
                        }),
                        room=session
                    )
    else:
        abort(404)
示例#5
0
def chats_route():
    action = get_arg_or_400('action')

    if action == 'show':
        chat_id = get_arg_or_none('chat_id', to_int=True)
        user_id = get_arg_or_none('user_id', to_int=True)    # С кем чат
        if user_id is None:
            if chat_id is None:
                return redirect(url_for('chat', action='all'))
            chat = Chat.get_or_404(chat_id)
            if chat.deleted is not None:
                redirect(url_for('chats_route', action='all'))
            members = chat.get_members()
            if len(members) > 2:
                return redirect(url_for('group_chats_route', action='show', chat_id=chat_id, group_id=chat.group_id))
            elif len(members) < 2:
                user_id = 'Deleted'
            else:
                user_id = members[0].id if members[0].id != current_user.id else members[1].id
            return redirect(url_for("chats_route", action='show', chat_id=chat_id, user_id=user_id))
        if chat_id is None:
            chat = ChatMember.get_private_chat(current_user.id, user_id)
            if chat is None:
                chat = Chat(admin_id=current_user.id, time=timestamp())
                db.session.add(chat)
                db.session.commit()
                chat_id = chat.id
                chat.add_member(current_user.id, is_group=False)
                chat.add_member(user_id, is_group=False)
                db.session.commit()
                history = []
            elif chat.deleted is not None:
                return redirect(url_for('chats_route', action='all'))
            else:
                return redirect(url_for("chats_route", action='show', chat_id=chat.id, user_id=user_id))
        else:
            history = Chat.get_or_404(int(chat_id)).get_history()
            ChatNotification.remove(user_id=current_user.id, chat_id=chat_id)

        members = Chat.get_or_404(chat_id).get_members()
        if user_id not in list(map(lambda x: x.id, members)):
            abort(404)
        user_id = members[0].id if members[0].id != current_user.id else members[1].id
        return render_template(
            "chat.html",
            user_id=user_id,
            current_user=current_user,
            chat_name=User.get_or_404(user_id).username,
            chat=Chat.get_or_404(chat_id),
            messages=history
        )

    elif action == 'all':
        chats = ChatMember.get_user_chats(current_user.id)
        for i in chats:
            if i.name is None:
                members = i.get_members()
                for u in members:
                    if u is not None and u.id != current_user.id:
                        i.name = u.username
        return render_template(
            "my_chats.html",
            notifications=current_user.get_notifications(),
            current_user=current_user,
            chats=chats
        )

    elif action == 'delete':
        chat_id = get_arg_or_400('chat_id', to_int=True)
        if chat_id is None:
            return redirect(url_for('chats_route', action='all'))
        chat_id = int(chat_id)
        chat_member = ChatMember.query.filter_by(chat_id=chat_id, user_id=current_user.id).first()
        if chat_member is None:
            return redirect(request.referrer)
        chat_member.deleted = timestamp()
        db.session.commit()
        if not current_user.is_notified():
            socketIO.emit("clear_message", {}, room=current_user.id)
        if chat_member.is_group:
            return redirect(request.referrer)
        return redirect(url_for('chats_route', action='all'))
    else:
        abort(400)
示例#6
0
def profile_route():
    if request.method == 'GET':
        action = get_arg_or_400('action')
        if action == 'my':
            groups = current_user.get_groups()
            friends = current_user.friends_get()
            videos: dict = UserVideos.get_all_for_user_id(current_user.id)
            return render_template("profile.html",
                                   current_user=current_user,
                                   user=current_user,
                                   groups=groups,
                                   friends=friends,
                                   my=True,
                                   videos=videos)
        elif action == 'show':
            id = get_arg_or_400('id', to_int=True)
            if current_user.id == id:
                return redirect(url_for('profile_route', action='my'))
            user = User.get_or_404(id)
            groups = user.get_groups()
            friends = user.friends_get()
            chat = ChatMember.get_private_chat(current_user.id, id)
            is_friend = True if current_user in friends else None
            videos: dict = UserVideos.get_all_for_user_id(user.id)
            return render_template("profile.html",
                                   chat_id=chat.id if chat else None,
                                   current_user=current_user,
                                   groups=groups,
                                   friends=friends,
                                   is_friend=is_friend,
                                   user=user,
                                   videos=videos)
        elif action == 'edit':
            form = EditProfileForm(name=current_user.name,
                                   last_name=current_user.last_name,
                                   age=current_user.age,
                                   gender=current_user.gender,
                                   sport=current_user.sport,
                                   times_values=PlayTime.get_all_for_user_id(
                                       current_user.id),
                                   city=current_user.city)
            return render_template("edit_profile.html",
                                   title="Edit profile",
                                   form=form,
                                   current_user=current_user)
        elif action == 'add_play_time':
            add_play_time_form = AddPlayTimeForm()
            all_play_times = PlayTime.get_all_for_user_id(current_user.id)
            current_play_time: Optional[PlayTime] = PlayTime.get(
                get_arg_or_none("id"))
            initial_location = nominatim.geocode(current_user.city)
            init_lat = initial_location.latitude if initial_location else None
            init_lng = initial_location.longitude if initial_location else None
            markers = []
            initial_zoom = 13
            if current_play_time is not None:
                add_play_time_form.day_of_week.data = current_play_time.day_of_week
                add_play_time_form.start_time.data = current_play_time.start_time
                add_play_time_form.end_time.data = current_play_time.end_time
                add_play_time_form.address.data = current_play_time.address.short_address
                location = Location.get(current_play_time.location_id)
                if location is not None:
                    markers.append((location.latitude, location.longitude))
                    init_lat = location.latitude
                    init_lng = location.longitude
                    initial_zoom = 14.5
            loc_map = Map(zoom=initial_zoom,
                          identifier="loc_map",
                          lat=init_lat,
                          lng=init_lng,
                          style="height:600px;width:600px;margin:8;",
                          language=current_user.language,
                          markers=markers)
            return render_template("add_play_time.html",
                                   all_play_times=all_play_times,
                                   form=add_play_time_form,
                                   map=loc_map)
        elif action == 'show_play_times':
            initial_zoom = 13
            initial_location = nominatim.geocode(current_user.city)
            init_lat = initial_location.latitude if initial_location else None
            init_lng = initial_location.longitude if initial_location else None
            markers = []
            current_play_time: Optional[PlayTime] = PlayTime.get(
                get_arg_or_none("id"))
            if current_play_time is not None:
                location = Location.get(current_play_time.location_id)
                if location is not None:
                    markers.append((location.latitude, location.longitude))
                    init_lat = location.latitude
                    init_lng = location.longitude
                    initial_zoom = 14.5
            loc_map = Map(zoom=initial_zoom,
                          identifier="loc_map",
                          lat=init_lat,
                          lng=init_lng,
                          style="height:600px;width:730px;margin:8;",
                          language=current_user.language,
                          markers=markers)
            user_id = get_arg_or_400('user_id', to_int=True)
            all_play_times = PlayTime.get_all_for_user_id(user_id)
            return render_template("show_play_times.html",
                                   map=loc_map,
                                   all_play_times=all_play_times,
                                   user_id=user_id,
                                   my=user_id == current_user.id)
        elif action == 'edit_videos':
            group = namedtuple('Group', ['sport', 'video'])
            videos = UserVideos.get_all_for_user_id(current_user.id)
            arr = [
                group(sport, (make_link(vid) if
                              (vid := videos.get(sport)) is not None else ""))
                for sport in current_user.sport
            ]
示例#7
0
def event_route():
    if request.method == 'GET':

        action = get_arg_or_400('action')
        if action == 'my':
            events = filter_not_none(current_user.get_events())
            return render_template(
                "my_events.html",
                events=events if len(events) > 0 else None
            )

        elif action == 'new':
            new_event_form = EditEventForm(groups=filter_not_none(current_user.get_groups()))
            return render_template("new_event.html", form=new_event_form)
        elif action == 'search':
            events = Event.query.all()
            user_vector = UserVector(
                age=current_user.age,
                gender=current_user.gender,
                sport=current_user.sport,
                city=current_user.city,
                last_login=current_user.last_login,
                include_play_times=True,
                play_times=PlayTime.get_all_for_user_id(current_user.id),
                user=current_user
            )
            sorted_events = list(
                map(
                    lambda x: x[0].event,
                    sorted(
                        map(
                            lambda x: (
                                x,
                                user_vector.calculate_diff_with_event(x)
                            ),
                            map(
                                lambda x: EventVector(
                                    sport=[x.sport],
                                    city=x.creator.city,
                                    group=x.group,
                                    closed=x.closed,
                                    last_login=x.creator.last_login,
                                    play_times=EventPlayTimes.get_all_for_event(x.id),
                                    event=x
                                ),
                                events
                            )
                        ),
                        key=lambda x: x[1],
                        reverse=True
                    )
                )
            )
            form = SearchEventForm()
            return render_template(
                "search_event.html",
                events=sorted_events,
                form=form
            )

        event_id = get_arg_or_400('event_id', to_int=True)
        event: Event = Event.get_or_404(event_id)
        group = event.group
        group: Group = group if group else None
        is_event_admin = event.creator_id == current_user.id or group is not None and group.admin_id == current_user.id
        all_play_times = EventPlayTimes.get_all_for_event(event_id)

        if action == 'delete':
            event.delete()
            return redirect(url_for("event_route", action='my'))

        elif action == 'accept_invitation' or action == 'reject_invitation':
            if current_user.id != event.creator_id:
                abort(403)
            invitation = Invitation.get_or_404(get_arg_or_400('id'))
            if action == 'accept_invitation':
                invitation.accept()
            else:
                invitation.reject()
            return redirect(url_for("event_route", action='invitations', event_id=event_id))

        elif action == 'show_play_times':
            return render_template(
                "show_event_play_times.html",
                map=get_loc_map(event, EventPlayTimes.get_or_none(get_arg_or_none("play_time_id"))),
                all_play_times=all_play_times,
                is_event_admin=is_event_admin,
                event_id=event_id
            )

        elif action == 'add_play_time':
            add_event_play_time_form = AddEventPlayTimeForm()
            current_play_time: EventPlayTimes = EventPlayTimes.get_or_none(get_arg_or_none("play_time_id"))
            if current_play_time:
                add_event_play_time_form.day_of_week.data = current_play_time.day_of_week
                add_event_play_time_form.start_time.data = current_play_time.start_time
                add_event_play_time_form.end_time.data = current_play_time.end_time
                add_event_play_time_form.address.data = Address.get(current_play_time.address_id).get_short_address()
            template = render_template(
                "add_event_play_time.html",
                map=get_loc_map(event, current_play_time, "height:600px;width:650px;margin:8;"),
                form=add_event_play_time_form,
                all_play_times=all_play_times,
                event_id=event_id
            )
            return template

        elif action == 'edit':
            if not is_event_admin:
                abort(403)
            play_time: Optional[EventPlayTimes] = pt if (pt := all_play_times[0] if all_play_times else None) else None
            edit_event_form = EditEventForm(
                groups=filter_not_none(current_user.get_groups()),
                closed=event.closed,
                name=event.name,
                description=event.description,
                sport=event.sport,
                recurring=event.recurring,
                day_of_week=play_time.day_of_week if play_time else None,
                start_time=play_time.start_time if play_time else None,
                end_time=play_time.end_time if play_time else None,
                address=play_time.address.short_address if play_time and play_time.address else None
            )
            initial_location = Location.get(play_time.location_id) if play_time else None
            loc_map = Map(
                zoom=14.5 if initial_location else 2,
                identifier="loc_map",
                lat=initial_location.latitude if initial_location else 0,
                lng=initial_location.longitude if initial_location else 0,
                style="height:600px;width:600px;margin:8;",
                language=current_user.language,
                markers=[(initial_location.latitude, initial_location.longitude)] if initial_location else []
            )
            return render_template("edit_event.html", form=edit_event_form, event=event, map=loc_map)

        elif action == 'invitations':
            if not is_event_admin:
                abort(403)
            event_invitations: List[Invitation] = Invitation.get_all_for_event(event_id)
            return render_template("event_invitations.html", invitations=event_invitations, event_id=event_id)

        elif action == 'show':
            members = event.get_members()
            is_member = True if current_user in members else None
            members = members if len(members) > 0 else None
            play_time_id = get_arg_or_none('play_time_id')
            selected_play_time = None
            if play_time_id is not None:
                selected_play_time = EventPlayTimes.query.filter_by(event_id=event_id, id=play_time_id).first()
            if selected_play_time is None:
                play_times = EventPlayTimes.get_all_for_event(event_id)
                # closest_play_time: EventPlayTimes = play_times[0] if play_times and len(play_times) else None # TODO
                current_day_of_week = get_current_day_of_week()
                current_time = get_current_time()
                valid_play_times = list(
                    filter(
                        lambda x:
                        x.day_of_week is not None and
                        x.start_time is not None and
                        (
                            (x.day_of_week == current_day_of_week and time_to_seconds(x.start_time) >= current_time) or
                            x.day_of_week != current_day_of_week
                        ),
                        play_times
                    )
                )
                sorted_play_times = list(
                    sorted(
                        valid_play_times,
                        key=lambda x: -10 * abs(current_day_of_week - x.day_of_week) - abs(current_time - time_to_seconds(x.start_time)),
                        reverse=True
                    )
                ) \
                    if valid_play_times \
                    else None
                closest_play_time = sorted_play_times[0] if sorted_play_times else None
                initial_location = LocationToAddress.get_location_for_address_id(closest_play_time.address_id) \
                    if closest_play_time \
                    else None
                loc_map = Map(
                    zoom=14.5 if initial_location else 2,
                    identifier="loc_map",
                    lat=initial_location.latitude if initial_location else 0,
                    lng=initial_location.longitude if initial_location else 0,
                    style="height:600px;width:600px;margin:8;",
                    language=current_user.language,
                    markers=[(initial_location.latitude, initial_location.longitude)] if initial_location else []
                ) if initial_location else None
                return render_template(
                    "event.html",
                    event=event,
                    group=group,
                    members=members,
                    is_member=is_member,
                    event_id=event_id,
                    is_event_admin=is_event_admin,
                    play_times=all_play_times,
                    closest_play_time=closest_play_time,
                    map=loc_map
                )
            else:
                initial_address: Address = Address.get(selected_play_time.address_id) if selected_play_time else None
                initial_location = LocationToAddress.get_location_for_address_id(
                    selected_play_time.address_id) if selected_play_time else None
                loc_map = Map(
                    zoom=14.5 if initial_location else 2,
                    identifier="loc_map",
                    lat=initial_location.latitude if initial_location else 0,
                    lng=initial_location.longitude if initial_location else 0,
                    style="height:600px;width:600px;margin:8;",
                    language=current_user.language,
                    markers=[(initial_location.latitude, initial_location.longitude)] if initial_location else []
                )
                return render_template(
                    "event.html",
                    event=event,
                    group=group,
                    members=members,
                    is_member=is_member,
                    event_id=event_id,
                    is_event_admin=is_event_admin,
                    play_times=all_play_times,
                    map_address=initial_address.get_short_address() if initial_address else None,
                    map=loc_map
                )

        elif action == 'join':
            if event.closed:
                Invitation.add(
                    InvitationType.TO_EVENT,
                    recipient_id=event.id,
                    referrer_id=current_user.id,
                    expiration_time=event.time
                )
                flash(gettext("Invitation sent!"), "success")
            else:
                event.add_member(current_user)
            return redirect(url_for('event_route', action='show', event_id=event_id))

        elif action == 'leave':
            event.remove_member(current_user)
            return redirect(url_for('event_route', action='show', event_id=event_id))

        elif action == 'find_people':
            # FIXME сделать нормальный фильтр
            event_users = set(event.get_members())
            invited = list(
                filter(
                    lambda x: x,
                    map(
                        lambda x: User.get_or_none(x.recipient_id),
                        Invitation.get_all_from_event(event_id)
                    )
                )
            )
            all_users = set(User.query.order_by(User.register_time).all())
            users: list = list(
                filter(
                    lambda user_tmp: event.sport in (user_tmp.sport if user_tmp.sport else []),
                    list(all_users - event_users - set(invited))
                )
            )
            return render_template(
                "find_people.html",
                form=SearchPlayerForm(),
                event_id=event.id,
                invited_people=invited,
                people=users if len(users) > 0 else None
            )
        elif action == 'send_invite':
            Invitation.add(
                type=InvitationType.FROM_EVENT,
                recipient_id=get_arg_or_400('user_id'),
                referrer_id=event_id
            )
            return redirect(url_for('event_route', action='find_people', event_id=event_id))
        elif action == 'revoke_invite':
            invitation = Invitation.query.filter(
                (Invitation.type==InvitationType.FROM_EVENT) &
                (Invitation.recipient_id==get_arg_or_400('user_id')) &
                (Invitation.referrer_id==event_id)
            ).first()
            if invitation:
                db.session.delete(invitation)
                db.session.commit()
            return redirect(url_for('event_route', action='find_people', event_id=event_id))
        else:
            abort(400)