def on_follow_short_link(self, request, short_id): link_target = get_url(self.redis, short_id) if not link_target: return self.error_404() increment_url(self.redis, short_id) return redirect(link_target)
def get_redirect_or_404(short_url): url = get_url(short_url) if not url: return abort(404) if not url.startswith('http'): url = 'http://' + url return redirect(url, code=301)
def catch_all(path): res = db.get_url(path) if res != 404: if res.startswith('http://') or res.startswith('https://'): return flask.redirect(res) else: return flask.redirect('http://' + res) return flask.abort(404)
def get_info_or_404(short_url): url = get_url(short_url) if not url: return abort(404) detail = {'name': short_url, 'url': url} if return_json(): return jsonify(detail) return render_template('detail.html', **detail)
def on_follow_short_link(self, request, short_id): # TODO: Достать из базы запись о ссылке по ее ид (get_url) # если такого ид в базе нет то кинуть 404 (NotFount()) # заинкрементить переход по ссылке (increment_url) link_target = get_url(self.redis, short_id) if not link_target: return NotFound() increment_url(self.redis, short_id) return redirect(link_target)
def _generate_shrinked_hash(): alphabet = string.ascii_letters + string.digits result = ''.join(secrets.choice(alphabet) for _ in range(default_length)) if db.get_url(result) is not None: result = ''.join( secrets.choice(alphabet) for _ in range(default_length)) return result
def on_follow_short_link(self, request, short_id): url = get_url(self.redis,short_id) if(not url): return NotFound() increment_url(self.redis,short_id) link_target = url return redirect(link_target)
def on_short_link_details(self, request, short_id): link_target = get_url(self.redis, short_id) if not link_target: NotFound() click_count = get_count(self.redis, short_id) return self.render_template( "short_link_details.html", link_target=link_target, short_id=short_id, click_count=click_count, )
def on_short_link_details(self, request, short_id): url = get_url(self.redis, short_id) if not url: return NotFound() click_count = get_count(self.redis, short_id) return self.render_template( "short_link_details.html", link_target=url.decode('utf-8'), short_id=short_id, click_count=click_count, )
def profile(self, trid, callback=None, _=''): if callback: cherrypy.response.headers['Content-Type']= 'text/javascript' else: cherrypy.response.headers['Content-Type']= 'application/json' url = db.get_url(trid); if url == None: ready = False url = '' else: ready = True results = { 'status' : ready, 'url' : url } return to_json(results, callback)
def on_short_link_details(self, request, short_id): # TODO: Достать из базы запись о ссылке по ее ид (get_url) # если такого ид в базе нет то кинуть 404 (NotFount()) url = get_url(self.redis, short_id) if not url: return NotFound() click_count = get_count(self.redis, short_id) link_target = "/" return self.render_template( "short_link_details.html", link_target=link_target, short_id=short_id, click_count=click_count, )
def get_url(): response = {} code = request.args.get('code') url = db.get_url(code) if url is None: response['success'] = False response['message'] = 'code could not be found' return dumps(response) response['success'] = True response['message'] = 'success' response['url'] = url return dumps(response)
def validate_name(name): from db import get_url name = name.strip() if len(name) < 2: raise ValidationError( {'name': 'Name needs to be at least 2 characters long.'}) if len(name) > 30: raise ValidationError({ 'name': 'This is supposed to be a *shortening* service. ' 'Names need to be at most 30 characters long.' }) if not re.match('^[{}]*$'.format(app.config.get('ALPHABET')), name): raise ValidationError({ 'name': 'A name may only contain the following characters: {}'.format( app.config.ALPHABET) }) if get_url(name): raise ValidationError({'name': 'Name already exists in database.'}) return name
async def callback(msg): if msg['data'].startswith('_+'): user, hash = msg['data'][2:].split('|') n = db.get_url(hash) print(msg['data'][2:]) if not n: await bot.answerCallbackQuery( msg['id'], text='Hash não encontrado...\nEssa mensagem pode ser velha', show_alert=True) else: url = n[0] if re.match( r'^(https?://)?(letras\.mus.br/|(m\.|www\.)?letras\.mus\.br/).+', url): a = await let.letra(url) elif re.match( r'^(https?://)?(musixmatch\.com/|(m\.|www\.)?musixmatch\.com/).+', url): a = await mux.letra(url) else: await bot.answerCallbackQuery(msg['id'], text=f'link inválido:\n{url}', show_alert=True) return True print(a) if 'traducao' in a: teclado = InlineKeyboardMarkup(inline_keyboard=[ [dict(text='Texto', callback_data=f'+{user}|{hash}')] + [ dict(text=a['tr_name'] or 'tradução', callback_data=f'_-{hash}') ] ]) else: teclado = InlineKeyboardMarkup(inline_keyboard=[[ dict(text='Texto', callback_data=f'+{user}|{hash}') ]]) print(n) text = '{} - {}\n{}'.format(a["musica"], a["autor"], n[1]) if 'inline_message_id' in msg: await bot.editMessageText(msg['inline_message_id'], text, reply_markup=teclado, parse_mode='markdown') else: await bot.editMessageText((msg['message']['chat']['id'], msg['message']['message_id']), text, reply_markup=teclado, parse_mode='markdown') elif msg['data'].startswith('_-'): user, hash = msg['data'][2:].split('|') n = db.get_url(hash) print(msg['data'][2:]) if not n: await bot.answerCallbackQuery( msg['id'], text='Hash não encontrado...\nEssa mensagem pode ser velha', show_alert=True) else: url = n[0] if re.match( r'^(https?://)?(letras\.mus.br/|(m\.|www\.)?letras\.mus\.br/).+', url): a = await let.letra(url) elif re.match( r'^(https?://)?(musixmatch\.com/|(m\.|www\.)?musixmatch\.com/).+', url): a = await mux.letra(url) else: await bot.answerCallbackQuery(msg['id'], text=f'link inválido:\n{url}', show_alert=True) return True if 'traducao' in a: teclado = InlineKeyboardMarkup(inline_keyboard=[ [dict(text='Texto', callback_data=f'-{user}|{hash}')] + [dict(text='Original', callback_data=f'_+{hash}')] ]) else: teclado = InlineKeyboardMarkup(inline_keyboard=[[ dict(text='Texto', callback_data=f'-{user}|{hash}') ]]) text = '{} - {}\n{}'.format(a["musica"], a["autor"], n[2]) if 'inline_message_id' in msg: await bot.editMessageText(msg['inline_message_id'], text, reply_markup=teclado, parse_mode='markdown') else: await bot.editMessageText((msg['message']['chat']['id'], msg['message']['message_id']), text, reply_markup=teclado, parse_mode='markdown') elif msg['data'].startswith('+'): user, hash = msg['data'][1:].split('|') url = db.get_url(hash) print(msg['data'][2:]) if not url: await bot.answerCallbackQuery( msg['id'], text='Hash não encontrado...\nEssa mensagem pode ser velha', show_alert=True) else: url = url[0] if re.match( r'^(https?://)?(letras\.mus.br/|(m\.|www\.)?letras\.mus\.br/).+', url): a = await let.letra(url) elif re.match( r'^(https?://)?(musixmatch\.com/|(m\.|www\.)?musixmatch\.com/).+', url): a = await mux.letra(url) else: await bot.answerCallbackQuery(msg['id'], text=f'link inválido:\n{url}', show_alert=True) return True if 'traducao' in a: teclado = InlineKeyboardMarkup(inline_keyboard=[[ dict(text='Telegra.ph', callback_data=f'_+{user}|{hash}') ] + [ dict(text=a['tr_name'] or 'tradução', callback_data=f'-{hash}') ]]) else: teclado = InlineKeyboardMarkup(inline_keyboard=[[ dict(text='Telegra.ph', callback_data=f'_+{user}|{hash}') ]]) text = '[{} - {}]({})\n{}'.format(a["musica"], a["autor"], a['link'], a['letra']) if 'inline_message_id' in msg: await bot.editMessageText(msg['inline_message_id'], text, reply_markup=teclado, parse_mode='markdown', disable_web_page_preview=True) else: await bot.editMessageText((msg['message']['chat']['id'], msg['message']['message_id']), text, reply_markup=teclado, parse_mode='markdown', disable_web_page_preview=True) elif msg['data'].startswith('-'): user, hash = msg['data'][1:].split('|') url = db.get_url(hash) print(msg['data'][2:]) if not url: await bot.answerCallbackQuery( msg['id'], text='Hash não encontrado...\nEssa mensagem pode ser velha', show_alert=True) else: url = url[0] if re.match( r'^(https?://)?(letras\.mus.br/|(m\.|www\.)?letras\.mus\.br/).+', url): a = await let.letra(url) elif re.match( r'^(https?://)?(musixmatch\.com/|(m\.|www\.)?musixmatch\.com/).+', url): a = await mux.letra(url) else: await bot.answerCallbackQuery(msg['id'], text=f'link inválido:\n{url}', show_alert=True) return True if 'traducao' in a: teclado = InlineKeyboardMarkup(inline_keyboard=[[ dict(text='Telegra.ph', callback_data=f'_-{user}|{hash}') ] + [dict(text='Original', callback_data=f'+{hash}')]]) else: teclado = InlineKeyboardMarkup(inline_keyboard=[[ dict(text='Telegra.ph', callback_data=f'_-{user}|{hash}') ]]) text = '[{} - {}]({})\n{}'.format(a["musica"], a["autor"], a['link'], a['traducao']) if 'inline_message_id' in msg: await bot.editMessageText(msg['inline_message_id'], text, reply_markup=teclado, parse_mode='markdown', disable_web_page_preview=True) else: await bot.editMessageText((msg['message']['chat']['id'], msg['message']['message_id']), text, reply_markup=teclado, parse_mode='markdown', disable_web_page_preview=True)
def redirect_shrinked_hash(shrinked_hash: str): # Check if shrinked_hash is legal if not _validate_hash(shrinked_hash): return None return db.get_url(shrinked_hash)
def on_follow_short_link(self, request, short_id): link_target = get_url(self.redis, short_id) if not link_target: return NotFound() increment_url(self.redis, short_id) return redirect(link_target.decode('utf-8'))