|
| 1 | +from flask import Flask, request, render_template, redirect, flash |
| 2 | +from helpers import random_string_generator, random_string_generator_only_alpha, is_valid_url |
| 3 | +from db import url_data_collection |
| 4 | +import os |
| 5 | +from datetime import datetime |
| 6 | + |
| 7 | + |
| 8 | +app = Flask(__name__) |
| 9 | +app.secret_key = os.environ['APP_SECRET'] |
| 10 | + |
| 11 | +url_ = os.environ['APP_URL'] |
| 12 | + |
| 13 | +reserved_keywords = ['login', 'logout', 'shorten-url'] |
| 14 | + |
| 15 | + |
| 16 | +@app.route("/", methods = ['GET']) |
| 17 | +def start(): |
| 18 | + return render_template("index.html") |
| 19 | + |
| 20 | +@app.route("/shorten-url", methods=['POST']) |
| 21 | +def shorten_url(): |
| 22 | + data = request.form |
| 23 | + url_input = data.get("url_input") |
| 24 | + data_id = random_string_generator_only_alpha(10) |
| 25 | + if not is_valid_url(str(url_input)): |
| 26 | + flash({'type':'error', 'data':"Inavlid URL"}) |
| 27 | + return redirect("/") |
| 28 | + random_slug = random_string_generator(7) |
| 29 | + shortened_url = f"{url_}/{random_slug}" |
| 30 | + shortened_url_ = shortened_url[len(url_)+1:] |
| 31 | + if shortened_url == url_input: |
| 32 | + flash({'type':'error', 'data':"Infinite Redirect Error!"}) |
| 33 | + return redirect("/") |
| 34 | + first_keyword = shortened_url_.split("/")[0] |
| 35 | + if first_keyword in reserved_keywords: |
| 36 | + flash({'type':'error', 'data':f"{first_keyword} is a reserved keyword! Please use any other word!"}) |
| 37 | + return redirect("/") |
| 38 | + incoming_data = { |
| 39 | + "no_of_/": shortened_url_.count("/"), |
| 40 | + "order": shortened_url_.split("/"), |
| 41 | + "redirect_url": url_input, |
| 42 | + "shortened_url": shortened_url, |
| 43 | + "data_id": data_id, |
| 44 | + "created_at": datetime.now() |
| 45 | + } |
| 46 | + if url_details := url_data_collection.find_one({"no_of_/": incoming_data['no_of_/'], "order":incoming_data['order']}): |
| 47 | + flash({'type':'error', 'data':"This Domain is Already Taken!"}) |
| 48 | + return redirect("/") |
| 49 | + url_data_collection.insert_one(incoming_data) |
| 50 | + flash({'type':'data', 'data':shortened_url}) |
| 51 | + return redirect("/") |
| 52 | + |
| 53 | + |
| 54 | +@app.before_request |
| 55 | +def before_request_func(): |
| 56 | + host_url = request.host_url |
| 57 | + url = request.url |
| 58 | + url = url[len(host_url):] |
| 59 | + incoming_data = { |
| 60 | + "no_of_/":url.count("/"), |
| 61 | + "order":url.split("/") |
| 62 | + } |
| 63 | + if url_details := url_data_collection.find_one({"no_of_/": incoming_data['no_of_/'], "order":incoming_data['order']}): |
| 64 | + redirect_url = url_details.get("redirect_url") |
| 65 | + return redirect(redirect_url) |
0 commit comments