Skip to content

Commit

Permalink
Extension Loader Rewrite
Browse files Browse the repository at this point in the history
  • Loading branch information
JohnGrubba committed Aug 7, 2024
1 parent d5cb833 commit 76dfa96
Show file tree
Hide file tree
Showing 5 changed files with 53 additions and 37 deletions.
2 changes: 1 addition & 1 deletion src/admin/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ <h1>Stats
<div id="modal-backdrop" class="modal-backdrop">
<div id="api-key-modal" class="modal">
<h2>Enter API Key</h2>
<input type="text" id="api-key-input" placeholder="Enter your API key">
<input type="password" id="api-key-input" placeholder="Enter your API key">
<button id="submit-api-key">Submit</button>
</div>
</div>
Expand Down
2 changes: 1 addition & 1 deletion src/admin/script.js
Original file line number Diff line number Diff line change
Expand Up @@ -159,7 +159,7 @@ document.addEventListener('DOMContentLoaded', () => {
if (apiKey) {
sessionStorage.setItem('apiKey', apiKey)
modalBackdrop.style.display = 'none'
update_stats()
location.reload()
} else {
alert('Please enter a valid API key.')
}
Expand Down
44 changes: 44 additions & 0 deletions src/api/helpers/extension_loader.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
import os
from fastapi import FastAPI
import importlib.util
import logging

logger = logging.getLogger("uvicorn")

modules = []


def load_extensions(app: FastAPI):
global modules
# Extension Loading
extensions_dir = "/src/app/extensions/"
if not os.path.exists(extensions_dir):
return
for item in os.listdir(extensions_dir):
item_path = os.path.join(extensions_dir, item)
init_file = os.path.join(item_path, "__init__.py")
try:
readme_file = open(os.path.join(item_path, "README.md"), "r").read()
except:
logger.error(f"Extension {item} is missing README.md")
continue
if os.path.isdir(item_path) and os.path.isfile(init_file):
spec = importlib.util.spec_from_file_location(item, init_file)
module = importlib.util.module_from_spec(spec)
try:
spec.loader.exec_module(module)
except Exception as e:
logger.error(f"Failed to load extension {item}: {e}")
if logger.level == logging.INFO:
raise e
continue
modules.append([spec, module, readme_file])

for spec, module, _ in modules:
app.include_router(module.router, prefix=f"/ext/{module.__name__}")

logger.info(
"\u001b[32m-> Loaded Extensions: "
+ ", ".join([module.__name__ for spec, module, _ in modules])
+ "\u001b[0m"
)
5 changes: 5 additions & 0 deletions src/api/internal.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
)
from crud.sessions import get_session, count_sessions
from threading import Lock
from api.helpers.extension_loader import modules

email_task_running = Lock()

Expand Down Expand Up @@ -170,4 +171,8 @@ async def stats():
"avg_sess_per_usr": sess_count / usr_count if usr_count else 0,
**count_oauth(),
"pending_users": len(r.scan(match="signup:*")[1]),
"loaded_extensions": [
{"name": module.__name__, "readme": readme}
for spec, module, readme in modules
],
}
37 changes: 2 additions & 35 deletions src/api/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,7 @@
from api.oauth_providers import router as oauthRouter
from api.sessions import router as sessionsRouter
import logging
import os
import importlib
import importlib.util
from api.helpers.extension_loader import load_extensions
from tools import SecurityConfig

__version__ = "0.8.3"
Expand Down Expand Up @@ -63,36 +61,5 @@ async def up():
app.include_router(internalRouter)


def load_extensions():
# Extension Loading
extensions_dir = "/src/app/extensions/"
if not os.path.exists(extensions_dir):
return
modules = []
for item in os.listdir(extensions_dir):
item_path = os.path.join(extensions_dir, item)
init_file = os.path.join(item_path, "__init__.py")
if os.path.isdir(item_path) and os.path.isfile(init_file):
spec = importlib.util.spec_from_file_location(item, init_file)
module = importlib.util.module_from_spec(spec)
try:
spec.loader.exec_module(module)
except Exception as e:
logger.error(f"Failed to load extension {item}: {e}")
if logger.level == logging.INFO:
raise e
continue
modules.append([spec, module])

for spec, module in modules:
app.include_router(module.router, prefix=f"/ext/{module.__name__}")

logger.info(
"\u001b[32m-> Loaded Extensions: "
+ ", ".join([module.__name__ for spec, module in modules])
+ "\u001b[0m"
)


load_extensions()
load_extensions(app)
logger.info("\u001b[32m--- API Startup Done ---\u001b[0m")

0 comments on commit 76dfa96

Please sign in to comment.