-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathapp.py
82 lines (66 loc) · 2.19 KB
/
app.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
from flask import Flask, request, redirect
import re
app = Flask(__name__)
SUPPORTING_WEB_CLIENTS = [
"syusui-s.github.io",
"snort.social",
"nostter.vercel.app",
"astraea.mousedev.page",
"stok33.github.io",
]
SUPPORTING_NATIVE_CLIENTS = [
"okhttp/5.0.0-alpha.11", # Amethyst
"Dart/3.0 (dart:io)", # Plebstr
"snort.social", # snort is web client but its info is included in User-Agent often
"imgproxy/3.19.0", # this is assumed snort
]
MAX_STORE_IP_NUM = 50
REMOVE_IP_NUM = 10
accessed_ip_list = []
accessed_ip_dict = {}
def is_supporting_client(uagent, referer, ip_addr):
try:
# for case that web client open image file URL in new tab or window
# Damus is not NIP-36 supporting
if uagent.find("damus") == -1 \
and ip_addr != None \
and accessed_ip_dict[ip_addr] == True:
return True
except:
pass
# native clients
for client_url in SUPPORTING_NATIVE_CLIENTS:
if uagent.find(client_url) != -1:
return True
# web clients
for client_url in SUPPORTING_WEB_CLIENTS:
if referer != None and referer.find(client_url) != -1:
return True
return False
def check_path(path):
pattern = r'^[a-zA-Z0-9/\.]*$'
if re.match(pattern, path):
return True
else:
return False
@app.route('/<path:path>')
def root_path(path):
global accessed_ip_list
global accessed_ip_dict
uagent = request.headers.get('User-Agent')
if not is_supporting_client(uagent, request.referrer, request.remote_addr):
return redirect("https://ryogrid.net/dist/nip36-needed.jpg")
if not check_path(path):
return "", 400
# store accessed IP address
accessed_ip_list.append(request.remote_addr)
accessed_ip_dict[request.remote_addr] = True
# remove old memoried IP addresses
if len(accessed_ip_list) > MAX_STORE_IP_NUM:
for idx in range(0, REMOVE_IP_NUM):
try:
del accessed_ip_dict[accessed_ip_list[idx]]
accessed_ip_list = accessed_ip_list[REMOVE_IP_NUM:]
except:
pass
return redirect("https://cdn.nostr.build/" + path)