import json
from flask import (
Flask,
make_response,
redirect,
request,
jsonify,
render_template,
send_from_directory,
send_file,
)
from flask_cors import CORS
import os
import dotenv
import requests
from cloudflare import Cloudflare
import datetime
import qrcode
import re
import binascii
import base64
from ansi2html import Ansi2HTMLConverter
from functools import cache
from solders.keypair import Keypair
from solders.pubkey import Pubkey
from solana.rpc.api import Client
from solders.system_program import TransferParams, transfer
from solana.transaction import Transaction
from solders.hash import Hash
from solders.message import MessageV0
from solders.transaction import VersionedTransaction
from solders.null_signer import NullSigner
from PIL import Image
app = Flask(__name__)
CORS(app)
dotenv.load_dotenv()
handshake_scripts = ''
restricted = ["ascii"]
redirects = {
"contact":"/#contact"
}
downloads = {
"pgp": "data/nathanwoodburn.asc"
}
sites = []
if os.path.isfile("data/sites.json"):
with open("data/sites.json") as file:
sites = json.load(file)
# Remove any sites that are not enabled
sites = [
site for site in sites if "enabled" not in site or site["enabled"] == True
]
projects = []
projectsUpdated = 0
ncConfig = requests.get(
"https://cloud.woodburn.au/s/4ToXgFe3TnnFcN7/download/website-conf.json"
)
ncConfig = ncConfig.json()
@cache
def getAddress(coin: str) -> str:
address = ""
if os.path.isfile(".well-known/wallets/" + coin.upper()):
with open(".well-known/wallets/" + coin.upper()) as file:
address = file.read()
return address
def find(name, path):
for root, dirs, files in os.walk(path):
if name in files:
return os.path.join(root, name)
# Assets routes
@app.route("/assets/")
def send_report(path):
if path.endswith(".json"):
return send_from_directory(
"templates/assets", path, mimetype="application/json"
)
if os.path.isfile("templates/assets/" + path):
return send_from_directory("templates/assets", path)
# Custom matching for images
pathMap = {
"img/hns/w": "img/external/HNS/white",
"img/hns/b": "img/external/HNS/black",
"img/hns": "img/external/HNS/black",
}
for key in pathMap:
print(path, key)
if path.startswith(key):
tmpPath = path.replace(key, pathMap[key])
print(tmpPath)
if os.path.isfile("templates/assets/" + tmpPath):
return send_from_directory("templates/assets", tmpPath)
# Try looking in one of the directories
filename: str = path.split("/")[-1]
if (
filename.endswith(".png")
or filename.endswith(".jpg")
or filename.endswith(".jpeg")
or filename.endswith(".svg")
):
if os.path.isfile("templates/assets/img/" + filename):
return send_from_directory("templates/assets/img", filename)
if os.path.isfile("templates/assets/img/favicon/" + filename):
return send_from_directory("templates/assets/img/favicon", filename)
return render_template("404.html"), 404
# region Special routes
@app.route("/meet")
@app.route("/meeting")
@app.route("/appointment")
def meet():
return redirect(
"https://cloud.woodburn.au/apps/calendar/appointment/PamrmmspWJZr", code=302
)
@app.route("/links")
def links():
return render_template("link.html")
@app.route("/sitemap")
@app.route("/sitemap.xml")
def sitemap():
# Remove all .html from sitemap
with open("templates/sitemap.xml") as file:
sitemap = file.read()
sitemap = sitemap.replace(".html", "")
return make_response(sitemap, 200, {"Content-Type": "application/xml"})
@app.route("/favicon.png")
def faviconPNG():
return send_from_directory("templates/assets/img/favicon", "favicon.png")
@app.route("/favicon.svg")
def faviconSVG():
return send_from_directory("templates/assets/img/favicon", "favicon.svg")
@app.route("/favicon.ico")
def faviconICO():
return send_from_directory("templates/assets/img/favicon", "favicon.ico")
@app.route("/https.js")
@app.route("/handshake.js")
@app.route("/redirect.js")
def handshake():
# return request.path
return send_from_directory("templates/assets/js", request.path.split("/")[-1])
@app.route("/generator/")
def removeTrailingSlash():
return render_template(request.path.split("/")[-2] + ".html")
@app.route("/.well-known/wallets/")
def wallet(path):
if path[0] == ".":
return send_from_directory(
".well-known/wallets", path, mimetype="application/json"
)
elif os.path.isfile(".well-known/wallets/" + path):
address = ""
with open(".well-known/wallets/" + path) as file:
address = file.read()
address = address.strip()
return make_response(address, 200, {"Content-Type": "text/plain"})
if os.path.isfile(".well-known/wallets/" + path.upper()):
return redirect("/.well-known/wallets/" + path.upper(), code=302)
return render_template("404.html"), 404
@app.route("/.well-known/nostr.json")
def nostr():
# Get name parameter
name = request.args.get("name")
if name:
return jsonify(
{
"names": {
name: "b57b6a06fdf0a4095eba69eee26e2bf6fa72bd1ce6cbe9a6f72a7021c7acaa82"
}
}
)
return jsonify(
{
"names": {
"nathan": "b57b6a06fdf0a4095eba69eee26e2bf6fa72bd1ce6cbe9a6f72a7021c7acaa82",
"_": "b57b6a06fdf0a4095eba69eee26e2bf6fa72bd1ce6cbe9a6f72a7021c7acaa82",
}
}
)
@app.route("/.well-known/xrp-ledger.toml")
def xrpLedger():
# Create a response with the xrp-ledger.toml file
with open(".well-known/xrp-ledger.toml") as file:
toml = file.read()
response = make_response(toml, 200, {"Content-Type": "application/toml"})
# Set cors headers
response.headers["Access-Control-Allow-Origin"] = "*"
return response
@app.route("/manifest.json")
def manifest():
host = request.host
if host == "nathan.woodburn.au":
return send_from_directory("templates", "manifest.json")
# Read as json
with open("templates/manifest.json") as file:
manifest = json.load(file)
if host != "localhost:5000" and host != "127.0.0.1:5000":
manifest["start_url"] = f"https://{host}/"
else:
manifest["start_url"] = "http://127.0.0.1:5000/"
return jsonify(manifest)
# region Sol Links
@app.route("/actions.json")
def actionsJson():
return jsonify(
{"rules": [{"pathPattern": "/donate**", "apiPath": "/api/donate**"}]}
)
@app.route("/api/donate", methods=["GET", "OPTIONS"])
def donateAPI():
data = {
"icon": "https://nathan.woodburn.au/assets/img/profile.png",
"label": "Donate to Nathan.Woodburn/",
"title": "Donate to Nathan.Woodburn/",
"description": "Student, developer, and crypto enthusiast",
"links": {
"actions": [
{"label": "0.01 SOL", "href": "/api/donate/0.01"},
{"label": "0.1 SOL", "href": "/api/donate/0.1"},
{"label": "1 SOL", "href": "/api/donate/1"},
{
"href": "/api/donate/{amount}",
"label": "Donate",
"parameters": [
{"name": "amount", "label": "Enter a custom SOL amount"}
],
},
]
},
}
response = make_response(jsonify(data), 200, {"Content-Type": "application/json"})
if request.method == "OPTIONS":
response.headers["Access-Control-Allow-Origin"] = "*"
response.headers["Access-Control-Allow-Methods"] = "GET, POST, PUT, OPTIONS"
response.headers["Access-Control-Allow-Headers"] = (
"Content-Type,Authorization,Content-Encoding,Accept-Encoding"
)
return response
@app.route("/api/donate/")
def donateAmount(amount):
data = {
"icon": "https://nathan.woodburn.au/assets/img/profile.png",
"label": f"Donate {amount} SOL to Nathan.Woodburn/",
"title": "Donate to Nathan.Woodburn/",
"description": "Donate {amount} SOL to Nathan.Woodburn/",
}
return jsonify(data)
@app.route("/api/donate/", methods=["POST"])
def donateAmountPost(amount):
if not request.json:
return jsonify({"message": "Error: No JSON data provided"})
if "account" not in request.json:
return jsonify({"message": "Error: No account provided"})
sender = request.json["account"]
# Make sure amount is a number
try:
amount = float(amount)
except:
return jsonify({"message": "Error: Invalid amount"})
# Create transaction
sender = Pubkey.from_string(sender)
receiver = Pubkey.from_string("AJsPEEe6S7XSiVcdZKbeV8GRp1QuhFUsG8mLrqL4XgiU")
transfer_ix = transfer(
TransferParams(
from_pubkey=sender, to_pubkey=receiver, lamports=int(amount * 1000000000)
)
)
solana_client = Client("https://api.mainnet-beta.solana.com")
blockhashData = solana_client.get_latest_blockhash()
blockhash = blockhashData.value.blockhash
msg = MessageV0.try_compile(
payer=sender,
instructions=[transfer_ix],
address_lookup_table_accounts=[],
recent_blockhash=blockhash,
)
tx = VersionedTransaction(message=msg, keypairs=[NullSigner(sender)])
tx = bytes(tx).hex()
raw_bytes = binascii.unhexlify(tx)
base64_string = base64.b64encode(raw_bytes).decode("utf-8")
return jsonify({"message": "Success", "transaction": base64_string})
# endregion
# endregion
# region Main routes
@app.route("/")
def index():
# Check if host if podcast.woodburn.au
if "podcast.woodburn.au" in request.host:
return render_template("podcast.html")
loaded = False
if request.referrer:
# Check if referrer includes nathan.woodburn.au
if "nathan.woodburn.au" in request.referrer:
loaded = True
# Check if crawler
if request.headers:
if "Googlebot" not in request.headers.get(
"User-Agent"
) and "Bingbot" not in request.headers.get("User-Agent"):
# Check if cookie is set
if not request.cookies.get("loaded") and not loaded:
# Set cookie
resp = make_response(
render_template("loading.html").replace(
"https://nathan.woodburn.au/loading", "https://nathan.woodburn.au/"
),
200,
{"Content-Type": "text/html"},
)
resp.set_cookie("loaded", "true", max_age=604800)
return resp
global handshake_scripts
global projects
global projectsUpdated
try:
git = requests.get(
"https://git.woodburn.au/api/v1/users/nathanwoodburn/activities/feeds?only-performed-by=true&limit=1",
headers={"Authorization": os.getenv("git_token")},
)
git = git.json()
git = git[0]
repo_name = git["repo"]["name"]
repo_name = repo_name.lower()
repo_description = git["repo"]["description"]
except:
repo_name = "nathanwoodburn.github.io"
repo_description = "Personal website"
git = {
"repo": {
"html_url": "https://nathan.woodburn.au",
"name": "nathanwoodburn.github.io",
"description": "Personal website",
}
}
print("Error getting git data")
# Get only repo names for the newest updates
if projects == [] or projectsUpdated < datetime.datetime.now() - datetime.timedelta(
hours=2
):
projectsreq = requests.get(
"https://git.woodburn.au/api/v1/users/nathanwoodburn/repos"
)
projects = projectsreq.json()
# Check for next page
pageNum = 1
while 'rel="next"' in projectsreq.headers["link"]:
projectsreq = requests.get(
"https://git.woodburn.au/api/v1/users/nathanwoodburn/repos?page="
+ str(pageNum)
)
projects += projectsreq.json()
pageNum += 1
for project in projects:
if (
project["avatar_url"] == "https://git.woodburn.au/"
or project["avatar_url"] == ""
):
project["avatar_url"] = "/favicon.png"
project["name"] = project["name"].replace("_", " ").replace("-", " ")
# Sort by last updated
projectsList = sorted(projects, key=lambda x: x["updated_at"], reverse=True)
projects = []
projectNames = []
projectNum = 0
while len(projects) < 3:
if projectsList[projectNum]["name"] not in projectNames:
projects.append(projectsList[projectNum])
projectNames.append(projectsList[projectNum]["name"])
projectNum += 1
projectsUpdated = datetime.datetime.now()
custom = ""
# Check for downtime
uptime = requests.get("https://uptime.woodburn.au/api/status-page/main/badge")
uptime = uptime.content.count(b"Up") > 1
if uptime:
custom += ""
else:
custom += ""
# Special names
if repo_name == "nathanwoodburn.github.io":
repo_name = "Nathan.Woodburn/"
html_url = git["repo"]["html_url"]
repo = '' + repo_name + ""
# If localhost, don't load handshake
if (
request.host == "localhost:5000"
or request.host == "127.0.0.1:5000"
or os.getenv("dev") == "true"
or request.host == "test.nathan.woodburn.au"
):
handshake_scripts = ""
# Get time
timezone_offset = datetime.timedelta(hours=ncConfig["time-zone"])
timezone = datetime.timezone(offset=timezone_offset)
time = datetime.datetime.now(tz=timezone)
time = time.strftime("%B %d")
time += """
"
HNSaddress = getAddress("HNS")
SOLaddress = getAddress("SOL")
BTCaddress = getAddress("BTC")
ETHaddress = getAddress("ETH")
# Set cookie
resp = make_response(
render_template(
"index.html",
handshake_scripts=handshake_scripts,
HNS=HNSaddress,
SOL=SOLaddress,
BTC=BTCaddress,
ETH=ETHaddress,
repo=repo,
repo_description=repo_description,
custom=custom,
sites=sites,
projects=projects,
time=time,
message=ncConfig["message"],
),
200,
{"Content-Type": "text/html"},
)
resp.set_cookie("loaded", "true", max_age=604800)
return resp
# region Now Pages
@app.route("/now")
@app.route("/now/")
def now():
global handshake_scripts
# If localhost, don't load handshake
if (
request.host == "localhost:5000"
or request.host == "127.0.0.1:5000"
or os.getenv("dev") == "true"
or request.host == "test.nathan.woodburn.au"
):
handshake_scripts = ""
# Get latest now page
files = os.listdir("templates/now")
# Remove template
files = [file for file in files if file != "template.html" and file != "old.html"]
files.sort(reverse=True)
date = files[0].strip(".html")
# Convert to date
date = datetime.datetime.strptime(date, "%y_%m_%d")
date = date.strftime("%A, %B %d, %Y")
return render_template(
"now/" + files[0], handshake_scripts=handshake_scripts, DATE=date
)
@app.route("/now/")
def now_path(path):
global handshake_scripts
# If localhost, don't load handshake
if (
request.host == "localhost:5000"
or request.host == "127.0.0.1:5000"
or os.getenv("dev") == "true"
or request.host == "test.nathan.woodburn.au"
):
handshake_scripts = ""
date = path
date = date.strip(".html")
try:
# Convert to date
date = datetime.datetime.strptime(date, "%y_%m_%d")
date = date.strftime("%A, %B %d, %Y")
except:
date = ""
if path.lower().replace(".html", "") == "template":
return render_template("404.html"), 404
# If file exists, load it
if os.path.isfile("templates/now/" + path):
return render_template(
"now/" + path, handshake_scripts=handshake_scripts, DATE=date
)
if os.path.isfile("templates/now/" + path + ".html"):
return render_template(
"now/" + path + ".html", handshake_scripts=handshake_scripts, DATE=date
)
return render_template("404.html"), 404
@app.route("/old")
@app.route("/old/")
@app.route("/now/old")
@app.route("/now/old/")
def now_old():
global handshake_scripts
# If localhost, don't load handshake
if (
request.host == "localhost:5000"
or request.host == "127.0.0.1:5000"
or os.getenv("dev") == "true"
or request.host == "test.nathan.woodburn.au"
):
handshake_scripts = ""
now_pages = os.listdir("templates/now")
now_pages = [
page for page in now_pages if page != "template.html" and page != "old.html"
]
now_pages.sort(reverse=True)
html = '
'
latest = " (Latest)"
for page in now_pages:
link = page.strip(".html")
date = datetime.datetime.strptime(link, "%y_%m_%d")
date = date.strftime("%A, %B %d, %Y")
html += f'