-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathqueue.rs
More file actions
2075 lines (1927 loc) Β· 74.1 KB
/
Copy pathqueue.rs
File metadata and controls
2075 lines (1927 loc) Β· 74.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
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
//! Persistent playback queue.
//!
//! The queue lives in the per-profile `data.db` via the `queue_item`
//! table (populated by [`fill_queue`]) and the `queue.current_index`
//! row of `profile_setting` (pointer to the active slot).
//!
//! Playing a track from the library view fills the whole queue with
//! the current view, sets `current_index` to the clicked row, and the
//! audio engine's auto-advance task walks forward through the queue
//! as each track ends. Shuffle / repeat behaviour is applied here,
//! not in the decoder thread.
//!
//! None of these functions touch the audio engine β they're pure DB
//! operations that return [`QueueTrack`]s for the caller to feed into
//! `AudioCmd::LoadAndPlay`.
//!
//! `dead_code` is tolerated module-wide because shuffle / unshuffle /
//! restore_state / persist_resume_point are consumed by later
//! checkpoints (12 = shuffle+repeat, 13 = startup restore).
#![allow(dead_code)]
use std::path::PathBuf;
use chrono::Utc;
use serde::{Deserialize, Serialize};
use sqlx::{FromRow, SqlitePool};
use crate::{
commands::player::PlayerStateSnapshot,
error::{AppError, AppResult},
};
/// Minimum track shape needed to hand off to the decoder thread. Kept
/// narrower than [`crate::commands::track::Track`] because playback
/// doesn't need the full metadata block; anything the UI wants on top
/// is fetched via `list_tracks`.
#[derive(Debug, Clone, Serialize, Deserialize, FromRow)]
pub struct QueueTrack {
pub id: i64,
pub file_path: String,
pub duration_ms: i64,
pub title: String,
pub artist_id: Option<i64>,
pub artist_name: Option<String>,
pub artist_ids: Option<String>,
pub album_title: Option<String>,
/// The album row, not just its title. Every per-album choice the
/// user makes (a hand-set motion cover, "go to album") is keyed by
/// id; with only the title on the playing track, the now-playing
/// surfaces could not reach any of them (#766).
pub album_id: Option<i64>,
pub artwork_hash: Option<String>,
pub artwork_format: Option<String>,
/// Audio quality fields, surfaced on the PlayerBar footer and on
/// the Hi-Res badge overlays. `None` when the scanner couldn't
/// extract them (lossy formats often skip bit_depth, very old
/// files may miss bitrate, β¦).
pub bitrate: Option<i64>,
pub sample_rate: Option<i64>,
pub channels: Option<i64>,
pub bit_depth: Option<i64>,
pub codec: Option<String>,
pub file_size: i64,
}
impl QueueTrack {
/// Return the absolute filesystem path the decoder should open.
pub fn as_path(&self) -> PathBuf {
PathBuf::from(&self.file_path)
}
}
/// Direction arguments for [`advance`].
#[derive(Debug, Clone, Copy)]
pub enum Direction {
Next,
Previous,
}
/// Repeat mode. Mirrors the `player.repeat_mode` profile_setting
/// string ('off' / 'all' / 'one').
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum RepeatMode {
Off,
All,
One,
}
impl RepeatMode {
pub fn from_str(s: &str) -> Self {
match s {
"all" => Self::All,
"one" => Self::One,
_ => Self::Off,
}
}
pub fn as_str(self) -> &'static str {
match self {
Self::Off => "off",
Self::All => "all",
Self::One => "one",
}
}
}
/// How shuffle reorders the queue. Mirrors the `player.shuffle_mode`
/// profile_setting string.
///
/// Three-way rather than the boolean it replaces, because "shuffle" was
/// answering two different questions with one switch (#618). Shuffling
/// individual tracks is right for a playlist; on a library full of
/// records it takes every album apart, which is the opposite of what
/// someone who listens to albums wants.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub enum ShuffleMode {
/// The queue plays in the order it was built.
#[default]
Off,
/// Individual tracks, in no relation to each other.
Tracks,
/// Whole records. Only the order of the albums is randomised β
/// inside each one the tracks keep disc and track order.
Albums,
}
impl ShuffleMode {
pub fn from_str(s: &str) -> Self {
match s {
"tracks" => Self::Tracks,
"albums" => Self::Albums,
_ => Self::Off,
}
}
pub fn as_str(self) -> &'static str {
match self {
Self::Off => "off",
Self::Tracks => "tracks",
Self::Albums => "albums",
}
}
/// Whether anything is being shuffled at all.
///
/// This is the whole of what the older `player.shuffle` boolean
/// could say, and what MPD's `random` flag can carry.
pub fn is_on(self) -> bool {
self != Self::Off
}
/// The form the decoder thread reads, out of a plain integer
/// atomic. Nothing but
/// [`SharedPlayback`](crate::audio::state::SharedPlayback) should
/// care what number a mode is.
pub fn as_bits(self) -> u8 {
match self {
Self::Off => 0,
Self::Tracks => 1,
Self::Albums => 2,
}
}
/// Inverse of [`Self::as_bits`], total on purpose: an unknown
/// number means the atomic was written by code this build does not
/// have, and `Off` is a better answer than a panic on the audio
/// path.
pub fn from_bits(bits: u8) -> Self {
match bits {
1 => Self::Tracks,
2 => Self::Albums,
_ => Self::Off,
}
}
/// The grouping half, as persisted. `Off` has none β turning
/// shuffle off is not a third way of grouping, it is the absence
/// of grouping, and the flavour the listener picked is kept so it
/// survives an off/on.
fn grouping(self) -> Option<&'static str> {
match self {
Self::Off => None,
Self::Tracks => Some("tracks"),
Self::Albums => Some("albums"),
}
}
}
// ---------------------------------------------------------------------
// Helpers: typed wrappers around profile_setting string values
// ---------------------------------------------------------------------
async fn read_setting_string(pool: &SqlitePool, key: &str) -> AppResult<Option<String>> {
let row: Option<String> = sqlx::query_scalar("SELECT value FROM profile_setting WHERE key = ?")
.bind(key)
.fetch_optional(pool)
.await?;
Ok(row)
}
async fn read_setting_i64(pool: &SqlitePool, key: &str) -> AppResult<Option<i64>> {
match read_setting_string(pool, key).await? {
Some(s) => Ok(s.parse::<i64>().ok()),
None => Ok(None),
}
}
/// Generic over the executor so a caller that needs several rows to land
/// together can pass its transaction instead of the pool.
async fn write_setting_i64<'e, E>(executor: E, key: &str, value: i64) -> AppResult<()>
where
E: sqlx::Executor<'e, Database = sqlx::Sqlite>,
{
let now = Utc::now().timestamp_millis();
sqlx::query(
"UPDATE profile_setting
SET value = ?, updated_at = ?
WHERE key = ?",
)
.bind(value.to_string())
.bind(now)
.bind(key)
.execute(executor)
.await?;
Ok(())
}
async fn write_setting_string(pool: &SqlitePool, key: &str, value: &str) -> AppResult<()> {
let now = Utc::now().timestamp_millis();
sqlx::query(
"INSERT INTO profile_setting (key, value, value_type, updated_at)
VALUES (?, ?, 'string', ?)
ON CONFLICT(key) DO UPDATE
SET value = excluded.value, updated_at = excluded.updated_at",
)
.bind(key)
.bind(value)
.bind(now)
.execute(pool)
.await?;
Ok(())
}
// ---------------------------------------------------------------------
// Read helpers used by player commands + analytics
// ---------------------------------------------------------------------
pub async fn read_repeat_mode(pool: &SqlitePool) -> RepeatMode {
match read_setting_string(pool, "player.repeat_mode").await {
Ok(Some(s)) => RepeatMode::from_str(&s),
_ => RepeatMode::Off,
}
}
pub async fn read_shuffle(pool: &SqlitePool) -> bool {
read_shuffle_mode(pool).await.is_on()
}
/// The shuffle state in force: the existing on/off switch crossed
/// with the grouping the listener picked.
///
/// Kept as two rows rather than one three-valued one, for three
/// reasons. `player.shuffle` is still what MPD's `random` flag maps
/// onto and what a build without album shuffle reads, so it stays
/// authoritative for "is shuffle on". The grouping is remembered
/// while shuffle is off, so someone who listens to records does not
/// have to re-pick it every time they turn shuffle back on. And a
/// profile that predates this upgrade needs no migration: no grouping
/// row means tracks, which is what shuffle has always done.
pub async fn read_shuffle_mode(pool: &SqlitePool) -> ShuffleMode {
let on = matches!(
read_setting_string(pool, "player.shuffle").await,
Ok(Some(ref s)) if s == "true"
);
if !on {
return ShuffleMode::Off;
}
match read_shuffle_grouping_preference(pool).await {
ShuffleMode::Off => ShuffleMode::Tracks,
grouping => grouping,
}
}
/// The remembered grouping on its own, ignoring whether shuffle is on.
/// Never `Off` in practice β an absent or unreadable row reads as
/// `Tracks`, which is what shuffle did before album grouping existed.
///
/// This is what "turn shuffle on" means for every surface that can
/// only say on: the player button, an MPD `random 1`, the Shuffle
/// action on an album or a playlist.
pub async fn read_shuffle_grouping_preference(pool: &SqlitePool) -> ShuffleMode {
match read_setting_string(pool, "player.shuffle_grouping").await {
Ok(Some(ref s)) => match ShuffleMode::from_str(s) {
ShuffleMode::Off => ShuffleMode::Tracks,
grouping => grouping,
},
_ => ShuffleMode::Tracks,
}
}
pub async fn write_repeat_mode(pool: &SqlitePool, mode: RepeatMode) -> AppResult<()> {
let now = Utc::now().timestamp_millis();
sqlx::query(
"UPDATE profile_setting
SET value = ?, updated_at = ?
WHERE key = 'player.repeat_mode'",
)
.bind(mode.as_str())
.bind(now)
.execute(pool)
.await?;
Ok(())
}
/// Persist a shuffle state: the switch always, the grouping only when
/// there is one to record.
///
/// The only setter, on purpose. A boolean one used to sit next to it
/// and now has no callers β and leaving it would have been a trap
/// rather than a convenience: `write_shuffle(pool, true)` forces the
/// `Tracks` grouping, so a future caller reaching for the obvious name
/// would silently throw away a listener's preference for whole
/// records. Turning shuffle on without choosing a grouping is
/// [`read_shuffle_grouping_preference`] followed by this.
///
/// Turning shuffle off deliberately leaves `player.shuffle_grouping`
/// alone β see [`read_shuffle_mode`] for why the listener's choice is
/// worth remembering.
pub async fn write_shuffle_mode(pool: &SqlitePool, mode: ShuffleMode) -> AppResult<()> {
let now = Utc::now().timestamp_millis();
if let Some(grouping) = mode.grouping() {
// Upserted rather than updated: this key is new, so no
// migration seeded a row for it to update.
sqlx::query(
"INSERT INTO profile_setting (key, value, value_type, updated_at)
VALUES ('player.shuffle_grouping', ?, 'string', ?)
ON CONFLICT(key) DO UPDATE SET value = excluded.value, updated_at = excluded.updated_at",
)
.bind(grouping)
.bind(now)
.execute(pool)
.await?;
}
sqlx::query(
"UPDATE profile_setting
SET value = ?, updated_at = ?
WHERE key = 'player.shuffle'",
)
.bind(if mode.is_on() { "true" } else { "false" })
.bind(now)
.execute(pool)
.await?;
Ok(())
}
/// Reorder the queue to match `mode`. The one place that knows which
/// of the three orderings a mode means, so the toggle, the MPD
/// `random` command and [`crate::commands::player::player_play_tracks`]
/// cannot drift on it.
pub async fn apply_shuffle_mode(pool: &SqlitePool, mode: ShuffleMode) -> AppResult<()> {
match mode {
ShuffleMode::Off => unshuffle(pool).await,
ShuffleMode::Tracks => shuffle(pool).await,
ShuffleMode::Albums => shuffle_by_album(pool).await,
}
}
/// Whether the persisted queue is whole records in their own order
/// (`queue.album_ordered`).
///
/// Read once per profile load and mirrored into the engine, the way the
/// shuffle mode is. An absent or unreadable row reads as `false`:
/// telling a listener their tracks are an album is the answer that
/// changes the gain, so it is the one that has to be asked for.
/// Record what the queue that now exists is, inside the transaction
/// that built it.
///
/// Every path that **replaces** the queue calls this, and there are
/// three of them: [`fill_queue`], and the empty-queue branches of
/// [`insert_after_current`] and [`append_to_user_queue`], each of which
/// builds a queue where there was none. A path that only inserts into
/// an existing queue leaves it alone β adding a track to a record
/// playing through does not stop it being one.
async fn write_album_ordered(
tx: &mut sqlx::SqliteConnection,
album_ordered: bool,
now: i64,
) -> AppResult<()> {
sqlx::query(
"INSERT INTO profile_setting (key, value, value_type, updated_at)
VALUES ('queue.album_ordered', ?, 'bool', ?)
ON CONFLICT(key) DO UPDATE SET value = excluded.value,
updated_at = excluded.updated_at",
)
.bind(if album_ordered { "true" } else { "false" })
.bind(now)
.execute(tx)
.await?;
Ok(())
}
pub async fn read_album_ordered(pool: &SqlitePool) -> bool {
matches!(
read_setting_string(pool, "queue.album_ordered").await,
Ok(Some(ref value)) if value == "true"
)
}
/// The queue cursor (`queue.current_index`), normalized to a valid index:
/// clamped into `[0, len)`, or `0` when the queue is empty or the stored
/// value is unset / out of range. The single source of truth for "which
/// entry is current" that the MPD `status` / `currentsong` handlers read β
/// a raw stored value can dangle past the end after the queue shrinks.
pub async fn current_index(pool: &SqlitePool) -> i64 {
let len = queue_length(pool).await.unwrap_or(0);
if len <= 0 {
return 0;
}
let raw = read_setting_i64(pool, "queue.current_index")
.await
.ok()
.flatten()
.unwrap_or(0);
raw.clamp(0, len - 1)
}
// ---------------------------------------------------------------------
// Core queue operations
// ---------------------------------------------------------------------
/// Clear the queue and insert new rows, one per track, with positions
/// 0..n. Also sets `queue.current_index` to `start_index`. Runs in a
/// single transaction so the UI never sees a partial state.
///
/// `album_ordered` says whether this list is whole records in their own
/// order β what a generator produces in album mode, and what no
/// `source_type` can express (#647). Persisted alongside the queue
/// rather than held in memory only, for the same reason the shuffle
/// mode is: a session survives a restart, and the gain decision has to
/// survive with it.
///
/// **Every replacement writes it**, including the ones that write
/// `false`. This is the single path that replaces the queue, which is
/// exactly what makes it the place a stale flag cannot outlive its
/// session.
pub async fn fill_queue(
pool: &SqlitePool,
source_type: &str,
source_id: Option<i64>,
track_ids: &[i64],
start_index: usize,
album_ordered: bool,
) -> AppResult<()> {
if track_ids.is_empty() {
return Err(AppError::Other(
"cannot fill queue with empty track list".into(),
));
}
if start_index >= track_ids.len() {
return Err(AppError::Other(format!(
"start_index {start_index} out of range (queue length {})",
track_ids.len()
)));
}
let mut tx = pool.begin().await?;
sqlx::query("DELETE FROM queue_item")
.execute(&mut *tx)
.await?;
let now = Utc::now().timestamp_millis();
for (pos, track_id) in track_ids.iter().enumerate() {
sqlx::query(
"INSERT INTO queue_item (track_id, position, source_type, source_id, added_at)
VALUES (?, ?, ?, ?, ?)",
)
.bind(track_id)
.bind(pos as i64)
.bind(source_type)
.bind(source_id)
.bind(now)
.execute(&mut *tx)
.await?;
}
sqlx::query(
"UPDATE profile_setting
SET value = ?, updated_at = ?
WHERE key = 'queue.current_index'",
)
.bind((start_index as i64).to_string())
.bind(now)
.execute(&mut *tx)
.await?;
write_album_ordered(&mut tx, album_ordered, now).await?;
// New queue invalidates any previous shuffle snapshot.
sqlx::query("DELETE FROM profile_setting WHERE key = 'queue.preshuffle'")
.execute(&mut *tx)
.await?;
tx.commit().await?;
Ok(())
}
/// Append `track_ids` to the end of the queue without disturbing the
/// current cursor. Used by the "Add to queue" context menu action so
/// the user can stack tracks without losing what's currently playing.
pub async fn append(
pool: &SqlitePool,
track_ids: &[i64],
source_type: &str,
source_id: Option<i64>,
) -> AppResult<()> {
if track_ids.is_empty() {
return Ok(());
}
let mut tx = pool.begin().await?;
let max_pos: Option<i64> = sqlx::query_scalar("SELECT MAX(position) FROM queue_item")
.fetch_one(&mut *tx)
.await?;
let start = max_pos.map(|p| p + 1).unwrap_or(0);
let now = Utc::now().timestamp_millis();
for (offset, id) in track_ids.iter().enumerate() {
sqlx::query(
"INSERT INTO queue_item (track_id, position, source_type, source_id, added_at)
VALUES (?, ?, ?, ?, ?)",
)
.bind(id)
.bind(start + offset as i64)
.bind(source_type)
.bind(source_id)
.bind(now)
.execute(&mut *tx)
.await?;
}
// Order changed β shuffle snapshot is no longer reusable.
sqlx::query("DELETE FROM profile_setting WHERE key = 'queue.preshuffle'")
.execute(&mut *tx)
.await?;
tx.commit().await?;
Ok(())
}
/// Append `track_ids` to the **user queue** β the contiguous block of
/// `source_type = 'manual'` items sitting between the current track
/// and the context tail (whatever album / playlist / smart-playlist
/// fill seeded the queue). Matches Spotify semantics: "Add to queue"
/// stacks tracks at the *bottom* of the user queue, not at the
/// absolute end past every remaining album track, so the user can
/// keep playing the album they started while their manual picks fire
/// one by one in between.
///
/// Boundary = `MIN(position)` among items past the current cursor
/// whose `source_type != 'manual'`. NULL boundary means the entire
/// tail is already manual (or there's nothing past the cursor) β that
/// degenerates into [`append`]. Empty queue still degenerates into
/// [`fill_queue`] so the first "Add to queue" click on a fresh
/// session starts playback.
/// Returns whether the queue was **replaced** rather than added to β
/// true only on the empty-queue branch, which builds a new queue and so
/// decides afresh what it is. The caller mirrors that into the engine
/// (#647).
pub async fn append_to_user_queue(
pool: &SqlitePool,
track_ids: &[i64],
source_id: Option<i64>,
) -> AppResult<bool> {
if track_ids.is_empty() {
return Ok(false);
}
// Single transaction wraps the boundary lookup AND the insert so the
// decision can't be invalidated between reads and writes by a
// concurrent advance / fill_queue / shuffle (SQLite WAL allows
// many readers but only one writer, and our reads were happening
// outside that single-writer envelope before this commit). Every
// SQL inside the function now runs against `&mut *tx`.
let mut tx = pool.begin().await?;
let now = Utc::now().timestamp_millis();
let len: i64 = sqlx::query_scalar("SELECT COUNT(*) FROM queue_item")
.fetch_one(&mut *tx)
.await?;
// Empty queue β replicate `fill_queue` inline so it stays in the
// same tx. Same shape, just bound to "manual" since we know the
// origin.
if len == 0 {
for (pos, id) in track_ids.iter().enumerate() {
sqlx::query(
"INSERT INTO queue_item (track_id, position, source_type, source_id, added_at)
VALUES (?, ?, 'manual', ?, ?)",
)
.bind(id)
.bind(pos as i64)
.bind(source_id)
.bind(now)
.execute(&mut *tx)
.await?;
}
sqlx::query(
"UPDATE profile_setting
SET value = ?, updated_at = ?
WHERE key = 'queue.current_index'",
)
.bind("0")
.bind(now)
.execute(&mut *tx)
.await?;
// A queue built out of picks the listener stacked by hand is not
// a session of records, whatever the last one was.
write_album_ordered(&mut tx, false, now).await?;
sqlx::query("DELETE FROM profile_setting WHERE key = 'queue.preshuffle'")
.execute(&mut *tx)
.await?;
tx.commit().await?;
return Ok(true);
}
let current_raw: Option<String> =
sqlx::query_scalar("SELECT value FROM profile_setting WHERE key = 'queue.current_index'")
.fetch_optional(&mut *tx)
.await?;
let current = current_raw
.and_then(|s| s.parse::<i64>().ok())
.unwrap_or(0)
.clamp(0, len - 1);
let boundary: Option<i64> = sqlx::query_scalar(
"SELECT MIN(position) FROM queue_item
WHERE position > ?
AND source_type != 'manual'",
)
.bind(current)
.fetch_one(&mut *tx)
.await?;
// NULL boundary = no context tail past the cursor (entire tail is
// already manual, or current is at the very end). Same end shape as
// `append`: drop the new rows at MAX(position) + 1.
let insert_at = match boundary {
Some(p) => p,
None => {
let max_pos: Option<i64> = sqlx::query_scalar("SELECT MAX(position) FROM queue_item")
.fetch_one(&mut *tx)
.await?;
max_pos.map(|p| p + 1).unwrap_or(0)
}
};
let needs_shift = boundary.is_some();
let count = track_ids.len() as i64;
if needs_shift {
// Park-shift detour β same trick as `insert_after_current`.
// SQLite checks UNIQUE(position) per row so a direct
// `position + N` collides mid-update; bump the affected rows
// to a high range, then bring them back down past the freshly
// inserted block.
const OFFSET: i64 = 10_000_000;
sqlx::query("UPDATE queue_item SET position = position + ? WHERE position >= ?")
.bind(OFFSET)
.bind(insert_at)
.execute(&mut *tx)
.await?;
for (offset, id) in track_ids.iter().enumerate() {
sqlx::query(
"INSERT INTO queue_item (track_id, position, source_type, source_id, added_at)
VALUES (?, ?, 'manual', ?, ?)",
)
.bind(id)
.bind(insert_at + offset as i64)
.bind(source_id)
.bind(now)
.execute(&mut *tx)
.await?;
}
sqlx::query("UPDATE queue_item SET position = position - ? + ? WHERE position >= ?")
.bind(OFFSET)
.bind(count)
.bind(insert_at + OFFSET)
.execute(&mut *tx)
.await?;
} else {
// No shift needed β append directly past the last row.
for (offset, id) in track_ids.iter().enumerate() {
sqlx::query(
"INSERT INTO queue_item (track_id, position, source_type, source_id, added_at)
VALUES (?, ?, 'manual', ?, ?)",
)
.bind(id)
.bind(insert_at + offset as i64)
.bind(source_id)
.bind(now)
.execute(&mut *tx)
.await?;
}
}
sqlx::query("DELETE FROM profile_setting WHERE key = 'queue.preshuffle'")
.execute(&mut *tx)
.await?;
tx.commit().await?;
Ok(false)
}
/// Insert `track_ids` immediately after the current cursor position.
/// Existing items past the cursor are pushed down to keep the queue
/// dense. The cursor itself doesn't move, so the currently-playing
/// track keeps playing.
///
/// Returns whether the queue was **replaced** rather than inserted
/// into: an empty one is filled instead, which is a new queue and a new
/// answer to what it is made of. The caller mirrors that into the
/// engine (#647).
pub async fn insert_after_current(
pool: &SqlitePool,
track_ids: &[i64],
source_type: &str,
source_id: Option<i64>,
) -> AppResult<bool> {
if track_ids.is_empty() {
return Ok(false);
}
let len = queue_length(pool).await?;
if len == 0 {
// No queue yet β fall back to filling it and starting at 0.
// An empty queue filled by "play next" is a hand-built list, not
// a session of records β whatever the tracks happen to be.
fill_queue(pool, source_type, source_id, track_ids, 0, false).await?;
return Ok(true);
}
let current = read_setting_i64(pool, "queue.current_index")
.await?
.unwrap_or(0)
.clamp(0, len - 1);
let insert_at = current + 1;
let count = track_ids.len() as i64;
let mut tx = pool.begin().await?;
// Push existing items down to make room. SQLite checks the
// UNIQUE(position) constraint per row, so a direct
// `position = position + N` would collide mid-update. Bump the
// affected rows into a high range first, then bring them back
// down past the inserted block. The 10_000_000 offset is well
// above any realistic queue length.
const OFFSET: i64 = 10_000_000;
sqlx::query("UPDATE queue_item SET position = position + ? WHERE position >= ?")
.bind(OFFSET)
.bind(insert_at)
.execute(&mut *tx)
.await?;
let now = Utc::now().timestamp_millis();
for (offset, id) in track_ids.iter().enumerate() {
sqlx::query(
"INSERT INTO queue_item (track_id, position, source_type, source_id, added_at)
VALUES (?, ?, ?, ?, ?)",
)
.bind(id)
.bind(insert_at + offset as i64)
.bind(source_type)
.bind(source_id)
.bind(now)
.execute(&mut *tx)
.await?;
}
// Bring the bumped rows back down past the freshly-inserted block.
sqlx::query("UPDATE queue_item SET position = position - ? + ? WHERE position >= ?")
.bind(OFFSET)
.bind(count)
.bind(insert_at + OFFSET)
.execute(&mut *tx)
.await?;
sqlx::query("DELETE FROM profile_setting WHERE key = 'queue.preshuffle'")
.execute(&mut *tx)
.await?;
tx.commit().await?;
// The queue was not replaced, so what it is made of has not
// changed. The inserted rows say `'manual'`, and a `'manual'` row
// is never read as a record playing through whatever session it
// landed in β see `SharedPlayback::listening_to`. Clearing the flag
// here instead would take the album gain from every record still
// queued behind the one track the listener slipped in.
Ok(false)
}
/// Move the queue item at `from` to the slot at `to`, shifting the
/// items between them in the opposite direction so positions stay
/// dense and unique. Also adjusts `queue.current_index` so the
/// playing track keeps playing β only the user's drag of the very
/// item that's playing should change which position is "current".
///
/// `from` / `to` are clamped to `[0, len-1]`; out-of-range drops
/// snap to the nearest end. SQLite's UNIQUE(position) is honored by
/// parking the moved row at a high offset before the shift, then
/// dropping it back to the target slot.
pub async fn reorder(pool: &SqlitePool, from: i64, to: i64) -> AppResult<()> {
let len = queue_length(pool).await?;
if len == 0 {
return Ok(());
}
let from = from.clamp(0, len - 1);
let to = to.clamp(0, len - 1);
if from == to {
return Ok(());
}
const PARK: i64 = 10_000_000;
let mut tx = pool.begin().await?;
// 1. Park the moved row out of the way.
sqlx::query("UPDATE queue_item SET position = ? WHERE position = ?")
.bind(PARK)
.bind(from)
.execute(&mut *tx)
.await?;
// 2. Shift the affected range, again via PARK detour to keep the
// UNIQUE constraint from firing mid-update on a contiguous
// range β SQLite checks per row, so a direct
// `position = position Β± 1` would collide on the first step.
if to > from {
// Items in (from, to] shift down by 1.
sqlx::query(
"UPDATE queue_item SET position = position + ?
WHERE position > ? AND position <= ?",
)
.bind(PARK)
.bind(from)
.bind(to)
.execute(&mut *tx)
.await?;
sqlx::query(
"UPDATE queue_item SET position = position - ? - 1
WHERE position > ? AND position <= ?",
)
.bind(PARK)
.bind(from + PARK)
.bind(to + PARK)
.execute(&mut *tx)
.await?;
} else {
// Items in [to, from) shift up by 1.
sqlx::query(
"UPDATE queue_item SET position = position + ?
WHERE position >= ? AND position < ?",
)
.bind(PARK)
.bind(to)
.bind(from)
.execute(&mut *tx)
.await?;
sqlx::query(
"UPDATE queue_item SET position = position - ? + 1
WHERE position >= ? AND position < ?",
)
.bind(PARK)
.bind(to + PARK)
.bind(from + PARK)
.execute(&mut *tx)
.await?;
}
// 3. Drop the parked row at its target.
sqlx::query("UPDATE queue_item SET position = ? WHERE position = ?")
.bind(to)
.bind(PARK)
.execute(&mut *tx)
.await?;
// 4. Adjust the cursor so the currently-playing track keeps
// pointing at itself even when we shifted rows around it.
let raw: Option<String> =
sqlx::query_scalar("SELECT value FROM profile_setting WHERE key = 'queue.current_index'")
.fetch_optional(&mut *tx)
.await?;
let current = raw.and_then(|s| s.parse::<i64>().ok()).unwrap_or(0);
let new_current = if current == from {
to
} else if from < to && current > from && current <= to {
current - 1
} else if to < from && current >= to && current < from {
current + 1
} else {
current
};
if new_current != current {
let now = Utc::now().timestamp_millis();
sqlx::query(
"UPDATE profile_setting SET value = ?, updated_at = ?
WHERE key = 'queue.current_index'",
)
.bind(new_current.to_string())
.bind(now)
.execute(&mut *tx)
.await?;
}
// Reordering invalidates the pre-shuffle snapshot β the original
// order can't be reconstructed from a manually-tweaked queue.
sqlx::query("DELETE FROM profile_setting WHERE key = 'queue.preshuffle'")
.execute(&mut *tx)
.await?;
tx.commit().await?;
Ok(())
}
/// Count of rows in `queue_item`. Used by [`advance`] to bound the
/// cursor when the queue length shrinks (e.g. a track is deleted).
pub async fn queue_length(pool: &SqlitePool) -> AppResult<i64> {
let n: i64 = sqlx::query_scalar("SELECT COUNT(*) FROM queue_item")
.fetch_one(pool)
.await?;
Ok(n)
}
/// Fetch the full queue as an ordered `Vec<QueueTrack>`. Joined
/// with track / album / artist / artwork so the frontend doesn't
/// have to issue N extra queries to render the panel.
pub async fn list_queue(pool: &SqlitePool) -> AppResult<Vec<QueueTrack>> {
let rows = sqlx::query_as::<_, QueueTrack>(
r#"
SELECT t.id,
t.file_path,
t.duration_ms,
t.title,
t.primary_artist AS artist_id,
(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,
(SELECT GROUP_CONCAT(id, ',') FROM (
SELECT ta2.artist_id AS id FROM track_artist ta2
WHERE ta2.track_id = t.id
ORDER BY ta2.position
)) AS artist_ids,
al.title AS album_title,
t.album_id,
aw.hash AS artwork_hash,
aw.format AS artwork_format,
t.bitrate, t.sample_rate, t.channels,
t.bit_depth, t.codec,
t.file_size
FROM queue_item q
JOIN track t ON t.id = q.track_id
LEFT JOIN album al ON al.id = t.album_id
LEFT JOIN artist ar ON ar.id = t.primary_artist
LEFT JOIN artwork aw ON aw.id = al.artwork_id
ORDER BY q.position
"#,
)
.fetch_all(pool)
.await?;
Ok(rows)
}
/// Fetch the track at a specific position in the queue.
async fn track_at_position(pool: &SqlitePool, position: i64) -> AppResult<Option<QueueTrack>> {
let row = sqlx::query_as::<_, QueueTrack>(
r#"
SELECT t.id,
t.file_path,
t.duration_ms,
t.title,
t.primary_artist AS artist_id,
(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,
(SELECT GROUP_CONCAT(id, ',') FROM (
SELECT ta2.artist_id AS id FROM track_artist ta2
WHERE ta2.track_id = t.id
ORDER BY ta2.position
)) AS artist_ids,
al.title AS album_title,
t.album_id,
aw.hash AS artwork_hash,
aw.format AS artwork_format,
t.bitrate, t.sample_rate, t.channels,
t.bit_depth, t.codec,
t.file_size
FROM queue_item q
JOIN track t ON t.id = q.track_id
LEFT JOIN album al ON al.id = t.album_id
LEFT JOIN artist ar ON ar.id = t.primary_artist
LEFT JOIN artwork aw ON aw.id = al.artwork_id
WHERE q.position = ?
LIMIT 1