def get_pr_by_cat(cat, tm): sql = 'SELECT channel FROM programme WHERE pstart < ? AND pstop > ? AND ' if cat == 'Пусто': res = get_db(epg=True).execute((sql + 'cat IS NULL'), (tm, tm)).fetchall() else: res = get_db(epg=True).execute((sql + 'cat = ?'), (tm, tm, cat)).fetchall() if not res: print('Nothing') pr = [r['channel'] for r in res] return pr
def register(): if request.method == 'POST': username = request.form['username'] password = request.form['password'] db = get_db() error = None if not username: error = _('Username is required.') elif not password: error = _('Password is required.') elif db.execute( 'SELECT id FROM user WHERE username = ?', (username,) ).fetchone() is not None: #error = _('User {} is already registered.'.format(username)) error = _('User is already registered.') if error is None: db.execute( 'INSERT INTO user (username, password) VALUES (?, ?)', (username, generate_password_hash(password)) ) db.commit() return redirect(url_for('auth.login')) flash(error) return render_template('auth/register.html')
def google(): secrets = get_db().execute( "SELECT * FROM secrets WHERE title = 'Google'" ).fetchone() mdata = { 'response_type' : 'code', 'client_id' : secrets['client_id'], 'client_secret' : secrets['client_secret'], 'redirect_uri' : secrets['redirect_uri'], 'scope' : 'https://www.googleapis.com/auth/userinfo.email', 'grant_type': 'authorization_code' } if 'code' not in request.args: #print(mdata['redirect_uri']) auth_uri = ('https://accounts.google.com/o/oauth2/v2/auth?response_type={}&client_id={}&redirect_uri={}&scope={}'. format(mdata['response_type'], mdata['client_id'], mdata['redirect_uri'], mdata['scope'])) return redirect(auth_uri) else: mdata['code'] = request.args.get('code') #print(mdata['code']) mdata.pop('response_type', None) r = requests.post('https://oauth2.googleapis.com/token', data=mdata) tok = r.json()['access_token'] #print(tok) headers = {'Authorization' : 'Bearer {}'.format(tok)} #print(headers) r = requests.get('https://www.googleapis.com/oauth2/v3/userinfo', headers=headers) return process_email(r.json()['email'])
def yandex(): secrets = get_db().execute( "SELECT * FROM secrets WHERE title = 'Yandex'" ).fetchone() mdata = { 'grant_type' : 'authorization_code', 'client_id' : secrets['client_id'], 'client_secret' : secrets['client_secret'], 'redirect_uri' : secrets['redirect_uri'] } if 'code' not in request.args : auth_uri = ("https://oauth.yandex.ru/authorize?response_type=code&client_id={}&redirect_uri={}". format(mdata['client_id'], mdata['redirect_uri'])) return redirect(auth_uri) else : mdata['code'] = request.args['code'] mdata.pop('redirect_uri', None) r = requests.post('https://oauth.yandex.ru/token', data = mdata) #print(r.json()) if 'access_token' in r.json() : tok = r.json()['access_token'] r = requests.get('https://login.yandex.ru/info', params = { "oauth_token" : tok }) #print(r.json()) return process_email(r.json()['emails'][0]) return redirect(url_for('m3u'))
def load_logged_in_user(): user_id = session.get('user_id') if user_id is None: g.user = None else: g.user = get_db().execute( 'SELECT * FROM user WHERE id = ?', (user_id,) ).fetchone()
def m3u_download(filename): id = filename[:filename.find('_')] post = get_db().execute('SELECT list FROM m3u WHERE author_id = ?',(id,)).fetchone() if os.path.exists(post['list']) : pos = post['list'].rfind('/') fp = post['list'][:pos] fn = post['list'][pos+1:] return send_from_directory(os.path.abspath(fp), fn, as_attachment=True) else : return abort(404,_("File must be saved"))
def update_telebot_db(chat_id, first_name, shift): if type(chat_id) is int: tbl = 'telebot' else: tbl = 'telebot_s' db = get_db(telebot=True) sql = f'SELECT first_name, shift FROM {tbl} WHERE chat_id = ?' res = db.execute(sql, (chat_id, )).fetchone() if res: sql = f'UPDATE {tbl} SET first_name = ?, shift = ? WHERE chat_id = ?' db.execute(sql, (first_name, shift, chat_id)) else: sql = f'INSERT INTO {tbl} VALUES ( ?, ?, ?)' db.execute(sql, (chat_id, first_name, shift)) db.commit()
def process_email(email) : db = get_db() user = db.execute('SELECT * FROM user WHERE username = ?', (email,)).fetchone() if user is not None : session.clear() session['user_id'] = user['id'] return redirect(url_for('m3u')) else : db.execute( 'INSERT INTO user (username, password) VALUES (?, ?)', (email, generate_password_hash(gen_pswd())) ) db.commit() flash(_('Your registred. Please log in.')) return render_template('auth/login.html')
def get_programme(chat_id, prm, tm): sql = ('SELECT pstart, pstop, title, pdesc FROM programme ' 'WHERE channel = ? AND pstart < ? AND pstop > ? ') res = get_db(epg=True).execute(sql, (prm, tm, tm)).fetchone() pr = [] if not res: pr.append('************************************') pr.append('К сожалению,') pr.append('************************************') pr.append('программа прередач отсутствует.') pr.append('************************************') else: pr.append(prm) pr.append(res['pstart']) pr.append(res['pstop']) pr.append(res['title']) if res['pdesc']: pr.append(res['pdesc']) else: pr.append('Содержание отсутствует') return pr
def m3u_select(): data = request.get_json() nm, shft = subs_name(data['name'].lower()) st = data['date'] date = datetime(int(st[:4]), int(st[5:7]), int(st[8:10]), int(st[11:13]) + shft, int(st[14:16]), int(st[17:19])) res = get_db(epg=True).execute( 'SELECT pstart, pstop, title, pdesc ' ' FROM programme p JOIN channel c ON p.channel = c.ch_id ' ' WHERE disp_name_l = ? AND pstart < ? AND pstop > ? ORDER BY pstart', (nm,date,date) ).fetchone() jsn = {} if res: jsn['start'] = (res['pstart'] - timedelta(hours=shft)).strftime("%Y-%m-%dT%H:%M:%S.%fZ") jsn['stop'] = (res['pstop'] - timedelta(hours=shft)).strftime("%Y-%m-%dT%H:%M:%S.%fZ") jsn['title'] = res['title'] jsn['desc'] = res['pdesc'] else: jsn['start'] = jsn['stop'] = jsn['title'] = jsn['desc'] ='' return json.dumps(jsn)
def m3u_save(): db = get_db() post = db.execute('SELECT list FROM m3u WHERE author_id = ?',(g.user['id'],)).fetchone() if post : if post['list'] == "" : rnd = ''.join(random.choice(string.ascii_letters) for i in range(5)) f_n = str(g.user['id']) + rnd + "_playlist.m3u8" f_name = current_app.instance_path + "/u_fls/" + f_n db.execute('UPDATE m3u SET title = ?, list = ? WHERE id = ?',("You m3u", f_name, g.user['id'])) db.commit() else : f_name = post['list'] f_n = f_name[f_name.rfind('/')+1:] else : return "*****" data = request.get_json() f = open(f_name,'w') f.write("#EXTM3U\n") for dt in data : f.write("#EXTINF:-1 ,{}\n".format(dt.rstrip('\n'))) f.write("{}\n".format(data[dt].rstrip('\n'))) f.close() return f_n
def get_m3u(id = None) : if not id : g.m3u = M3Uclass.M3U(empty=True) g.resm3u = M3Uclass.M3U(empty=True) return if 'm3u' not in g : g.m3u = M3Uclass.M3U(empty=True) if 'resm3u' in g : return db = get_db() post = db.execute('SELECT list FROM m3u WHERE author_id = ?',(id,)).fetchone() if post : f_name = post['list'] if (f_name and os.path.exists(f_name)) : with open(f_name) as f : lines = f.readlines() g.resm3u = M3Uclass.M3U(lines) else : g.resm3u = M3Uclass.M3U(empty=True) else : db.execute('INSERT INTO m3u (title, list, author_id) VALUES (?, ?, ?)',("Your list", "", g.user['id'])) db.commit() g.resm3u = M3Uclass.M3U(empty=True)
def login(): if request.method == 'POST': username = request.form['username'] password = request.form['password'] db = get_db() error = None user = db.execute( 'SELECT * FROM user WHERE username = ?', (username,) ).fetchone() if user is None: error = _('Incorrect username.') elif not check_password_hash(user['password'], password): error = _('Incorrect password.') if error is None: session.clear() session['user_id'] = user['id'] return redirect(url_for('m3u')) flash(error) return render_template('auth/login.html')
def get_pr_by_letters(str): sql = 'SELECT ch_id FROM channel WHERE disp_name_l LIKE ? ' ptrn = f'%{str.lower()}%' res = get_db(epg=True).execute(sql, (ptrn, )).fetchall() pr = [r['ch_id'] for r in res] return pr
def get_pr_cat(): res = get_db( epg=True).execute('SELECT DISTINCT cat FROM programme').fetchall() cat = [r['cat'] for r in res] return cat
def send_message(chat_id, lst, tp): method = "sendMessage" with open(current_app.instance_path + '/teletoken') as f: token = f.readline()[:-1] url = f"https://api.telegram.org/bot{token}/{method}" if tp == 1 or tp == 2 or tp == 5: reply_markup = {} l0 = [] l1 = [] i = 1 text = '' for l in lst: if i % 8 == 0: l1.append(l0) reply_markup['inline_keyboard'] = l1 r_m = json.dumps(reply_markup) data = {"chat_id": chat_id, "text": text, "reply_markup": r_m} requests.post(url, data=data) text = '' l0.clear() l1.clear() if l == None: s = 'Пусто' else: s = l if tp == 2: sql = 'SELECT disp_name FROM channel WHERE ch_id = ?' res = get_db(epg=True).execute(sql, (s, )).fetchone() s = res['disp_name'] text += f"{i}. {s}.\n" if tp == 1: s = '$' + s # category if tp == 5: s = '#' + s # location if tp == 2: s = l l0.append({'text': str(i), 'callback_data': s}) i += 1 l1.append(l0) reply_markup['inline_keyboard'] = l1 r_m = json.dumps(reply_markup) data = {"chat_id": chat_id, "text": text, "reply_markup": r_m} elif tp == 3: if type(chat_id) is int: tbl = 'telebot' else: tbl = 'telebot_s' sql = f'SELECT shift FROM {tbl} WHERE chat_id = ?' res = get_db(telebot=True).execute(sql, (chat_id, )).fetchone() if res: period = ( (lst[1] + timedelta(minutes=res['shift'])).strftime("%H:%M") + ' - ' + (lst[2] + timedelta(minutes=res['shift'])).strftime("%H:%M")) else: period = lst[1].strftime("%H:%M") + ' - ' + lst[2].strftime( "%H:%M") + 'UTC' sql = 'SELECT disp_name FROM channel WHERE ch_id = ?' rs = get_db(epg=True).execute(sql, (lst[0], )).fetchone() text = '<b>' + rs[ 'disp_name'] + '\n</b>' + '<i>' + period + '\n</i>' + '<b><i>' + lst[ 3] + '\n</i></b>' + lst[4] + '\n' reply_markup = ({ 'inline_keyboard': [[{ 'text': '<<', 'callback_data': f"<{lst[0]};{lst[1]}" }, { 'text': '==', 'callback_data': lst[0] }, { 'text': '>>', 'callback_data': f">{lst[0]};{lst[2]}" }]] }) r_m = json.dumps(reply_markup) data = { "chat_id": chat_id, "text": text, 'parse_mode': 'HTML', "reply_markup": r_m } elif tp == 4: text = '' for l in lst: text += l + '\n' data = {'chat_id': chat_id, 'text': text} requests.post(url, data=data)