-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathapp.py
More file actions
286 lines (228 loc) · 10.7 KB
/
app.py
File metadata and controls
286 lines (228 loc) · 10.7 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
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
from flask import Flask, render_template, request, Response, stream_with_context
import os
import signal
import requests
import time
import json
import threading
from dotenv import load_dotenv
load_dotenv()
# ─────────────────────────────────────────────────────────────
# APP SETTINGS
# ─────────────────────────────────────────────────────────────
app = Flask(__name__)
app.secret_key = os.getenv("CODEBARR_SECRET_KEY", "your_secret_key_here")
LIDARR_URL = os.getenv("LIDARR_URL").rstrip("/")
API_KEY = os.getenv("LIDARR_API_KEY")
HEADERS = {"X-Api-Key": API_KEY}
REQUEST_TIMEOUT = 10
USERNAME = os.getenv("CODEBARR_USERNAME")
PASSWORD = os.getenv("CODEBARR_PASSWORD")
LIDARR_DEFAULTS = {
"rootFolderPath": os.getenv("LIDARR_ROOT_FOLDER_PATH", "/music"),
"qualityProfileId": int(os.getenv("LIDARR_QUALITY_PROFILE", 2)),
"metadataProfileId": int(os.getenv("LIDARR_METADATA_PROFILE", 1)),
"monitorNewItems": os.getenv("LIDARR_MONITOR_NEW_ITEMS", "none"),
"addOptions": {
"searchForMissingAlbums": os.getenv("LIDARR_SEARCH_ON_ADD", "False").lower() in {"true","1","yes"}
}
}
# ─────────────────────────────────────────────────────────────
# AUTH
# ─────────────────────────────────────────────────────────────
def check_auth(username, password):
return username == USERNAME and password == PASSWORD
def authenticate():
return Response("Authentication required", 401,
{"WWW-Authenticate": 'Basic realm="Codebarr"'})
def requires_auth(f):
def decorated(*args, **kwargs):
auth = request.authorization
if not auth or not check_auth(auth.username, auth.password):
return authenticate()
return f(*args, **kwargs)
decorated.__name__ = f.__name__
return decorated
# ─────────────────────────────────────────────────────────────
# MUSICBRAINZ
# ─────────────────────────────────────────────────────────────
def get_release_from_barcode(barcode):
r = requests.get(
f"https://musicbrainz.org/ws/2/release/?query=barcode:{barcode}&fmt=json",
timeout=REQUEST_TIMEOUT
)
r.raise_for_status()
data = r.json()
if not data.get("releases"):
raise Exception(f"No release found for barcode {barcode}")
return data["releases"][0]
# ─────────────────────────────────────────────────────────────
# LIDARR HELPERS (SAFE)
# ─────────────────────────────────────────────────────────────
def get_artist_by_mbid(artist_mbid):
artists = requests.get(
f"{LIDARR_URL}/api/v1/artist",
headers=HEADERS,
timeout=REQUEST_TIMEOUT
).json()
return next(
(a for a in artists if a.get("foreignArtistId") == artist_mbid),
None
)
def wait_for_album_ready(album_id, timeout=60):
elapsed = 0
while elapsed < timeout:
album = requests.get(
f"{LIDARR_URL}/api/v1/album/{album_id}",
headers=HEADERS,
timeout=REQUEST_TIMEOUT
).json()
# Album refresh is done when statistics exist
if album.get("statistics"):
return album
time.sleep(2)
elapsed += 2
raise Exception("Album never finished refreshing")
def create_artist(artist_name, artist_mbid):
payload = {
"artistName": artist_name,
"foreignArtistId": artist_mbid,
"rootFolderPath": LIDARR_DEFAULTS["rootFolderPath"],
"qualityProfileId": LIDARR_DEFAULTS["qualityProfileId"],
"metadataProfileId": LIDARR_DEFAULTS["metadataProfileId"],
"monitored": False,
"monitorNewItems": LIDARR_DEFAULTS["monitorNewItems"],
"addOptions": LIDARR_DEFAULTS["addOptions"]
}
r = requests.post(
f"{LIDARR_URL}/api/v1/artist",
headers=HEADERS,
json=payload,
timeout=REQUEST_TIMEOUT
)
r.raise_for_status()
return r.json()["id"]
def wait_for_album(artist_id, release_group_mbid, timeout=60):
elapsed = 0
while elapsed < timeout:
albums = requests.get(
f"{LIDARR_URL}/api/v1/album?artistId={artist_id}",
headers=HEADERS,
timeout=REQUEST_TIMEOUT
).json()
album = next(
(a for a in albums if a.get("foreignAlbumId") == release_group_mbid),
None
)
if album:
return album
time.sleep(2)
elapsed += 2
raise Exception("Album never appeared in Lidarr")
def wait_for_release(album_id, release_mbid, timeout=60):
elapsed = 0
while elapsed < timeout:
r = requests.get(
f"{LIDARR_URL}/api/v1/album/{album_id}",
headers=HEADERS,
timeout=REQUEST_TIMEOUT
)
if r.status_code == 404:
time.sleep(2)
elapsed += 2
continue
album = r.json()
releases = album.get("releases", [])
release = next(
(rel for rel in releases if rel.get("foreignReleaseId") == release_mbid),
None
)
if release:
return album, releases
time.sleep(2)
elapsed += 2
raise Exception("Exact release never appeared")
# ─────────────────────────────────────────────────────────────
# MAIN PROCESS (BULLETPROOF)
# ─────────────────────────────────────────────────────────────
def process_barcode(barcode):
try:
yield json.dumps({"status": "🔍 Looking up barcode...", "progress": 5}) + "\n\n"
release = get_release_from_barcode(barcode)
release_mbid = release["id"]
release_group_mbid = release["release-group"]["id"]
album_title = release["title"]
artist_credit = release["artist-credit"][0]
artist_name = artist_credit["name"]
artist_mbid = artist_credit["artist"]["id"]
yield json.dumps({"status": f"🎵 Found '{album_title}' by {artist_name}", "progress": 15}) + "\n\n"
# ───── ARTIST ─────
yield json.dumps({"status": "👤 Checking artist...", "progress": 30}) + "\n\n"
artist = get_artist_by_mbid(artist_mbid)
if not artist:
artist_id = create_artist(artist_name, artist_mbid)
else:
artist_id = artist["id"]
# ───── ALBUM ─────
yield json.dumps({"status": "📀 Checking album...", "progress": 50}) + "\n\n"
try:
album = wait_for_album(artist_id, release_group_mbid)
album_id = album["id"]
yield json.dumps({"status": f"Album '{album_title}' exists", "progress": 55}) + "\n\n"
except Exception:
# Album not yet created by Lidarr, create it
artist_data = requests.get(f"{LIDARR_URL}/api/v1/artist/{artist_id}", headers=HEADERS, timeout=REQUEST_TIMEOUT).json()
payload = {
"artistId": artist_id,
"artist": artist_data,
"foreignAlbumId": release_group_mbid,
"title": album_title,
"monitored": False,
"addOptions": {"searchForNewAlbum": False}
}
r = requests.post(f"{LIDARR_URL}/api/v1/album", headers=HEADERS, json=payload, timeout=REQUEST_TIMEOUT)
r.raise_for_status()
album_id = r.json()["id"]
yield json.dumps({"status": f"Album '{album_title}' created", "progress": 55}) + "\n\n"
# ───── WAIT FOR ALBUM REFRESH ─────
yield json.dumps({"status": "⏳ Waiting for album refresh...", "progress": 75}) + "\n\n"
album_data = wait_for_album_ready(album_id)
# ───── PIN AND MONITOR EXACT RELEASE ─────
album_data["monitored"] = True
album_data["foreignReleaseId"] = release_mbid
releases = album_data.get("releases", [])
for r in releases:
r["monitored"] = (r.get("foreignReleaseId") == release_mbid)
album_data["releases"] = releases
requests.put(f"{LIDARR_URL}/api/v1/album/{album_id}", headers=HEADERS, json=album_data, timeout=REQUEST_TIMEOUT).raise_for_status()
yield json.dumps({"status": f"✅ Monitoring exact release of '{album_title}'", "progress": 100}) + "\n\n"
except requests.exceptions.RequestException as e:
yield json.dumps({"status": f"❌ Network/Lidarr error: {e}", "progress": 100}) + "\n\n"
except Exception as e:
yield json.dumps({"status": f"❌ Error: {e}", "progress": 100}) + "\n\n"
# ─────────────────────────────────────────────────────────────
# ROUTES
# ─────────────────────────────────────────────────────────────
@app.route("/")
@requires_auth
def index():
return render_template("index.html")
@app.route("/submit", methods=["POST"])
def submit():
barcode = request.form.get("barcode")
if not barcode:
return Response("No barcode", status=400)
return Response(
stream_with_context(process_barcode(barcode)),
mimetype="text/event-stream"
)
@app.route("/shutdown", methods=["POST"])
def shutdown():
def delayed():
time.sleep(1)
os.kill(os.getpid(), signal.SIGTERM)
threading.Thread(target=delayed).start()
return Response("Codebarr is shutting down...", mimetype="text/plain")
# ─────────────────────────────────────────────────────────────
if __name__ == "__main__":
app.run(host="0.0.0.0", port=5083, debug=True)