def get_code(): code = bottle.request.query.code try: access_token, user_id, email = vk.auth_code(code, '/auth') except ValueError as e: return pages.PageBuilder( 'auth', error=e.vkerror['error'], error_description=e.vkerror['error_description']) with dbutils.dbopen() as db: db.execute( "SELECT email, passwd FROM users WHERE vkuserid='{}'".format( user_id)) if not email or len(db.last()) == 0: return pages.PageBuilder( 'auth', error='Ошибка авторизации', error_description="Пользователь не найден.") email = db.last()[0][0] password = db.last()[0][1] try: pages.auth.login(email, password) except ValueError: time.sleep(3) return pages.PageBuilder( 'auth', error='Ошибка авторизации', error_description='Неверный email или пароль') raise bottle.redirect('/games')
def _get_games(*args): ptype = args[0] sport_type = 0 page_n = 1 if ptype == 'all' or ptype == 'old': page_n = args[1] elif ptype == 'sport': sport_type = args[1] page_n = args[2] with dbutils.dbopen() as db: count = len( games.get_recent(sport_type=sport_type, count=slice(0, 99999), old=ptype == 'old', dbconnection=db)) # TODO: REWORK total_pages = count // GAMES_PER_PAGE + ( 1 if count % GAMES_PER_PAGE != 0 else 0) if page_n > total_pages and count > 0: if not bottle.request.is_ajax: raise bottle.HTTPError(404) else: return {"stop": True, "games": list()} sports = sport_types.get(0, dbconnection=db) if not count: if not bottle.request.is_ajax: return pages.PageBuilder("games", games=list(), sports=sports, bysport=sport_type, old=ptype == 'old', total_count=0) else: return {"stop": True, "games": list()} allgames = games.get_recent( sport_type=sport_type, old=ptype == 'old', count=slice(*modules.pager(page_n, count=GAMES_PER_PAGE)), dbconnection=db) if not bottle.request.is_ajax: return pages.PageBuilder('games', games=allgames, sports=sports, total_count=count, bysport=sport_type, old=ptype == 'old') else: data = {"stop": page_n >= total_pages, "games": list()} page = pages.PageBuilder("game", tab_name="all") for game in allgames: page.add_param("game", game) game_tpl = page.template() data["games"].append(game_tpl) return data
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 add_post(): with dbutils.dbopen() as db: params = {i: bottle.request.forms.get(i) for i in bottle.request.forms} params.pop('submit_add') params['datetime'] = params['date'] + ' ' + params['time'] + ':00' params.pop('date') params.pop('time') params['created_by'] = pages.auth.current().user_id() intersection = games.court_game_intersection( params['court_id'], params['datetime'], params['duration'].encode().split(b' ')[0].decode(), dbconnection=db) if intersection: return pages.PageBuilder( 'text', message='Обнаружен конфликт', description= 'В это время уже идет другая <a href="/games/{}">игра</a>'. format(intersection)) page = check_responsible(params['responsible_user_id'], params['datetime'], params['duration'].split(' ')[0], db) if page: return page if int(params['capacity']) > 0: params['reserved'] = round(int(params['capacity']) / 4) game_id = games.add(dbconnection=db, **params) assigned_responsible(game_id, int(params['responsible_user_id']), db) return bottle.redirect('/games/{}'.format(game_id))
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 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 index(): with dbutils.dbopen() as db: respdict = get_users(db) fin = finances.get_current_month(dbconnection=db) fin = finances.Finances(fin, db) respdict.update(get_logs(db)) return pages.PageBuilder('admin', fin=fin, **respdict)
def logs_page(): with dbutils.dbopen(**dbutils.logsdb_connection) as db: page = pages.PageBuilder('logs', logs=logs.Logs(db), prob_den=finances.probability_density()) with dbutils.dbopen() as db: dates = db.execute("SELECT regdate FROM users ORDER BY regdate ASC") page.add_param("start_date", dates[0][0]) page.add_param("end_date", dates[-1][0]) dates = list(map(lambda x: str(x[0]), dates)) dates_dict = dict() for date in dates: if date in dates_dict: dates_dict[date] += 1 else: dates_dict[date] = 1 #page.add_param("dates", dates) page.add_param("dates_dict", dates_dict) def daterange(start_date, end_date): for n in range(int((end_date - start_date).days)): yield start_date + datetime.timedelta(n) page.add_param("daterange", daterange) return page
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 add(): with dbutils.dbopen() as db: _sport_types = sport_types.get(0, dbconnection=db) _cities = cities.get(0, dbconnection=db) _court_types = court_types.get(0, dbconnection=db) return pages.PageBuilder('addcourt', sport_types=_sport_types, cities=_cities, court_types=_court_types)
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)
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'}
def get(): with dbutils.dbopen() as db: count = db.execute("SELECT COUNT(user_id) FROM users")[0][0] allusers = users.get( 0, count=slice(*modules.pager(1, count=USERS_PER_PAGE))) page = pages.PageBuilder('users', allusers=allusers, count=count) if pages.auth.loggedin(): if len(pages.auth.current().friends()) > 0: friends = pages.auth.current().friends(True) page.add_param('myfriends', friends) return page
def edit(court_id: int): with dbutils.dbopen() as db: court = courts.get(court_id, dbconnection=db) _sport_types = sport_types.get(0, dbconnection=db) _cities = cities.get(0, dbconnection=db) _court_types = court_types.get(0, dbconnection=db) return pages.PageBuilder('editcourt', sport_types=_sport_types, cities=_cities, court=court, court_types=_court_types)
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 get_blog(): with dbutils.dbopen() as db: posts = blog.get_posts() tags = blog.get_all_tags() tags_posts = list() for tag in tags: tags_posts.append( (tag, len(blog.get_posts_by_tag(tag.tag_id(), dbconnection=db)))) tags_posts = sorted(tags_posts, reverse=True, key=lambda x: x[1])[:11] # первые десять return pages.PageBuilder('blog_main', posts=posts, alltags=tags_posts)
def post(): if pages.auth.loggedin(): raise bottle.redirect('/profile') email = bottle.request.forms.email password = bottle.request.forms.password try: pages.auth.login(email, password) except ValueError: return pages.PageBuilder('auth', email=email, error='Ошибка авторизации', error_description='Неверный email или пароль') return bottle.redirect('/games')
def add(): with dbutils.dbopen() as db: _sports = 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) return pages.PageBuilder("addgame", sports=_sports, game_types=_game_types, cities=_cities, courts=_courts, responsibles=responsibles)
def get(): user_id = pages.auth.current().user_id() with dbutils.dbopen() as db: if 'deleteall' in bottle.request.query: models.notifications.delete(-user_id) raise bottle.redirect('/notifications') count = models.notifications.get_count(user_id, dbconnection=db) notifications = dict() notifications['all'] = models.notifications.get(user_id, type=0, all=count == 0, dbconnection=db) notifications['subscribed'] = models.notifications.get(user_id, type=1, all=count == 0, dbconnection=db) if pages.auth.current().userlevel.resporgadmin(): notifications['responsible'] = models.notifications.get(user_id, type=2, all=count == 0, dbconnection=db) return pages.PageBuilder("notifications", notifications=notifications, all=count == 0)
def post(): if bottle.request.is_ajax: section = bottle.request.forms.get("section") startfrom = int(bottle.request.forms.get("startfrom")) data = list() if section == 'all': with dbutils.dbopen() as db: allusers = users.get(0, count=slice(startfrom, USERS_PER_PAGE), dbconnection=db) page = pages.PageBuilder('user_row') if pages.auth.loggedin(): if len(pages.auth.current().friends()) > 0: friends = pages.auth.current().friends(True) page.add_param('myfriends', friends) for user in allusers: page.add_param('user', user) user_tpl = page.template() data.append(user_tpl) return bottle.json_dumps(data) return '' else: if 'search' in bottle.request.forms: query = bottle.request.forms.get('q') with dbutils.dbopen() as db: allusers = users.search(query, dbconnection=db) page = pages.PageBuilder( 'users', allusers=users.get(allusers, dbconnection=db), count=len(allusers), search=True, search_q=bottle.request.forms.get('q')) if pages.auth.loggedin() and len( pages.auth.current().friends()) > 0: friends = pages.auth.current().friends(True) page.add_param('myfriends', friends) return page
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 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 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 get_article(post_id: int): with dbutils.dbopen() as db: post = blog.get_post(post_id, dbconnection=db) if not post: raise bottle.HTTPError(404) tags = blog.get_all_tags(dbconnection=db) tags_posts = list() for tag in tags: tags_posts.append( (tag, len(blog.get_posts_by_tag(tag.tag_id(), dbconnection=db)))) tags_posts = sorted(tags_posts, reverse=True, key=lambda x: x[1])[:11] # первые десять seo_info = SeoInfo({ 'tplname': 'blog_post', 'keywords': post.keywords(), 'description': post.description() }) return pages.PageBuilder('blog_post', post=post, alltags=tags_posts, seo_info=seo_info)