-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathplaylist.rs
More file actions
947 lines (887 loc) · 36.1 KB
/
Copy pathplaylist.rs
File metadata and controls
947 lines (887 loc) · 36.1 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
//! Playlist CRUD commands.
//!
//! Mirrors [`super::library`] but targets the `playlist` / `playlist_track`
//! tables. A playlist is an ordered, user-curated collection of tracks that
//! can cross library boundaries — the track rows themselves still live under
//! a `library_id`, the playlist just points at them through `playlist_track`.
//!
//! All mutations bump `playlist.updated_at` so the sidebar (which orders
//! playlists by `updated_at DESC` as a tie-break) reflects recent edits.
use chrono::Utc;
use sqlx::FromRow;
use waveflow_core::repository::{
playlist::{PlaylistDraft, PlaylistRepository, PlaylistUpdate},
sqlite::{
playlist::{
append_track_conn, append_tracks_conn, delete_conn, insert_custom_conn,
remove_track_conn, reorder_track_conn, update_conn,
},
SqlitePlaylistRepository, SqliteTrackRepository,
},
track::{TrackRepository, TrackSource},
};
use crate::{
error::{AppError, AppResult},
state::{AppState, Leased},
};
// `Playlist` + input DTOs moved to `waveflow_core::domain::playlist` in
// the Phase 1.a refactor. Re-exported so existing call sites
// (`crate::commands::playlist::Playlist`) keep resolving.
pub use waveflow_core::domain::playlist::{CreatePlaylistInput, Playlist, UpdatePlaylistInput};
fn now_millis() -> i64 {
Utc::now().timestamp_millis()
}
/// Build a playlist repository over the active profile's pool. Wrapped
/// in [`Leased`] for the same reason as `library::library_repo` — the
/// lease must outlive the repository (issue #332).
async fn playlist_repo(state: &AppState) -> AppResult<Leased<SqlitePlaylistRepository>> {
let (pool, lease) = state.require_profile_pool().await?.into_parts();
Ok(Leased::new(SqlitePlaylistRepository::new(pool), lease))
}
/// Resolve `cover_hash` to an absolute on-disk path if (and only if) the
/// file is present in the shared metadata cache. Mutates the playlist in
/// place — kept as a free function so both list and detail queries share
/// the resolver without duplicating the path glue.
fn resolve_cover_path(p: &mut Playlist, paths: &crate::paths::AppPaths) {
if let Some(hash) = p.cover_hash.as_deref() {
p.cover_path = crate::metadata_artwork::existing_path(&paths.metadata_artwork_dir, hash);
}
}
/// List every playlist in the active profile, ordered by `position` first
/// (for future manual reordering) then `updated_at DESC` as a tie-break so
/// recently-edited playlists float to the top by default.
#[tauri::command]
pub async fn list_playlists(state: tauri::State<'_, AppState>) -> AppResult<Vec<Playlist>> {
let mut playlists = playlist_repo(&state).await?.list_all_with_counts().await?;
for p in &mut playlists {
resolve_cover_path(p, &state.paths);
}
Ok(playlists)
}
/// Fetch a single playlist by id. Used by the PlaylistView header.
#[tauri::command]
pub async fn get_playlist(
state: tauri::State<'_, AppState>,
playlist_id: i64,
) -> AppResult<Playlist> {
let mut playlist = playlist_repo(&state)
.await?
.get_with_counts(playlist_id)
.await?
.ok_or_else(|| {
AppError::Other(format!(
"playlist {playlist_id} not found in active profile"
))
})?;
resolve_cover_path(&mut playlist, &state.paths);
Ok(playlist)
}
/// Create a new playlist. Follows the same defaults as
/// [`CreatePlaylistModal`](../../../../src/components/common/CreatePlaylistModal.tsx):
/// violet color, music icon.
#[tauri::command]
pub async fn create_playlist(
state: tauri::State<'_, AppState>,
input: CreatePlaylistInput,
) -> AppResult<Playlist> {
let name = input.name.trim().to_string();
if name.is_empty() {
return Err(AppError::Other("playlist name cannot be empty".into()));
}
let color_id = input.color_id.unwrap_or_else(|| "violet".to_string());
let icon_id = input.icon_id.unwrap_or_else(|| "music".to_string());
let now = now_millis();
let draft = PlaylistDraft {
name: name.clone(),
description: input.description.clone(),
color_id: color_id.clone(),
icon_id: icon_id.clone(),
now_ms: now,
};
// Atomic write + outbox enqueue (issue #193). The playlist
// INSERT and the matching `sync_pending_op` row land in the
// same SQLite transaction; either both commit or both roll
// back. Closes the drift window the fire-and-forget
// `enqueue_op` had between two consecutive commits.
let pool = state.require_profile_pool().await?;
let mut tx = pool.begin().await?;
let id = insert_custom_conn(&mut tx, &draft).await?;
// Mint the canonical id INSIDE the same tx so the playlist row +
// sync_id_map row + outbox op all reference the same UUID. Other
// devices reading the broadcast will route entity_id through
// their own sync_id_map to find the local rowid.
let canonical = crate::sync::canonical::ensure_local_playlist(&mut tx, id).await?;
let stamp = crate::sync::hooks::enqueue_op_in_tx(
&mut tx,
&crate::sync::hooks::PendingOpDraft {
entity: "playlist".into(),
entity_id: canonical,
field: None,
op: "insert".into(),
payload: Some(serde_json::json!({
"name": name,
"description": input.description,
"color_id": color_id,
"icon_id": icon_id,
})),
},
)
.await?;
// Phase B.0 — stamp the playlist row with the queued op's HLC +
// payload_hash so the desktop's metadata_digest reflects the
// INSERT. Only fires when `enqueue_op_in_tx` actually wrote (sync
// gate / SyncMode::Local short-circuits return `None`); the row
// INSERT itself proceeds either way.
if let Some(stamp) = stamp {
if let Some(fields) = crate::sync::payload::playlist::fields_from_row(&mut tx, id).await? {
crate::sync::payload::playlist::stamp_in_tx(&mut tx, id, fields, stamp).await?;
}
}
tx.commit().await?;
// Wake the drain task so a chatty user's edits don't wait the
// full 30 s tick before reaching the server.
state.drain.notify();
Ok(Playlist {
id,
// Desktop single-tenant — profile boundary is the database
// file itself. `0` is the sentinel waveflow-core's
// `Playlist.profile_id` doc-comment defines for this side.
profile_id: 0,
name,
description: input.description,
color_id,
icon_id,
is_smart: 0,
cover_hash: None,
cover_path: None,
cover_is_auto: 1,
position: 0,
created_at: now,
updated_at: now,
track_count: 0,
total_duration_ms: 0,
smart_rules: None,
})
}
/// Partial update — name/description/color/icon. Bumps `updated_at`.
#[tauri::command]
pub async fn update_playlist(
state: tauri::State<'_, AppState>,
playlist_id: i64,
input: UpdatePlaylistInput,
) -> AppResult<()> {
let trimmed_name = input.name.as_ref().map(|s| s.trim().to_string());
if let Some(name) = &trimmed_name {
if name.is_empty() {
return Err(AppError::Other("playlist name cannot be empty".into()));
}
}
let patch = PlaylistUpdate {
name: trimmed_name.clone(),
description: input.description.clone(),
color_id: input.color_id.clone(),
icon_id: input.icon_id.clone(),
};
// Atomic existence-check + update + per-field outbox ops in one
// tx. `update_conn` now returns the rows-affected boolean so a
// concurrent delete between the pre-1.f exists() probe and the
// UPDATE can't slip an enqueue past — if no row was touched we
// drop the tx (auto-rollback on drop) and return the same 404-
// style error the previous shape did, but without the race
// window. One Lamport bump per supplied field so the server can
// replay them in order against concurrent updates from another
// device.
let pool = state.require_profile_pool().await?;
let mut tx = pool.begin().await?;
let updated = update_conn(&mut tx, playlist_id, &patch, now_millis()).await?;
if !updated {
return Err(AppError::Other(format!(
"playlist {playlist_id} not found in active profile"
)));
}
// Resolve the playlist's canonical id so the outbox row carries
// the cross-device identifier rather than the local rowid. A
// playlist without a canonical (pre-1.f.desktop.4b row that
// dodged the migration backfill — shouldn't happen, but the
// fallback keeps the tx atomic) gets one minted here.
let entity_id = crate::sync::canonical::ensure_local_playlist(&mut tx, playlist_id).await?;
let mut last_stamp: Option<crate::sync::hooks::EnqueuedStamp> = None;
for (field, value) in [
("name", trimmed_name.map(serde_json::Value::String)),
(
"description",
input.description.map(serde_json::Value::String),
),
("color_id", input.color_id.map(serde_json::Value::String)),
("icon_id", input.icon_id.map(serde_json::Value::String)),
] {
if let Some(value) = value {
let stamp = crate::sync::hooks::enqueue_op_in_tx(
&mut tx,
&crate::sync::hooks::PendingOpDraft {
entity: "playlist".into(),
entity_id: entity_id.clone(),
field: Some(field.into()),
op: "set".into(),
payload: Some(serde_json::json!({ "value": value })),
},
)
.await?;
if let Some(s) = stamp {
last_stamp = Some(s);
}
}
}
// Phase B.0 — stamp once at the end with the latest queued op's
// HLC, reading the canonical fields from the persisted row so the
// hash reflects what's actually on disk (defence-in-depth against
// future normalisation in `update_conn`).
if let Some(stamp) = last_stamp {
if let Some(fields) =
crate::sync::payload::playlist::fields_from_row(&mut tx, playlist_id).await?
{
crate::sync::payload::playlist::stamp_in_tx(&mut tx, playlist_id, fields, stamp)
.await?;
}
}
tx.commit().await?;
// Wake the drain task so a chatty user's edits don't wait the
// full 30 s tick before reaching the server.
state.drain.notify();
Ok(())
}
/// Delete a playlist. `ON DELETE CASCADE` on `playlist_track` removes the
/// track links, but the underlying `track` rows are preserved — they still
/// belong to their library.
#[tauri::command]
pub async fn delete_playlist(state: tauri::State<'_, AppState>, playlist_id: i64) -> AppResult<()> {
let pool = state.require_profile_pool().await?;
let mut tx = pool.begin().await?;
// Resolve canonical BEFORE the DELETE — the row (and any
// canonical_id column on it) is gone after delete_conn.
let canonical = crate::sync::canonical::canonical_for_local(
&mut tx,
crate::sync::canonical::ENTITY_PLAYLIST,
playlist_id,
)
.await?;
if !delete_conn(&mut tx, playlist_id).await? {
return Err(AppError::Other(format!(
"playlist {playlist_id} not found in active profile"
)));
}
// Drop the mapping row in the same tx so a future inbound op
// referencing the same canonical doesn't get routed to a
// dangling rowid. Falls back to the local rowid as `entity_id`
// when the mapping was missing (pre-1.f.desktop.4b row that
// dodged the migration backfill — shouldn't happen, but the
// fallback keeps the tx shape consistent).
let entity_id = if let Some(ref c) = canonical {
crate::sync::canonical::drop_mapping(&mut tx, crate::sync::canonical::ENTITY_PLAYLIST, c)
.await?;
c.clone()
} else {
playlist_id.to_string()
};
let stamp = crate::sync::hooks::enqueue_op_in_tx(
&mut tx,
&crate::sync::hooks::PendingOpDraft {
entity: "playlist".into(),
entity_id,
field: None,
op: "delete".into(),
payload: None,
},
)
.await?;
// Phase B.0 — bump the playlist digest counter on delete. No row
// to stamp (the DELETE already ran), but the set member's removal
// still has to be visible to the backfill protocol.
if stamp.is_some() {
crate::sync::payload::bump_digest_in_tx(&mut tx, "playlist").await?;
}
tx.commit().await?;
// Wake the drain task so a chatty user's edits don't wait the
// full 30 s tick before reaching the server.
state.drain.notify();
tracing::info!(playlist_id, "playlist deleted");
Ok(())
}
/// List every track of a playlist in its stored order. Mirrors the SELECT in
/// [`super::track::list_tracks`] with an extra `JOIN playlist_track` so the
/// ordering follows the user's arrangement (`pt.position ASC`) instead of
/// the alphabetical artist/album/disc/track sort.
#[tauri::command]
pub async fn list_playlist_tracks(
state: tauri::State<'_, AppState>,
playlist_id: i64,
) -> AppResult<crate::commands::track::ListTracksResponse> {
let pool = state.require_profile_pool().await?;
let profile_id = state.require_profile_id().await?;
let artwork_dir = state.paths.profile_artwork_dir(profile_id);
let rows = SqliteTrackRepository::new((*pool).clone())
.list_in_playlist(playlist_id)
.await?;
// Same blocking-pool offload as `list_tracks` — large playlists
// (the Liked Songs pseudo-playlist routinely runs 800+ rows on a
// healthy library) would otherwise stall the runtime on per-row
// `Path::exists` thumbnail probes.
let artwork_dir_for_blocking = artwork_dir.clone();
let items = tokio::task::spawn_blocking(move || {
rows.into_iter()
.map(|row| {
crate::commands::track::track_list_item_from_row(row, &artwork_dir_for_blocking)
})
.collect()
})
.await
.map_err(|e| AppError::Other(format!("list_playlist_tracks join: {e}")))?;
Ok(crate::commands::track::ListTracksResponse {
artwork_base: artwork_dir.to_string_lossy().into_owned(),
items,
})
}
/// Return the IDs of every user playlist that currently contains `track_id`.
/// Smart playlists are excluded — their membership is computed on the fly
/// from rules and would be misleading to expose as a toggle target.
///
/// Used by the `+` popover to render a checkmark on rows the track is
/// already in (and to flip the click handler from "add" to "remove").
#[tauri::command]
pub async fn list_playlists_containing_track(
state: tauri::State<'_, AppState>,
track_id: i64,
) -> AppResult<Vec<i64>> {
Ok(playlist_repo(&state)
.await?
.list_user_playlists_containing(track_id)
.await?)
}
/// Append a single track to the end of a playlist. Idempotent — if the track
/// is already in the playlist the existing row is preserved and `updated_at`
/// is still bumped so the UI reflects the user's intent.
#[tauri::command]
pub async fn add_track_to_playlist(
state: tauri::State<'_, AppState>,
playlist_id: i64,
track_id: i64,
) -> AppResult<()> {
let pool = state.require_profile_pool().await?;
let profile_id = state.require_profile_id().await?;
let now = now_millis();
let mut tx = pool.begin().await?;
append_track_conn(&mut tx, playlist_id, track_id, now).await?;
let entity_id = crate::sync::canonical::ensure_local_playlist(&mut tx, playlist_id).await?;
// Phase 1.j.b — fold per-track snapshots into the outbound
// payload so the server's `playlist_track.snapshot_*` columns
// land populated and the public share preview can render the
// track without resolving the local-i64 id cross-device.
let snapshots = crate::sync::track_snapshots::build_snapshots(&mut tx, &[track_id]).await?;
crate::sync::hooks::enqueue_op_in_tx(
&mut tx,
&crate::sync::hooks::PendingOpDraft {
entity: "playlist".into(),
entity_id,
field: Some("tracks".into()),
op: "insert".into(),
payload: Some(serde_json::json!({
"track_ids": [track_id],
"snapshots": snapshots,
})),
},
)
.await?;
tx.commit().await?;
// Wake the drain task so a chatty user's edits don't wait the
// full 30 s tick before reaching the server.
state.drain.notify();
// Cover regen runs OUTSIDE the tx — it does its own pool read +
// a filesystem-level rasterise, neither of which belongs in the
// atomic write window.
super::playlist_cover::maybe_regen_auto_cover(&pool, &state.paths, profile_id, playlist_id)
.await;
Ok(())
}
/// Bulk variant of [`add_track_to_playlist`]. Inserts every track one by one
/// (so positions stay contiguous even if some are duplicates) and returns
/// the count that were actually inserted.
#[tauri::command]
pub async fn add_tracks_to_playlist(
state: tauri::State<'_, AppState>,
playlist_id: i64,
track_ids: Vec<i64>,
) -> AppResult<u32> {
let pool = state.require_profile_pool().await?;
let profile_id = state.require_profile_id().await?;
let now = now_millis();
let mut tx = pool.begin().await?;
let inserted = append_tracks_conn(&mut tx, playlist_id, &track_ids, now).await?;
let entity_id = crate::sync::canonical::ensure_local_playlist(&mut tx, playlist_id).await?;
// Phase 1.j.b — per-track snapshots for the public share
// preview. See [`add_track_to_playlist`] for the rationale.
let snapshots = crate::sync::track_snapshots::build_snapshots(&mut tx, &track_ids).await?;
// One coalesced op for the whole batch — emitting N ops would
// cost N Lamport draws and bloat the queue without giving the
// server side any extra signal.
crate::sync::hooks::enqueue_op_in_tx(
&mut tx,
&crate::sync::hooks::PendingOpDraft {
entity: "playlist".into(),
entity_id,
field: Some("tracks".into()),
op: "insert".into(),
payload: Some(serde_json::json!({
"track_ids": track_ids,
"snapshots": snapshots,
})),
},
)
.await?;
tx.commit().await?;
// Wake the drain task so a chatty user's edits don't wait the
// full 30 s tick before reaching the server.
state.drain.notify();
super::playlist_cover::maybe_regen_auto_cover(&pool, &state.paths, profile_id, playlist_id)
.await;
Ok(inserted)
}
/// Remove a single track and renumber the tail so positions stay contiguous.
#[tauri::command]
pub async fn remove_track_from_playlist(
state: tauri::State<'_, AppState>,
playlist_id: i64,
track_id: i64,
) -> AppResult<()> {
let pool = state.require_profile_pool().await?;
let profile_id = state.require_profile_id().await?;
let mut tx = pool.begin().await?;
let removed = remove_track_conn(&mut tx, playlist_id, track_id, now_millis()).await?;
// Only enqueue when the local DELETE actually touched a row —
// otherwise a `remove` op against a track that wasn't in the
// playlist (concurrent removal, double-click, stale UI state)
// would replay on the server and drop a row that legitimately
// belonged there. The tx still commits so the no-op stays
// idempotent from the caller's POV.
if removed {
let entity_id = crate::sync::canonical::ensure_local_playlist(&mut tx, playlist_id).await?;
crate::sync::hooks::enqueue_op_in_tx(
&mut tx,
&crate::sync::hooks::PendingOpDraft {
entity: "playlist".into(),
entity_id,
field: Some("tracks".into()),
op: "delete".into(),
payload: Some(serde_json::json!({ "track_ids": [track_id] })),
},
)
.await?;
}
tx.commit().await?;
// Wake the drain task so a chatty user's edits don't wait the
// full 30 s tick before reaching the server.
state.drain.notify();
if removed {
super::playlist_cover::maybe_regen_auto_cover(&pool, &state.paths, profile_id, playlist_id)
.await;
}
Ok(())
}
/// Move a track to a new absolute position inside a playlist, shifting
/// the surrounding rows so positions stay dense. Used by the
/// drag-and-drop UI. `new_position` is clamped to `[0, length - 1]`
/// so an out-of-range drop snaps to the nearest end instead of erroring.
///
/// `playlist_track.position` is non-UNIQUE (just an index for ORDER BY)
/// so the shift is a single bulk UPDATE per direction; no offset
/// gymnastics needed unlike the queue's UNIQUE-positioned variant.
#[tauri::command]
pub async fn reorder_playlist_track(
state: tauri::State<'_, AppState>,
playlist_id: i64,
track_id: i64,
new_position: i64,
) -> AppResult<()> {
let pool = state.require_profile_pool().await?;
let profile_id = state.require_profile_id().await?;
// Atomic move + outbox enqueue in one tx. `reorder_track_conn`
// returns the effective position (the value after the repo's
// internal clamp) so the sync payload matches the row's actual
// new state — closes the divergence path #192 documented when
// sending the raw `new_position` to the server.
let mut tx = pool.begin().await?;
let effective =
reorder_track_conn(&mut tx, playlist_id, track_id, new_position, now_millis()).await?;
let Some(position_for_sync) = effective else {
return Err(AppError::Other(format!(
"track {track_id} not in playlist {playlist_id}"
)));
};
let entity_id = crate::sync::canonical::ensure_local_playlist(&mut tx, playlist_id).await?;
crate::sync::hooks::enqueue_op_in_tx(
&mut tx,
&crate::sync::hooks::PendingOpDraft {
entity: "playlist".into(),
entity_id,
field: Some("tracks".into()),
op: "set".into(),
payload: Some(serde_json::json!({
"track_id": track_id,
"position": position_for_sync,
})),
},
)
.await?;
tx.commit().await?;
// Wake the drain task so a chatty user's edits don't wait the
// full 30 s tick before reaching the server.
state.drain.notify();
super::playlist_cover::maybe_regen_auto_cover(&pool, &state.paths, profile_id, playlist_id)
.await;
Ok(())
}
/// Add every available track matching a source (folder, album, artist) to a
/// playlist in one server-side transaction — avoids round-tripping thousands
/// of track IDs through the IPC bridge.
///
/// `source_type` must be one of `"folder"`, `"album"`, `"artist"`.
/// Returns the number of tracks actually inserted (duplicates are skipped).
#[tauri::command]
pub async fn add_source_to_playlist(
state: tauri::State<'_, AppState>,
playlist_id: i64,
source_type: String,
source_id: i64,
) -> AppResult<u32> {
let pool = state.require_profile_pool().await?;
let profile_id = state.require_profile_id().await?;
let source = match source_type.as_str() {
"folder" => TrackSource::Folder(source_id),
"album" => TrackSource::Album(source_id),
"artist" => TrackSource::Artist(source_id),
other => {
return Err(AppError::Other(format!(
"unknown source_type '{other}', expected folder/album/artist"
)));
}
};
let track_ids = SqliteTrackRepository::new(pool.clone())
.list_ids_in_source(source)
.await?;
let mut tx = pool.begin().await?;
let inserted = append_tracks_conn(&mut tx, playlist_id, &track_ids, now_millis()).await?;
let entity_id = crate::sync::canonical::ensure_local_playlist(&mut tx, playlist_id).await?;
// Phase 1.j.b — per-track snapshots for the public share
// preview.
let snapshots = crate::sync::track_snapshots::build_snapshots(&mut tx, &track_ids).await?;
crate::sync::hooks::enqueue_op_in_tx(
&mut tx,
&crate::sync::hooks::PendingOpDraft {
entity: "playlist".into(),
entity_id,
field: Some("tracks".into()),
op: "insert".into(),
payload: Some(serde_json::json!({
"track_ids": track_ids,
"snapshots": snapshots,
"via_source": { "type": source_type, "id": source_id },
})),
},
)
.await?;
tx.commit().await?;
// Wake the drain task so a chatty user's edits don't wait the
// full 30 s tick before reaching the server.
state.drain.notify();
super::playlist_cover::maybe_regen_auto_cover(&pool, &state.paths, profile_id, playlist_id)
.await;
Ok(inserted)
}
// ── M3U / M3U8 import + export ──────────────────────────────────────
//
// Plain-text playlist exchange so users can move between WaveFlow and
// foobar2000 / VLC / Rekordbox / car stereos. Format:
//
// #EXTM3U
// #PLAYLIST:<name>
// #EXTINF:<seconds>,<artist> - <title>
// <absolute path>
//
// We always write UTF-8 (.m3u8). On import we accept both encodings —
// UTF-8 first, lossy latin-1 fallback for older players' .m3u dumps.
#[derive(Debug, serde::Serialize)]
pub struct ImportPlaylistResult {
pub playlist_id: i64,
pub imported: i64,
pub missing: i64,
/// Up to 20 unmatched paths so the UI can surface them to the
/// user. Truncated server-side to keep the IPC payload bounded
/// even when a user imports a 10 k-line broken playlist.
pub missing_paths: Vec<String>,
}
/// Build a comparable key from a filesystem path. We canonicalize
/// when possible (resolves symlinks, fixes case, tightens drive
/// letters) then strip the `\\?\` and `\\?\UNC\` extended-length
/// prefixes Windows' `canonicalize` adds. Falls back to the input
/// path when canonicalize fails so library-relative .m3u entries can
/// still match scanned tracks even if the file isn't currently
/// mounted.
///
/// **Platform-aware case folding**: filesystems are case-insensitive on
/// Windows + macOS (HFS+/APFS default) and case-sensitive on Linux. We
/// lowercase only on Windows so a Linux library where `Song.flac` and
/// `song.flac` are two distinct files (rare but legal) doesn't collide
/// during the M3U → DB match. macOS is treated as case-sensitive too —
/// the rare case-sensitive HFS+/APFS volume gets a correct match, and
/// the common case-insensitive one only suffers when the M3U casing
/// disagrees with the on-disk casing (which `canonicalize` usually
/// fixes anyway).
fn canonical_path_key(p: &std::path::Path) -> String {
let canon = std::fs::canonicalize(p).unwrap_or_else(|_| p.to_path_buf());
let s = canon.to_string_lossy().to_string();
#[cfg(windows)]
{
// Windows: strip `\\?\` / `\\?\UNC\` prefixes that canonicalize
// adds (extended-length paths), then lowercase since NTFS is
// case-insensitive by default. Byte-level prefix match used so
// some shells that mangle raw strings can't drop a backslash.
let bytes = s.as_bytes();
let has_verbatim = bytes.len() >= 4
&& bytes[0] == b'\\'
&& bytes[1] == b'\\'
&& bytes[2] == b'?'
&& bytes[3] == b'\\';
let has_unc = has_verbatim
&& bytes.len() >= 8
&& (bytes[4] == b'U' || bytes[4] == b'u')
&& (bytes[5] == b'N' || bytes[5] == b'n')
&& (bytes[6] == b'C' || bytes[6] == b'c')
&& bytes[7] == b'\\';
if has_unc {
// \\?\UNC\server\share\... → \\server\share\...
return format!("\\\\{}", &s[8..]).to_lowercase();
}
if has_verbatim {
// \\?\C:\... → C:\...
return s[4..].to_lowercase();
}
s.to_lowercase()
}
#[cfg(not(windows))]
{
// Linux / macOS: case-sensitive matching. No extended-length
// prefix to strip — `canonicalize` returns plain absolute paths.
s
}
}
/// Write the active playlist out as a UTF-8 .m3u8 file at `dest_path`.
/// Caller (frontend) is responsible for picking the destination via
/// the native save dialog and supplying an absolute path.
#[tauri::command]
pub async fn export_playlist_m3u(
state: tauri::State<'_, AppState>,
playlist_id: i64,
dest_path: String,
) -> AppResult<()> {
let pool = state.require_profile_pool().await?;
let name = SqlitePlaylistRepository::new(pool.clone())
.get_name(playlist_id)
.await?
.ok_or_else(|| {
AppError::Other(format!(
"playlist {playlist_id} not found in active profile"
))
})?;
// Custom projection for the export — small enough that it doesn't
// earn its own repository method.
#[derive(FromRow)]
struct ExportRow {
title: String,
artist_name: Option<String>,
duration_ms: i64,
file_path: String,
}
let rows = sqlx::query_as::<_, ExportRow>(
r#"
SELECT t.title,
(SELECT GROUP_CONCAT(name, ', ') FROM (
SELECT ar2.name FROM track_artist ta2
JOIN artist ar2 ON ar2.id = ta2.artist_id
WHERE ta2.track_id = t.id
ORDER BY ta2.position
)) AS artist_name,
t.duration_ms,
t.file_path
FROM playlist_track pt
JOIN track t ON t.id = pt.track_id
WHERE pt.playlist_id = ?
ORDER BY pt.position ASC
"#,
)
.bind(playlist_id)
.fetch_all(&*pool)
.await?;
let mut out = String::with_capacity(rows.len() * 200 + 64);
out.push_str("#EXTM3U\n");
out.push_str(&format!("#PLAYLIST:{}\n", name.replace(['\r', '\n'], " ")));
for row in &rows {
let secs = (row.duration_ms / 1000).max(0);
let artist = row.artist_name.as_deref().unwrap_or("").trim();
let display = if artist.is_empty() {
row.title.clone()
} else {
format!("{artist} - {}", row.title)
};
let display = display.replace(['\r', '\n'], " ");
out.push_str(&format!("#EXTINF:{secs},{display}\n"));
out.push_str(&row.file_path);
out.push('\n');
}
let dest = std::path::PathBuf::from(&dest_path);
if let Some(parent) = dest.parent() {
if !parent.as_os_str().is_empty() {
std::fs::create_dir_all(parent)
.map_err(|e| AppError::Other(format!("create parent dir: {e}")))?;
}
}
std::fs::write(&dest, out).map_err(|e| AppError::Other(format!("write m3u file: {e}")))?;
tracing::info!(
playlist_id,
path = %dest.display(),
tracks = rows.len(),
"playlist exported as m3u8"
);
Ok(())
}
/// Parse an .m3u / .m3u8 file at `source_path`, match each entry
/// against the active profile's library, and create a new playlist
/// holding the tracks that resolved. Unmatched entries are returned
/// (truncated to 20) so the UI can warn the user.
#[tauri::command]
pub async fn import_playlist_m3u(
state: tauri::State<'_, AppState>,
source_path: String,
) -> AppResult<ImportPlaylistResult> {
let pool = state.require_profile_pool().await?;
let profile_id = state.require_profile_id().await?;
let src = std::path::PathBuf::from(&source_path);
let raw = std::fs::read(&src).map_err(|e| AppError::Other(format!("read m3u file: {e}")))?;
// UTF-8 (.m3u8) first; fall back to byte→char lossy decode so legacy
// .m3u files in latin-1 / cp1252 still produce readable paths.
let text = match std::str::from_utf8(&raw) {
Ok(s) => s.to_string(),
Err(_) => raw.iter().map(|b| *b as char).collect::<String>(),
};
let parent = src.parent().unwrap_or_else(|| std::path::Path::new(""));
// Collect candidate paths in playlist order, resolving relatives
// against the m3u's own directory (matches what every desktop
// player does and what users intuitively expect).
let mut candidates: Vec<std::path::PathBuf> = Vec::new();
for raw_line in text.lines() {
// BOMs sneak in on Windows-edited m3u8 files; strip them once.
let line = raw_line.trim_start_matches('\u{feff}').trim();
if line.is_empty() || line.starts_with('#') {
continue;
}
let p = std::path::PathBuf::from(line);
let resolved = if p.is_absolute() { p } else { parent.join(&p) };
candidates.push(resolved);
}
// Build two lowercase lookups over every available track in the
// active library — one full table scan, O(1) per candidate. The
// canonical lookup is the primary match (handles different drive
// mounts, symlinks, case differences). The basename lookup is a
// last-resort fallback when the .m3u was authored on a machine
// whose absolute paths don't resolve here — common when sharing
// playlists across libraries with the same filename layout.
#[derive(FromRow)]
struct PathRow {
id: i64,
file_path: String,
}
let all =
sqlx::query_as::<_, PathRow>("SELECT id, file_path FROM track WHERE is_available = 1")
.fetch_all(&*pool)
.await?;
let mut by_canonical: std::collections::HashMap<String, i64> =
std::collections::HashMap::with_capacity(all.len());
let mut by_basename: std::collections::HashMap<String, i64> =
std::collections::HashMap::with_capacity(all.len());
for r in all {
let p = std::path::Path::new(&r.file_path);
by_canonical.insert(canonical_path_key(p), r.id);
if let Some(stem) = p.file_name().and_then(|s| s.to_str()) {
// Last-write-wins on basename collisions — that's fine,
// the user can still curate the playlist after import.
by_basename.insert(stem.to_lowercase(), r.id);
}
}
let mut matched: Vec<i64> = Vec::with_capacity(candidates.len());
let mut missing: Vec<String> = Vec::new();
for path in &candidates {
let key = canonical_path_key(path);
if let Some(id) = by_canonical.get(&key) {
matched.push(*id);
continue;
}
if let Some(stem) = path.file_name().and_then(|s| s.to_str()) {
if let Some(id) = by_basename.get(&stem.to_lowercase()) {
matched.push(*id);
continue;
}
}
missing.push(path.to_string_lossy().to_string());
}
if matched.is_empty() && !candidates.is_empty() {
// Surface the first few resolved keys + a peek at the
// library's stored basenames so the user can immediately tell
// whether the divergence is path-shape or "the tracks just
// aren't scanned in this profile".
let sample: Vec<String> = candidates
.iter()
.take(3)
.map(|p| canonical_path_key(p))
.collect();
let library_sample: Vec<String> = by_basename.keys().take(3).cloned().collect();
tracing::warn!(
?sample,
library_sample = ?library_sample,
library_size = by_basename.len(),
total = candidates.len(),
"m3u import: no entries matched the active library"
);
}
let name = src
.file_stem()
.and_then(|s| s.to_str())
.map(|s| s.trim().to_string())
.filter(|s| !s.is_empty())
.unwrap_or_else(|| "Imported playlist".to_string());
let now = now_millis();
let draft = PlaylistDraft {
name,
description: None,
color_id: "violet".to_string(),
icon_id: "music".to_string(),
now_ms: now,
};
let (new_id, imported_u32) = SqlitePlaylistRepository::new(pool.clone())
.create_with_tracks(&draft, &matched)
.await?;
let imported = i64::from(imported_u32);
let missing_count = missing.len() as i64;
tracing::info!(
playlist_id = new_id,
path = %src.display(),
imported,
missing = missing_count,
"playlist imported from m3u"
);
let missing_paths: Vec<String> = missing.into_iter().take(20).collect();
super::playlist_cover::maybe_regen_auto_cover(&pool, &state.paths, profile_id, new_id).await;
Ok(ImportPlaylistResult {
playlist_id: new_id,
imported,
missing: missing_count,
missing_paths,
})
}