added
This commit is contained in:
74
Lnkshrt/main/app.py
Normal file
74
Lnkshrt/main/app.py
Normal file
@@ -0,0 +1,74 @@
|
||||
from flask import Flask, render_template, request
|
||||
import os
|
||||
import re # <--- FIX 1: Added missing import
|
||||
|
||||
app = Flask(__name__)
|
||||
|
||||
# Ensure a directory exists to hold the generated links
|
||||
# This makes sure we don't clutter the root directory
|
||||
OUTPUT_DIR = "generated_links"
|
||||
if not os.path.exists(OUTPUT_DIR):
|
||||
os.makedirs(OUTPUT_DIR)
|
||||
|
||||
@app.route('/')
|
||||
def home():
|
||||
return render_template('index.html')
|
||||
|
||||
def is_valid_subdirectory(name):
|
||||
pattern = r"^[a-zA-Z0-9_-]+$"
|
||||
# Added check to ensure 'name' isn't None
|
||||
return bool(name and re.match(pattern, name))
|
||||
|
||||
def is_valid_link(url):
|
||||
pattern = r"^(https?:\/\/)?([\da-z\.-]+)\.([a-z\.]{2,6})([\/\w \.-]*)*\/?$"
|
||||
return bool(url and re.match(pattern, url.lower()))
|
||||
|
||||
def create_redirect_html(filename, target_url):
|
||||
# Ensure target_url has a protocol so the browser doesn't think it's a local file
|
||||
if not target_url.startswith(('http://', 'https://')):
|
||||
target_url = 'https://' + target_url
|
||||
|
||||
if not filename.endswith(".html"):
|
||||
filename += ".html"
|
||||
|
||||
# Save inside the output directory
|
||||
file_path = os.path.join(OUTPUT_DIR, filename)
|
||||
|
||||
html_content = f"""<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<meta http-equiv="refresh" content="0; url={target_url}">
|
||||
<title>Redirecting...</title>
|
||||
</head>
|
||||
<body>
|
||||
<p>If you are not redirected, <a href="{target_url}">click here</a>.</p>
|
||||
</body>
|
||||
</html>"""
|
||||
|
||||
try:
|
||||
with open(file_path, "w", encoding="utf-8") as file:
|
||||
file.write(html_content)
|
||||
return filename
|
||||
except Exception as e:
|
||||
print(f"An error occurred: {e}")
|
||||
return None
|
||||
|
||||
@app.route('/submit', methods=['POST'])
|
||||
def submit():
|
||||
val1 = request.form.get('first_name') # The URL
|
||||
val2 = request.form.get('second_name') # The New Name
|
||||
|
||||
# FIX 2: Validate correctly and use the right order in the function call
|
||||
if is_valid_link(val1) and is_valid_subdirectory(val2):
|
||||
# We want: create_redirect_html(filename, destination)
|
||||
generated_file = create_redirect_html(val2, val1)
|
||||
|
||||
if generated_file:
|
||||
return f"Success! Created p.wholeworldcoding.com/{generated_file}"
|
||||
else:
|
||||
return "Error: Could not write file.", 500
|
||||
else:
|
||||
return "Invalid Input! Ensure the link is valid and the page name has no slashes.", 400
|
||||
|
||||
if __name__ == '__main__':
|
||||
app.run(debug=True)
|
||||
Reference in New Issue
Block a user