-
-
Notifications
You must be signed in to change notification settings - Fork 140
Expand file tree
/
Copy pathapp_provider_migration.py
More file actions
1769 lines (1610 loc) · 60.7 KB
/
Copy pathapp_provider_migration.py
File metadata and controls
1769 lines (1610 loc) · 60.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
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
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""Provider migration tool — Flask blueprint.
This module is the single add-on entry point for switching the active media
server provider on a running AudioMuse-AI install. It adds a wizard page at
``/provider-migration`` plus the backing REST API under ``/api/migration/*``.
Credentials for the *target* provider stay in ``migration_session.target_creds``
and are passed explicitly to ``tasks.provider_probe`` (which never reads
``config``), so the current live provider keeps working throughout the dry-run
and manual matching steps of the wizard. On successful execution the migration
task writes the new provider settings to ``app_config`` and triggers a config
reload + process restart via ``restart_manager``.
"""
import csv
import io
import json
import logging
from flask import Blueprint, jsonify, render_template, request
# App-level singletons (DB connection, Redis, RQ queues). Importing here keeps
# the blueprint file self-contained — the rest of the app doesn't need to hand
# anything in.
from app_helper import get_db, redis_conn, rq_queue_high, validate_outbound_url
from tasks.mediaserver_helper import detect_path_format as _detect_path_format
logger = logging.getLogger(__name__)
migration_bp = Blueprint('migration_bp', __name__)
# ---------------------------------------------------------------------------
# Lazy provider_probe import — keeps the _import_module bypass test happy
# because we don't trigger ``tasks/__init__.py`` at module-load time.
# ---------------------------------------------------------------------------
class _LazyProbe:
"""Lazy-imports ``tasks.provider_probe`` on first attribute access.
Tests replace ``provider_probe`` on the module directly with a MagicMock,
so the lazy loader never fires during tests.
"""
_real = None
def _load(self):
if self._real is None:
import importlib
self._real = importlib.import_module('tasks.provider_probe')
return self._real
def __getattr__(self, name):
return getattr(self._load(), name)
provider_probe = _LazyProbe()
# ---------------------------------------------------------------------------
# Supported target providers (what the tool knows how to talk to)
# ---------------------------------------------------------------------------
_SUPPORTED_TARGETS = frozenset({'jellyfin', 'navidrome', 'emby', 'lyrion', 'mpd'})
# ---------------------------------------------------------------------------
# SSRF guard for the user-supplied media-server URL. Delegates to the shared
# ``app_helper.validate_outbound_url`` (allows LAN/loopback, blocks non-HTTP(S)
# schemes and link-local/cloud-metadata). MPD targets carry no URL, so a missing
# url is allowed and left to the downstream probe.
# ---------------------------------------------------------------------------
def _validate_probe_url(creds):
"""Return (True, None) if ``creds['url']`` is safe to fetch, else (False, reason)."""
url = (creds or {}).get('url')
if not url:
return True, None
return validate_outbound_url(url)
# ---------------------------------------------------------------------------
# Source path sanity check — matching tiers 1 (path) and 2 (path tail) need
# absolute filesystem paths in ``score.file_path``. If the user's current
# provider stored garbage (Navidrome without Report Real Path, Lyrion stream
# URIs, etc.), we can re-probe the current provider to get real paths and
# apply them to ``old_rows`` before matching.
# ---------------------------------------------------------------------------
_SOURCE_PATH_SAMPLE_SIZE = 100
def _sample_score_file_paths(limit=_SOURCE_PATH_SAMPLE_SIZE):
"""Return up to ``limit`` ``file_path`` values from the score table."""
db = get_db()
with db.cursor() as cur:
cur.execute(
"SELECT file_path FROM score WHERE file_path IS NOT NULL LIMIT %s",
(limit,),
)
rows = cur.fetchall() or []
return [r[0] for r in rows]
def _detect_source_path_format():
"""Classify ``score.file_path`` values by sampling and running
the shared path-format helper. Returns one of
``'absolute' | 'relative' | 'none' | 'mixed'``.
"""
samples = _sample_score_file_paths()
tracks = [{'path': p} for p in samples]
return _detect_path_format(tracks)
def _current_provider_creds():
"""Build a creds dict from ``config`` for the currently active provider.
Returns ``(provider_type, creds_dict)`` or ``(None, {})`` when the
provider isn't one we can re-probe (e.g. MPD — its paths come from the
filesystem directly and don't need refreshing).
"""
import config as cfg
t = (getattr(cfg, 'MEDIASERVER_TYPE', '') or '').lower()
if t == 'jellyfin':
return t, {
'url': getattr(cfg, 'JELLYFIN_URL', ''),
'user_id': getattr(cfg, 'JELLYFIN_USER_ID', ''),
'token': getattr(cfg, 'JELLYFIN_TOKEN', ''),
}
if t == 'emby':
return t, {
'url': getattr(cfg, 'EMBY_URL', ''),
'user_id': getattr(cfg, 'EMBY_USER_ID', ''),
'token': getattr(cfg, 'EMBY_TOKEN', ''),
}
if t == 'navidrome':
return t, {
'url': getattr(cfg, 'NAVIDROME_URL', ''),
'user': getattr(cfg, 'NAVIDROME_USER', ''),
'password': getattr(cfg, 'NAVIDROME_PASSWORD', ''),
}
if t == 'lyrion':
return t, {'url': getattr(cfg, 'LYRION_URL', '')}
return None, {}
def _apply_source_path_overrides(old_rows, overrides):
"""Patch ``old_rows[i]['file_path']`` from the overrides dict in place.
Pure function: the caller runs it before handing ``old_rows`` to the
matcher, so matcher tests don't need to know about overrides at all.
"""
if not overrides:
return old_rows
for r in old_rows:
real = overrides.get(r.get('item_id'))
if real:
r['file_path'] = real
return old_rows
# ---------------------------------------------------------------------------
# Routes — wizard page
# ---------------------------------------------------------------------------
@migration_bp.route('/provider-migration')
def provider_migration_page():
"""
Provider migration wizard page.
---
tags:
- Provider Migration
summary: HTML wizard for migrating analysis state between media-server providers (Jellyfin/Emby/Navidrome/Lyrion).
description: Resumes any in-flight session so a page refresh lands on the right step.
responses:
200:
description: Wizard HTML rendered with `active_session_id` if a non-terminal session exists.
"""
# Look up an in-flight migration so a page refresh can resume the wizard
# at the right step instead of creating a brand new session.
active_session_id = None
try:
db = get_db()
with db.cursor() as cur:
cur.execute(
"SELECT id FROM migration_session "
"WHERE status NOT IN ('completed', 'failed') "
"ORDER BY id DESC LIMIT 1"
)
row = cur.fetchone()
if row:
active_session_id = row[0]
except Exception as e:
logger.warning(
"provider_migration_page: failed to look up active session: %s",
e, exc_info=True,
)
active_session_id = None
return render_template(
'provider_migration.html',
title='Provider Migration',
active='provider_migration',
active_session_id=active_session_id,
)
# ---------------------------------------------------------------------------
# Routes — session CRUD
# ---------------------------------------------------------------------------
@migration_bp.route('/api/migration/session/start', methods=['POST'])
def session_start():
"""
Start a new migration session.
---
tags:
- Provider Migration
summary: Create a `migration_session` row and prune any already-terminal sessions.
requestBody:
required: true
content:
application/json:
schema:
type: object
required: [target_type, target_creds]
properties:
target_type:
type: string
enum: [jellyfin, emby, navidrome, lyrion]
target_creds:
type: object
additionalProperties: true
responses:
200:
description: Session id returned.
content:
application/json:
schema:
type: object
properties:
session_id:
type: integer
400:
description: Unsupported target_type.
"""
payload = request.get_json(silent=True) or {}
target_type = (payload.get('target_type') or '').lower()
target_creds = payload.get('target_creds') or {}
if target_type not in _SUPPORTED_TARGETS:
return jsonify({'error': f'target_type must be one of {sorted(_SUPPORTED_TARGETS)}'}), 400
ok, reason = _validate_probe_url(target_creds)
if not ok:
return jsonify({'error': f'target_creds url is not allowed: {reason}'}), 400
import config
source_type = getattr(config, 'MEDIASERVER_TYPE', '') or ''
db = get_db()
with db.cursor() as cur:
# Prune terminal rows so the table does not grow unboundedly.
# Safe: never touches in-flight sessions (in_progress / dry_run_ready).
cur.execute(
"DELETE FROM migration_session WHERE status IN ('completed', 'failed')"
)
cur.execute(
"INSERT INTO migration_session "
"(source_type, target_type, target_creds, state, status) "
"VALUES (%s, %s, %s, %s, 'in_progress') RETURNING id",
(source_type, target_type, json.dumps(target_creds), json.dumps({})),
)
row = cur.fetchone()
db.commit()
return jsonify({'session_id': row[0]})
@migration_bp.route('/api/migration/session/<int:session_id>', methods=['GET'])
def session_get(session_id):
"""
Inspect a migration session.
---
tags:
- Provider Migration
summary: Return current status and JSON state for a session.
parameters:
- name: session_id
in: path
required: true
schema: { type: integer }
responses:
200:
description: Session summary.
content:
application/json:
schema:
type: object
properties:
id:
type: integer
source_type:
type: string
target_type:
type: string
status:
type: string
enum: [in_progress, dry_run_ready, completed, failed]
state:
type: object
404:
description: Session not found.
"""
db = get_db()
with db.cursor() as cur:
cur.execute(
"SELECT id, source_type, target_type, status, state "
"FROM migration_session WHERE id = %s",
(session_id,),
)
row = cur.fetchone()
if not row:
return jsonify({'error': 'session not found'}), 404
_id, source_type, target_type, status, state = row
if isinstance(state, str):
try:
state = json.loads(state)
except Exception:
state = {}
return jsonify({
'id': _id,
'source_type': source_type,
'target_type': target_type,
'status': status,
'state': state,
})
# ---------------------------------------------------------------------------
# Routes — probe (delegates to tasks.provider_probe, passes creds explicitly)
# ---------------------------------------------------------------------------
@migration_bp.route('/api/migration/session/<int:session_id>', methods=['DELETE'])
def session_discard(session_id):
"""
Discard an in-flight migration session.
---
tags:
- Provider Migration
summary: Delete a non-terminal session row (used by the wizard's Discard button).
description: |
Refuses to touch sessions in `completed` or `failed` status — those are
pruned automatically on the next `session_start`.
parameters:
- name: session_id
in: path
required: true
schema: { type: integer }
responses:
200:
description: Session deleted.
400:
description: Session is already in a terminal state.
404:
description: Session not found.
"""
db = get_db()
with db.cursor() as cur:
cur.execute(
"SELECT status FROM migration_session WHERE id = %s",
(session_id,),
)
row = cur.fetchone()
if not row:
return jsonify({'error': 'session not found'}), 404
if row[0] in ('completed', 'failed'):
return jsonify({'error': 'cannot discard a finished session'}), 400
cur.execute("DELETE FROM migration_session WHERE id = %s", (session_id,))
db.commit()
return jsonify({'ok': True})
@migration_bp.route('/api/migration/probe/test', methods=['POST'])
def probe_test():
"""
Test a target-provider connection.
---
tags:
- Provider Migration
summary: Probe a media-server provider with given credentials and report path quality.
requestBody:
required: true
content:
application/json:
schema:
type: object
required: [type, creds]
properties:
type:
type: string
enum: [jellyfin, emby, navidrome, lyrion]
creds:
type: object
additionalProperties: true
responses:
200:
description: Probe result (always 200; check `ok` for success).
content:
application/json:
schema:
type: object
properties:
ok:
type: boolean
error:
type: string
path_format:
type: string
enum: [absolute, relative, virtual, none]
sample_count:
type: integer
warnings:
type: array
items:
type: string
"""
payload = request.get_json(silent=True) or {}
t = (payload.get('type') or '').lower()
creds = payload.get('creds') or {}
ok, reason = _validate_probe_url(creds)
if not ok:
return jsonify({'ok': False, 'error': reason, 'path_format': 'none',
'sample_count': 0, 'warnings': []}), 200
try:
result = provider_probe.test_connection(t, creds)
except NotImplementedError as e:
return jsonify({'ok': False, 'error': str(e), 'path_format': 'none',
'sample_count': 0, 'warnings': []}), 200
except Exception as e:
return jsonify({'ok': False, 'error': str(e), 'path_format': 'none',
'sample_count': 0, 'warnings': []}), 200
return jsonify(result)
@migration_bp.route('/api/migration/libraries', methods=['POST'])
def libraries_list():
"""
List target-provider music libraries.
---
tags:
- Provider Migration
summary: Step 2 — return the target provider's libraries plus the user's prior checkbox selection.
description: Uses session-stored credentials, never `config`, so the live provider keeps working.
requestBody:
required: true
content:
application/json:
schema:
type: object
required: [session_id]
properties:
session_id:
type: integer
responses:
200:
description: Library list (always 200; check `error` for failures).
content:
application/json:
schema:
type: object
properties:
libraries:
type: array
items:
type: object
unsupported:
type: boolean
selected_libraries:
type: array
items:
type: string
error:
type: string
400:
description: Missing session_id.
404:
description: Session not found.
"""
payload = request.get_json(silent=True) or {}
session_id = payload.get('session_id')
if session_id is None:
return jsonify({'error': 'session_id is required'}), 400
session = _fetch_session_creds(session_id)
if session is None:
return jsonify({'error': 'session not found'}), 404
target_type, creds = session
state = _load_state(session_id) or {}
selected = state.get('selected_libraries')
try:
result = provider_probe.list_libraries(target_type, creds)
except Exception as e:
logger.warning("libraries_list failed for session %s: %s", session_id, e, exc_info=True)
return jsonify({
'libraries': [],
'unsupported': False,
'selected_libraries': selected,
'error': str(e),
}), 200
return jsonify({
'libraries': result.get('libraries', []),
'unsupported': bool(result.get('unsupported', False)),
'selected_libraries': selected,
}), 200
@migration_bp.route('/api/migration/libraries/select', methods=['POST'])
def libraries_select():
"""
Persist library selection into session state.
---
tags:
- Provider Migration
summary: Step 2 — save the user's library checkbox selection (null = no filter, [] = normalized to null).
description: |
Library names cannot contain commas because `MUSIC_LIBRARIES` is stored
as a comma-separated string and split at scan time.
requestBody:
required: true
content:
application/json:
schema:
type: object
required: [session_id]
properties:
session_id:
type: integer
libraries:
type: array
nullable: true
items:
type: string
responses:
200:
description: Selection saved.
content:
application/json:
schema:
type: object
properties:
ok:
type: boolean
selected_libraries:
type: array
nullable: true
items:
type: string
400:
description: Missing session_id, libraries not a list, or comma-containing library name.
"""
payload = request.get_json(silent=True) or {}
session_id = payload.get('session_id')
if session_id is None:
return jsonify({'error': 'session_id is required'}), 400
libraries = payload.get('libraries')
if libraries is not None and not isinstance(libraries, list):
return jsonify({'error': 'libraries must be a list of names or null'}), 400
if isinstance(libraries, list):
cleaned = [str(name).strip() for name in libraries if str(name).strip()]
# MUSIC_LIBRARIES is stored as a comma-separated string and split on
# ',' at scan time, so a name containing a comma would silently
# corrupt the round-trip into multiple bogus fragments.
if any(',' in name for name in cleaned):
return jsonify({'error': 'Library names cannot contain commas.'}), 400
selected = cleaned or None
else:
selected = None
_update_state(session_id, selected_libraries=selected)
return jsonify({'ok': True, 'selected_libraries': selected}), 200
@migration_bp.route('/api/migration/search-albums', methods=['POST'])
def search_albums():
"""
Search target-provider albums.
---
tags:
- Provider Migration
summary: Free-text album search against the target provider (used by step 4 manual matching).
requestBody:
required: true
content:
application/json:
schema:
type: object
required: [session_id]
properties:
session_id:
type: integer
query:
type: string
responses:
200:
description: Album candidates.
content:
application/json:
schema:
type: object
properties:
albums:
type: array
items:
type: object
404:
description: Session not found.
500:
description: Provider error during search.
"""
payload = request.get_json(silent=True) or {}
session_id = payload.get('session_id')
query = payload.get('query') or ''
session = _fetch_session_creds(session_id)
if session is None:
return jsonify({'error': 'session not found'}), 404
target_type, creds = session
try:
albums = provider_probe.search_albums(target_type, creds, query)
except Exception as e:
return jsonify({'error': str(e)}), 500
return jsonify({'albums': albums})
# ---------------------------------------------------------------------------
# Routes — dry run, manual match, finalize
# ---------------------------------------------------------------------------
@migration_bp.route('/api/migration/source-paths/refresh', methods=['POST'])
def source_paths_refresh():
"""
Refresh source-provider real paths.
---
tags:
- Provider Migration
summary: Re-probe the currently active provider to build a {item_id → real_path} override map.
description: |
Called when `score.file_path` is unusable (e.g. Navidrome analyzed
without "Report Real Path"). After refresh, the dry-run can use the
fresh paths for matcher tiers 1 and 2 without rebuilding analysis
from scratch.
requestBody:
required: true
content:
application/json:
schema:
type: object
required: [session_id]
properties:
session_id:
type: integer
responses:
200:
description: Refresh result with override count and any warnings.
content:
application/json:
schema:
type: object
properties:
ok:
type: boolean
source_type:
type: string
path_format:
type: string
overrides_count:
type: integer
warnings:
type: array
items:
type: string
400:
description: Missing session_id, or current provider doesn't support path refresh.
500:
description: Provider probe failed.
"""
payload = request.get_json(silent=True) or {}
session_id = payload.get('session_id')
if session_id is None:
return jsonify({'error': 'session_id is required'}), 400
source_type, creds = _current_provider_creds()
if not source_type:
return jsonify({
'ok': False,
'error': 'The current provider does not support path refresh.',
}), 400
try:
tracks = provider_probe.fetch_all_tracks(source_type, creds)
except Exception as e:
return jsonify({'ok': False, 'error': str(e)}), 500
path_format = _detect_path_format(tracks)
overrides = {
t['id']: t['path']
for t in tracks
if t.get('id') and t.get('path')
}
warnings = []
if path_format != 'absolute':
warnings.append(
f'{source_type} is still not returning absolute paths. '
'Double-check that "Report Real Path" (Navidrome) or the '
'equivalent setting is enabled, then refresh again. You can '
'also proceed with metadata-only matching.'
)
_update_state(session_id, source_path_overrides=overrides)
return jsonify({
'ok': True,
'source_type': source_type,
'path_format': path_format,
'overrides_count': len(overrides),
'warnings': warnings,
})
@migration_bp.route('/api/migration/dry-run', methods=['POST'])
def dry_run():
"""
Run the migration matcher (dry-run).
---
tags:
- Provider Migration
summary: Step 3 — match score rows against the target provider's tracks and persist the result.
description: |
Source `score.file_path` values are sanity-checked first. If they don't
look like absolute filesystem paths, the endpoint returns **409** with
`needs_source_refresh=true` so the UI can prompt the user to enable
"Report Real Path" and call `/source-paths/refresh`. Pass
`bypass_source_check=true` to skip the gate and use metadata-only
matching.
requestBody:
required: true
content:
application/json:
schema:
type: object
required: [session_id]
properties:
session_id:
type: integer
bypass_source_check:
type: boolean
default: false
allow_title_artist_only:
type: boolean
default: false
description: Allow the matcher to fall back to title+artist when album metadata differs.
responses:
200:
description: Dry-run summary.
content:
application/json:
schema:
type: object
properties:
tier_counts:
type: object
matched:
type: integer
unmatched:
type: integer
unmatched_albums_count:
type: integer
404:
description: Session not found.
409:
description: Source paths look unusable; refresh required.
500:
description: Target provider error.
"""
payload = request.get_json(silent=True) or {}
session_id = payload.get('session_id')
bypass_source_check = bool(payload.get('bypass_source_check'))
allow_title_artist_only = bool(payload.get('allow_title_artist_only'))
session = _fetch_session_creds(session_id)
if session is None:
return jsonify({'error': 'session not found'}), 404
target_type, creds = session
# Gate on source path quality. Skip if the user has already refreshed
# (overrides present) or explicitly opted to proceed with metadata-only.
state = _load_state(session_id) or {}
source_overrides = state.get('source_path_overrides') or {}
if not source_overrides and not bypass_source_check:
source_format = _detect_source_path_format()
if source_format != 'absolute':
source_type, _ = _current_provider_creds()
return jsonify({
'needs_source_refresh': True,
'current_source_type': source_type,
'path_format': source_format,
'hint': (
'Your score.file_path values are not absolute filesystem '
'paths. Automatic path-based matching will fall back to '
'metadata only. Refresh source paths, or proceed with '
'metadata-only matching.'
),
}), 409
try:
new_tracks = provider_probe.fetch_all_tracks(target_type, creds)
except Exception as e:
return jsonify({'error': str(e)}), 500
old_rows = _load_score_rows_as_dicts()
_apply_source_path_overrides(old_rows, source_overrides)
# Lazy import of matcher — same reasoning as provider_probe
import importlib
matcher = importlib.import_module('tasks.provider_migration_matcher')
result = matcher.match_tracks(
old_rows, new_tracks,
allow_title_artist_only=allow_title_artist_only,
)
# Serialize only what we need for persistence (no unmatched row dicts in state —
# keep it light; unmatched_by_album is reconstructed from unmatched on demand)
state_dry_run = {
'matches': result['matches'],
'match_tiers': result['match_tiers'],
'tier_counts': result['tier_counts'],
'unmatched_albums': _albums_payload(result['unmatched_by_album']),
# Persist the full count so the wizard can warn the user when the
# rendered list is only a truncated sample.
'unmatched_albums_total': len(result['unmatched_by_album']),
}
# Also snapshot new track metadata keyed by new_id for the post-execute
# score refresh (file_path, title, artist, album, album_artist, year).
new_meta = {
n['id']: {
'path': n.get('path'),
'title': n.get('title'),
'artist': n.get('artist'),
'album': n.get('album'),
'album_artist': n.get('album_artist'),
'year': n.get('year'),
}
for n in new_tracks if n.get('id')
}
_update_state(session_id, dry_run=state_dry_run, new_meta=new_meta,
manual_matches={}, manual_unmatches=[], final_counts=None)
return jsonify({
'tier_counts': result['tier_counts'],
'matched': len(result['matches']),
'unmatched': len(result['unmatched']),
'unmatched_albums_count': len(result['unmatched_by_album']),
})
@migration_bp.route('/api/migration/match-album', methods=['POST'])
def match_album():
"""
Manually match an album.
---
tags:
- Provider Migration
summary: Step 4 — user picked a target album; auto-match its tracks by title (or rematch existing auto-matches).
description: |
With `rematch=true`, the endpoint reprocesses rows that were already
auto-matched for this album: any auto-match for the album is discarded
and replaced by the new target. Rows that don't match in the new target
become explicit orphans via `manual_unmatches`.
requestBody:
required: true
content:
application/json:
schema:
type: object
required: [session_id, old_album_key, new_album_id]
properties:
session_id:
type: integer
old_album_key:
type: array
items:
type: string
description: "[album_artist, album]"
new_album_id:
type: string
rematch:
type: boolean
default: false
responses:
200:
description: Match result for the album.
content:
application/json:
schema:
type: object
properties:
matched:
type: integer
unmatched:
type: integer
unmatched_item_ids:
type: array
items:
type: string
404:
description: Session not found.
500:
description: Target provider error.
"""
payload = request.get_json(silent=True) or {}
session_id = payload.get('session_id')
old_album_key = payload.get('old_album_key') # [album_artist, album]
new_album_id = payload.get('new_album_id')
rematch = bool(payload.get('rematch'))
session = _fetch_session_creds(session_id)
if session is None:
return jsonify({'error': 'session not found'}), 404
target_type, creds = session
try:
new_tracks = provider_probe.get_album_tracks(target_type, creds, new_album_id)
except Exception as e:
return jsonify({'error': str(e)}), 500
import importlib
matcher = importlib.import_module('tasks.provider_migration_matcher')
old_album_tuple = tuple(old_album_key) if isinstance(old_album_key, list) else old_album_key
if rematch:
old_rows = _load_rows_for_album(old_album_tuple)
else:
old_rows = _load_unmatched_for_album(session_id, old_album_tuple)
# Match within the album: exact title, then normalized title
by_title = {}
by_norm_title = {}
for n in new_tracks:
t = (n.get('title') or '').lower()
if t and t not in by_title:
by_title[t] = n['id']
nt = matcher.normalize_meta(n.get('title'))
if nt and nt not in by_norm_title:
by_norm_title[nt] = n['id']
newly_matched = {}
still_unmatched = []
for old in old_rows:
title_l = (old.get('title') or '').lower()
nt = matcher.normalize_meta(old.get('title'))
if title_l in by_title:
newly_matched[old['item_id']] = by_title[title_l]
elif nt and nt in by_norm_title:
newly_matched[old['item_id']] = by_norm_title[nt]
else:
still_unmatched.append(old['item_id'])
if rematch:
_rematch_album_rows(session_id, newly_matched, still_unmatched)
else:
_merge_manual_matches(session_id, newly_matched)
return jsonify({
'matched': len(newly_matched),
'unmatched': len(still_unmatched),
'unmatched_item_ids': still_unmatched,
})
@migration_bp.route('/api/migration/skip-album', methods=['POST'])
def skip_album():
"""
Skip an album (mark its rows as orphans).
---
tags:
- Provider Migration
summary: Step 4 — orphan an album so its score rows will be deleted by execute.
description: |
First-time skips (unmatched albums) just need a ledger note. Rematch
skips (`rematch=true`) push every row in the album into
`manual_unmatches` so finalize overrides the existing auto-match.
requestBody:
required: true
content:
application/json:
schema:
type: object
required: [session_id, old_album_key]
properties:
session_id: