Пример #1
0
def create_meeting(meetingData: MeetingType):
    """
    Create a new meeting.
    """

    try:

        meeting = Meeting()
        meeting.validate(meetingData)

        meeting = Meeting.create(**dump_schema(meetingData))

        headers = {"Content-Location": f"/v1/meetings/{meeting.id}"}

        msg = "Meeting created successfully."

        log.info(f"{msg} with id: {meeting.id}")
        return HTTP_201, {"message": f"{msg}"}, headers

    except ValidationError as error:

        log.error(f"ValidationError: {error}")
        raise HTTPError(HTTP_400, {"errors": str(error)})

    except ConflictError as error:

        log.error(f"ConflictError: {error}")
        raise HTTPError(HTTP_409, {"errors": str(error)})
Пример #2
0
def add_meeting():
    """
    This functin accepted meeting details from post request
    and saves them in the db.
    """
    output = dict()
    status = 422

    data = json.loads(request.data.decode('utf-8'))
    if not data:
        return jsonify({"error": "Missing data to save"}), status
    try:
        user_id = data['user_id']
        name = data['name']
        event_type = data['event_type']
        description = data['description']
        duration = data['duration']

        newMeeting = Meeting(user_id, name, event_type, description, duration)
        result = Meeting.save(newMeeting)
        if result:
            output["success"] = f"meeting {data} saved"
            status = 200
        else:
            output["error"] = "Could not save"
        return jsonify(output), status
    except Exception as e:
        output['error'] = f'{e}'
        status = 500
        return jsonify(output), status
Пример #3
0
def edit_meeting(meeting_id):
    user = User.get_by_email(session['email'])
    if request.method == 'POST' and user is not None:
        # get meeting from DB
        meeting = Meeting.from_mongo(meeting_id)

        # get Updated Data from user
        day = request.form['day']
        time = request.form['time']
        p1 = request.form['p1']
        p2 = request.form['p2']
        p3 = request.form['p3']
        p4 = request.form['p4']
        p5 = request.form['p5']
        p6 = request.form['p6']
        p7 = request.form['p7']
        p8 = request.form['p8']
        p9 = request.form['p9']
        p10 = request.form['p10']
        # make json object (or python dict...same thing)
        members = {
            'p1': p1,
            'p2': p2,
            'p3': p3,
            'p4': p4,
            'p5': p5,
            'p6': p6,
            'p7': p7,
            'p8': p8,
            'p9': p9,
            'p10': p10
        }

        # double check the meeeting day-time combo is not taken already
        # proceed to check if anything has changed from original...
        # if so swap using update_meeting()
        if meeting.isAvailable(day, time):
            if day != meeting.day:
                meeting.update_meeting(meeting_id, 'day', day)
            if time != meeting.time:
                meeting.update_meeting(meeting_id, 'time', time)

        # Next Compare dictionaries of user made member-list vs. original member-list
        # returns the different items between the two dictionaries in the member dicts
        items_to_update = dict_compare(meeting.members, members)

        if items_to_update is not None:
            # get keys of the elements in the update list
            k = items_to_update.keys()
            for key in k:
                # items[key] returns a tuple: ('OLD VALUE', 'NEW VALUE') so we need the second element
                v = items_to_update[key][1]
                meeting.update_members(meeting_id, key, v)
        # GET MEETINGS
        meetings = Meeting.get_by_email(session['email'])
        return render_template('meetings-by-creator.html', email=session['email'], name=user.name, meetings=meetings)
    return render_template('create_meeting_error.html', error='Could not update Meeting')
Пример #4
0
def get_meetings():
    if session['email'] is not None:
        user = User.get_by_email(session['email'])

        if Meeting.get_by_email(session['email']) is not None:
            meetings = Meeting.get_by_email(session['email'])
        else:
            meetings = []
        return render_template('meetings-by-creator.html', email=session['email'], name=user.name, meetings=meetings)
    return make_response(back_to_profile())
Пример #5
0
def create_meeting():
    if request.method == 'POST':
        email = session['email']

        day = request.form['day']
        time = request.form['time']
        p1 = request.form['p1']
        p2 = request.form['p2']
        p3 = request.form['p3']
        p4 = request.form['p4']
        p5 = request.form['p5']
        p6 = request.form['p6']
        p7 = request.form['p7']
        p8 = request.form['p8']
        p9 = request.form['p9']
        p10 = request.form['p10']

        member_emails = {
            'p1': p1,
            'p2': p2,
            'p3': p3,
            'p4': p4,
            'p5': p5,
            'p6': p6,
            'p7': p7,
            'p8': p8,
            'p9': p9,
            'p10': p10
        }

        # get all available rooms in DB
        rooms = RoomMatrix.get_rooms()

        # gets random room number to assign new meetings to random room number
        random.random()
        # random.randint selects (start, end) with both ends inclusive
        r_int = random.randint(0, (len(rooms) - 1))
        # get room object using a random room_id assigned from the RoomMatrix
        room = Room.get_from_mongo(rooms[r_int]['room_id'])
        # room object stores room number
        r_number = room.roomNum
        # create the meeeting
        meeting = Meeting(day=day, time=time, r_number=r_number, email=email, members=member_emails)

        # if meeting day/time available, ALSO update room list with new meeting and save meeting to DB
        if meeting.isAvailable(day, time):
            room.update_meetings(room._id, day + time, meeting._id)
            meeting.save_to_mongo()
            return make_response(back_to_profile())
    return render_template('create_meeting_error.html', error="Meeting Day-Time already taken", email=session['email'])
Пример #6
0
def back_to_profile():
    if session['email'] is not None:
        user = User.get_by_email(session['email'])
        if Meeting.get_by_email(session['email']) is not None:
            meetings = Meeting.get_by_email(session['email'])
        else:
            meetings = []
        if user.check_if_client():
            return render_template('client_profile.html', email=session['email'], name=user.name)
        elif user.check_if_admin():
            return render_template('admin_profile.html', email=session['email'], name=user.name)
        else:
            return render_template('login_error.html', error='Invalid Request')
    return render_template('login_error.html', error='Invalid Request')
Пример #7
0
def generate_meetings(session):
    import random
    from models.meeting import Meeting
    from faker import Faker

    faker = Faker()
    clients = list(range(1, 3001))
    friend_groups = list(range(1, 2001))
    for i in range(1, 5000):
        meeting = Meeting()
        meeting.client_id = random.choice(clients)
        meeting.friend_group_id = random.choice(friend_groups)
        meeting.date = faker.date_between(start_date='-1y', end_date='today')
        session.add(meeting)
    session.commit()
Пример #8
0
    def authorize():
        error = request.args.get('error', default="", type=str)
        if error != "":
            return make_response(
                redirect(f"http://localhost:3000/after-login?error={error}!"))
        google = gauth.create_client('google')
        token = google.authorize_access_token()
        resp = google.get('userinfo')
        user_info = resp.json()
        g_user = gauth.google.userinfo()
        session["access_token"] = token["access_token"]
        """
        If user exists in DB then db_user will be dict.
        But if we are saving brand new user object
        Then db_user would be object containing
        property inserted_id
        """
        my_user = User(g_user)
        db_user = my_user.save("users")
        session['profile'] = user_info
        # User exists then db_user is dict
        if type(db_user) is dict:
            user_id = db_user["_id"]
            query = {"_id": ObjectId(db_user["_id"])}
            resonse = make_response(
                redirect("http://localhost:3000/dashboard?access_token=" +
                         token["access_token"] + "&user_id=" + str(user_id) +
                         "&email=" + g_user.email + "&jwt_token=" +
                         token["id_token"]))
        else:
            user_id = db_user.inserted_id
            query = {"_id": db_user.inserted_id}
            meeting = Meeting(user_id, "First meeting", "one-to-one",
                              "my meeting", 60)
            saveMeeting = meeting.save("meeting")
            if saveMeeting.inserted_id:
                my_user.add_meeting_id(saveMeeting.inserted_id)
            resonse = make_response(
                redirect(
                    "http://localhost:3000/profile_settings?access_token=" +
                    token["access_token"] + "&user_id=" + str(user_id) +
                    "&email=" + g_user.email + "&jwt_token=" +
                    token["id_token"]))

        newValues = {"$set": {"access_token": token["access_token"]}}
        result = User.update(query, newValues)
        session.permanent = True
        return resonse
Пример #9
0
def update_meeting(id: int, meetingData: MeetingType):
    """
    Update a meeting by id
    """

    try:

        meeting = Meeting.find_or_fail(id)
        meeting.validate(meetingData)

        meeting.update(**dump_schema(meetingData))
        meeting.save()

        msg = f"Meeting update successfully."

        log.info(f"{msg} with id: {id}")
        return HTTP_200, {"message": msg}

    except ValidationError as error:

        log.error(f"ValidationError: {error}")
        raise HTTPError(HTTP_400, {"errors": str(error)})

    except NotFoundError as error:

        log.error(f"NotFoundError: {error}")
        raise HTTPError(HTTP_404, {"errors": str(error)})

    except ConflictError as error:

        log.error(f"ConflictError: {error}")
        raise HTTPError(HTTP_409, {"errors": str(error)})
    def set_time(_id: int, time_date: str) -> Meeting:
        time_to_db = datetime.datetime.strptime(time_date, "%H:%M %d.%m.%Y")

        meeting = Meeting.get((Meeting.initiator_id == _id) & (Meeting.is_ready == False))
        meeting.meeting_time = time_to_db
        meeting.is_ready = True
        meeting.save()
        return meeting
 def set_status(_id: int, status: MeetingStatus) -> Optional[Meeting]:
     meeting = Meeting.select().where(Meeting.id == _id)
     if meeting.exists():
         meeting = meeting.get()
         meeting.status = status
         meeting.save()
         return meeting
     return None
 def get_exist_records(user_id: int) -> list:
     results = set()
     query_set = Meeting.select().where((Meeting.initiator_id == user_id) |
                                        (Meeting.companion_id == user_id))
     for i in query_set:
         results.add(i.initiator_id.id)
         results.add(i.companion_id.id)
     return list(results)
 def rate_meeting(_id: int, rating: int) -> Meeting:
     meeting = Meeting.get((Meeting.initiator_id == _id) | (Meeting.companion_id == _id))
     if _id == meeting.initiator_id:
         meeting.initiator_rate = rating
         meeting.save()
     if _id == meeting.companion_id:
         meeting.companion_rate = rating
         meeting.save()
     return meeting
 def leave_feedback(_id: int, feedback: str) -> Meeting:
     meeting = Meeting.get((Meeting.initiator_id == _id) | (Meeting.companion_id == _id))
     if _id == meeting.initiator_id:
         meeting.initiator_feedback = feedback
         meeting.save()
     if _id == meeting.companion_id:
         meeting.companion_feedback = feedback
         meeting.save()
     return meeting
Пример #15
0
 def get(self, meeting_key=None):
     login_user = self.get_current_user()
     m = Meeting.get(meeting_key)
     if m is None:
         return self.error(404)
     if m.creator != login_user:
         return self.error(401) # access denied
     m.delete()
     return self.redirect_back()
Пример #16
0
    def get(self, meeting_key=None, user_name=None):
        login_user = self.get_current_user()
        m = Meeting.get(meeting_key)
        if m is None:
            return self.error(404)
        if m.creator != login_user:
            return self.error(401)

        profile = Profile.gql('WHERE nickname = :1', user_name).get()
        m.delete_member(profile.get_user())
        return self.redirect_back()
Пример #17
0
 def create_with_owner(self, obj_in: Dict[str, Any],
                       user_id: int) -> Dict[str, Any]:
     db_obj = Meeting(**obj_in, user_id=user_id)
     db.session.add(db_obj)
     try:
         db.session.commit()
     except IntegrityError:
         db.session.rollback()
         return {'added': False}
     db.session.refresh(db_obj)
     return {'added': True, 'db_obj': db_obj}
    def get_active_meeting(_id: int) -> str:
        query = ((Meeting.initiator_id == _id) | (Meeting.companion_id == _id)) \
                & ((Meeting.status == MeetingStatus.planned) | (Meeting.status == MeetingStatus.planned))
        meeting: Meeting = Meeting.get(query)
        if _id == meeting.initiator_id.id:
            companion: User = User.get(User.id == meeting.companion_id)
        else:
            companion: User = User.get(User.id == meeting.initiator_id)

        meeting_time = meeting.meeting_time.strftime("%H:%M %d.%m.%Y")

        return f"Время:\n{meeting_time}\n\n" + UserController.get_info(companion.id)
Пример #19
0
def meeting(room):

    meeting_data = {
        "title": fake.text(60),
        "date_start": fake.iso8601(),
        "date_end": fake.future_datetime(end_date="+10m").isoformat(),
        "owner": fake.name(),
        "room_id": room.get("id"),
    }
    meeting = Meeting.create(**meeting_data)

    yield meeting.serialize()
    meeting.delete()
Пример #20
0
 def post(self, meeting_key=None):
     login_user = self.get_current_user()
     m = Meeting.get(meeting_key)
     if m is None:
         return self.error(404)
     if m.creator != login_user:
         return self.error(401)
     
     user_name = self.request.get('user_name')
     profile = Profile.gql('WHERE nickname = :1', user_name).get()
     if profile:
         m.add_member(profile.get_user())
     return self.redirect_back()
Пример #21
0
    def post(self, meeting_key=None):
        from models.blip import Blip
        login_user = self.get_current_user()
        m = Meeting.get(meeting_key)
        if m is None:
            return self.error(404)
        if not m.has_member(login_user):
            return self.error(401)

        content = self.request.get('text', '').strip()
        attachment = self.request.get('attachment', '').strip()
        blip = Blip.new(login_user, content,
                        attachment=attachment, meeting=m)
        return self.redirect(m.href())
Пример #22
0
    def get_info(_id: int) -> str:
        user = User.get(User.id == _id)

        meetings_as_initiator = Meeting.select().where(
            user.id == Meeting.initiator_id)
        ratings_as_initiator = []
        for meeting in meetings_as_initiator:
            ratings_as_initiator.append(meeting.companion_rate)
        try:
            rating_as_initiator = round(
                sum(ratings_as_initiator) / len(ratings_as_initiator), 0)
        except ZeroDivisionError:
            rating_as_initiator = 0

        meetings_as_companion = Meeting.select().where(
            user.id == Meeting.companion_id)
        ratings_as_companion = []
        for meeting in meetings_as_companion:
            if meeting.initiator_rate is not None:
                ratings_as_companion.append(meeting.initiator_rate)
        try:
            rating_as_companion = round(
                sum(ratings_as_companion) / len(ratings_as_companion), 0)
        except ZeroDivisionError:
            rating_as_companion = 0

        if rating_as_initiator == 0:
            rating = rating_as_companion
        elif rating_as_companion == 0:
            rating = rating_as_initiator
        else:
            rating = (rating_as_initiator + rating_as_companion) / 2

        rating_str = "⭐" * int(rating)

        return f"Имя: \n{user.name}\n\nО себе: \n{user.bio}\n\nРейтинг: \n{rating_str if rating_str != '' else 'нет рейтинга'}"
    def get_history(_id: int) -> str:
        query = ((Meeting.initiator_id == _id) | (Meeting.companion_id == _id))
        meetings = Meeting.select().where(query).order_by(Meeting.id.desc()).limit(5)

        history_entries = []
        meeting: Meeting
        for meeting in meetings:
            if _id == meeting.initiator_id.id:
                companion = meeting.companion_id
            else:
                companion = meeting.initiator_id

            history_entries.append(f"Дата: {meeting.meeting_time.strftime('%H:%M %d.%m.%Y')}\nС кем: {companion.name}")

        return "\n\n".join(history_entries)
Пример #24
0
 def add_meeting():
     if request.method == 'POST':
         data = request.json
         meeting = {
             'subject': data['subject'],
             'location': data['location'],
             'date': data['date'],
             'time': data['time'],
             'attending': data['attending']
         }
         new_meeting = Meeting(meeting['subject'], meeting['location'],
                               meeting['date'], meeting['time'],
                               meeting['attending'])
         session.add(new_meeting)
         session.commit()
         print(meeting, 'Added To The Database Successfully.')
         return 'Instance added successfully'
Пример #25
0
def get_meeting_by_id(id: int):
    """
    Get meeting by id.
    """

    try:

        meeting = Meeting.find_or_fail(id)

        log.info(f"Get meeting by id: {id}")

        return meeting.serialize()

    except NotFoundError as error:

        log.error(f"NotFoundError: {error}")
        raise HTTPError(HTTP_404, {"errors": str(error)})
Пример #26
0
def get_meetings(room_id: Optional[QueryParam], date: Optional[QueryParam]):
    """
    Return all meetings.
    """

    try:

        meetings = Meeting.by_room_id(room_id).by_date(date).get()

        log.info("Get all meetings")

        return HTTP_200, meetings.serialize()

    except ValidationError as error:

        log.error(f"ValidationError: {error}")
        raise HTTPError(HTTP_400, {"errors": str(error)})
Пример #27
0
def delete_meeting(id: int):
    """
    Delete a meeting by id.
    """

    try:

        meeting = Meeting.find_or_fail(id)
        meeting.delete()

        msg = f"Meeting deleted successfully."

        log.info(f"{msg} with id: {id}")
        return HTTP_200, {"message": msg}

    except NotFoundError as error:

        log.error(f"NotFoundError: {error}")
        raise HTTPError(HTTP_404, {"errors": str(error)})
Пример #28
0
def delete_one(meeting_id):
    # need day and time of meeting
    meeting = Meeting.from_mongo(meeting_id)
    day = meeting.day
    time = meeting.time
    searchKey = day + time

    # find rooms with the given meeting_id in the 'meetings.**' field
    # to delete them from 'room' collection
    # .get_rooms() returns a dict() object which must be access like a python dict().
    # room_id is accessed as room['room_id'] but not room.room_id (class access)

    # search rooms by a meeting_id; if search returns True
    if Room.find_by_meeting(searchKey=searchKey, meeting_id=meeting_id):
        room_object = Room.find_by_meeting(searchKey=searchKey, meeting_id=meeting_id)

        # update the room using _id to erase the meeting from the existing meeting. list
        Room.erase_meeting(room_id=room_object._id, searchKey=searchKey)

    # delete the meeting from 'meetings' collection and return to profile dashboard
    meeting.delete_meeting(meeting_id)
    return make_response(back_to_profile())
Пример #29
0
def create_meeting():
    form = CreateMeetingForm()
    if form.validate_on_submit():
        meeting = Meeting(
            meeting_creator=current_user.id,
            max_bikers=form.num_of_bikers.data,
            area=form.area.data,
            trail=form.trail.data,
            date_time=datetime.fromisoformat(f"{form.date.data} {form.time.data}"),
            title=form.title.data,
            description=form.description.data,
            min_skill=form.min_skill.data
        )
        db.session.add(meeting)
        current_user.participations.append(meeting)
        db.session.commit()
        return redirect(url_for("main.profile"))

    context = {
        "title": "Create a meeting",
        "form": form
    }
    return render_template("meeting/create_meeting.html", **context)
Пример #30
0
    def get(self, meeting_key=None):
        from models.blip import Blip
        login_user = self.get_current_user()
        meeting = Meeting.get(meeting_key)
        if meeting is None or not meeting.is_active:
            return self.error(404)
        if not meeting.has_member(login_user):
            return self.error(401)
        c, p = Profile.get_or_create_from_user(meeting.creator)
        
        admin_profiles = [p]

        member_profiles = []
        members = meeting.members(include_creator=False)
        for u in members:
            c, p = Profile.get_or_create_from_user(u)
            member_profiles.append(p)

        followees = Follow.your_subscribers(login_user)
        followee_profiles = []
        for f in followees:
            if f.to_user not in members:
                c, p = Profile.get_or_create_from_user(f.to_user)
                followee_profiles.append(p)
            
        try:
            page = int(self.request.get('page', '1'))
        except ValueError:
            page = 1

        pagesize = settings.ROOM_PAGE_SIZE
        paginator = SimplePaginator(Blip.qs_for_meeting(meeting),
                                     page, pagesize)
        
        blips = each_profiles(paginator.object_list)
        return self.render('meeting_item.html', locals())
 def check_status(_id: int, status: MeetingStatus) -> bool:
     meeting = Meeting.get((Meeting.initiator_id == _id) | (Meeting.companion_id == _id))
     current_status = MeetingStatus(meeting.status)
     return current_status == status
Пример #32
0
 def all(self):
     return Meeting.all()
Пример #33
0
 def get_by_key(self, key):
     return Meeting.all().filter("__key__ = ", db.Key(key)).get()
Пример #34
0
 def previous_meetings(self):
     meetings = Meeting.all()
     meetings.filter("day <", datetime.now())
     meetings.order("day")
     return meetings
Пример #35
0
 def next(self):
     meetings = Meeting.all()
     meetings.filter("day >=", datetime.now())
     meetings.order("day")
     return meetings.get()
Пример #36
0
 def get(self):
     " Create a new meeting. "
     login_user = self.get_current_user()
     m = Meeting(creator=login_user)
     m.put()
     return self.redirect(m.href())
 def create_meeting(*, initiator_id: int, companion_id: int) -> Meeting:
     return Meeting.create(initiator_id=initiator_id, companion_id=companion_id)
 def get_by_id(meeting_id) -> Optional[Meeting]:
     query_set = Meeting.select().where(Meeting.id == meeting_id)
     if query_set.exists():
         return query_set.get()
     return None
 def get_in_progress(initiator_id: int) -> Meeting:
     return Meeting.select().where((Meeting.initiator_id == initiator_id) & (Meeting.is_ready == False)).get()
 def delete_not_is_ready(initiator_id: int):
     Meeting.delete().where((Meeting.initiator_id == initiator_id) & (Meeting.is_ready == False)).execute()