def edit_post(game_id:int):
    with dbutils.dbopen() as db:
        params = {i: bottle.request.forms.get(i) for i in bottle.request.forms}
        params.pop('submit_edit')
        params['datetime'] = params['date'] + ' ' + params['time'] + ':00'
        params.pop('date')
        params.pop('time')
        params.pop('game_id')
        responsible_old = games.get_by_id(game_id, dbconnection=db).responsible_user_id()
        if responsible_old != int(params['responsible_user_id']):
            page = check_responsible(params['responsible_user_id'], params['datetime'],
                                          params['duration'].split(' ')[0], db)
            if page: return page
            assigned_responsible(game_id, int(params['responsible_user_id']), db)
            unassigned_responsible(game_id, responsible_old, db)
        games.update(game_id, dbconnection=db, **params)
        game = games.get_by_id(game_id, dbconnection=db)
        if not game.datetime.passed:
            for user_id in game.subscribed():
                utils.spool_func(notificating.site.subscribed, user_id, 'Игра "{}" была отредактирована.<br>Проверьте изменения!'.format(
                    modules.create_link.game(game)), 1, game_id)
            if responsible_old == int(params['responsible_user_id']):
                utils.spool_func(notificating.site.responsible, responsible_old, 'Игра "{}" была отредактирована.<br>Проверьте изменения!'.format(
                    modules.create_link.game(game)), 1, game_id)
        raise bottle.redirect('/games/{}'.format(game_id))
def unreserve(user_id:int, game_id:int):
    with dbutils.dbopen() as db:
        game = games.get_by_id(game_id, dbconnection=db)
        if game.datetime.passed: raise bottle.HTTPError(404)
        if pages.auth.current().banned():
            return pages.PageBuilder("game", game=game, conflict=2)
        if user_id not in set(game.reserved_people()):
            return pages.PageBuilder("game", game=game, conflict=11)
        games.unsubscribe(user_id, game_id, dbconnection=db)
        game = games.get_by_id(game_id, dbconnection=db)
        return pages.PageBuilder("game", game=game)
def fromreserve(user_id:int, game_id:int):
    with dbutils.dbopen() as db:
        game = games.get_by_id(game_id, dbconnection=db)
        if user_id not in set(game.reserved_people()):
            return pages.PageBuilder("game", game=game, conflict=11)
        if user_id in set(game.subscribed()):
            return pages.PageBuilder("game", game=game, conflict=5)
        if game.capacity() > 0 and len(game.subscribed()) == game.capacity():
            return pages.PageBuilder("game", game=game, conflict=4)
        games.unsubscribe(user_id, game_id, dbconnection=db)
        games.subscribe(user_id, game_id, dbconnection=db)
        game = games.get_by_id(game_id, dbconnection=db)
        return pages.PageBuilder("game", game=game)
def unsubscribe(user_id:int, game_id:int, suspress:bool=False):
    with dbutils.dbopen() as db:
        game = games.get_by_id(game_id, dbconnection=db)
        if game.datetime.passed: raise bottle.HTTPError(404)
        if user_id not in set(game.subscribed()):
            return pages.PageBuilder("game", game=game, conflict=6)
        if not suspress and game.datetime.tommorow and game.datetime.time().hour<=12 and datetime.datetime.now().hour>=20:
            return pages.PageBuilder("game", game=game, conflict=11)
        games.unsubscribe(user_id, game_id, dbconnection=db)
        if datetime.datetime.now()-game.datetime()<datetime.timedelta(days=3):
            user = users.get(user_id, dbconnection=db) if user_id!=pages.auth.current().user_id() else pages.auth.current()
            message = '{} отписался от игры "{}"'.format(create_link.user(user), create_link.game(game))
            utils.spool_func(notificating.site.responsible, game.responsible_user_id(), message, 1, game_id)
        game = games.get_by_id(game_id, dbconnection=db)
        return pages.PageBuilder("game", game=game)
def autocreate(game_id:int):
    with dbutils.dbopen() as db:
        game = games.get_by_id(game_id, dbconnection=db)
        newgame = {
            "description": game.description(),
            "city_id": game.city_id(),
            "sport_type": game.sport_type(),
            "game_type": game.game_type(),
            "court_id": game.court_id(),
            "duration": game.duration(),
            "cost": game.cost(),
            "capacity": game.capacity(),
            "responsible_user_id": game.responsible_user_id(),
            "created_by": game.created_by(),
            "reserved": game.reserved(),
            "datetime": str(game.datetime()+datetime.timedelta(days=7)).split('.')[0]
        }
        intersection = games.court_game_intersection(newgame['court_id'],newgame['datetime'],newgame['duration'],
                                                     dbconnection=db)
        if intersection:
            return pages.PageBuilder('text', message='Обнаружен конфликт',
                                     description='В это время уже идет другая <a href="/games/{}">игра</a>'.format(
                                         intersection))
        page = check_responsible(newgame['responsible_user_id'], newgame['datetime'],
                                      newgame['duration'], db)
        if page: return page
        game_id = games.add(dbconnection=db, **newgame)
        assigned_responsible(game_id, int(newgame['responsible_user_id']), db)
        raise bottle.redirect("/games/edit/{}".format(game_id))
def unassigned_responsible(game_id:int, user_id:int, db):
    if user_id == pages.auth.current().user_id():
        return
    game = games.get_by_id(game_id, dbconnection=db)
    notification = 'Вы больше не являетесь ответственным за игру "{}".'
    notification = notification.format(modules.create_link.game(game))
    utils.spool_func(notificating.site.responsible, user_id, notification, 2, game_id)
def get():
    with dbutils.dbopen() as db:
        user_id = pages.auth.current().user_id()
        user = users.get(user_id, dbconnection=db)
        page = pages.PageBuilder('profile', user=user)
        page.add_param('user_games',
                       games.get_by_id(games.get_user_played_games(user_id, dbconnection=db), dbconnection=db))
        page.add_param('responsible_games',
                       games.get_by_id(games.get_responsible_games(user_id, dbconnection=db), dbconnection=db))
        page.add_param('organizer_games',
                       games.get_by_id(games.get_organizer_games(user_id, dbconnection=db), dbconnection=db))
        with dbutils.dbopen(**dbutils.logsdb_connection) as logsdb:
            logsdb.execute("SELECT COUNT(DISTINCT(ip)), COUNT(ip) FROM access WHERE path='/profile?user_id={}' and user_id!=0".format(user_id))
            page.add_param('views', logsdb.last()[0][1])
            page.add_param('uviews', logsdb.last()[0][0])
        return page
def delete(game_id:int):
    with dbutils.dbopen() as db:
        game = games.get_by_id(game_id, dbconnection=db)
        if game.created_by() != pages.auth.current().user_id() and not pages.auth.current().userlevel.admin():
            return pages.templates.permission_denied()
        games.delete(game_id, dbconnection=db)
        raise bottle.redirect('/games')
def edit(game_id:int):
    with dbutils.dbopen() as db:
        game = games.get_by_id(game_id, dbconnection=db)
        if len(game) == 0:
            raise bottle.HTTPError(404)
        if pages.auth.current().user_id() != game.created_by() and \
                        pages.auth.current().user_id() != game.responsible_user_id() and \
                not pages.auth.current().userlevel.admin():
            return pages.templates.permission_denied()
        _sport_types = sport_types.get(0, dbconnection=db)
        _game_types = game_types.get(0, dbconnection=db)
        _cities = cities.get(0, dbconnection=db)
        _courts = courts.get(0, dbconnection=db)
        responsibles = users.get(0, 2, dbconnection=db)
        unsubscribed = games.get_unsubscribed_users(game_id, dbconnection=db)
        unsubscribed_list = list()
        db.execute("SELECT * FROM users WHERE user_id IN (SELECT DISTINCT user_id FROM reports WHERE user_id!=0 AND status=2 AND game_id IN (SELECT game_id FROM games WHERE deleted=0 AND datetime+INTERVAL duration MINUTE < NOW() AND court_id='{}' AND sport_type='{}' AND game_type='{}'))".format( # as long as my dick
            game.court_id(), game.sport_type(), game.game_type()), dbutils.dbfields['users'])
        last_users = list(map(lambda x: User(x, db), db.last()))
        for i in unsubscribed:
            user = users.get(i[0], dbconnection=db)
            dt = i[1]
            unsubscribed_list.append((user, dt))
        return pages.PageBuilder('editgame', game=game, sports=_sport_types, game_types=_game_types, cities=_cities,
                                 courts=_courts, responsibles=responsibles, unsubscribed=unsubscribed_list,
                                 last_users=last_users)
def assigned_responsible(game_id:int, user_id:int, db):
    if user_id == pages.auth.current().user_id():
        return
    game = games.get_by_id(game_id, dbconnection=db)
    notification = 'Вас назначили ответственным на игру "{}"<br>Свяжитесь с "{}"!'
    notification = notification.format(modules.create_link.game(game),
                                       modules.create_link.user(game.created_by(True)))
    utils.spool_func(notificating.site.responsible, user_id, notification, 2, game_id)
def subscribed_list(game_id:int):
    with dbutils.dbopen() as db:
        game = games.get_by_id(game_id, dbconnection=db)
        if len(game) == 0:
            raise bottle.HTTPError(404)
        if pages.auth.current().user_id() != game.created_by() and pages.auth.current().user_id() != game.responsible_user_id() and not pages.auth.current().userlevel.admin():
            return pages.templates.permission_denied()
        return pages.PageBuilder('list', game=game)
Beispiel #12
0
def unassigned_responsible(game_id: int, user_id: int, db):
    if user_id == pages.auth.current().user_id():
        return
    game = games.get_by_id(game_id, dbconnection=db)
    notification = 'Вы больше не являетесь ответственным за игру "{}".'
    notification = notification.format(modules.create_link.game(game))
    utils.spool_func(notificating.site.responsible, user_id, notification, 2,
                     game_id)
Beispiel #13
0
def delete(game_id: int):
    with dbutils.dbopen() as db:
        game = games.get_by_id(game_id, dbconnection=db)
        if game.created_by() != pages.auth.current().user_id(
        ) and not pages.auth.current().userlevel.admin():
            return pages.templates.permission_denied()
        games.delete(game_id, dbconnection=db)
        raise bottle.redirect('/games')
def notify_array(game_id:int):
    with dbutils.dbopen() as db:
        game = games.get_by_id(game_id, dbconnection=db)
        db.execute("SELECT DISTINCT user_id FROM reports WHERE user_id!=0 AND status=2 AND game_id IN (SELECT game_id FROM games WHERE deleted=0 AND datetime+INTERVAL duration MINUTE < NOW() AND court_id='{}' AND sport_type='{}' AND game_type='{}')".format( # as long as my dick
            game.court_id(), game.sport_type(), game.game_type()))
        if len(db.last())==0: return json.dumps({'users':list(), 'count':0})
        users_ = users.get(list(map(lambda x: x[0], db.last())), dbconnection=db)
        users_ = list(map(lambda x: {'user_id':x.user_id(), 'name':str(x.name), 'visits':user_visits(x, db)}, users_))
        return json.dumps({'count':len(users_), 'users':users_})
def reserve(user_id:int, game_id:int):
    with dbutils.dbopen() as db:
        game = games.get_by_id(game_id, dbconnection=db)
        if game.datetime.passed: raise bottle.HTTPError(404)
        #if not pages.auth.current().activated():
        #    return pages.PageBuilder("game", game=game, conflict=3)
        if pages.auth.current().banned():
            return pages.PageBuilder("game", game=game, conflict=2)
        if game.reserved()==0:
            return pages.PageBuilder("game", game=game, conflict=8)
        if len(game.subscribed())<game.capacity():
            return pages.PageBuilder("game", game=game, conflict=10)
        if user_id in set(game.reserved_people()):
            return pages.PageBuilder("game", game=game, conflict=7)
        if len(game.reserved_people())==game.reserved():
            return pages.PageBuilder("game", game=game, conflict=9)
        games.subscribe(user_id, game_id, True, dbconnection=db)
        game = games.get_by_id(game_id, dbconnection=db)
        return pages.PageBuilder("game", game=game)
Beispiel #16
0
def subscribed_list(game_id: int):
    with dbutils.dbopen() as db:
        game = games.get_by_id(game_id, dbconnection=db)
        if len(game) == 0:
            raise bottle.HTTPError(404)
        if pages.auth.current().user_id() != game.created_by(
        ) and pages.auth.current().user_id() != game.responsible_user_id(
        ) and not pages.auth.current().userlevel.admin():
            return pages.templates.permission_denied()
        return pages.PageBuilder('list', game=game)
Beispiel #17
0
def assigned_responsible(game_id: int, user_id: int, db):
    if user_id == pages.auth.current().user_id():
        return
    game = games.get_by_id(game_id, dbconnection=db)
    notification = 'Вас назначили ответственным на игру "{}"<br>Свяжитесь с "{}"!'
    notification = notification.format(
        modules.create_link.game(game),
        modules.create_link.user(game.created_by(True)))
    utils.spool_func(notificating.site.responsible, user_id, notification, 2,
                     game_id)
def reserve(user_id: int, game_id: int):
    with dbutils.dbopen() as db:
        game = games.get_by_id(game_id, dbconnection=db)
        if game.datetime.passed: raise bottle.HTTPError(404)
        #if not pages.auth.current().activated():
        #    return pages.PageBuilder("game", game=game, conflict=3)
        if pages.auth.current().banned():
            return pages.PageBuilder("game", game=game, conflict=2)
        if game.reserved() == 0:
            return pages.PageBuilder("game", game=game, conflict=8)
        if len(game.subscribed()) < game.capacity():
            return pages.PageBuilder("game", game=game, conflict=10)
        if user_id in set(game.reserved_people()):
            return pages.PageBuilder("game", game=game, conflict=7)
        if len(game.reserved_people()) == game.reserved():
            return pages.PageBuilder("game", game=game, conflict=9)
        games.subscribe(user_id, game_id, True, dbconnection=db)
        game = games.get_by_id(game_id, dbconnection=db)
        return pages.PageBuilder("game", game=game)
def admin_unsubscribe(game_id:int, user_id:int):
    resp = unsubscribe(user_id, game_id, suspress=True)
    if 'conflict' in resp:
        if bottle.request.is_ajax:
            return json.dumps({'error_code':resp.param('conflict')})
        return pages.templates.message('Ошибка', 'Конфликт: {}'.format(resp.param('conflict')))
    if bottle.request.is_ajax:
        return json.dumps({'error_code':0})
    game = games.get_by_id(game_id)
    notificating.site.subscribed(user_id, "Вы были отписаны от игры {}".format(create_link.game(game)), 1, game_id)
    raise bottle.redirect(pages.referer('/games/{}'.format(game_id)))
def get_subscribed(game_id: int):
    game = games.get_by_id(game_id)
    if not game: raise Error.game_not_found(game_id)
    return {
        'count':
        len(game.subscribed()),
        'users': [{
            'user_id': user.user_id(),
            'name': str(user.name)
        } for user in game.subscribed(True)]
    }
def get_report(game_id:int):
    with dbutils.dbopen() as db:
        game = games.get_by_id(game_id, dbconnection=db)
        if len(game) == 0:
            raise bottle.HTTPError(404)
        if game.created_by() != pages.auth.current().user_id() and game.responsible_user_id() != pages.auth.current().user_id() and not pages.auth.current().userlevel.admin():
            return pages.templates.permission_denied()
        if not game.datetime.passed:
            return pages.templates.message("Вы не можете отправить отчет по игре", "Игра еще не закончилась")
        return pages.PageBuilder("report", game=game, showreport=game.reported(),
                                 ask_autocreate=('ask_autocreate' in bottle.request.query and game.reported()))
def notify(game_id:int):
    with dbutils.dbopen() as db:
        game = games.get_by_id(game_id, dbconnection=db)
        db.execute("SELECT DISTINCT user_id FROM reports WHERE user_id!=0 AND status=2 AND game_id IN (SELECT game_id FROM games WHERE deleted=0 AND datetime+INTERVAL duration MINUTE < NOW() AND court_id='{}' AND sport_type='{}' AND game_type='{}')".format( # as long as my dick
            game.court_id(), game.sport_type(), game.game_type()))
        if len(db.last())==0: return json.dumps({'users':list(), 'count':0})
        users_ = users.get(list(map(lambda x: x[0], db.last())), dbconnection=db)
        users_ = list(filter(lambda x: user_visits(x, db)<3 and x.user_id() not in set(game.subscribed()), users_))
        for user in users_:
            send_notify_email(user.user_id(), game.game_id())
        ids = list(map(lambda x: x.user_id(), users_))
        return json.dumps({'count':len(ids), 'users':[[user.user_id(), str(user.name)] for user in users_]})
def get_by_id(user_id:int):
    with dbutils.dbopen() as db:
        if user_id == pages.auth.current().user_id():
            raise bottle.redirect('/profile')
        user = users.get(user_id, dbconnection=db)
        if len(user) == 0:
            raise bottle.HTTPError(404)
        page = pages.PageBuilder('profile', user=user,
                                 myfriend=users.are_friends(
                                     pages.auth.current().user_id(),
                                     user_id, dbconnection=db))
        page.add_param('user_games',
                       games.get_by_id(games.get_user_played_games(user_id, dbconnection=db), dbconnection=db))
        page.add_param('responsible_games',
                       games.get_by_id(games.get_responsible_games(user_id, dbconnection=db), dbconnection=db))
        page.add_param('organizer_games', games.get_all(dbconnection=db))
        with dbutils.dbopen(**dbutils.logsdb_connection) as logsdb:
            logsdb.execute("SELECT COUNT(DISTINCT(ip)), COUNT(ip) FROM access WHERE (path='/profile?user_id={}' or path='/profile/{}') and user_id!=0".format(user_id, user_id))
            page.add_param('views', logsdb.last()[0][1])
            page.add_param('uviews', logsdb.last()[0][0])
        return page
def unsubscribe(user_id: int, game_id: int, suspress: bool = False):
    with dbutils.dbopen() as db:
        game = games.get_by_id(game_id, dbconnection=db)
        if game.datetime.passed: raise bottle.HTTPError(404)
        if user_id not in set(game.subscribed()):
            return pages.PageBuilder("game", game=game, conflict=6)
        if not suspress and game.datetime.tommorow and game.datetime.time(
        ).hour <= 12 and datetime.datetime.now().hour >= 20:
            return pages.PageBuilder("game", game=game, conflict=11)
        games.unsubscribe(user_id, game_id, dbconnection=db)
        if datetime.datetime.now() - game.datetime() < datetime.timedelta(
                days=3):
            user = users.get(user_id,
                             dbconnection=db) if user_id != pages.auth.current(
                             ).user_id() else pages.auth.current()
            message = '{} отписался от игры "{}"'.format(
                create_link.user(user), create_link.game(game))
            utils.spool_func(notificating.site.responsible,
                             game.responsible_user_id(), message, 1, game_id)
        game = games.get_by_id(game_id, dbconnection=db)
        return pages.PageBuilder("game", game=game)
def subscribe(user_id:int, game_id:int):
    with dbutils.dbopen() as db:
        game = games.get_by_id(game_id, dbconnection=db)
        if game.datetime.passed: raise bottle.HTTPError(404)
        if pages.auth.current().banned():
            return pages.PageBuilder("game", game=game, conflict=2)
        #if not pages.auth.current().activated():
        #    return pages.PageBuilder("game", game=game, conflict=3)
        if game.capacity() > 0 and len(game.subscribed()) == game.capacity():
            return pages.PageBuilder("game", game=game, conflict=4)
        if user_id in set(game.subscribed()):
            return pages.PageBuilder("game", game=game, conflict=5)
        another_game = games.user_game_intersection(user_id, game, dbconnection=db)
        if another_game:
            return pages.PageBuilder("game", game=game, conflict=1, conflict_data=another_game)
        games.subscribe(user_id, game_id, dbconnection=db)
        if game.datetime.tommorow or game.datetime.today:
            user = users.get(user_id, dbconnection=db) if user_id!=pages.auth.current().user_id() else pages.auth.current()
            message = 'На игру "{}" записался {}'.format(create_link.game(game), create_link.user(user))
            utils.spool_func(notificating.site.responsible, game.responsible_user_id(), message, 1, game_id,)
        game = games.get_by_id(game_id, dbconnection=db)
        return pages.PageBuilder("game", game=game)
def admin_unsubscribe(game_id: int, user_id: int):
    resp = unsubscribe(user_id, game_id, suspress=True)
    if 'conflict' in resp:
        if bottle.request.is_ajax:
            return json.dumps({'error_code': resp.param('conflict')})
        return pages.templates.message(
            'Ошибка', 'Конфликт: {}'.format(resp.param('conflict')))
    if bottle.request.is_ajax:
        return json.dumps({'error_code': 0})
    game = games.get_by_id(game_id)
    notificating.site.subscribed(
        user_id, "Вы были отписаны от игры {}".format(create_link.game(game)),
        1, game_id)
    raise bottle.redirect(pages.referer('/games/{}'.format(game_id)))
def subscribe(user_id: int, game_id: int):
    with dbutils.dbopen() as db:
        game = games.get_by_id(game_id, dbconnection=db)
        if game.datetime.passed: raise bottle.HTTPError(404)
        if pages.auth.current().banned():
            return pages.PageBuilder("game", game=game, conflict=2)
        #if not pages.auth.current().activated():
        #    return pages.PageBuilder("game", game=game, conflict=3)
        if game.capacity() > 0 and len(game.subscribed()) == game.capacity():
            return pages.PageBuilder("game", game=game, conflict=4)
        if user_id in set(game.subscribed()):
            return pages.PageBuilder("game", game=game, conflict=5)
        another_game = games.user_game_intersection(user_id,
                                                    game,
                                                    dbconnection=db)
        if another_game:
            return pages.PageBuilder("game",
                                     game=game,
                                     conflict=1,
                                     conflict_data=another_game)
        games.subscribe(user_id, game_id, dbconnection=db)
        if game.datetime.tommorow or game.datetime.today:
            user = users.get(user_id,
                             dbconnection=db) if user_id != pages.auth.current(
                             ).user_id() else pages.auth.current()
            message = 'На игру "{}" записался {}'.format(
                create_link.game(game), create_link.user(user))
            utils.spool_func(
                notificating.site.responsible,
                game.responsible_user_id(),
                message,
                1,
                game_id,
            )
        game = games.get_by_id(game_id, dbconnection=db)
        return pages.PageBuilder("game", game=game)
Beispiel #28
0
def autocreate(game_id: int):
    with dbutils.dbopen() as db:
        game = games.get_by_id(game_id, dbconnection=db)
        newgame = {
            "description":
            game.description(),
            "city_id":
            game.city_id(),
            "sport_type":
            game.sport_type(),
            "game_type":
            game.game_type(),
            "court_id":
            game.court_id(),
            "duration":
            game.duration(),
            "cost":
            game.cost(),
            "capacity":
            game.capacity(),
            "responsible_user_id":
            game.responsible_user_id(),
            "created_by":
            game.created_by(),
            "reserved":
            game.reserved(),
            "datetime":
            str(game.datetime() + datetime.timedelta(days=7)).split('.')[0]
        }
        intersection = games.court_game_intersection(newgame['court_id'],
                                                     newgame['datetime'],
                                                     newgame['duration'],
                                                     dbconnection=db)
        if intersection:
            return pages.PageBuilder(
                'text',
                message='Обнаружен конфликт',
                description=
                'В это время уже идет другая <a href="/games/{}">игра</a>'.
                format(intersection))
        page = check_responsible(newgame['responsible_user_id'],
                                 newgame['datetime'], newgame['duration'], db)
        if page: return page
        game_id = games.add(dbconnection=db, **newgame)
        assigned_responsible(game_id, int(newgame['responsible_user_id']), db)
        raise bottle.redirect("/games/edit/{}".format(game_id))
def unsubscribe(game_id: int):
    with dbutils.dbopen() as db:
        user = current_user(db, detalized=True)
        game = games.get_by_id(game_id, dbconnection=db)
        if user.user_id() not in set(game.subscribed()):
            return pages.PageBuilder("game", game=game, conflict=6)
        if game.datetime.tommorow and game.datetime.time(
        ).hour <= 12 and datetime.datetime.now().hour >= 20:
            return pages.PageBuilder("game", game=game, conflict=11)
        games.unsubscribe(user.user_id(), game_id, dbconnection=db)
        if datetime.datetime.now() - game.datetime() < datetime.timedelta(
                days=3):
            user = users.get(user.user_id(), dbconnection=db) if user.user_id(
            ) != pages.auth.current().user_id() else pages.auth.current()
            message = '{} отписался от игры "{}"'.format(
                create_link.user(user), create_link.game(game))
            utils.spool_func(notificating.site.responsible,
                             game.responsible_user_id(), message, 1, game_id)
        return {'status': 'ok'}
Beispiel #30
0
def get_report(game_id: int):
    with dbutils.dbopen() as db:
        game = games.get_by_id(game_id, dbconnection=db)
        if len(game) == 0:
            raise bottle.HTTPError(404)
        if game.created_by() != pages.auth.current().user_id(
        ) and game.responsible_user_id() != pages.auth.current().user_id(
        ) and not pages.auth.current().userlevel.admin():
            return pages.templates.permission_denied()
        if not game.datetime.passed:
            return pages.templates.message(
                "Вы не можете отправить отчет по игре",
                "Игра еще не закончилась")
        return pages.PageBuilder(
            "report",
            game=game,
            showreport=game.reported(),
            ask_autocreate=('ask_autocreate' in bottle.request.query
                            and game.reported()))
Beispiel #31
0
def notify_array(game_id: int):
    with dbutils.dbopen() as db:
        game = games.get_by_id(game_id, dbconnection=db)
        db.execute(
            "SELECT DISTINCT user_id FROM reports WHERE user_id!=0 AND status=2 AND game_id IN (SELECT game_id FROM games WHERE deleted=0 AND datetime+INTERVAL duration MINUTE < NOW() AND court_id='{}' AND sport_type='{}' AND game_type='{}')"
            .format(  # as long as my dick
                game.court_id(), game.sport_type(), game.game_type()))
        if len(db.last()) == 0:
            return json.dumps({'users': list(), 'count': 0})
        users_ = users.get(list(map(lambda x: x[0], db.last())),
                           dbconnection=db)
        users_ = list(
            map(
                lambda x: {
                    'user_id': x.user_id(),
                    'name': str(x.name),
                    'visits': user_visits(x, db)
                }, users_))
        return json.dumps({'count': len(users_), 'users': users_})
Beispiel #32
0
def notify(game_id: int):
    with dbutils.dbopen() as db:
        game = games.get_by_id(game_id, dbconnection=db)
        db.execute(
            "SELECT DISTINCT user_id FROM reports WHERE user_id!=0 AND status=2 AND game_id IN (SELECT game_id FROM games WHERE deleted=0 AND datetime+INTERVAL duration MINUTE < NOW() AND court_id='{}' AND sport_type='{}' AND game_type='{}')"
            .format(  # as long as my dick
                game.court_id(), game.sport_type(), game.game_type()))
        if len(db.last()) == 0:
            return json.dumps({'users': list(), 'count': 0})
        users_ = users.get(list(map(lambda x: x[0], db.last())),
                           dbconnection=db)
        users_ = list(
            filter(
                lambda x: user_visits(x, db) < 3 and x.user_id() not in set(
                    game.subscribed()), users_))
        for user in users_:
            send_notify_email(user.user_id(), game.game_id())
        ids = list(map(lambda x: x.user_id(), users_))
        return json.dumps({
            'count':
            len(ids),
            'users': [[user.user_id(), str(user.name)] for user in users_]
        })
def post(game_id:int):
    game = games.get_by_id(game_id)
    if game.created_by() != pages.auth.current().user_id() and game.responsible_user_id() != pages.auth.current().user_id() and not pages.auth.current().userlevel.admin():
        return pages.templates.permission_denied()
    if game.reported() or game.deleted(): return pages.templates.message('Чё', 'Эээ')
    users_ = {int(user_id.split('=')[-1]): {"status": bottle.request.forms.get(user_id)} for user_id in
              filter(lambda x: x.startswith("status"), bottle.request.forms)}
    registered = {user_id: users_[user_id] for user_id in filter(lambda x: x > 0, users_)}
    unregistered = {user_id: users_[user_id] for user_id in filter(lambda x: x < 0, users_)}
    for user_id in unregistered:
        info = {key.split('=')[0]: bottle.request.forms.get(key) for key in
                filter(lambda x: x.endswith(str(user_id)), bottle.request.forms)}
        unregistered[user_id] = info
    report = dict()
    report['registered'] = {'count': len(registered), 'users': registered}
    report['unregistered'] = {'count': len(unregistered), 'users': unregistered}
    report['additional_charges'] = {int(i.split('=')[1]):(bottle.request.forms.get(i), bottle.request.forms.get('amount'+i.split('=')[1])) for i in filter(lambda x: x.startswith('description'), bottle.request.forms)}
    with dbutils.dbopen() as db:
        for user_id in report['unregistered']['users']:
            user = report['unregistered']['users'][user_id]
            name = user['first_name'].strip()+' '+user['last_name'].strip()
            reports.report_unregistered(game_id, user['status'], name, user['phone'], dbconnection=db)
        for user_id in report['registered']['users']:
            user = report['registered']['users'][user_id]
            status = user['status']
            reports.report(game_id, user_id, status, dbconnection=db)
        for n in report['additional_charges']:
            reports.report_additional_charges(game_id, *report['additional_charges'][n], dbconnection=db)
    if "photo" in bottle.request.files:
        images.save_report(game_id, bottle.request.files.get("photo"))
    if pages.auth.current().user_id() != game.created_by():
        notificating.site.responsible(game.created_by(), 'Ответственный "{}" отправил отчет по игре "{}"'.format(
            modules.create_link.user(users.get(pages.auth.current().user_id())),
            modules.create_link.game(game)), game_id)
    finances.add_game_finances(game_id, dbconnection=db)
    cacher.drop_by_table_name('games', 'game_id', game_id)
    raise bottle.redirect('/games/report/{}?ask_autocreate'.format(game_id))
def get_by_id(game_id:int):
    with dbutils.dbopen() as db:
        game = games.get_by_id(game_id, dbconnection=db)
        if len(game) == 0:
            raise bottle.HTTPError(404)
        return pages.PageBuilder('game', game=game, standalone=True)
Beispiel #35
0
def get_by_id(game_id: int):
    with dbutils.dbopen() as db:
        game = games.get_by_id(game_id, dbconnection=db)
        if len(game) == 0:
            raise bottle.HTTPError(404)
        return pages.PageBuilder('game', game=game, standalone=True)
Beispiel #36
0
def post(game_id: int):
    game = games.get_by_id(game_id)
    if game.created_by() != pages.auth.current(
    ).user_id() and game.responsible_user_id() != pages.auth.current().user_id(
    ) and not pages.auth.current().userlevel.admin():
        return pages.templates.permission_denied()
    if game.reported() or game.deleted():
        return pages.templates.message('Чё', 'Эээ')
    users_ = {
        int(user_id.split('=')[-1]): {
            "status": bottle.request.forms.get(user_id)
        }
        for user_id in filter(lambda x: x.startswith("status"),
                              bottle.request.forms)
    }
    registered = {
        user_id: users_[user_id]
        for user_id in filter(lambda x: x > 0, users_)
    }
    unregistered = {
        user_id: users_[user_id]
        for user_id in filter(lambda x: x < 0, users_)
    }
    for user_id in unregistered:
        info = {
            key.split('=')[0]: bottle.request.forms.get(key)
            for key in filter(lambda x: x.endswith(str(user_id)),
                              bottle.request.forms)
        }
        unregistered[user_id] = info
    report = dict()
    report['registered'] = {'count': len(registered), 'users': registered}
    report['unregistered'] = {
        'count': len(unregistered),
        'users': unregistered
    }
    report['additional_charges'] = {
        int(i.split('=')[1]):
        (bottle.request.forms.get(i),
         bottle.request.forms.get('amount' + i.split('=')[1]))
        for i in filter(lambda x: x.startswith('description'),
                        bottle.request.forms)
    }
    with dbutils.dbopen() as db:
        for user_id in report['unregistered']['users']:
            user = report['unregistered']['users'][user_id]
            name = user['first_name'].strip() + ' ' + user['last_name'].strip()
            reports.report_unregistered(game_id,
                                        user['status'],
                                        name,
                                        user['phone'],
                                        dbconnection=db)
        for user_id in report['registered']['users']:
            user = report['registered']['users'][user_id]
            status = user['status']
            reports.report(game_id, user_id, status, dbconnection=db)
        for n in report['additional_charges']:
            reports.report_additional_charges(game_id,
                                              *report['additional_charges'][n],
                                              dbconnection=db)
    if "photo" in bottle.request.files:
        images.save_report(game_id, bottle.request.files.get("photo"))
    if pages.auth.current().user_id() != game.created_by():
        notificating.site.responsible(
            game.created_by(),
            'Ответственный "{}" отправил отчет по игре "{}"'.format(
                modules.create_link.user(
                    users.get(pages.auth.current().user_id())),
                modules.create_link.game(game)), game_id)
    finances.add_game_finances(game_id, dbconnection=db)
    cacher.drop_by_table_name('games', 'game_id', game_id)
    raise bottle.redirect('/games/report/{}?ask_autocreate'.format(game_id))
Beispiel #37
0
def send_notify_email(user_id, game_id):
    user = users.get(user_id)
    game = games.get_by_id(game_id)
    notificating.mail.tpl.game_invite(game, user)
def send_notify_email(user_id, game_id):
    user = users.get(user_id)
    game = games.get_by_id(game_id)
    notificating.mail.tpl.game_invite(game, user)