This repository was archived by the owner on May 22, 2022. It is now read-only.
-
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmain.py
234 lines (203 loc) · 7.82 KB
/
main.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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
import uvicorn
from fastapi import FastAPI, BackgroundTasks, HTTPException, Response, Request
from fastapi.responses import RedirectResponse, StreamingResponse, PlainTextResponse
from dotenv import load_dotenv
import os
from deta import Deta
from typing import Optional
import yaml
from datetime import datetime
from lxml import objectify, etree
import sentry_sdk
import secure
load_dotenv()
DETA_TOKEN = os.getenv("DETA_TOKEN")
sentry_sdk.init(
"https://e7f6d56016d747bc88bbdb5a29d0fdd5@o309026.ingest.sentry.io/5834878",
traces_sample_rate=1.0
)
app = FastAPI(title="StopModReposts API",
description="The official StopModReposts API to get our list in all kinds of formats.",
version="2.0",
docs_url="/debug",
redoc_url="/docs")
deta = Deta(DETA_TOKEN)
drive = deta.Drive("formats")
stats = deta.Base("smr-stats")
times = deta.Base("smr-timestamps")
"""
secure_headers = secure.Secure()
@app.middleware("http")
async def set_secure_headers(request, call_next):
response = await call_next(request)
secure_headers.framework.fastapi(response)
return response
"""
def statcounter():
try:
month = str(datetime.now().month)
request = stats.fetch({"month": month}).items[0]
stats.update({
"month": month,
"total": int(request["total"]) + 1
}, request["key"])
except:
month = str(datetime.now().month)
stats.insert({
"month": month,
"total": 1
})
def timestamps(game):
try:
if game is None:
request = times.fetch({"job": "cron-all"}).items[0]
else:
request = times.fetch({"job": "cron-single"}).items[0]
except:
request = "ERROR - TIMESTAMP DB IS NOT WORKING"
return request
@app.get("/")
def root(request: Request):
return RedirectResponse("/docs")
@app.get("/sites.yaml")
def get_yaml(request: Request, background_tasks: BackgroundTasks, game: Optional[str] = None):
"""
Get the combined list in the YAML format.
"""
background_tasks.add_task(statcounter)
if game is None: game = "sites"
res = drive.get("{0}2.yaml".format(game))
return StreamingResponse(res.iter_chunks(1024), media_type="application/yaml")
@app.get("/sites.json")
def get_json(request: Request, background_tasks: BackgroundTasks, game: Optional[str] = None):
"""
Get the combined list in the JSON format.
"""
background_tasks.add_task(statcounter)
if game is None: game = "sites"
res = drive.get("{0}2.yaml".format(game))
return yaml.load(res.read(), Loader=yaml.FullLoader)
@app.get("/sites.txt", response_class=PlainTextResponse)
def get_txt(request: Request, background_tasks: BackgroundTasks, game: Optional[str] = None):
"""
Get the combined list in the TXT format.
"""
background_tasks.add_task(statcounter)
if game is None: game = "sites"
res = drive.get("{0}2.yaml".format(game))
data = yaml.load(res.read(), Loader=yaml.FullLoader)
txt = ""
for item in data:
if item["path"] != "/":
path = item["path"]
else:
path = ""
txt = txt + item["domain"] + path + "\n"
return txt
@app.get("/hosts.txt", response_class=PlainTextResponse)
def get_hosts(request: Request, background_tasks: BackgroundTasks, game: Optional[str] = None):
"""
Get the combined list in the HOSTS.TXT format.
"""
background_tasks.add_task(statcounter)
request = timestamps(game)
if game is None: game = "sites"
res = drive.get("{0}2.yaml".format(game))
data = yaml.load(res.read(), Loader=yaml.FullLoader)
with open("templates/hosts.txt", "r") as f:
hosts = f.read().format(str(request["updated"]))
hosts = hosts + "\n \n"
wwwhosts = ""
for item in data:
if item["path"] == "/":
hosts = hosts + "0.0.0.0 " + item["domain"] + "\n"
wwwhosts = wwwhosts + "0.0.0.0 " + "www." + item["domain"] + "\n"
hosts = hosts + wwwhosts + "\n" + "# === End of StopModReposts site list ==="
return hosts
@app.get("/ublacklist",response_class=PlainTextResponse)
def get_ublacklist(request: Request, background_tasks: BackgroundTasks, game: Optional[str] = None):
"""
Get the combined list in the uBlacklist format.
"""
background_tasks.add_task(statcounter)
if game is None: game = "sites"
res = drive.get("{0}2.yaml".format(game))
data = yaml.load(res.read(), Loader=yaml.FullLoader)
blacklist = ""
for item in data:
if item["path"] != "/":
path = item["path"] + "/*"
else:
path = "/*"
blacklist = blacklist + "*://*." + item["domain"] + path + "\n"
return blacklist
@app.get("/sites.xml")
def get_xml(request: Request, background_tasks: BackgroundTasks, game: Optional[str] = None):
"""
Get the combined list in the XML format.
"""
background_tasks.add_task(statcounter)
if game is None: game = "sites"
res = drive.get("{0}2.yaml".format(game))
data = yaml.load(res.read(), Loader=yaml.FullLoader)
sites = objectify.Element("sites", nsmap='', _pytype='')
for item in data:
site = objectify.Element("site", nsmap='', _pytype='')
site.domain = item["domain"]
site.notes = item["notes"]
site.path = item["path"]
site.reason = item["reason"]
sites.append(site)
objectify.deannotate(sites)
etree.cleanup_namespaces(sites)
return Response(content=etree.tostring(sites, pretty_print=True, xml_declaration=True, with_tail=False), media_type="application/xml")
@app.get("/sites.nbt")
def get_nbt(request: Request, background_tasks: BackgroundTasks):
"""
Get the combined list in the NBT format **(deprecated - will be removed soon)**.
"""
background_tasks.add_task(statcounter)
raise HTTPException(status_code=400, detail="This format is deprecated. Please use a different one: https://github.com/StopModReposts/Illegal-Mod-Sites/wiki/API-access-and-formats")
@app.get("/stats")
def get_stats(request: Request):
"""
Get the API and refresh stats.
"""
month = str(datetime.now().month)
counter = stats.fetch({"month": month}).items[0]["total"]
cronall = times.fetch({"job": "cron-all"}).items[0]["updated"]
cronsingle = times.fetch({"job": "cron-single"}).items[0]["updated"]
return {"requests_this_month": counter,
"latest_cron_refresh": {
"cron-all": cronall,
"cron-single": cronsingle
}}
@app.get("/shields/{shield}")
def get_shields(request: Request, shield: str):
"""
Get the data needed to generate a shield.
"""
if shield == "total":
sites = 0
res = drive.get("sites.yaml")
data = yaml.load(res.read(), Loader=yaml.FullLoader)
sites = len(data)
return {"schemaVersion": 1,
"label": "sites",
"message": str(sites),
"color": "blue"}
elif shield == "refreshed":
time = times.fetch({"job": "cron-all"}).items[0]["updated"]
return {"schemaVersion": 1,
"label": "refreshed",
"message": str(time) + " UTC",
"color": "blue"}
elif shield == "visits":
month = str(datetime.now().month)
visits = stats.fetch({"month": month}).items[0]["total"]
return {"schemaVersion": 1,
"label": "visits this month",
"message": str(visits),
"color": "blue"}
#if __name__ == "__main__":
# uvicorn.run(app, host="localhost", port=80)