-
Notifications
You must be signed in to change notification settings - Fork 5
/
main.py
334 lines (285 loc) Β· 9.95 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
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
import warnings
from deta import Base
from hanapin import Google
from datetime import datetime
from BingImages import BingImages
from fastapi import FastAPI, Request
from fastapi.templating import Jinja2Templates
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import HTMLResponse, FileResponse, JSONResponse, RedirectResponse
app = FastAPI()
app.add_middleware(CORSMiddleware, allow_origins=["*"])
pages = Jinja2Templates(directory="templates")
config = Base("config")
history = Base("history")
bookmarks = Base("bookmarks")
integrations = Base("integrations")
class NoCacheFileResponse(FileResponse):
def __init__(self, path: str, **kwargs):
super().__init__(path, **kwargs)
self.headers["Cache-Control"] = "no-cache"
async def settings_check():
data = config.get("settings")
if not data:
data = config.put(
{
"settings": [
{"theme": "ocean-blue", "search": "Moderate", "history": True}
]
},
"settings",
)
return data
async def integrations_check(integration: str):
data = integrations.get(integration)
if not data:
data = integrations.put({"data": [{"integration": integration}]}, integration)
return data
@app.get("/", response_class=HTMLResponse)
async def home(request: Request):
return pages.TemplateResponse(
"index.html",
{"request": request, "settings": await settings_check()},
)
@app.get("/image", response_class=HTMLResponse)
async def image_results(request: Request, query: str, limit: int = 25):
data = await settings_check()
time = datetime.now()
try:
if data["settings"][0]["history"] == True:
history.put(
{
"query": query,
"time": f"{time.strftime('%A')}, {time.strftime('%B')} {time.strftime('%-d')}, {time.strftime('%Y')} {time.strftime('%-H')}:{time.strftime('%M')}:{time.strftime('%S')} {time.strftime('%p')}",
}
)
results = BingImages(query, count=limit).get()
id = 1
items = []
for item in results:
items.append(
{
"title": item,
"image": item,
"thumbnail": item,
# "height": item["height"], Deprecated
# "width": item["width"], Deprecated
# "source": item["source"], Deprecated
"id": id,
}
)
id += 1
return pages.TemplateResponse(
"image.html",
{"request": request, "items": items, "query": query, "settings": data},
)
except Exception as e:
warnings.warn(e)
return JSONResponse(
content={"message": "An error occurred", "error": e},
)
@app.get("/search", response_class=HTMLResponse)
async def search_results(request: Request, query: str, limit: int = 50):
data = await settings_check()
if query.startswith(">surf:home"):
return RedirectResponse("/")
elif query.startswith(">surf:history"):
return RedirectResponse("/history")
elif query.startswith(">surf:bookmarks"):
return RedirectResponse("/bookmarks?typ=site")
elif query.startswith(">surf:settings"):
return RedirectResponse("/settings")
elif query.startswith(">surf:image"):
return RedirectResponse(f"/image?query={query.removeprefix('>surf:image')}")
else:
time = datetime.now()
try:
if data["settings"][0]["history"] == True:
history.put(
{
"query": query,
"time": f"{time.strftime('%A')}, {time.strftime('%B')} {time.strftime('%-d')}, {time.strftime('%Y')} {time.strftime('%-H')}:{time.strftime('%M')}:{time.strftime('%S')} {time.strftime('%p')}",
}
)
results = Google(query, count=limit).results()
id = 1
items = []
for item in results:
items.append(
{
"title": item["title"],
# "body": item["body"], Deprecated
"href": item["link"],
"id": id,
}
)
id += 1
return pages.TemplateResponse(
"search.html",
{"request": request, "items": items, "query": query, "settings": data},
)
except Exception as e:
warnings.warn(e)
return JSONResponse(
content={"message": "An error occurred", "error": e},
)
@app.post("/bookmark")
async def bookmark_add_site(title: str, content: str, url: str, typ: str):
bookmarks.put({"title": title, "content": [content], "url": url, "type": typ})
return {"message": "success"}
@app.delete("/bookmark")
async def bookmark_remove(id: str):
bookmarks.delete(id)
return {"message": "success"}
@app.get("/bookmarks")
async def bookmarks_page(request: Request, typ: str):
res = bookmarks.fetch()
items = res.items
while res.last:
res = bookmarks.fetch(last=res.last)
items += res.items
list = []
for item in items:
if item["type"] == typ:
list.append(item)
return pages.TemplateResponse(
f"bookmarks-{typ}.html",
{"request": request, "items": list, "settings": await settings_check()},
)
@app.delete("/history")
async def history_remove(id: str):
history.delete(id)
return {"message": "success"}
@app.get("/history")
async def history_page(request: Request):
res = history.fetch()
items = res.items
while res.last:
res = history.fetch(last=res.last)
items += res.items
return pages.TemplateResponse(
"history.html",
{"request": request, "items": items, "settings": await settings_check()},
)
@app.get("/settings")
async def settings_page(request: Request):
return pages.TemplateResponse(
"settings.html",
{
"request": request,
"settings": await settings_check(),
"blackhole": await integrations_check("blackhole"),
},
)
@app.patch("/settings")
async def settings_update(theme: str = None, search: str = None, history: bool = None):
data = config.get("settings")
if theme == None:
theme = data["settings"][0]["theme"]
else:
theme = theme
if search == None:
search = data["settings"][0]["search"]
else:
search = search
if history == None:
history = data["settings"][0]["history"]
else:
history = history
config.put(
{"settings": [{"theme": theme, "search": search, "history": history}]},
"settings",
)
return {"message": "success"}
@app.delete("/settings")
async def settings_delete(type: str):
# Type: bookmarks/history
base = Base(type)
res = base.fetch()
items = res.items
while res.last:
res = bookmarks.fetch(last=res.last)
items += res.items
for i in items:
base.delete(i["key"])
return {"message": "success"}
@app.get("/settings/data")
async def settings_data():
data = config.get("settings")
return data
@app.post("/integration/{integration}")
async def integration_configure(integration: str, url: str):
integrations.put({"data": [{"integration": integration, "url": url}]}, integration)
return {"message": "success"}
@app.get("/integration/{integration}")
async def integration_data(integration: str):
data = integrations.get(integration)
return data
@app.get("/api/search/image")
async def api_search_image(query: str, results: int = 25):
data = await settings_check()
time = datetime.now()
if data["settings"][0]["history"] == True:
history.put(
{
"query": query,
"time": f"{time.strftime('%A')}, {time.strftime('%B')} {time.strftime('%-d')}, {time.strftime('%Y')} {time.strftime('%-H')}:{time.strftime('%M')}:{time.strftime('%S')} {time.strftime('%p')}",
}
)
results = BingImages(query, count=results).get()
id = 1
items = []
for item in results:
items.append(
{
"title": item,
"image": item,
"thumbnail": item,
# "height": item["height"], Deprecated
# "width": item["width"], Deprecated
# "source": item["source"], Deprecated
"id": id,
}
)
id += 1
return {"items": items, "query": query, "settings": data}
@app.get("/api/search/text")
async def api_search_text(query: str, limit: int = 50):
data = await settings_check()
time = datetime.now()
if data["settings"][0]["history"] == True:
history.put(
{
"query": query,
"time": f"{time.strftime('%A')}, {time.strftime('%B')} {time.strftime('%-d')}, {time.strftime('%Y')} {time.strftime('%-H')}:{time.strftime('%M')}:{time.strftime('%S')} {time.strftime('%p')}",
}
)
results = Google(query, count=limit).results()
id = 1
items = []
for item in results:
items.append(
{
"title": item["title"],
"href": item["link"],
"id": id,
}
)
id += 1
return {"items": items, "query": query, "settings": data}
# Automatic
@app.post("/__space/v0/actions")
async def actions(request: Request):
data = await request.json()
event = data["event"]
if event["id"] == "history":
res = history.fetch()
items = res.items
while res.last:
res = history.fetch(last=res.last)
items += res.items
for item in items:
history.delete(item["key"])
@app.get("/static/{path:path}")
async def static(path: str):
return NoCacheFileResponse(f"./static/{path}")