-
Notifications
You must be signed in to change notification settings - Fork 2
/
main.py
238 lines (199 loc) · 7.93 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
235
236
237
238
from fastapi import FastAPI, Response, Query, Header, Request, Form
from fastapi.responses import StreamingResponse, JSONResponse
from typing import List
from fastapi.encoders import jsonable_encoder
from fastapi.routing import APIRoute
from typing import List, Annotated
import time
import string
import secrets
import asyncio
import psutil
import ansi
import os
from slowapi import Limiter, _rate_limit_exceeded_handler
from slowapi.util import get_remote_address
from slowapi.errors import RateLimitExceeded
from slowapi.middleware import SlowAPIMiddleware
from fastapi.middleware.cors import CORSMiddleware
app = FastAPI(title="radi8's api", description="radi8's multi-tool api")
startTime = time.time()
limiter = Limiter(key_func=get_remote_address)
app = FastAPI()
app.state.limiter = limiter
app.add_exception_handler(RateLimitExceeded, _rate_limit_exceeded_handler)
origins = [
"https://sparkshell.dev",
]
app.add_middleware(
CORSMiddleware,
allow_origins=origins,
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
@app.get("/")
async def root():
return {
"status": "ok",
"version": 0.8, # probably
"uptime": time.time() - startTime,
"docs": "/docs",
}
@app.get("/routes")
def getRoutes():
routes = []
for route in app.routes:
routeInfo = {}
routeInfo["path"] = route.path
routeInfo["methods"] = route.methods
routes.append(routeInfo)
return JSONResponse(content=jsonable_encoder(routes))
@app.get("/meminfo")
async def meminfo():
memory = psutil.virtual_memory()
return {"total": memory.total, "available": memory.available, "used": memory.used}
@app.get("/password")
async def generatePassword(
length: int = Query(8, gt=0, lt=256),
includeUppercase: bool = True,
includeLowercase: bool = True,
includeDigits: bool = True,
includePunctuation: bool = True,
):
if not any([includeUppercase, includeLowercase, includeDigits, includePunctuation]):
return {"error": "at least one option must be enabled"}
chars = ""
password = ""
if includeUppercase:
chars += string.ascii_uppercase
password += secrets.choice(string.ascii_uppercase)
if includeLowercase:
chars += string.ascii_lowercase
password += secrets.choice(string.ascii_lowercase)
if includeDigits:
chars += string.digits
password += secrets.choice(string.digits)
if includePunctuation:
chars += string.punctuation
password += secrets.choice(string.punctuation)
remainingLength = length - len(password)
password += "".join(secrets.choice(chars) for _ in range(remainingLength))
passwordList = list(password)
secrets.SystemRandom().shuffle(passwordList)
shuffledPassword = "".join(passwordList)
return Response(content=shuffledPassword)
@app.get("/pin")
async def generatePin(length: int = Query(4, gt=3, lt=7)):
digits = string.digits
pin = "".join(secrets.choice(digits) for _ in range(length))
return Response(content=pin)
@app.get("/rainbow")
async def rainbow(times: int = 0):
rainbow_colors = [
"\033[38;5;196m", # red
"\033[38;5;202m", # orange
"\033[38;5;226m", # yellow
"\033[38;5;118m", # green
"\033[38;5;45m", # blue
"\033[38;5;99m", # indigo
"\033[38;5;201m", # violet
]
delay = 0.5
async def generate_rainbow():
if times == 0:
while True:
for i in range(len(rainbow_colors)):
color_index = i % len(rainbow_colors)
color = rainbow_colors[color_index]
yield color + "███████████\033[0m\n"
await asyncio.sleep(delay)
else:
for _ in range(times):
for i in range(len(rainbow_colors)):
color_index = i % len(rainbow_colors)
color = rainbow_colors[color_index]
yield color + "███████████\033[0m\n"
await asyncio.sleep(delay)
return StreamingResponse(generate_rainbow(), media_type="text/plain")
@app.get("/fakefact")
async def fakefact():
facts = (
"Salty water boils quicker",
"You swallow on average 8 spiders every year",
"If you drop a penny for the Empire State you can kill someone",
"Mt. Everest is the tallest mountain in the world",
"The world is flat",
"Blood without oxygen is blue",
"Tomatoes are vegatables",
"Humans only use 10% of their brains",
"Coffee stunts your growth",
"Coffee helps you sober up",
"Bananas are actually an herb",
"Zebras are just horses with stripes",
"The Loch Ness Monster is real",
"Napoleon Bonaparte was extremely short",
"Microwaving food removes its nutrients",
"The Moon landng was faked",
"Thyme is technically a tree",
"There are more than 30 blimps in the world",
"Gold nuggets were named after chicken nuggets - not the other way around",
"The first video uploaded to YouTube was taken down in 2016 for ToS violation",
"Your kneecap is the roundest part in your body",
"Bubbles have a seam",
"Peppermint can't be smelt by guinea pigs",
"NASA made powdered water",
"Thomas Edison invented the first light bulb",
"Electromagnetic radiation from cell phones and microwaves cause cancer",
"1/4 of the US population doesn't believe in the moon",
"Purified water is more dangerous to our health than tap water",
"The sea is only 4% water",
"This fact has a higher chance to appear than the others",
"Pickles are legal tender in Arkansas",
"Half-Life 4 will come out",
"Lemons are named after the color - not the other way around",
"Bees violate the laws of physics by flying",
"The term 'petabyte' was invented when a small COD patch was released",
"In one of the first revisions of the ASCII standard, the lowercase letter z was left out. It was shortly fixed",
"This statement is false",
"If only slightly chemically altered, lemons are combustible",
"Adults are much more accepting of other people than kids are",
"The xbox 360 was origanally named the xbox 0, anticipating the xbox 1. No one is quite sure why it was changed",
"Doom can be run on moon rocks, but its highly discouraged due to moon rock poisoning",
"None of these facts are portal references",
"jeffalo is the only CEO that isnt a lizard person",
"Watermelons are 91.5% fire",
"The color green doesn't exist",
)
return Response(content=secrets.choice(facts))
@app.get("/kidsaremuchmore")
async def kidsAreMuchMore():
return Response(
content="Kids are much more accepting of other people than adults are."
)
@app.get("/amogus")
async def amogus():
return Response(content=ansi.amogus, media_type="text/plain")
@app.get("/jeffalo")
async def jeffalo():
return Response(content=ansi.jeffalo, media_type="text/plain")
@app.get("/flags")
def flags():
return list(ansi.flags.keys())
@app.get("/flags/{flag}")
async def prideflag(flag: str, user_agent: Annotated[str | None, Header()] = None):
if not user_agent.startswith("curl/"):
return Response(content="please use curl")
try:
return Response(content=f"{ansi.flags[flag]}\n", media_type="text/plain")
except:
return {"error": "flag not found"}
@app.post("/sparkshell-email")
@limiter.limit("2/minute")
async def sparkshellEmail(request: Request, email: str = Form()):
if not os.path.isfile("./sparkshell-emails.txt"): # don't worry, nobody else will see this !
with open("./sparkshell-emails.txt", "w") as f:
f.write("")
with open("./sparkshell-emails.txt", "a") as f:
f.write(f"{email}\n")
return Response(content="thanks! :)")