From c1c5883a56624cb9eded4ee08d3b201787e4c7c1 Mon Sep 17 00:00:00 2001 From: Manuel Vergara Date: Tue, 27 Feb 2024 23:20:35 +0100 Subject: [PATCH] Add link shortener --- catch-all/04_acortador_url/acortar.py | 107 ++++++++++++++++++++++++ catch-all/04_acortador_url/app.py | 32 +++++++ catch-all/04_acortador_url/codigos.json | 22 +++++ 3 files changed, 161 insertions(+) create mode 100644 catch-all/04_acortador_url/acortar.py create mode 100644 catch-all/04_acortador_url/app.py create mode 100644 catch-all/04_acortador_url/codigos.json diff --git a/catch-all/04_acortador_url/acortar.py b/catch-all/04_acortador_url/acortar.py new file mode 100644 index 0000000..d1fc7d6 --- /dev/null +++ b/catch-all/04_acortador_url/acortar.py @@ -0,0 +1,107 @@ +""" +Acortador de enlaces +""" + +import argparse +import json +import regex +import secrets +import string +import signal +import sys + +from termcolor import colored + + +def signal_handler(sig, frame): + + print(colored('\n[!] Saliendo...', 'red')) + sys.exit(0) + + +signal.signal(signal.SIGINT, signal_handler) + + +def generar_codigo(): + + # Definir caracteres para cadena aleatoria + alfanumerica = string.ascii_letters + string.digits + + # Generar cadena aleatoria + codigo = ''.join(secrets.choice(alfanumerica) for i in range(8)) + + return codigo + + +def acortar_url(url): + + codigo = generar_codigo() + data = [] + + with open('codigos.json', 'r') as f: + + data = json.load(f) + + codigo_existe = any(item['codigo'] == codigo for item in data) + + if codigo_existe: + codigo = generar_codigo() + + with open('codigos.json', 'w') as f: + + data.append( + { + 'codigo': codigo, + 'url': f"http://localhost:5000/{codigo}", + 'redireccion': url, + } + ) + + json.dump(data, f, indent=4) + + +def comprobar_url(url): + + # Comprobar si la URL tiene http o https + if not url.startswith('http://') and not url.startswith('https://'): + url = f'https://{url}' + + if url.endswith('/'): + url = url[:-1] + + # Comprobar formato de URL con los patrones + if regex.match(r'^https?://[\w.-]+\.[\w.-]+(/[\w.-]+)*$', url): + + return url + + else: + + raise ValueError(colored('URL no válida', 'red')) + + +def main(): + + try: + parser = argparse.ArgumentParser(description='Acortador de URL') + parser.add_argument('-u', '--url', help='URL a acortar') + args = parser.parse_args() + url = args.url + + if not url: + + url = input(colored('Introduce la URL a acortar: ', 'cyan')) + + url = comprobar_url(url) + + acortar_url(url) + + except argparse.ArgumentError as e: + print(colored(f'[!] Error en los argumentos: {e}', 'red')) + + except Exception as e: + print(colored(f'[!] Error en la ejecución principal: {e}', 'red')) + + +if __name__ == "__main__": + + main() diff --git a/catch-all/04_acortador_url/app.py b/catch-all/04_acortador_url/app.py new file mode 100644 index 0000000..d1e8ec6 --- /dev/null +++ b/catch-all/04_acortador_url/app.py @@ -0,0 +1,32 @@ +""" +Redirecciona a una URL a partir de un código +""" + +import os +from flask import Flask, redirect +import json + +app = Flask(__name__) + + +@app.route('/') +def redireccion(codigo: str): + + data = [] + + with open('codigos.json', 'r') as f: + + data = json.load(f) + + r = list(filter(lambda x: x['codigo'] == codigo, data)) + + if r: + return redirect(r[0]['redireccion'], code=302) + + return { + 'message': 'Código no encontrado' + } + +if __name__ == "__main__": + + app.run(host="0.0.0.0", port=5000, debug=True) diff --git a/catch-all/04_acortador_url/codigos.json b/catch-all/04_acortador_url/codigos.json new file mode 100644 index 0000000..6cb4422 --- /dev/null +++ b/catch-all/04_acortador_url/codigos.json @@ -0,0 +1,22 @@ +[ + { + "codigo": "", + "url": "", + "redireccion": "" + }, + { + "codigo": "NA1w9oky", + "url": "http://localhost:5000/NA1w9oky", + "redireccion": "https://vergaracarmona.es" + }, + { + "codigo": "XuI6ysnl", + "url": "http://localhost:5000/XuI6ysnl", + "redireccion": "https://www.linkedin.com/in/manu-vergara" + }, + { + "codigo": "uMsW2vzQ", + "url": "http://localhost:5000/uMsW2vzQ", + "redireccion": "https://gitea.vergaracarmona.es/manudocker" + } +] \ No newline at end of file