This repository was archived by the owner on Dec 19, 2025. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
152 lines (128 loc) · 4.58 KB
/
main.py
File metadata and controls
152 lines (128 loc) · 4.58 KB
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
import os
import atexit
import sqlite3
import queue
import logging
import json
import platform
import subprocess
from flask import Flask
from datetime import datetime
from apscheduler.schedulers.background import BackgroundScheduler
from apscheduler.events import EVENT_JOB_EXECUTED, EVENT_JOB_ERROR, EVENT_JOB_SUBMITTED
from dotenv import load_dotenv
from services.indexer import create_schema, DB_FILE
from services.tasks import TASK_DEFINITIONS, register_task, TASKS, TASK_EVENTS, push_task_event
from services.jobs import job_submitted, job_executed, job_error
from routes.tasks import init_tasks
# --- Load environment ---
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
env_path = os.path.join(BASE_DIR, ".env")
load_dotenv(env_path)
# --- Collect runtime info ---
def get_runtime_info():
try:
os_name = subprocess.check_output(["lsb_release", "-si"]).decode().strip()
os_version = subprocess.check_output(["lsb_release", "-sr"]).decode().strip()
except Exception:
os_name = platform.system()
os_version = platform.release()
return {
"RUNTIME_VERSION": f"Python {platform.python_version()}",
"OS_NAME": os_name,
"OS_VERSION": os_version,
}
# --- Update env.json and .env ---
def update_env_files():
static_dir = os.path.join(BASE_DIR, "static")
os.makedirs(static_dir, exist_ok=True)
env_json_path = os.path.join(static_dir, "env.json")
info = get_runtime_info()
data = {
"APP_NAME": os.getenv("APP_NAME", "Catalogerr"),
"APP_VERSION": os.getenv("APP_VERSION", "dev"),
"INSTANCE_NAME": os.getenv("INSTANCE_NAME", os.uname().nodename),
**info
}
# Write env.json
with open(env_json_path, "w") as f:
json.dump(data, f, indent=2)
logging.info(f"✅ env.json generated at {env_json_path}")
# Update only runtime keys in .env
env_lines = []
if os.path.exists(env_path):
with open(env_path, "r") as f:
env_lines = f.readlines()
keys_to_update = ["RUNTIME_VERSION", "OS_NAME", "OS_VERSION"]
new_lines, updated = [], set()
for line in env_lines:
key = line.split("=")[0].strip()
if key in keys_to_update:
new_lines.append(f"{key}={info[key]}\n")
updated.add(key)
else:
new_lines.append(line)
# Add missing keys at the end
for k in keys_to_update:
if k not in updated:
new_lines.append(f"{k}={info[k]}\n")
with open(env_path, "w") as f:
f.writelines(new_lines)
logging.info(f"✅ Updated runtime info in .env")
# Generate env.json and update .env on startup
update_env_files()
# Debug: log important env vars
for key in ["RADARR_URL", "RADARR_API_KEY", "SONARR_URL", "SONARR_API_KEY", "TMDB_API_KEY"]:
val = os.getenv(key)
if not val:
logging.warning(f"⚠️ Missing env var: {key}")
else:
logging.info(f"✅ Loaded env var: {key}={val[:6]}...")
push_task_event("start", {"task": "Scan"})
# --- Flask app ---
app = Flask(__name__)
app.secret_key = os.getenv("APP_SECRET", "changeme")
@app.context_processor
def inject_now():
return {'now': datetime.now()}
# --- Database init ---
with sqlite3.connect(DB_FILE) as conn:
create_schema(conn)
# --- Scheduler ---
scheduler = BackgroundScheduler()
scheduler.start()
atexit.register(lambda: scheduler.shutdown(wait=False))
for task in TASK_DEFINITIONS:
register_task(task, scheduler, TASKS)
scheduler.add_listener(job_submitted, EVENT_JOB_SUBMITTED)
scheduler.add_listener(job_executed, EVENT_JOB_EXECUTED)
scheduler.add_listener(job_error, EVENT_JOB_ERROR)
# --- Register routes ---
from routes.auth import auth_bp
from routes.catalog import catalog_bp
from routes.drives import drives_bp
from routes.system import system_bp
from routes.scan import scan_bp
from routes.tasks import tasks_bp
from routes.connectors import connectors_bp
from routes.backup import backup_bp
from routes.list import list_bp
from routes.stats import stats_bp
# init tasks with shared queue + scheduler
TASK_EVENTS = queue.Queue()
init_tasks(scheduler)
# blueprints
app.register_blueprint(auth_bp)
app.register_blueprint(catalog_bp)
app.register_blueprint(drives_bp)
app.register_blueprint(system_bp)
app.register_blueprint(scan_bp)
app.register_blueprint(stats_bp)
app.register_blueprint(tasks_bp)
app.register_blueprint(connectors_bp)
app.register_blueprint(backup_bp)
app.register_blueprint(list_bp)
# --- Entry point ---
if __name__ == "__main__":
debug_mode = os.getenv("FLASK_ENV", "development") == "development"
app.run(debug=debug_mode, host="0.0.0.0", port=int(os.getenv("PORT", 8008)))