-
Notifications
You must be signed in to change notification settings - Fork 2
/
invoker.py
384 lines (325 loc) · 12.3 KB
/
invoker.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
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
"""The invoker module is the glue between three concepts.
It combines:
- the BeetSessions (interacting with beets, implementing core functions)
- the Tags (our sql database model, grabbed by the gui to display everything static)
- the Redis Queue (to run the tasks in the background)
"""
from __future__ import annotations
from datetime import datetime
from typing import TYPE_CHECKING
import requests
from rq.decorators import job
from sqlalchemy import delete
from beets_flask.beets_sessions import MatchedImportSession, PreviewSession, colorize
from beets_flask.config import config
from beets_flask.database import Tag, db_session
from beets_flask.redis import import_queue, preview_queue, redis_conn, tag_queue
from beets_flask.routes.errors import InvalidUsage
from beets_flask.routes.status import update_client_view
from beets_flask.utility import log
if TYPE_CHECKING:
from sqlalchemy.orm import Session
def enqueue(id: str, session: Session | None = None):
"""Delegate an existing tag to a redis worker, depending on its kind."""
with db_session(session) as s:
tag = Tag.get_by(Tag.id == id, session=s)
if tag is None:
raise InvalidUsage(f"Tag {id} not found in database")
tag.status = "pending"
s.merge(tag)
s.commit()
update_client_view(
type="tag",
tagId=tag.id,
tagPath=tag.album_folder,
attributes={
"kind": tag.kind,
"status": tag.status,
"updated_at": tag.updated_at.isoformat(),
},
message="Tag enqueued",
)
log.info(f"Enqueued {tag.id=} {tag.album_folder=} {tag.kind=}")
try:
if tag.kind == "preview":
preview_queue.enqueue(runPreview, id)
elif tag.kind == "import":
import_queue.enqueue(runImport, id)
elif tag.kind == "auto":
preview_job = preview_queue.enqueue(runPreview, id)
import_queue.enqueue(AutoImport, id, depends_on=preview_job)
else:
raise ValueError(f"Unknown kind {tag.kind}")
except Exception as e:
log.error(f"Failed to enqueue {tag.id=} {tag.album_folder=} {tag.kind=}")
def enqueue_tag_path(path: str, kind: str, session: Session | None = None):
"""Create or update a tag by a given path.
For a given path that is taggable, update the existing tag or create a new one.
"""
with db_session(session) as s:
tag = Tag.get_by(Tag.album_folder == path, session=s) or Tag(
album_folder=path, kind=kind
)
tag.kind = kind
s.merge(tag)
s.commit()
enqueue(tag.id, session=s)
@job(timeout=600, queue=tag_queue, connection=redis_conn)
def runPreview(
tagId: str,
callback_url: str | None = None,
) -> str | None:
"""Start a preview Session on an existing tag.
Parameters
----------
callback_url: str, optional
Called on success/failure of preview.
Returns
-------
str: the match url, if we found one, else None.
"""
with db_session() as session:
log.debug(f"Preview task on {tagId}")
bt = Tag.get_by(Tag.id == tagId, session=session)
if bt is None:
raise InvalidUsage(f"Tag {tagId} not found in database")
bt.status = "tagging"
bt.updated_at = datetime.now()
session.merge(bt)
session.commit()
update_client_view(
type="tag",
tagId=bt.id,
tagPath=bt.album_folder,
attributes={
"kind": bt.kind,
"status": bt.status,
"updated_at": bt.updated_at.isoformat(),
},
message="Tagging started",
)
try:
bs = PreviewSession(path=bt.album_folder)
bs.run_and_capture_output()
log.debug(bs.preview)
bt.preview = bs.preview
bt.distance = bs.match_dist
bt.match_url = bs.match_url
bt.match_album = bs.match_album
bt.match_artist = bs.match_artist
bt.num_tracks = bs.match_num_tracks
bt.status = (
"tagged"
if (bt.match_url is not None and bs.status == "ok")
else bs.status
)
except Exception as e:
log.debug(e)
bt.status = "failed"
if callback_url:
requests.post(
callback_url,
json={"status": "beets preview failed", "tag": bt.to_dict()},
)
return None
finally:
bt.updated_at = datetime.now()
session.commit()
update_client_view(
type="tag",
tagPath=bt.album_folder,
tagId=bt.id,
attributes="all",
message=f"Tagging finished with status: {bt.status}",
)
if callback_url:
requests.post(
callback_url,
json={"status": "beets preview done", "tag": bt.to_dict()},
)
log.debug(f"preview done. {bt.status=}, {bt.match_url=}")
return bt.match_url
@job(timeout=600, queue=import_queue, connection=redis_conn)
def runImport(
tagId: str,
match_url: str | None = None,
callback_url: str | None = None,
) -> list[str]:
"""Start Import session for a tag.
Relies on a preview to have been generated before.
If it was not, we do it here (blocking the import thread).
We do not import if no match is found according to your beets config.
Parameters
----------
callback_url: str, optional
Called when the import status changes.
Returns
-------
List of track paths after import, as strings. (empty if nothing imported)
"""
with db_session() as session:
log.debug(f"Import task on {tagId}")
bt = Tag.get_by(Tag.id == tagId)
if bt is None:
raise InvalidUsage(f"Tag {tagId} not found in database")
bt.status = "importing"
bt.updated_at = datetime.now()
session.merge(bt)
session.commit()
update_client_view(
type="tag",
tagId=bt.id,
tagPath=bt.album_folder,
attributes={
"kind": bt.kind,
"status": bt.status,
"updated_at": bt.updated_at.isoformat(),
},
message="Importing started",
)
match_url = match_url or _get_or_gen_match_url(tagId, session)
if not match_url:
if callback_url:
requests.post(
callback_url,
json={
"status": "beets import failed: no match url found.",
"tag": bt.to_dict(),
},
)
return []
try:
bs = MatchedImportSession(
path=bt.album_folder, match_url=match_url, tag_id=bt.id
)
bs.run_and_capture_output()
bt.preview = bs.preview
bt.distance = bs.match_dist
bt.match_url = bs.match_url
bt.match_album = bs.match_album
bt.match_artist = bs.match_artist
bt.num_tracks = bs.match_num_tracks
bt.track_paths_after = bs.track_paths_after_import
bt.status = "imported" if bs.status == "ok" else bs.status
log.debug(f"tried import {bt.status=}")
except Exception as e:
log.debug(e)
bt.distance = 1.0
bt.preview = colorize("text_error", str(e))
bt.track_paths_after = []
bt.status = "failed"
if callback_url:
requests.post(
callback_url,
json={"status": "beets import failed", "tag": bt.to_dict()},
)
return []
finally:
bt.updated_at = datetime.now()
session.merge(bt)
session.commit()
log.debug(f"finally {bt.status=}")
update_client_view(
type="tag",
tagId=bt.id,
tagPath=bt.album_folder,
attributes="all",
message=f"Importing finished with status: {bt.status}",
)
if callback_url:
requests.post(
callback_url,
json={"status": "beets preview done", "tag": bt.to_dict()},
)
# cleanup_status()
return bt.track_paths_after
@job(timeout=600, queue=import_queue, connection=redis_conn)
def AutoImport(tagId: str, callback_url: str | None = None) -> list[str] | None:
"""Automatically run an import session.
Runs an import on a tag after a preview has been generated.
We check preview quality and user settings before running the import.
Parameters
----------
tagId:str
The ID of the tag to be imported.
callback_url: str, optional
URL to call on status change
Returns
-------
List of track paths after import, as strings. (empty if nothing imported)
"""
with db_session() as session:
log.debug(f"AutoImport task on {tagId}")
bt = Tag.get_by(Tag.id == tagId, session=session)
if bt is None:
raise InvalidUsage(f"Tag {tagId} not found in database")
if bt.status != "tagged":
log.info(
f"Skipping auto import, we only import after a successfull preview (status 'tagged' not '{bt.status}'). {bt.album_folder=}"
)
# we should consider to do an explicit duplicate check here
# because two previews yielding the same match might finish at the same time
return []
if bt.kind != "auto":
log.debug(
f"For auto importing, tag kind needs to be 'auto' not '{bt.kind}'. {bt.album_folder=}"
)
return []
if config["import"]["timid"].get(bool):
log.info(
"Auto importing is disabled if `import:timid=yes` is set in config"
)
return []
strong_rec_thresh = config["match"]["strong_rec_thresh"].get(float)
if bt.distance is None or bt.distance > strong_rec_thresh: # type: ignore
log.info(
f"Skipping auto import of {bt.album_folder=} with {bt.distance=} > {strong_rec_thresh=}"
)
return []
return runImport(tagId, callback_url=callback_url)
def _get_or_gen_match_url(tagId, session: Session) -> str | None:
bt = Tag.get_by(Tag.id == tagId, session=session)
if bt is None:
raise InvalidUsage(f"Tag {tagId} not found in database")
if bt.match_url is not None:
log.debug(f"Match url already exists for {bt.album_folder}: {bt.match_url}")
return bt.match_url
if bt.distance is None:
log.debug(f"No unique match for {bt.album_folder}: {bt.match_url}")
# preview task was run but no match found.
return None
log.debug(
f"Running preview task to get match url for {bt.album_folder}: {bt.match_url}"
)
bs = PreviewSession(path=bt.album_folder)
bs.run_and_capture_output()
return bs.match_url
def tag_status(
id: str | None = None, path: str | None = None, session: Session | None = None
):
"""Get a tags status.
Get the status of a tag by its id or path.
Returns "untagged" if the tag does not exist or the path was not tagged yet.
"""
with db_session(session) as s:
bt = None
if id is not None:
bt = Tag.get_by(Tag.id == id, session=s)
elif path is not None:
bt = Tag.get_by(Tag.album_folder == path, session=s)
if bt is None or bt.status is None:
return "untagged"
return bt.status
def delete_tags(with_status: list[str]):
"""Delete tags by status.
Delete all tags that have a certain status from the database.
We call this during container launch, to clear up things that
did not finish.
"""
with db_session() as session:
stmt = delete(Tag).where(Tag.status.in_(with_status))
result = session.execute(stmt)
log.debug(
f"Deleted {result.rowcount} tags with statuses: {', '.join(with_status)}"
)
session.commit()