800 lines
29 KiB
Python
800 lines
29 KiB
Python
from flask import Flask, make_response, redirect, request, jsonify, render_template, send_from_directory, send_file
|
|
import os
|
|
import dotenv
|
|
import requests
|
|
import datetime
|
|
import json
|
|
import render
|
|
import payments
|
|
import threading
|
|
import account
|
|
import qrcode
|
|
import nextcloud
|
|
from io import BytesIO
|
|
from werkzeug.middleware.proxy_fix import ProxyFix
|
|
|
|
app = Flask(__name__)
|
|
app.wsgi_app = ProxyFix(app.wsgi_app, x_proto=1, x_host=1)
|
|
dotenv.load_dotenv()
|
|
|
|
# Exchange cache
|
|
exchange = {
|
|
'timestamp': 0,
|
|
'rate': 0
|
|
}
|
|
|
|
DEV = os.getenv('DEV', 'false').lower() in ['true', '1', 'yes']
|
|
tlds = ['australia', 'newzealand']
|
|
|
|
#Assets routes
|
|
@app.route('/assets/<path:path>')
|
|
def send_report(path):
|
|
return send_from_directory('templates/assets', path)
|
|
|
|
@app.route('/sitemap')
|
|
@app.route('/sitemap.xml')
|
|
@app.route('/ownthedot/sitemap')
|
|
@app.route('/ownthedot/sitemap.xml')
|
|
@app.route('/articles/sitemap.xml')
|
|
@app.route('/articles/sitemap')
|
|
def sitemap():
|
|
if is_ownthedot() or request.path.startswith('/ownthedot/sitemap') or request.path.startswith('/articles/sitemap'):
|
|
try:
|
|
sitemap_xml = nextcloud.nextcloud_provider.generate_sitemap("https://ownthedot.com")
|
|
return make_response(sitemap_xml, 200, {'Content-Type': 'application/xml; charset=utf-8'})
|
|
except nextcloud.NextcloudConnectionError as e:
|
|
return make_response(f"<!-- Nextcloud Connection Error: {e} -->", 503, {'Content-Type': 'text/plain'})
|
|
|
|
# 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('/robots.txt')
|
|
@app.route('/ownthedot/robots.txt')
|
|
def robots():
|
|
sitemap_url = 'https://ownthedot.com/sitemap.xml' if is_ownthedot() or request.path.startswith('/ownthedot') else 'https://hns.au/sitemap.xml'
|
|
return make_response(f"User-agent: *\nAllow: /\nSitemap: {sitemap_url}\n", 200, {'Content-Type': 'text/plain'})
|
|
|
|
@app.route('/favicon.png')
|
|
def faviconPNG():
|
|
if is_ownthedot():
|
|
try:
|
|
site_config = nextcloud.nextcloud_provider.get_site_config()
|
|
custom_favicon = site_config.get('favicon')
|
|
if custom_favicon and custom_favicon.startswith('/assets/'):
|
|
rel_path = custom_favicon.replace('/assets/', '', 1)
|
|
return send_from_directory('templates/assets', rel_path)
|
|
except Exception:
|
|
pass
|
|
return send_from_directory('templates/assets/img', 'favicon.png')
|
|
|
|
@app.route('/favicon.ico')
|
|
def faviconICO():
|
|
if is_ownthedot():
|
|
try:
|
|
site_config = nextcloud.nextcloud_provider.get_site_config()
|
|
custom_favicon = site_config.get('favicon')
|
|
if custom_favicon and custom_favicon.startswith('/assets/'):
|
|
rel_path = custom_favicon.replace('/assets/', '', 1)
|
|
return send_from_directory('templates/assets', rel_path, mimetype='image/png')
|
|
except Exception:
|
|
pass
|
|
return send_from_directory('templates/assets/img', 'favicon.png', mimetype='image/png')
|
|
|
|
@app.route('/https.js')
|
|
@app.route('/handshake.js')
|
|
@app.route('/redirect.js')
|
|
def handshake():
|
|
# return request.path
|
|
return send_from_directory('templates/', request.path.split('/')[-1])
|
|
|
|
@app.route('/.well-known/wallets/<path:path>')
|
|
def wallet(path):
|
|
return send_from_directory('templates/.well-known/wallets', path, mimetype='text/plain')
|
|
|
|
|
|
|
|
# Special routes
|
|
@app.route('/email')
|
|
def email():
|
|
return redirect('mailto:hns@hns.au')
|
|
|
|
@app.route('/pins')
|
|
def pins():
|
|
global exchange
|
|
|
|
year = datetime.datetime.now().year
|
|
# Get current exchange rate if not in cache
|
|
if exchange['timestamp'] < datetime.datetime.now().timestamp() - 3600:
|
|
response = requests.get('https://api.coingecko.com/api/v3/simple/price?ids=handshake&vs_currencies=usd')
|
|
exchange['rate'] = response.json()['handshake']['usd']
|
|
exchange['timestamp'] = datetime.datetime.now().timestamp()
|
|
|
|
hns_45 = 45 / exchange['rate']
|
|
hns_30 = 30 / exchange['rate']
|
|
hns_50 = 50 / exchange['rate']
|
|
|
|
# Round to the nearest 5 HNS and add commas
|
|
hns_45 = int(hns_45 / 5) * 5
|
|
hns_30 = int(hns_30 / 5) * 5
|
|
hns_50 = int(hns_50 / 5) * 5
|
|
|
|
hns_45 = "{:,}".format(hns_45)
|
|
hns_30 = "{:,}".format(hns_30)
|
|
hns_50 = "{:,}".format(hns_50)
|
|
|
|
|
|
return render_template('pins.html', year=year, hns_45=hns_45, hns_30=hns_30,hns_50=hns_50)
|
|
|
|
@app.route('/pins/<path:path>')
|
|
def pins_redirect(path):
|
|
global exchange
|
|
|
|
if not os.path.isfile('templates/pins/'+path + ".html"):
|
|
return render_template('404.html'), 404
|
|
|
|
year = datetime.datetime.now().year
|
|
# Get current exchange rate if not in cache
|
|
if exchange['timestamp'] < datetime.datetime.now().timestamp() - 3600:
|
|
response = requests.get('https://api.coingecko.com/api/v3/simple/price?ids=handshake&vs_currencies=usd')
|
|
exchange['rate'] = response.json()['handshake']['usd']
|
|
exchange['timestamp'] = datetime.datetime.now().timestamp()
|
|
|
|
hns_45 = 45 / exchange['rate']
|
|
hns_30 = 30 / exchange['rate']
|
|
hns_50 = 50 / exchange['rate']
|
|
|
|
# Round to the nearest 5 HNS and add commas
|
|
hns_45 = int(hns_45 / 5) * 5
|
|
hns_30 = int(hns_30 / 5) * 5
|
|
hns_50 = int(hns_50 / 5) * 5
|
|
|
|
hns_45 = "{:,}".format(hns_45)
|
|
hns_30 = "{:,}".format(hns_30)
|
|
hns_50 = "{:,}".format(hns_50)
|
|
return render_template('pins/'+path + ".html", year=year, hns_45=hns_45, hns_30=hns_30,hns_50=hns_50)
|
|
|
|
@app.route('/pins/order/<path:path>')
|
|
def pins_order(path):
|
|
if not os.path.isfile('templates/pins/'+path + ".html"):
|
|
return render_template('404.html'), 404
|
|
|
|
# Get cookies
|
|
cookies = request.cookies
|
|
if 'cart' in cookies:
|
|
cart = cookies['cart']
|
|
else:
|
|
cart = '[]'
|
|
|
|
cart = json.loads(cart)
|
|
item = {
|
|
'name': path,
|
|
'quantity': 1
|
|
}
|
|
for i in range(len(cart)):
|
|
if cart[i]['name'] == path:
|
|
cart[i]['quantity'] += 1
|
|
item = None
|
|
break
|
|
|
|
if item:
|
|
cart.append(item)
|
|
cart = json.dumps(cart)
|
|
|
|
response = make_response(redirect('/cart'))
|
|
response.set_cookie('cart', cart)
|
|
return response
|
|
|
|
@app.route('/pins/update/<path:path>', methods=['POST'])
|
|
def pins_update(path):
|
|
# Get cookies
|
|
cookies = request.cookies
|
|
if 'cart' in cookies:
|
|
cart = cookies['cart']
|
|
else:
|
|
cart = '[]'
|
|
|
|
cart = json.loads(cart)
|
|
data = request.json
|
|
for i in range(len(cart)):
|
|
if cart[i]['name'] == path:
|
|
cart[i]['quantity'] = data['quantity']
|
|
break
|
|
|
|
|
|
# Remove any item with less than 1 quantity
|
|
cart = [item for item in cart if int(item['quantity']) > 0]
|
|
cart = json.dumps(cart)
|
|
|
|
response = make_response(jsonify({'status': 'ok'}))
|
|
response.set_cookie('cart', cart)
|
|
return response
|
|
|
|
@app.route('/cart')
|
|
def cart():
|
|
year = datetime.datetime.now().year
|
|
# Get cookies
|
|
cookies = request.cookies
|
|
if 'cart' in cookies:
|
|
cart = cookies['cart']
|
|
else:
|
|
cart = '[]'
|
|
|
|
promo_message = ''
|
|
if 'promo' in cookies:
|
|
promo = cookies['promo']
|
|
else:
|
|
promo = ''
|
|
|
|
cart = json.loads(cart)
|
|
cartHtml = render.cart(cart)
|
|
|
|
if promo != '':
|
|
promo = payments.getPromo(promo)
|
|
if not promo:
|
|
promo_message = 'Invalid promo code'
|
|
promo = ''
|
|
else:
|
|
promo_message = f'Promo code {promo["id"]} applied'
|
|
|
|
total_usd = render.total_usd(cart,promo)
|
|
total_hns = render.total_hns(cart,promo)
|
|
promoCode = ''
|
|
if promo:
|
|
promoCode = promo["id"]
|
|
else:
|
|
total_usd = render.total_usd(cart, False)
|
|
total_hns = render.total_hns(cart, False)
|
|
promoCode = ''
|
|
|
|
return render_template('cart.html', year=year, cart=cartHtml, total_usd=total_usd, total_hns=total_hns,promo=promoCode, promo_message=promo_message)
|
|
|
|
@app.route('/cart/promo', methods=['POST'])
|
|
def cart_promo():
|
|
data = request.form
|
|
response = make_response(redirect('/cart'))
|
|
response.set_cookie('promo', data['promo'])
|
|
return response
|
|
|
|
@app.route('/payment')
|
|
def payment():
|
|
year = datetime.datetime.now().year
|
|
# Get cookies
|
|
cookies = request.cookies
|
|
if 'cart' in cookies:
|
|
cart = cookies['cart']
|
|
else:
|
|
cart = '[]'
|
|
|
|
if cart == '[]':
|
|
return redirect('/cart')
|
|
|
|
cart = json.loads(cart)
|
|
cartHtml = render.cart_total(cart)
|
|
|
|
if 'promo' in cookies:
|
|
promo = cookies['promo']
|
|
promo = payments.getPromo(promo)
|
|
total_usd = render.total_usd(cart,promo)
|
|
total_hns = render.total_hns(cart,promo)
|
|
else:
|
|
promo = ''
|
|
total_usd = render.total_usd(cart, False)
|
|
total_hns = render.total_hns(cart, False)
|
|
|
|
|
|
|
|
return render_template('payment.html', year=year, cart=cartHtml, total_usd=total_usd, total_hns=total_hns)
|
|
|
|
@app.route('/payment', methods=['POST'])
|
|
def payment_post():
|
|
# Get cookies
|
|
cookies = request.cookies
|
|
if 'cart' in cookies:
|
|
cart = cookies['cart']
|
|
else:
|
|
cart = '[]'
|
|
|
|
if cart == '[]':
|
|
return redirect('/cart')
|
|
|
|
cart = json.loads(cart)
|
|
if 'promo' in cookies:
|
|
promo = cookies['promo']
|
|
promo = payments.getPromo(promo)
|
|
total_usd = render.total_usd(cart,promo)
|
|
total_hns = render.total_hns(cart,promo)
|
|
else:
|
|
promo = False
|
|
total_usd = render.total_usd(cart, False)
|
|
total_hns = render.total_hns(cart, False)
|
|
|
|
|
|
data = request.form
|
|
if 'email' in data:
|
|
email = data['email']
|
|
else:
|
|
email = ''
|
|
if 'mobile' in data:
|
|
mobile = data['mobile']
|
|
else:
|
|
mobile = ''
|
|
|
|
if 'address' in data:
|
|
address = data['address']
|
|
else:
|
|
address = ''
|
|
|
|
if 'country' in data:
|
|
country = data['country']
|
|
else:
|
|
country = ''
|
|
|
|
if 'name' in data:
|
|
name = data['name']
|
|
else:
|
|
name = ''
|
|
|
|
cartHtml = render.cart_total(cart)
|
|
|
|
if email == '' or address == '' or name == '' or country == '' or mobile == '':
|
|
return render_template('payment.html', error='Please fill all fields',
|
|
email=email, address=address, name=name, mobile=mobile, country=country,
|
|
cart=cartHtml, total_usd=total_usd, total_hns=total_hns)
|
|
|
|
# All good, check out
|
|
payment = payments.generate_payment(name, email, mobile,address,country, cart, render.total_hns(cart, promo,True), promo)
|
|
|
|
if payment == False:
|
|
return render_template('payment.html', error='There was an error processing your payment', email=email, address=address, name=name,
|
|
cart=cartHtml, total_usd=total_usd, total_hns=total_hns)
|
|
|
|
finalPrice = payment['ID']
|
|
HNSaddress = payment['HNSaddress']
|
|
qr = f"<img src='/qr/{HNSaddress}' style='width: 200px; height: 200px;'>"
|
|
|
|
# Center the QR code
|
|
qr = f"<div style='text-align: center;'>{qr}</div>"
|
|
|
|
responce = make_response(render_template('payment_info.html',cart=cartHtml, total_hns=finalPrice,address=HNSaddress, year=datetime.datetime.now().year, qr=qr))
|
|
responce.set_cookie('cart', '[]')
|
|
return responce
|
|
|
|
@app.route('/qr/<path:path>')
|
|
def qr(path):
|
|
# Generate QR code
|
|
qr = qrcode.make(path)
|
|
|
|
# Save the QR code to a bytes buffer
|
|
buffer = BytesIO()
|
|
qr.save(buffer, format='PNG')
|
|
buffer.seek(0)
|
|
|
|
# Serve the image
|
|
return send_file(buffer, mimetype='image/png')
|
|
|
|
|
|
|
|
# Promo routes
|
|
@app.route('/promo')
|
|
def promo():
|
|
year = datetime.datetime.now().year
|
|
# Check user is logged in
|
|
token = request.cookies.get('token')
|
|
if not token:
|
|
return redirect('/login')
|
|
|
|
if not account.token(token):
|
|
return redirect('/login')
|
|
|
|
promos = payments.getPromos()
|
|
promos = render.promoList(promos)
|
|
|
|
return render_template('promo.html', year=year, promos=promos)
|
|
|
|
@app.route('/promo', methods=['POST'])
|
|
def promo_post():
|
|
data = request.form
|
|
token = request.cookies.get('token')
|
|
if not token:
|
|
return redirect('/login')
|
|
|
|
if not account.token(token):
|
|
return redirect('/login')
|
|
|
|
id = data['code']
|
|
constant = data['constant']
|
|
percent = data['percent']
|
|
uses = data['uses']
|
|
payments.addPromo(id, constant, percent, uses)
|
|
|
|
return redirect('/promo')
|
|
|
|
@app.route('/promo/delete/<path:path>')
|
|
def promo_delete(path):
|
|
token = request.cookies.get('token')
|
|
if not token:
|
|
return redirect('/login')
|
|
|
|
if not account.token(token):
|
|
return redirect('/login')
|
|
|
|
payments.deletePromo(path)
|
|
return redirect('/promo')
|
|
|
|
@app.route('/login', methods=['POST'])
|
|
def login():
|
|
data = request.form
|
|
token = account.login(data['email'], data['password'])
|
|
if token:
|
|
response = make_response(redirect('/promo'))
|
|
response.set_cookie('token', token)
|
|
return response
|
|
return redirect('/login')
|
|
|
|
|
|
# Own The Dot Helper Functions
|
|
def is_ownthedot():
|
|
host = request.host.lower()
|
|
return 'ownthedot' in host or request.args.get('site') == 'otd'
|
|
|
|
def get_hns_scripts():
|
|
if 'localhost' in request.host or '127.0.0.1' in request.host or DEV:
|
|
return ''
|
|
return '<script src="https://gday.hnsau/handshake.js" domain="gday.hnsau" async></script><script src="https://gday.hnsau/https.js" async></script>'
|
|
|
|
|
|
def render_otd_error(e, url_prefix=''):
|
|
year = datetime.datetime.now().year
|
|
hns_scripts = get_hns_scripts()
|
|
site_config = {
|
|
"title": "Own The Dot",
|
|
"tagline": "The future of domain ownership starts with you.",
|
|
"hashtag": "#OwnTheDot",
|
|
"description": "Handshake replaces central registrars with true cryptographic ownership.",
|
|
"social_links": {},
|
|
"footer": {"attribution": "OWN THE DOT is marked CC0 1.0 Universal."}
|
|
}
|
|
return render_template('ownthedot/error.html', year=year, handshake_scripts=hns_scripts, site_config=site_config, error_message=str(e), url_prefix=url_prefix), 503
|
|
|
|
|
|
# Main routes
|
|
@app.route('/')
|
|
def index():
|
|
year = datetime.datetime.now().year
|
|
hns_scripts = get_hns_scripts()
|
|
|
|
if is_ownthedot():
|
|
try:
|
|
site_config = nextcloud.nextcloud_provider.get_site_config()
|
|
home_data = nextcloud.nextcloud_provider.get_home_data()
|
|
articles_list = nextcloud.nextcloud_provider.get_articles()
|
|
return render_template('ownthedot/index.html', year=year, handshake_scripts=hns_scripts, site_config=site_config, home_data=home_data, articles=articles_list, active_section='home', url_prefix='')
|
|
except nextcloud.NextcloudConnectionError as e:
|
|
return render_otd_error(e, url_prefix='')
|
|
|
|
tld = request.host.split('.')[-1]
|
|
if tld not in tlds and 'localhost' not in tld:
|
|
return render_template('index.html', year=year, handshake_scripts=hns_scripts)
|
|
|
|
hns_scripts = '<script src="https://gday.hnsau/https.js" async></script>'
|
|
if 'localhost' in tld:
|
|
tld = tlds[0]
|
|
hns_scripts = ''
|
|
|
|
return render_template('index.html', year=year, handshake_scripts=hns_scripts)
|
|
|
|
|
|
# Own The Dot Top-Level Routes (for ownthedot.com)
|
|
@app.route('/articles', strict_slashes=False)
|
|
def articles():
|
|
year = datetime.datetime.now().year
|
|
hns_scripts = get_hns_scripts()
|
|
url_prefix = '' if is_ownthedot() else '/ownthedot'
|
|
try:
|
|
site_config = nextcloud.nextcloud_provider.get_site_config()
|
|
articles_page = nextcloud.nextcloud_provider.get_articles_page_data()
|
|
articles_list = nextcloud.nextcloud_provider.get_articles()
|
|
all_tags = sorted(list({tag for a in articles_list for tag in a.get('tags', []) if tag}))
|
|
return render_template('ownthedot/articles.html', year=year, handshake_scripts=hns_scripts, site_config=site_config, articles_page=articles_page, articles=articles_list, all_tags=all_tags, active_section='articles', url_prefix=url_prefix)
|
|
except nextcloud.NextcloudConnectionError as e:
|
|
return render_otd_error(e, url_prefix=url_prefix)
|
|
|
|
|
|
@app.route('/articles/<path:slug>')
|
|
def article_detail(slug):
|
|
slug = slug.strip('/')
|
|
url_prefix = '' if is_ownthedot() else '/ownthedot'
|
|
try:
|
|
if slug.endswith('.md'):
|
|
clean_slug = slug[:-3]
|
|
article = nextcloud.nextcloud_provider.get_article(clean_slug)
|
|
if article:
|
|
return make_response(article.get('raw_markdown', ''), 200, {'Content-Type': 'text/plain; charset=utf-8'})
|
|
return render_template('404.html'), 404
|
|
|
|
year = datetime.datetime.now().year
|
|
hns_scripts = get_hns_scripts()
|
|
site_config = nextcloud.nextcloud_provider.get_site_config()
|
|
article = nextcloud.nextcloud_provider.get_article(slug)
|
|
if not article:
|
|
return render_template('404.html'), 404
|
|
|
|
return render_template('ownthedot/article.html', year=year, handshake_scripts=hns_scripts, site_config=site_config, article=article, active_section='articles', url_prefix=url_prefix)
|
|
except nextcloud.NextcloudConnectionError as e:
|
|
return render_otd_error(e, url_prefix=url_prefix)
|
|
|
|
|
|
# Subpath Routes (for hns.au/ownthedot)
|
|
@app.route('/ownthedot', strict_slashes=False)
|
|
def ownthedot_subpath():
|
|
year = datetime.datetime.now().year
|
|
hns_scripts = get_hns_scripts()
|
|
try:
|
|
site_config = nextcloud.nextcloud_provider.get_site_config()
|
|
home_data = nextcloud.nextcloud_provider.get_home_data()
|
|
articles_list = nextcloud.nextcloud_provider.get_articles()
|
|
return render_template('ownthedot/index.html', year=year, handshake_scripts=hns_scripts, site_config=site_config, home_data=home_data, articles=articles_list, active_section='home', url_prefix='/ownthedot')
|
|
except nextcloud.NextcloudConnectionError as e:
|
|
return render_otd_error(e, url_prefix='/ownthedot')
|
|
|
|
|
|
@app.route('/ownthedot/about', strict_slashes=False)
|
|
def ownthedot_subpath_about():
|
|
year = datetime.datetime.now().year
|
|
hns_scripts = get_hns_scripts()
|
|
try:
|
|
site_config = nextcloud.nextcloud_provider.get_site_config()
|
|
about_data = nextcloud.nextcloud_provider.get_about_content()
|
|
return render_template('ownthedot/about.html', year=year, handshake_scripts=hns_scripts, site_config=site_config, about_data=about_data, about_content=about_data.get('html_content', ''), active_section='about', url_prefix='/ownthedot')
|
|
except nextcloud.NextcloudConnectionError as e:
|
|
return render_otd_error(e, url_prefix='/ownthedot')
|
|
|
|
|
|
@app.route('/ownthedot/articles', strict_slashes=False)
|
|
def ownthedot_subpath_articles():
|
|
year = datetime.datetime.now().year
|
|
hns_scripts = get_hns_scripts()
|
|
try:
|
|
site_config = nextcloud.nextcloud_provider.get_site_config()
|
|
articles_page = nextcloud.nextcloud_provider.get_articles_page_data()
|
|
articles_list = nextcloud.nextcloud_provider.get_articles()
|
|
all_tags = sorted(list({tag for a in articles_list for tag in a.get('tags', []) if tag}))
|
|
return render_template('ownthedot/articles.html', year=year, handshake_scripts=hns_scripts, site_config=site_config, articles_page=articles_page, articles=articles_list, all_tags=all_tags, active_section='articles', url_prefix='/ownthedot')
|
|
except nextcloud.NextcloudConnectionError as e:
|
|
return render_otd_error(e, url_prefix='/ownthedot')
|
|
|
|
|
|
@app.route('/ownthedot/articles/<path:slug>')
|
|
def ownthedot_subpath_article_detail(slug):
|
|
slug = slug.strip('/')
|
|
try:
|
|
if slug.endswith('.md'):
|
|
clean_slug = slug[:-3]
|
|
article = nextcloud.nextcloud_provider.get_article(clean_slug)
|
|
if article:
|
|
return make_response(article.get('raw_markdown', ''), 200, {'Content-Type': 'text/plain; charset=utf-8'})
|
|
return render_template('404.html'), 404
|
|
|
|
year = datetime.datetime.now().year
|
|
hns_scripts = get_hns_scripts()
|
|
site_config = nextcloud.nextcloud_provider.get_site_config()
|
|
article = nextcloud.nextcloud_provider.get_article(slug)
|
|
if not article:
|
|
return render_template('404.html'), 404
|
|
|
|
return render_template('ownthedot/article.html', year=year, handshake_scripts=hns_scripts, site_config=site_config, article=article, active_section='articles', url_prefix='/ownthedot')
|
|
except nextcloud.NextcloudConnectionError as e:
|
|
return render_otd_error(e, url_prefix='/ownthedot')
|
|
|
|
|
|
# RSS Feeds and Media
|
|
@app.route('/feed.xml')
|
|
@app.route('/rss.xml')
|
|
@app.route('/articles/feed.xml')
|
|
@app.route('/ownthedot/feed.xml')
|
|
def rss_feed():
|
|
site_url = 'https://ownthedot.com' if is_ownthedot() else 'https://hns.au/ownthedot'
|
|
try:
|
|
feed_xml = nextcloud.nextcloud_provider.generate_rss_feed(site_url)
|
|
return make_response(feed_xml, 200, {'Content-Type': 'application/rss+xml; charset=utf-8'})
|
|
except nextcloud.NextcloudConnectionError as e:
|
|
return make_response(f"<!-- Nextcloud Connection Error: {e} -->", 503, {'Content-Type': 'text/plain'})
|
|
|
|
|
|
@app.route('/articles/media/<path:path>')
|
|
@app.route('/ownthedot/media/<path:path>')
|
|
@app.route('/media/<path:path>')
|
|
def nextcloud_media(path):
|
|
try:
|
|
media = nextcloud.nextcloud_provider.get_media(path)
|
|
if media:
|
|
return send_file(BytesIO(media[0]), mimetype=media[1])
|
|
return render_template('404.html'), 404
|
|
except nextcloud.NextcloudConnectionError:
|
|
return render_template('404.html'), 503
|
|
|
|
|
|
@app.route('/api/otd/refresh', methods=['GET', 'POST'])
|
|
@app.route('/api/refresh', methods=['GET', 'POST'])
|
|
def otd_refresh():
|
|
try:
|
|
hard = request.args.get('hard') in ('1', 'true', 'yes')
|
|
if hard:
|
|
nextcloud.nextcloud_provider.clear_cache(clear_disk=True)
|
|
health_info = nextcloud.nextcloud_provider.warm_cache(force=True)
|
|
return jsonify({
|
|
'status': 'ok',
|
|
'message': 'Cache refreshed and pre-warmed successfully',
|
|
'article_count': health_info.get('article_count', 0),
|
|
'source': health_info.get('source'),
|
|
'cached_entries': health_info.get('cached_entries'),
|
|
'timestamp': health_info.get('timestamp'),
|
|
}), 200
|
|
except nextcloud.NextcloudConnectionError as e:
|
|
return jsonify({
|
|
'status': 'error',
|
|
'error': 'Failed to connect to Nextcloud instance',
|
|
'message': str(e),
|
|
'source': nextcloud.nextcloud_provider.get_source_info(),
|
|
'timestamp': datetime.datetime.now(datetime.timezone.utc).isoformat(),
|
|
}), 503
|
|
|
|
|
|
@app.route('/api/health', methods=['GET'])
|
|
@app.route('/api/status', methods=['GET'])
|
|
@app.route('/api/otd/health', methods=['GET'])
|
|
@app.route('/api/otd/status', methods=['GET'])
|
|
@app.route('/api/source', methods=['GET'])
|
|
@app.route('/api/otd/source', methods=['GET'])
|
|
@app.route('/healthz', methods=['GET'])
|
|
def health_check():
|
|
"""
|
|
Health and status check endpoint for deployment rollouts.
|
|
Actively pulls and warms the cache from Nextcloud before returning success.
|
|
Returns 200 if Nextcloud is healthy and cache is populated.
|
|
Returns 503 if Nextcloud cannot be reached or data fails to load.
|
|
"""
|
|
try:
|
|
force = request.args.get('force') in ('1', 'true', 'yes')
|
|
health_info = nextcloud.nextcloud_provider.warm_cache(force=force)
|
|
return jsonify(health_info), 200
|
|
except nextcloud.NextcloudConnectionError as e:
|
|
return jsonify({
|
|
'status': 'unhealthy',
|
|
'healthy': False,
|
|
'error': 'Failed to connect to Nextcloud instance or pull cache',
|
|
'message': str(e),
|
|
'source': nextcloud.nextcloud_provider.get_source_info(),
|
|
'timestamp': datetime.datetime.now(datetime.timezone.utc).isoformat(),
|
|
}), 503
|
|
|
|
|
|
# Generic Catch-all and Custom Nextcloud Pages
|
|
@app.route('/<path:path>')
|
|
def catch_all(path):
|
|
clean_path = path.strip('/')
|
|
if clean_path in ('ownthedot/sitemap', 'ownthedot/sitemap.xml'):
|
|
return sitemap()
|
|
if clean_path == 'ownthedot':
|
|
return ownthedot_subpath()
|
|
if clean_path == 'ownthedot/about':
|
|
return ownthedot_subpath_about()
|
|
if clean_path == 'ownthedot/articles':
|
|
return ownthedot_subpath_articles()
|
|
if clean_path.startswith('ownthedot/articles/'):
|
|
slug = clean_path.replace('ownthedot/articles/', '', 1)
|
|
return ownthedot_subpath_article_detail(slug)
|
|
|
|
year = datetime.datetime.now().year
|
|
hns_scripts = get_hns_scripts()
|
|
|
|
# Redirect legacy own-the-dot URL to ownthedot
|
|
if clean_path == 'own-the-dot':
|
|
return redirect('/ownthedot', code=301)
|
|
if clean_path.startswith('own-the-dot/'):
|
|
sub = clean_path.replace('own-the-dot/', '', 1)
|
|
return redirect(f'/ownthedot/{sub}', code=301)
|
|
|
|
# Check for custom Nextcloud subpath pages: /ownthedot/<slug>
|
|
if clean_path.startswith('ownthedot/'):
|
|
sub_slug = clean_path.replace('ownthedot/', '', 1).strip('/')
|
|
try:
|
|
if sub_slug.endswith('.md'):
|
|
clean_sub = sub_slug[:-3]
|
|
page = nextcloud.nextcloud_provider.get_page(clean_sub)
|
|
if page:
|
|
return make_response(page.get('raw_markdown', ''), 200, {'Content-Type': 'text/plain; charset=utf-8'})
|
|
page = nextcloud.nextcloud_provider.get_page(sub_slug)
|
|
if page:
|
|
site_config = nextcloud.nextcloud_provider.get_site_config()
|
|
return render_template('ownthedot/page.html', year=year, handshake_scripts=hns_scripts, site_config=site_config, page=page, active_section=page.get('slug', ''), url_prefix='/ownthedot')
|
|
except nextcloud.NextcloudConnectionError as e:
|
|
return render_otd_error(e, url_prefix='/ownthedot')
|
|
|
|
# Check for custom Nextcloud root pages on ownthedot.com
|
|
if is_ownthedot():
|
|
try:
|
|
if clean_path.endswith('.md'):
|
|
clean_sub = clean_path[:-3]
|
|
page = nextcloud.nextcloud_provider.get_page(clean_sub)
|
|
if page:
|
|
return make_response(page.get('raw_markdown', ''), 200, {'Content-Type': 'text/plain; charset=utf-8'})
|
|
page = nextcloud.nextcloud_provider.get_page(clean_path)
|
|
if page:
|
|
site_config = nextcloud.nextcloud_provider.get_site_config()
|
|
return render_template('ownthedot/page.html', year=year, handshake_scripts=hns_scripts, site_config=site_config, page=page, active_section=page.get('slug', ''), url_prefix='')
|
|
except nextcloud.NextcloudConnectionError as e:
|
|
return render_otd_error(e, url_prefix='')
|
|
|
|
# If file exists, load it
|
|
if os.path.isfile('templates/' + path):
|
|
return render_template(path, year=year, handshake_scripts=hns_scripts)
|
|
|
|
# Try with .html
|
|
if os.path.isfile('templates/' + path + '.html'):
|
|
return render_template(path + '.html', year=year, handshake_scripts=hns_scripts)
|
|
|
|
if os.path.isfile('templates/' + clean_path + '.html'):
|
|
return render_template(clean_path + '.html', year=year, handshake_scripts=hns_scripts)
|
|
|
|
return render_template('404.html'), 404
|
|
|
|
|
|
# Redirects
|
|
@app.route('/contact', strict_slashes=False)
|
|
def contact():
|
|
if is_ownthedot():
|
|
try:
|
|
page = nextcloud.nextcloud_provider.get_page('contact')
|
|
if page:
|
|
year = datetime.datetime.now().year
|
|
hns_scripts = get_hns_scripts()
|
|
site_config = nextcloud.nextcloud_provider.get_site_config()
|
|
return render_template('ownthedot/page.html', year=year, handshake_scripts=hns_scripts, site_config=site_config, page=page, active_section='contact', url_prefix='')
|
|
except nextcloud.NextcloudConnectionError:
|
|
pass
|
|
return redirect('/#contact')
|
|
|
|
|
|
@app.route('/about', strict_slashes=False)
|
|
def about():
|
|
if is_ownthedot():
|
|
try:
|
|
year = datetime.datetime.now().year
|
|
hns_scripts = get_hns_scripts()
|
|
site_config = nextcloud.nextcloud_provider.get_site_config()
|
|
about_data = nextcloud.nextcloud_provider.get_about_content()
|
|
return render_template('ownthedot/about.html', year=year, handshake_scripts=hns_scripts, site_config=site_config, about_data=about_data, about_content=about_data.get('html_content', ''), active_section='about', url_prefix='')
|
|
except nextcloud.NextcloudConnectionError as e:
|
|
return render_otd_error(e, url_prefix='')
|
|
return redirect('/#about')
|
|
|
|
@app.route('/support', strict_slashes=False)
|
|
@app.route('/donate', strict_slashes=False)
|
|
def donate():
|
|
return redirect('/#support')
|
|
|
|
|
|
# 404 catch all
|
|
@app.errorhandler(404)
|
|
def not_found(e):
|
|
return render_template('404.html'), 404
|
|
|
|
|
|
def repeat_check_payments(auto=False):
|
|
# Run check_payments function
|
|
payments.check_payments()
|
|
# Schedule the function to run again after 10 seconds
|
|
if not auto:
|
|
threading.Timer(10, repeat_check_payments).start()
|
|
|
|
def check_payments():
|
|
payments.check_payments()
|
|
|
|
if __name__ == '__main__':
|
|
app.run(debug=True, port=5000, host='127.0.0.1')
|