This commit is contained in:
codey 2024-08-10 22:49:00 -04:00
commit db73abf647
4 changed files with 205 additions and 0 deletions

3
README.md Normal file
View File

@ -0,0 +1,3 @@
API Server Rewrite
FastAPI - https://fastapi.tiangolo.com/

110
endpoints/LyricSearch.py Normal file
View File

@ -0,0 +1,110 @@
#!/usr/bin/env python3.12
import importlib
import urllib.parse
import regex
import logging
from typing import Any, Annotated
from fastapi import FastAPI, Form, HTTPException
from pydantic import BaseModel
class ValidRequest(BaseModel):
a: str | None = None
s: str | None = None
t: str | None = None
sub: str | None = None
extra: bool | None = False
src: str | None = None
class LyricSearch(FastAPI):
def __init__(self, app: FastAPI, util, constants):
self.app = app
self.util = util
self.constants = constants
self.lyrics_engine = importlib.import_module("lyrics_engine").LyricsEngine()
self.endpoint_name = "/search/"
self.search_method_order = [
666,
1,
8,
2,
3
]
self.acceptable_request_sources = [
"WEB",
"IRC-MS",
"IRC-FS",
"IRC-KALI",
"DISC-ACES",
"DISC-HAVOC",
"LIMNORIA-SHARED"
]
app.add_api_route(self.endpoint_name, self.search_handler, methods=["POST"])
async def search_handler(self, data: ValidRequest):
print(f"HI, DATA:\n{data}")
src = data.src.upper()
if not(src in self.acceptable_request_sources):
raise HTTPException(detail="Invalid request source", status_code=403)
searchArtist = data.a
searchSong = data.s
searchText = data.t
addExtras = data.extra
subSearch = data.sub
searchObject = None
random_song_requested = (searchArtist == "!" and searchSong == "!")
query_valid = (
not(searchArtist is None) and
not(searchSong is None) and
len(searchArtist) >= 1 and
len(searchSong) >= 1 and
len(searchArtist) + len(searchSong) >= 3
)
if not(random_song_requested) and not(query_valid):
logging.debug(f"DEBUG!\nsearchSong: {searchSong}\nsearchArtist: {searchArtist}")
return {
"err": True,
"errorText": "Invalid parameters"
}
if searchArtist and searchSong:
searchArtist = self.constants.DOUBLE_SPACE_REGEX.sub(" ", searchArtist.strip())
searchSong = self.constants.DOUBLE_SPACE_REGEX.sub(" ", searchSong.strip())
searchArtist = urllib.parse.unquote(searchArtist)
searchSong = urllib.parse.unquote(searchSong)
if searchText is None:
searchObject = self.lyrics_engine.create_query_object("%s : %s" % (searchArtist, searchSong))
if subSearch:
searchObject = self.lyrics_engine.create_query_object("%s : %s : %s" % (searchArtist, searchSong, subSearch))
searchWorker = await self.lyrics_engine.lyrics_worker(searching=searchObject,
method_order=self.search_method_order,
recipient='anyone')
if not(searchWorker) or not('l') in searchWorker.keys():
return {
'err': True,
'errorText': 'Sources exhausted, lyrics not located.'
}
return {
'err': False,
'artist': searchWorker['artist'],
'song': searchWorker['song'],
'combo_lev': f'{searchWorker['combo_lev']:.2f}',
'lyrics': regex.sub(r"\s/\s", "<br>", " ".join(searchWorker['l'])),
'from_cache': searchWorker['method'].strip().lower().startswith("local cache"),
'src': searchWorker['method'] if addExtras else None,
}

69
main.py Normal file
View File

@ -0,0 +1,69 @@
#!/usr/bin/env python3.12
import importlib
import logging
from typing import Union, Any
from fastapi import FastAPI, HTTPException, Response, Form
from fastapi.middleware.cors import CORSMiddleware
logger = logging.getLogger()
logger.setLevel(logging.DEBUG)
app = FastAPI()
util = importlib.import_module("util").Utilities()
constants = importlib.import_module("constants").Constants()
origins = [
"https://codey.lol",
]
app.add_middleware(CORSMiddleware,
allow_origins=origins,
allow_credentials=True,
allow_methods=["POST"],
allow_headers=["*"])
"""
Blacklisted routes
"""
@app.get("/")
def disallow_get():
return util.get_blocked_response()
@app.get("/favicon.ico")
def disallow_get():
return util.get_blocked_response()
@app.get("/{any}")
def disallow_get(any: Any):
return util.get_blocked_response()
@app.post("/")
def disallow_base_post():
return util.get_blocked_response()
"""
End Blacklisted Routes
"""
"""
Actionable Routes
"""
lyric_search_endpoint = importlib.import_module("endpoints.LyricSearch").LyricSearch(app, util, constants)
"""
End Actionable Routes
"""
# @app.get("/items/{item_id}")
# def read_item(item_id: int, q: Union[str, None] = None):
# return {"item_id": item_id, "q": q}

23
util.py Normal file
View File

@ -0,0 +1,23 @@
#!/usr/bin/env python3.12
import logging
from fastapi import Response
class Utilities:
def __init__(self):
self.blocked_response_status = 422
self.blocked_response_content = None
pass
def get_blocked_response(self, path: str | None = None):
logging.error("Rejected request: Blocked")
return Response(content=self.blocked_response_content,
status_code=self.blocked_response_status)
def get_no_endpoint_found(self, path: str | None = None):
logging.error("Rejected request: No such endpoint")
raise HTTPException(detail="Unknown endpoint", status_code=404)