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 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 city(city_id: int, db: dbutils.DBConnection) -> dict: city = cities.get(city_id, dbconnection=db) return { "city_id": city.city_id(), "title": city.title(), "geopoint": city.geopoint() }
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 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 edit(): with dbutils.dbopen() as db: _cities = cities.get(0, dbconnection=db) user = users.get(pages.auth.current().user_id(), dbconnection=db) _ampluas = ampluas.get(0, dbconnection=db) _ampluas = { sport_type_title: list(filter(lambda x: x.sport_type(True).title() == sport_type_title, _ampluas)) for sport_type_title in {i.sport_type(True).title() for i in _ampluas}} return pages.PageBuilder('editprofile', user=user, cities=_cities, ampluas=_ampluas, haveavatar=images.have_avatar(pages.auth.current().user_id()))
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 edit(): with dbutils.dbopen() as db: _cities = cities.get(0, dbconnection=db) user = users.get(pages.auth.current().user_id(), dbconnection=db) _ampluas = ampluas.get(0, dbconnection=db) _ampluas = { sport_type_title: list( filter( lambda x: x.sport_type(True).title() == sport_type_title, _ampluas)) for sport_type_title in {i.sport_type(True).title() for i in _ampluas} } return pages.PageBuilder('editprofile', user=user, cities=_cities, ampluas=_ampluas, haveavatar=images.have_avatar( pages.auth.current().user_id()))
def reg_post(): if pages.auth.loggedin(): raise bottle.redirect('/profile') params = {i: bottle.request.forms.get(i) for i in bottle.request.forms} _cities = cities.get(0) token = bottle.request.forms.get('token') params['email'] = activation.get(token) params.pop('token') params['token'] = token if params['bdate'] == '00.00.0000': return pages.PageBuilder( 'registration', error='Ошибка', error_description='Неверно указана дата рождения', cities=_cities, **params) params['regdate'] = str(datetime.date.today()) params['lasttime'] = str(datetime.datetime.now()) params.pop('confirm_passwd') city_title = 'Екатеринбург' # TODO #params.pop('city') if 'avatar' in bottle.request.forms: params.pop('avatar') with dbutils.dbopen() as db: db.execute( "SELECT city_id FROM cities WHERE title='{}'".format(city_title)) if len(db.last()) > 0: params['city_id'] = db.last()[0][0] else: return pages.PageBuilder( 'registration', error='Ошибка', error_description='Мы не работаем в городе {}'.format( city_title), cities=_cities, **params) try: date = params['bdate'].split('.') date.reverse() date = datetime.date(*list(map(int, date))) if date > datetime.date.today(): params.pop('bdate') return pages.PageBuilder('registration', error='Ошибка', error_description='Ты из будущего?', cities=_cities, **params) if datetime.date.today() - date < datetime.timedelta(days=2555): params.pop('bdate') return pages.PageBuilder( 'registration', error='Ошибка', error_description= 'Такой маленький, а уже пользуешься интернетом?', cities=_cities, **params) params['bdate'] = params['bdate'].split('.') params['bdate'].reverse() params['bdate'] = '-'.join(params['bdate']) except: params.pop('bdate') return pages.PageBuilder( 'registration', error='Ошибка', error_description='Ошибка преобразования даты рождения.', cities=_cities, **params) vkparams = pages.get_cookie('vkinfo', '') bottle.response.delete_cookie('vkinfo') if vkparams: vkparams = pickle.loads(vkparams) params['vkuserid'] = vkparams['vkuserid'] referer = pages.get_cookie('referer', 0) if referer: params['referer'] = referer params.pop('token') sql = 'INSERT INTO users ({dbkeylist}) VALUES ({dbvaluelist})' keylist = list(params.keys()) sql = sql.format(dbkeylist=', '.join(keylist), dbvaluelist=', '.join([ "'{}'".format(str(params[key])) for key in keylist ])) db.execute(sql) db.execute( "SELECT user_id, vkuserid, first_name, last_name, email, passwd FROM users WHERE email='{}'" .format(params['email'])) user_id = db.last()[0][0] email = db.last()[0][4] passwd = db.last()[0][5] vkuserid = db.last()[0][1] first_name = db.last()[0][2] username = db.last()[0][2] + ' ' + db.last()[0][3] if 'avatar' in bottle.request.files: images.save_avatar(user_id, bottle.request.files.get('avatar')) elif vkparams and 'vkphoto' in vkparams: images.save_avatar_from_url(user_id, vkparams['vkphoto']) if vkuserid: friends = vk.exec(None, "friends.get", user_id=vkuserid)['items'] if len(friends) > 0: friends = map(str, friends) db.execute( "SELECT user_id, first_name, last_name FROM users WHERE vkuserid IN ({})" .format(','.join(friends))) for friend in db.last(): friend_id = friend[0] friend_name = friend[1] + ' ' + friend[2] try: utils.spool_func( notificating.site.all, friend_id, 'Ваш друг <a href="/profile/{}">{}</a> зарегистрировался на сайте!' .format(user_id, username)) utils.spool_func( notificating.site.all, user_id, 'Ваш друг <a href="/profile/{}">{}</a> уже зарегистрирован на сайте.' .format(friend_id, friend_name)) except: utils.spool_func( notificating.site.all, friend_id, 'Ваш <a href="/profile/{}">друг</a> зарегистрировался на сайте!' .format(user_id)) utils.spool_func( notificating.site.all, user_id, 'Ваш <a href="/profile/{}">друг</a> уже зарегистрирован на сайте.' .format(friend_id)) users.add_friend(user_id, friend_id, dbconnection=db) users.add_friend(friend_id, user_id, dbconnection=db) activation.register(params['email'], dbconnection=db) pages.delete_cookie('referer') pages.delete_cookie('token') pages.auth.login(email, passwd) raise bottle.redirect('/profile')
def registration(): if pages.auth.loggedin(): raise bottle.redirect('/profile') if 'ref' in bottle.request.query: referer = bottle.request.query.get('ref') with dbutils.dbopen() as db: db.execute( "SELECT user_id, first_name, last_name FROM users WHERE user_id='{}'" .format(referer)) if len(db.last()) == 0: return pages.templates.message( 'Ошибка', 'Неверный реферальный код <b>{}</b>'.format(referer)) pages.set_cookie('referer', referer) raise bottle.redirect('/') if 'code' in bottle.request.query: code = bottle.request.query.get('code') _cities = cities.get(0) try: access_token, user_id, email = vk.auth_code(code, '/registration') except ValueError as e: token = pages.get_cookie('token', None) email = activation.get(token) return pages.PageBuilder( 'registration', cities=_cities, error=e.vkerror['error'], error_description=e.vkerror['error_description'], token=token, email=email) user = vk.exec( access_token, 'users.get', fields=['sex', 'bdate', 'city', 'photo_max', 'contacts'])[0] data = dict() data['vkuserid'] = user_id pickledata = {'vkuserid': user_id} data['first_name'] = user['first_name'] data['last_name'] = user['last_name'] data['sex'] = 'male' if user['sex'] == 2 else ( 'female' if user['sex'] == 1 else None) try: # dirty hack data['bdate'] = vk.convert_date( user['bdate']) if 'bdate' in user else None except: pass if 'camera' not in user['photo_max']: pickledata['vkphoto'] = user['photo_max'] data['vkphoto'] = user['photo_max'] pages.set_cookie('vkinfo', pickle.dumps(pickledata)) token = pages.get_cookie('token', None) if not token: return pages.PageBuilder('registration', cities=_cities, error='Не найден код.', **data) data['token'] = token data['email'] = activation.get(token) data = {i: data[i] for i in data if data[i]} return pages.PageBuilder('registration', cities=_cities, **data) if 'token' in bottle.request.query: token = bottle.request.query.get('token') with dbutils.dbopen() as db: try: email = activation.get(token, dbconnection=db) except ValueError: return pages.templates.message('Ошибка', 'Неверный код.') pages.set_cookie('token', token) status = activation.status(email, dbconnection=db) if status == 0: activation.activate(email, dbconnection=db) elif status == 2: return pages.PageBuilder( 'auth', error='Вы уже зарегестрированы в системе', error_description='Используйте пароль, чтобы войти', email=email) _cities = cities.get(0, dbconnection=db) return pages.PageBuilder('registration', cities=_cities, email=email, token=token) raise bottle.HTTPError(404)
def get_courts_map(): with dbutils.dbopen() as db: city = cities.get(1, dbconnection=db) courts_list = courts.get(0, city_id=city.city_id(), dbconnection=db) _games = games.get_recent(dbconnection=db) colors = [ 'redPoint', 'greenPoint', 'bluePoint', 'yellowPoint', 'orangePoint', 'darkbluePoint', 'greyPoint', 'whitePoint', 'lightbluePoint' ] court_games = { court.court_id(): list(filter(lambda x: x.court_id() == court.court_id(), _games)) for court in courts_list } _sport_types = { sport_type.title(): sport_type for court in courts_list for sport_type in court.sport_types(True) } group_string = 'createGroup("{title}", [{courts}], "default#{color}")' court_string = 'createPlacemark(new YMaps.GeoPoint({geopoint}), "{title} <br> {address}", "<a href=\'/courts/{court_id}\' target=\'_blank\'>Подробнее...</a>")' games_string = '<br><br>Ближайшие игры:' game_string = '<br>{n}. <a href=\'/games/{game_id}\' target=\'_blank\'>{datetime} | {sport_type} - {game_type}</a>' def create_group(courts: list, color_n: int, name: str) -> str: court_strings = [] for court in courts: court_string_f = court_string.format( geopoint=court.geopoint(), title='\\"'.join(court.title().split('"')), address=','.join(court.address().split(',')[-3:]), court_id=court.court_id()) if len(court_games[court.court_id()]) > 0: court_string_f = court_string_f[:-2] + games_string for n, game in enumerate(court_games[court.court_id()], 1): court_string_f += game_string.format( datetime=game.datetime.beautiful, sport_type=game.sport_type(True).title(), game_type=game.game_type(True).title(), game_id=game.game_id(), n=n) court_string_f += '")' court_string_f = court_string_f[:-1] court_string_f += ',' + ('false', 'true')[len( list( filter(lambda x: x.sport_type(True).title() == name, court_games[court.court_id()]) ) if name != 'Все' else court_games[court.court_id()]) > 0] dic = { game.sport_type(): game.sport_type(True).title() for game in court_games[court.court_id()] } court_string_f += ', [{}]'.format(','.join([ '[{}, "{}"]'.format(sport_type_id, dic[sport_type_id]) for sport_type_id in dic ])) court_string_f += ')' court_strings.append(court_string_f) return group_string.format(title=name, courts=','.join(court_strings), color=colors[color_n]) groups = [create_group(courts_list, -1, 'Все')] for n, sport_type_title in enumerate(_sport_types): sport_type = _sport_types[sport_type_title] court_list = [ court for court in courts_list if sport_type.title() in {sport_type.title() for sport_type in court.sport_types(True)} ] groups.append(create_group(court_list, n, sport_type_title)) return pages.PageBuilder('courtsmap', groups=groups, city=city)
def reg_post(): if pages.auth.loggedin(): raise bottle.redirect('/profile') params = {i: bottle.request.forms.get(i) for i in bottle.request.forms} _cities = cities.get(0) token = bottle.request.forms.get('token') params['email'] = activation.get(token) params.pop('token') params['token'] = token if params['bdate'] == '00.00.0000': return pages.PageBuilder('registration', error='Ошибка', error_description='Неверно указана дата рождения', cities=_cities, **params) params['regdate'] = str(datetime.date.today()) params['lasttime'] = str(datetime.datetime.now()) params.pop('confirm_passwd') city_title = 'Екатеринбург' # TODO #params.pop('city') if 'avatar' in bottle.request.forms: params.pop('avatar') with dbutils.dbopen() as db: db.execute("SELECT city_id FROM cities WHERE title='{}'".format(city_title)) if len(db.last()) > 0: params['city_id'] = db.last()[0][0] else: return pages.PageBuilder('registration', error='Ошибка', error_description='Мы не работаем в городе {}'.format(city_title), cities=_cities, **params) try: date = params['bdate'].split('.') date.reverse() date = datetime.date(*list(map(int, date))) if date > datetime.date.today(): params.pop('bdate') return pages.PageBuilder('registration', error='Ошибка', error_description='Ты из будущего?', cities=_cities, **params) if datetime.date.today() - date < datetime.timedelta( days=2555): params.pop('bdate') return pages.PageBuilder('registration', error='Ошибка', error_description='Такой маленький, а уже пользуешься интернетом?', cities=_cities, **params) params['bdate'] = params['bdate'].split('.') params['bdate'].reverse() params['bdate'] = '-'.join(params['bdate']) except: params.pop('bdate') return pages.PageBuilder('registration', error='Ошибка', error_description='Ошибка преобразования даты рождения.', cities=_cities, **params) vkparams = pages.get_cookie('vkinfo', '') bottle.response.delete_cookie('vkinfo') if vkparams: vkparams = pickle.loads(vkparams) params['vkuserid'] = vkparams['vkuserid'] referer = pages.get_cookie('referer', 0) if referer: params['referer'] = referer params.pop('token') sql = 'INSERT INTO users ({dbkeylist}) VALUES ({dbvaluelist})' keylist = list(params.keys()) sql = sql.format( dbkeylist=', '.join(keylist), dbvaluelist=', '.join(["'{}'".format(str(params[key])) for key in keylist])) db.execute(sql) db.execute( "SELECT user_id, vkuserid, first_name, last_name, email, passwd FROM users WHERE email='{}'".format(params['email'])) user_id = db.last()[0][0] email = db.last()[0][4] passwd = db.last()[0][5] vkuserid = db.last()[0][1] first_name = db.last()[0][2] username = db.last()[0][2] + ' ' + db.last()[0][3] if 'avatar' in bottle.request.files: images.save_avatar(user_id, bottle.request.files.get('avatar')) elif vkparams and 'vkphoto' in vkparams: images.save_avatar_from_url(user_id, vkparams['vkphoto']) if vkuserid: friends = vk.exec(None, "friends.get", user_id=vkuserid)['items'] if len(friends) > 0: friends = map(str, friends) db.execute("SELECT user_id, first_name, last_name FROM users WHERE vkuserid IN ({})".format( ','.join(friends))) for friend in db.last(): friend_id = friend[0] friend_name = friend[1] + ' ' + friend[2] try: utils.spool_func(notificating.site.all, friend_id, 'Ваш друг <a href="/profile/{}">{}</a> зарегистрировался на сайте!'.format( user_id, username)) utils.spool_func(notificating.site.all, user_id, 'Ваш друг <a href="/profile/{}">{}</a> уже зарегистрирован на сайте.'.format( friend_id, friend_name)) except: utils.spool_func(notificating.site.all, friend_id, 'Ваш <a href="/profile/{}">друг</a> зарегистрировался на сайте!'.format( user_id)) utils.spool_func(notificating.site.all, user_id, 'Ваш <a href="/profile/{}">друг</a> уже зарегистрирован на сайте.'.format( friend_id)) users.add_friend(user_id, friend_id, dbconnection=db) users.add_friend(friend_id, user_id, dbconnection=db) activation.register(params['email'], dbconnection=db) pages.delete_cookie('referer') pages.delete_cookie('token') pages.auth.login(email, passwd) raise bottle.redirect('/profile')
def registration(): if pages.auth.loggedin(): raise bottle.redirect('/profile') if 'ref' in bottle.request.query: referer = bottle.request.query.get('ref') with dbutils.dbopen() as db: db.execute("SELECT user_id, first_name, last_name FROM users WHERE user_id='{}'".format(referer)) if len(db.last())==0: return pages.templates.message('Ошибка', 'Неверный реферальный код <b>{}</b>'.format(referer)) pages.set_cookie('referer', referer) raise bottle.redirect('/') if 'code' in bottle.request.query: code = bottle.request.query.get('code') _cities = cities.get(0) try: access_token, user_id, email = vk.auth_code(code, '/registration') except ValueError as e: token = pages.get_cookie('token', None) email = activation.get(token) return pages.PageBuilder('registration', cities=_cities, error=e.vkerror['error'], error_description=e.vkerror['error_description'], token=token, email=email) user = vk.exec(access_token, 'users.get', fields=['sex', 'bdate', 'city', 'photo_max', 'contacts'])[0] data = dict() data['vkuserid'] = user_id pickledata = {'vkuserid': user_id} data['first_name'] = user['first_name'] data['last_name'] = user['last_name'] data['sex'] = 'male' if user['sex'] == 2 else ('female' if user['sex'] == 1 else None) try: # dirty hack data['bdate'] = vk.convert_date(user['bdate']) if 'bdate' in user else None except: pass if 'camera' not in user['photo_max']: pickledata['vkphoto'] = user['photo_max'] data['vkphoto'] = user['photo_max'] pages.set_cookie('vkinfo', pickle.dumps(pickledata)) token = pages.get_cookie('token', None) if not token: return pages.PageBuilder('registration', cities=_cities, error='Не найден код.', **data) data['token'] = token data['email'] = activation.get(token) data = {i: data[i] for i in data if data[i]} return pages.PageBuilder('registration', cities=_cities, **data) if 'token' in bottle.request.query: token = bottle.request.query.get('token') with dbutils.dbopen() as db: try: email = activation.get(token, dbconnection=db) except ValueError: return pages.templates.message('Ошибка', 'Неверный код.') pages.set_cookie('token', token) status = activation.status(email, dbconnection=db) if status==0: activation.activate(email, dbconnection=db) elif status==2: return pages.PageBuilder('auth', error='Вы уже зарегестрированы в системе', error_description='Используйте пароль, чтобы войти', email=email) _cities = cities.get(0, dbconnection=db) return pages.PageBuilder('registration', cities=_cities, email=email, token=token) raise bottle.HTTPError(404)