Example #1
0
def get_feedback(env: TEnvironment, query: TQuery, cookie: TCookie) -> TResponse:
    """ Account data HTTP request
    Got day num and return day event for feedback
    # TODO: Get data if feedback already exist

    Args:
        env: HTTP request environment
        query: url query parameters
        cookie: http cookie parameters (may be empty)

    Returns:
        Response - result of request
    """

    day = query['date']  # TODO: Check dd.mm of day_id

    # Safety get user_obj
    user_obj = get_user_by_response(cookie)
    if user_obj is None:
        return http.wrong_cookie(host=env['HTTP_HOST'])

    feedback_template, feedback_data = sql.get_feedback(user_obj['id'], day)
    top_object = sql.get_top(user_obj['id'], day)

    data = {'template': feedback_template, 'data': feedback_data, 'top': top_object}
    return http.ok(json_dict=data)
Example #2
0
def post_edit_project(env: TEnvironment, query: TQuery, cookie: TCookie) -> TResponse:
    """ Post edit project HTTP request
    Edit project signed by cookie

    Args:
        env: HTTP request environment
        query: url query parameters
        cookie: http cookie parameters (may be empty)

    Note:
        Send:
            200 Ok: if all are ok
            401 Unauthorized: if wrong session id
            405 Method Not Allowed: already got it

    Returns:
        Response - result of request
    """

    # Get json from response
    project_obj = get_json_by_response(env)

    # Safety get user_obj
    user_obj = get_user_by_response(cookie)
    if user_obj is None:
        return http.wrong_cookie(host=env['HTTP_HOST'])

    # Check current user can edit
    if user_obj['user_type'] == 0 and user_obj['project_id'] != project_obj['id']:
        return http.not_allowed()

    sql.update_in_table(project_obj, 'projects')

    return http.ok(host=env['HTTP_HOST'])
Example #3
0
def get_credits(env: TEnvironment, query: TQuery, cookie: TCookie) -> TResponse:
    """ Credits data HTTP request
    Get credits data for chart according to user

    Args:
        env: HTTP request environment
        query: url query parameters
        cookie: http cookie parameters (may be empty)

    Returns:
        Response - result of request
    """

    # Safety get user_obj
    user_obj = get_user_by_response(cookie)
    if user_obj is None:
        return http.wrong_cookie(host=env['HTTP_HOST'])

    user_id = user_obj['id']

    if 'id' in query:  # Request other's user credits
        if user_obj['user_type'] > 0:  # Check admin rights
            user_id = query['id']
        else:
            return http.forbidden()

    data = sql.get_credits_by_user_id(user_id)
    return http.ok(host=env['HTTP_HOST'], json_dict=data)
Example #4
0
def post_deenroll_project(env: TEnvironment, query: TQuery, cookie: TCookie) -> TResponse:
    """ De Enroll current user to project HTTP request

    Args:
        env: HTTP request environment
        query: url query parameters
        cookie: http cookie parameters (may be empty)

    Note:
        Send:
            200 Ok: if all are ok
            401 Unauthorized: if wrong session id
            405 Method Not Allowed: already got it

    Returns:
        Response - result of request
    """

    # Safety get user_obj
    user_obj = get_user_by_response(cookie)
    if user_obj is None:
        return http.wrong_cookie(host=env['HTTP_HOST'])

    # Check current user can edit
    if user_obj['project_id'] == 0:
        return http.conflict()

    sql.deenroll_project(user_obj['id'])

    return http.ok(host=env['HTTP_HOST'])
Example #5
0
def post_notification(env: TEnvironment, query: TQuery, cookie: TCookie) -> TResponse:
    """ Sing in current user to pushup notifications

    Args:
        env: HTTP request environment
        query: url query parameters
        cookie: http cookie parameters (may be empty)

    Returns:
        Response - result of request
        None; Only http answer
    """

    user_obj = get_user_by_response(cookie)
    if user_obj is None:
        return http.wrong_cookie(env['HTTP_HOST'])

    key_obj = get_json_by_response(env)
    registration_id = key_obj['token']

    sess = sql.get_session(cookie.get('sessid', ''))  # Get session object
    hash_ = hash(sess['user_agent'] + sess['last_ip'])  # TODO: save hash

    sql.set_notification(user_obj['id'], registration_id)  # TODO: check status

    message_title = "Uber update"
    message_body = f"Hi {user_obj['name']}, your customized news for today is ready"
    result = push_service.notify_single_device(registration_id=registration_id, message_title=message_title,
                                               message_body=message_body)

    print('!!!!!!result!!!!!!!', result)

    return http.ok(env['HTTP_HOST'])
Example #6
0
def admin(env: TEnvironment, query: TQuery, cookie: TCookie) -> TResponse:
    """ Manage admin HTTP request
    Will check session id and permissions

    Note:
        If there is no cookie or it is incorrect - Error

    Args:
        env: HTTP request environment
        query: url query parameters
        cookie: http cookie parameters (may be empty)

    Returns:
        Response - result of request
    """

    logger('admin_panel()', 'Admin try with cookie {cookie}', type_='LOG')

    # Safety get user_obj
    user_obj = get_user_by_response(cookie)
    if user_obj is None:
        return http.wrong_cookie(host=env['HTTP_HOST'])

    logger('admin_panel()', f'Admin try with user: {user_obj}', type_='LOG')

    if user_obj['user_type'] == 0:
        return http.not_allowed()

    logger('admin_panel()', f'Admin want to {env["PATH_INFO"]}', type_='LOG')

    functions = {
        '/admin_get_config': get_config,
        '/admin_post_config': post_config,
        '/admin_get_places': get_places,
        '/admin_post_places': post_places,
        '/admin_get_credits': get_credits,
        '/checkin': post_checkin,
        '/admin_get_table': get_table,
        '/admin_clear_table': clear_table,
        '/admin_send_data': send_data,
        '/admin_remove_data': remove_data,
        '/admin_codes': codes,
        '/admin_change_password': change_password
    }

    if env['PATH_INFO'] in functions:
        return functions[env['PATH_INFO']](env, query, cookie)
Example #7
0
def post(env: TEnvironment, query: TQuery, cookie: TCookie) -> TResponse:
    """ POST HTTP request
    Will manage and call specific function [login, register]

    Args:
        env: HTTP request environment
        query: url query parameters
        cookie: http cookie parameters (may be empty)

    Returns:
        Response - result of request
    """

    functions = {
        '/login': post_login,
        '/register': post_register,
        '/logout': post_logout,
        '/notification': post_notification,

        '/feedback': post_feedback,

        '/project': post_project,
        '/edit_project': post_edit_project,
        '/enroll_project': post_enroll_project,
        '/deenroll_project': post_deenroll_project,

        '/credits': post_credits,
        '/mark_enrolls': post_mark_enrolls,
        '/create_enroll': post_create_enroll,
        '/remove_enroll': post_remove_enroll,
    }

    if env['PATH_INFO'] in functions:
        return functions[env['PATH_INFO']](env, query, cookie)

    if env['PATH_INFO'] == '/enroll':
        # TODO: Remove on release - admin
        user_obj = get_user_by_response(cookie)
        if user_obj is None:
            return http.wrong_cookie(env['HTTP_HOST'])
        if user_obj['user_type'] == 0:
            return http.unauthorized()

        return post_enroll(env, query, cookie)

    return http.not_allowed()
Example #8
0
def post_mark_enrolls(env: TEnvironment, query: TQuery, cookie: TCookie) -> TResponse:
    """ Sing in at lecture  HTTP request (by student )
    By cookie add credits to user

    Args:
        env: HTTP request environment
        query: url query parameters
        cookie: http cookie parameters (may be empty)

    Note:
        Send:
            200 Ok: if all are ok
            401 Unauthorized: if wrong session id
            405 Method Not Allowed: already got it or timeout

    Returns:
        Response - result of request
        None; Only http answer
    """

    # Safety get user_obj
    user_obj = get_user_by_response(cookie)
    if user_obj is None:
        return http.wrong_cookie(host=env['HTTP_HOST'])

    enrolls = get_json_by_response(env)
    config_dict = config.get_config()

    if enrolls is not None:

        # TODO: check do better
        for enroll in enrolls:
            sql.update_in_table(enroll, 'enrolls')

            if enroll['attendance'] in (True, 'true'):
                sql.pay_credit(enroll['user_id'], enroll['class_id'],
                               config_dict['CREDITS_MASTER'] + min(config_dict['CREDITS_ADDITIONAL'], enroll['bonus']),
                               get_datetime_str())
                # TODO: CREDITS_MASTER CREDITS_LECTURE check

        return http.ok(host=env['HTTP_HOST'])

    else:
        return http.not_allowed()
Example #9
0
def post_remove_enroll(env: TEnvironment, query: TQuery, cookie: TCookie) -> TResponse:
    """ Remove  HTTP request (by student )
    By cookie add credits to user

    Args:
        env: HTTP request environment
        query: url query parameters
        cookie: http cookie parameters (may be empty)

    Note:
        Send:
            200 Ok: if all are ok
            401 Unauthorized: if wrong session id
            405 Method Not Allowed: already got it or timeout

    Returns:
        Response - result of request
        None; Only http answer
    """

    # Safety get user_obj
    user_obj = get_user_by_response(cookie)
    if user_obj is None:
        return http.wrong_cookie(host=env['HTTP_HOST'])

    enroll_id = query['id']
    enroll = sql.get_in_table(enroll_id, 'enrolls')

    if enroll is not None and (
            user_obj['user_type'] == 0 and enroll['user_id'] == user_obj['id'] or user_obj['user_type'] >= 1):
        # Check admin or user remove himself

        event = sql.get_event_with_date(enroll['class_id'])

        if not check_enroll_time(event['date'], event['time']):  # Close for 15 min
            return http.gone()

        sql.remove_enroll(enroll_id)

        return http.ok(host=env['HTTP_HOST'])

    else:
        return http.not_allowed()
Example #10
0
def post_credits(env: TEnvironment, query: TQuery, cookie: TCookie) -> TResponse:
    """ Sing in at lecture  HTTP request (by student )
    By cookie add credits to user

    Args:
        env: HTTP request environment
        query: url query parameters
        cookie: http cookie parameters (may be empty)

    Note:
        Send:
            200 Ok: if all are ok
            401 Unauthorized: if wrong session id
            405 Method Not Allowed: already got it or timeout

    Returns:
        Response - result of request
        None; Only http answer
    """

    # TODO: CREDITS

    # Event code
    # code = query['code']
    # print('Credits code: ', code)

    event_id = 42  # TODO: Get event id from code

    # Safety get user_obj
    user_obj = get_user_by_response(cookie)
    if user_obj is None:
        return http.wrong_cookie(env['HTTP_HOST'])

    event_obj = sql.get_event(event_id)
    if event_obj is not None:
        # gsheets.save_credits(user_obj, event_obj)
        sql.checkin_user(user_obj, event_obj)
        logger('post_credits()', f'Checkin user {user_obj} to {event_obj}', type_='LOG')

        return http.ok(env['HTTP_HOST'])

    else:
        return http.not_allowed()
Example #11
0
def get_user(env: TEnvironment, query: TQuery, cookie: TCookie) -> TResponse:
    """ User data HTTP request
    Will check session id and return data according to user

    Args:
        env: HTTP request environment
        query: url query parameters
        cookie: http cookie parameters (may be empty)

    Returns:
        Response - result of request
    """

    # Safety get user_obj
    user_obj = get_user_by_response(cookie)
    if user_obj is None:
        return http.wrong_cookie(host=env['HTTP_HOST'])

    if 'id' in query:  # Request other's user boi
        if user_obj['user_type'] > 0:  # Check admin rights
            user_obj = sql.get_user_by_id(query['id'])
        else:
            return http.forbidden(host=env['HTTP_HOST'])

    # Json account data
    data = user_obj
    del data['pass']

    data['enrolls'] = [{'class_id': enroll['class_id'], 'attendance': enroll['attendance'], 'bonus': enroll['bonus']} for enroll in sql.get_enrolls_by_user_id(user_obj['id'])]  # TODO: Think do it that way ot not

    data['calendar'] = True
    data['feedback'] = False  # TODO: Notifacation
    data['projects'] = user_obj['project_id'] == 0 or user_obj['project_id'] == '0'

    data['total'] = config.get_config()['CREDITS_TOTAL']
    data['today'] = get_date_str()  # TODO: remove. Only for debug???

    database_update_time = sql.get_update_times()

    data['update_time'] = database_update_time

    return http.ok(host=env['HTTP_HOST'], json_dict=data)
Example #12
0
def post_create_enroll(env: TEnvironment, query: TQuery, cookie: TCookie) -> TResponse:
    """ Create  HTTP request (by student )
    By cookie add enroll to user

    Args:
        env: HTTP request environment
        query: url query parameters
        cookie: http cookie parameters (may be empty)

    Note:
        Send:
            200 Ok: if all are ok
            401 Unauthorized: if wrong session id
            405 Method Not Allowed: already got it or timeout

    Returns:
        Response - result of request
        None; Only http answer
    """

    # Safety get user_obj
    user_obj = get_user_by_response(cookie)
    if user_obj is None:
        return http.wrong_cookie(host=env['HTTP_HOST'])

    event_id = query['event_id']

    event = sql.get_event_with_date(event_id)

    if event is None:
        return http.not_allowed()

    if not check_enroll_time(event['date'], event['time']):  # Close for 15 min
        return http.gone()

    if sql.enroll_user(event_id, user_obj['id'], event['date'], get_datetime_str()):

        return http.ok(host=env['HTTP_HOST'])

    else:
        return http.not_allowed()
Example #13
0
def post_feedback(env: TEnvironment, query: TQuery, cookie: TCookie) -> TResponse:
    """ Login HTTP request
    By cookie create feedback for day

    Args:
        env: HTTP request environment
        query: url query parameters
        cookie: http cookie parameters (may be empty)

    Note:
        Send:
            200 Ok: if all are ok
            401 Unauthorized: if wrong session id
            405 Method Not Allowed: already got it

    Returns:
        Response - result of request
        None; Only http answer
    """

    date = query['date']

    # Safety get user_obj
    user_obj = get_user_by_response(cookie)
    if user_obj is None:
        return http.wrong_cookie(env['HTTP_HOST'])

    # Get json from response
    feedback_obj = get_json_by_response(env)
    users = feedback_obj['users']
    events = feedback_obj['events']

    print('EVENTS', events)
    print('USERS', users)

    # TODO: check
    if sql.post_feedback(user_obj['id'], events) or sql.post_top(user_obj['id'], date, users):
        return http.ok(env['HTTP_HOST'])
    else:
        return http.not_allowed()
Example #14
0
def post_enroll(env: TEnvironment, query: TQuery, cookie: TCookie) -> TResponse:
    """ Enroll at lecture HTTP request (by student )
    By cookie add user to this event

    Args:
        env: HTTP request environment
        query: url query parameters
        cookie: http cookie parameters (may be empty)

    Note:
        Send:
            200 Ok: if all are ok
            401 Unauthorized: if wrong session id
            405 Method Not Allowed: already got it or nop places

    Returns:
        Response - result of request
        None; Only http answer
    """

    # Event code
    event_id = query['id']

    # Safety get user_obj
    user_obj = get_user_by_response(cookie)
    if user_obj is None:
        return http.wrong_cookie(host=env['HTTP_HOST'])

    # TODO:

    if sql.enroll_user(event_id, user_obj, get_datetime_str()):
        event = sql.get_event(event_id)

        # Json event data
        data = {'count': event[4], 'total': event[5]}  # TODO: Count total
        return http.ok(host=env['HTTP_HOST'], json_dict=data)

    else:
        return http.not_allowed()  # TODO: Return count and total
Example #15
0
def post_project(env: TEnvironment, query: TQuery, cookie: TCookie) -> TResponse:
    """ Post project HTTP request
    Create new project signed by cookie

    Args:
        env: HTTP request environment
        query: url query parameters
        cookie: http cookie parameters (may be empty)

    Note:
        Send:
            200 Ok: if all are ok
            401 Unauthorized: if wrong session id
            405 Method Not Allowed: already got it

    Returns:
        Response - result of request
    """

    # Get json from response
    project_obj = get_json_by_response(env)

    # Safety get user_obj
    user_obj = get_user_by_response(cookie)
    if user_obj is None:
        return http.wrong_cookie(host=env['HTTP_HOST'])

    # Mb there are some project for current user?
    if user_obj['project_id'] != 0:
        return http.conflict()

    # Check current user in the project
    if user_obj['name'] not in project_obj['users']:
        project_obj['users'].append(user_obj['name'])

    if sql.save_project(project_obj):  # If user exist
        return http.ok(host=env['HTTP_HOST'])
    else:
        return http.conflict()
Example #16
0
def get_account(env: TEnvironment, query: TQuery, cookie: TCookie) -> TResponse:
    """ Account data HTTP request
    Will check session id and return data according to user

    Args:
        env: HTTP request environment
        query: url query parameters
        cookie: http cookie parameters (may be empty)

    Returns:
        Response - result of request
    """

    # Safety get user_obj
    user_obj = get_user_by_response(cookie)
    if user_obj is None:
        return http.wrong_cookie(host=env['HTTP_HOST'])

    # Json account data
    data = user_obj
    data['total'] = config.get_config()['CREDITS_TOTAL']

    return http.ok(host=env['HTTP_HOST'], json_dict=data)
Example #17
0
def post_checkin(env: TEnvironment, query: TQuery,
                 cookie: TCookie) -> TResponse:
    """ Check in at lecture  HTTP request (by admin)
    By cookie add credits to user

    Args:
        env: HTTP request environment
        query: url query parameters
        cookie: http cookie parameters (may be empty)

    Note:
        Send:
            200 Ok: if all are ok
            401 Unauthorized: if wrong session id
            405 Method Not Allowed: already got it or timeout

    Returns:
        Response - result of request
        None; Only http answer
    """

    checkins = get_json_by_response(env)
    event_id = query['event']

    # Safety get user_obj
    user_obj = get_user_by_response(cookie)

    event = sql.get_in_table(event_id, 'events')

    if event is None:  # No such event
        return http.not_allowed(host=env['HTTP_HOST'])

    config_dict = config.get_config()

    # Set up credits and enrolls attendance
    if event['type'] == 1 and event['total'] > 0:
        # master
        # Check there are enrolls
        enrolls = sql.get_enrolls_by_event_id(event_id)

        users_in_enrolls = {
            enroll['user_id']
            for enroll in enrolls if not enroll['attendance']
        }  # type: tp.Set[int]
        users_in_checkins = {
            int(checkin['id']): min(int(checkin['bonus']),
                                    config_dict['CREDITS_ADDITIONAL'])
            for checkin in checkins
        }  # type: tp.Dict[int, int]

        users_to_set_credits = {
            k
            for k in users_in_checkins.keys() if k in users_in_enrolls
        }  # type: tp.Set[int]

        # Setup attendance for enrolls
        enrolls = [
            enroll for enroll in enrolls
            if enroll['user_id'] in users_to_set_credits
        ]  # type: tp.List[sql.TTableObject]
        for i in range(len(enrolls)):
            enrolls[i]['attendance'] = True
            enrolls[i]['bonus'] = users_in_checkins[enrolls[i]['user_id']]

            sql.update_in_table(enrolls[i], 'enrolls')

        # TODO: Minus balls if not attendant
        credits = [{
            'user_id':
            int(checkin['id']),
            'event_id':
            event_id,
            'validator_id':
            user_obj['id'],
            'time':
            get_datetime_str(),
            'value':
            config_dict['CREDITS_MASTER'] +
            min(int(checkin['bonus']), config_dict['CREDITS_ADDITIONAL'])
        } for checkin in checkins if int(checkin['id']) in users_to_set_credits
                   ]  # type: tp.List[sql.TTableObject]
        for credit in credits:
            sql.insert_to_table(credit, 'credits')

        logger('post_checkin()',
               f'Checkin users {users_in_checkins} to master event {event_id}',
               type_='LOG')
    else:
        # lecture
        enrolls = [{
            'class_id':
            event_id,
            'user_id':
            int(checkin['id']),
            'time':
            get_datetime_str(),
            'attendance':
            True,
            'bonus':
            min(int(checkin['bonus']), config_dict['CREDITS_ADDITIONAL'])
        } for checkin in checkins]  # type: tp.List[sql.TTableObject]
        for enroll in enrolls:
            sql.update_in_table(enroll, 'enrolls')

        credits = [{
            'user_id':
            int(checkin['id']),
            'event_id':
            event_id,
            'time':
            get_datetime_str(),
            'value':
            config_dict['CREDITS_LECTURE'] +
            min(int(checkin['bonus']), config_dict['CREDITS_ADDITIONAL'])
        } for checkin in checkins]  # type: tp.List[sql.TTableObject]
        for credit in credits:
            sql.insert_to_table(credit, 'credits')

        logger('post_checkin()',
               f'Checkin user {checkins} to lecture event {event_id}',
               type_='LOG')

    return http.ok(env['HTTP_HOST'])