niming_backend/app.py

65 lines
1.8 KiB
Python
Raw Normal View History

2024-11-08 01:41:39 +08:00
from flask import Flask, request, Response
2024-11-07 16:55:35 +08:00
import os, requests, time
from hashlib import sha256
2024-11-08 01:41:39 +08:00
from supaclient import logger
2024-11-07 16:55:35 +08:00
from dotenv import load_dotenv
2024-11-08 01:41:39 +08:00
from supabase import Client, create_client
2024-11-07 16:55:35 +08:00
load_dotenv()
2024-11-08 01:41:39 +08:00
# supabase
2024-11-07 16:55:35 +08:00
URL = os.getenv("SUPABASE_IP") + "/"
2024-11-08 01:41:39 +08:00
KEY = os.getenv("SUPABASE_KEY")
supabase = create_client(URL, KEY)
2024-11-07 02:19:53 +08:00
2024-11-08 01:41:39 +08:00
# app
2024-11-07 02:19:53 +08:00
app = Flask(__name__)
app.config["SECRET_KEY"] = os.urandom(64)
2024-11-07 16:55:35 +08:00
# main
@app.route("/")
def index(): return "Hello, world!"
# reverse proxy
@app.route('/r/<path:path>',methods=['GET', 'POST'])
def proxy(path):
2024-11-08 01:41:39 +08:00
headers = request.headers
# process
if request.method == 'GET':
2024-11-07 16:55:35 +08:00
resp = requests.get(f'{URL}{path}', headers = headers) # forward
elif request.method=='POST':
# get items
json_ctx = request.get_json()
2024-11-07 17:33:34 +08:00
# flags
logger_args = []
2024-11-08 01:41:39 +08:00
# edit request
2024-11-07 16:55:35 +08:00
if path == "rest/v1/niming_posts": # niming post
# hash
hash = sha256( (json_ctx["content"] + str(time.time())).encode() ).hexdigest()
# ig posting
igid = None
2024-11-07 17:33:34 +08:00
# set logger
logger_args.append("newpost")
logger_args.append(hash)
2024-11-07 16:55:35 +08:00
# edit payload
json_ctx["hash"] = hash
json_ctx["igid"] = igid
# forward
2024-11-08 01:41:39 +08:00
resp = requests.post(f'{URL}{path}',json=json_ctx, headers = headers)
2024-11-07 16:55:35 +08:00
2024-11-07 17:33:34 +08:00
# logger
2024-11-08 01:41:39 +08:00
logger_res = logger(supabase, logger_args)
# make response
excluded_headers = ['content-encoding', 'content-length', 'transfer-encoding', 'connection']
headers = [(name, value) for (name, value) in resp.raw.headers.items() if name.lower() not in excluded_headers]
response = Response(resp.content, resp.status_code, headers)
return response
2024-11-07 02:19:53 +08:00
# run
if __name__ == "__main__":
app.run(host = "0.0.0.0", port = 8000, debug = False)