-
Notifications
You must be signed in to change notification settings - Fork 24
/
Copy pathplayer.rs
2088 lines (1753 loc) · 63.2 KB
/
player.rs
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
use crate::{
api, bus, db, injector,
prelude::*,
settings,
song_file::{SongFile, SongFileBuilder},
spotify_id::SpotifyId,
template::Template,
timer,
track_id::TrackId,
utils::{self, PtDuration},
Uri,
};
use chrono::{DateTime, Utc};
use failure::{bail, format_err, Error};
use parking_lot::RwLock;
use std::{
collections::VecDeque,
sync::Arc,
time::{Duration, Instant},
};
use tokio_bus::{Bus, BusReader};
use tokio_threadpool::ThreadPool;
mod connect;
mod youtube;
static DEFAULT_CURRENT_SONG_TEMPLATE: &'static str = "Song: {{name}}{{#if artists}} by {{artists}}{{/if}}{{#if paused}} (Paused){{/if}} ({{duration}})\n{{#if user~}}Request by: @{{user~}}{{/if}}";
static DEFAULT_CURRENT_SONG_STOPPED_TEMPLATE: &'static str = "Not Playing";
/// Event used by player integrations.
#[derive(Debug)]
pub enum IntegrationEvent {
/// Indicate that the current device changed.
DeviceChanged,
}
/// The source of action.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Source {
/// Event was generated automatically, don't broadcast feedback.
Automatic,
/// Event was generated from user input. Broadcast feedback.
Manual,
}
/// Information on a single track.
#[derive(Debug, Clone, serde::Deserialize, serde::Serialize)]
#[serde(tag = "type")]
pub enum Track {
#[serde(rename = "spotify")]
Spotify { track: api::spotify::FullTrack },
#[serde(rename = "youtube")]
YouTube { video: api::youtube::Video },
}
impl Track {
/// Get artists involved as a string.
pub fn artists(&self) -> Option<String> {
match *self {
Track::Spotify { ref track } => utils::human_artists(&track.artists),
Track::YouTube { ref video } => {
video.snippet.as_ref().and_then(|s| s.channel_title.clone())
}
}
}
/// Get name of the track.
pub fn name(&self) -> String {
match *self {
Track::Spotify { ref track } => track.name.to_string(),
Track::YouTube { ref video } => video
.snippet
.as_ref()
.map(|s| s.title.as_str())
.unwrap_or("no name")
.to_string(),
}
}
/// Convert into JSON.
/// TODO: this is a hack to avoid breaking web API.
pub fn to_json(&self) -> Result<serde_json::Value, Error> {
let json = match *self {
Track::Spotify { ref track } => serde_json::to_value(&track)?,
Track::YouTube { ref video } => serde_json::to_value(&video)?,
};
Ok(json)
}
}
#[derive(Debug, Clone)]
pub struct Item {
pub track_id: TrackId,
pub track: Track,
pub user: Option<String>,
pub duration: Duration,
}
impl Item {
/// Human readable version of playback item.
pub fn what(&self) -> String {
match self.track {
Track::Spotify { ref track } => {
if let Some(artists) = utils::human_artists(&track.artists) {
format!("\"{}\" by {}", track.name, artists)
} else {
format!("\"{}\"", track.name)
}
}
Track::YouTube { ref video } => match video.snippet.as_ref() {
Some(snippet) => match snippet.channel_title.as_ref() {
Some(channel_title) => {
format!("\"{}\" from \"{}\"", snippet.title, channel_title)
}
None => format!("\"{}\"", snippet.title),
},
None => String::from("*Some YouTube Video*"),
},
}
}
}
/// A volume modification.
pub enum ModifyVolume {
Increase(u32),
Decrease(u32),
Set(u32),
}
impl ModifyVolume {
/// Apply the given modification.
pub fn apply(self, v: u32) -> u32 {
use self::ModifyVolume::*;
let v = match self {
Increase(n) => v.saturating_add(n),
Decrease(n) => v.saturating_sub(n),
Set(v) => v,
};
u32::min(100, v)
}
}
#[derive(Debug)]
pub enum Command {
/// Skip the current song.
Skip(Source),
/// Toggle playback.
Toggle(Source),
/// Pause playback.
Pause(Source),
/// Start playback.
Play(Source),
/// Start playback on a specific song state.
Sync { song: Song },
/// The queue was modified.
Modified(Source),
/// Play the given item as a theme at the given offset.
Inject(Source, Arc<Item>, Duration),
}
impl Command {
/// Get the source of a command.
pub fn source(&self) -> Source {
use self::Command::*;
match *self {
Skip(source)
| Toggle(source)
| Pause(source)
| Play(source)
| Modified(source)
| Inject(source, ..) => source,
Sync { .. } => Source::Automatic,
}
}
}
/// Run the player.
pub fn run(
injector: &injector::Injector,
db: db::Database,
spotify: Arc<api::Spotify>,
youtube: Arc<api::YouTube>,
global_bus: Arc<bus::Bus<bus::Global>>,
youtube_bus: Arc<bus::Bus<bus::YouTube>>,
settings: settings::Settings,
) -> Result<(Player, impl Future<Output = Result<(), Error>>), Error> {
let settings = settings.scoped("player");
let mut futures = utils::Futures::default();
let (connect_stream, connect_player, device) =
connect::setup(&mut futures, spotify.clone(), settings.scoped("spotify"))?;
let youtube_player = youtube::setup(
&mut futures,
youtube_bus.clone(),
settings.scoped("youtube"),
)?;
let bus = EventBus {
bus: Arc::new(RwLock::new(Bus::new(1024))),
};
let queue = Queue::new(db.clone());
let song = Arc::new(RwLock::new(None));
let closed = Arc::new(RwLock::new(None));
let (song_update_interval_stream, song_update_interval) = settings
.stream("song-update-interval")
.or_with(utils::Duration::seconds(1))?;
let song_update_interval = match song_update_interval.is_empty() {
true => None,
false => Some(timer::Interval::new_interval(song_update_interval.as_std())),
};
let (commands_tx, commands) = mpsc::unbounded();
let (detached_stream, detached) = settings.stream("detached").or_default()?;
let duplicate_duration = settings.var("duplicate-duration", utils::Duration::default())?;
let song_switch_feedback = settings.var("song-switch-feedback", true)?;
let max_songs_per_user = settings.var("max-songs-per-user", 2)?;
let max_queue_length = settings.var("max-queue-length", 30)?;
let parent_player = Player {
inner: Arc::new(PlayerInner {
device: device.clone(),
queue: queue.clone(),
connect_player: connect_player.clone(),
youtube_player: youtube_player.clone(),
max_queue_length,
max_songs_per_user,
duplicate_duration,
spotify: spotify.clone(),
youtube: youtube.clone(),
commands_tx,
bus: bus.clone(),
song: song.clone(),
themes: injector.var()?,
closed: closed.clone(),
}),
};
let player = parent_player.clone();
// future to initialize the player future.
// Yeah, I know....
let future = async move {
log::trace!("Waiting for token to become ready");
{
// Add tracks from database.
for song in db.list()? {
let item = convert_item(
&*spotify,
&*youtube,
song.user.as_ref().map(|user| user.as_str()),
&song.track_id,
None,
)
.await?;
if let Some(item) = item {
queue.push_back_queue(Arc::new(item));
} else {
log::warn!("failed to convert db item: {:?}", song);
}
}
}
let mixer = Mixer {
queue,
sidelined: Default::default(),
fallback_items: Default::default(),
fallback_queue: Default::default(),
};
let future = PlaybackFuture {
spotify: spotify.clone(),
connect_stream,
connect_player: connect_player.clone(),
youtube_player,
commands,
bus,
mixer,
state: State::None,
player: PlayerKind::None,
detached,
detached_stream,
song: song.clone(),
song_file: None,
song_switch_feedback,
song_update_interval,
song_update_interval_stream,
global_bus,
timeout: None,
};
if let Some(p) = spotify.me_player().await? {
log::trace!("Detected playback: {:?}", p);
match Song::from_playback(&p) {
Some(song) => {
log::trace!("Syncing playback");
let volume_percent = p.device.volume_percent;
device.sync_device(Some(p.device))?;
connect_player.set_scaled_volume(volume_percent)?;
player.play_sync(song)?;
}
None => {
log::trace!("Pausing playback since item is missing");
player.pause_with_source(Source::Automatic)?;
}
}
}
let futures = future::try_join_all(futures);
future::try_join(future.run(settings), futures)
.await
.map(|_| ())
};
Ok((parent_player, future))
}
/// Events emitted by the player.
#[derive(Debug, Clone)]
pub enum Event {
/// Player is empty.
Empty,
/// Player is playing the given song.
Playing(bool, Arc<Item>),
/// Player is pausing.
Pausing,
/// queue was modified in some way.
Modified,
/// player has not been configured.
NotConfigured,
/// Player is detached.
Detached,
}
/// Information on current song.
#[derive(Debug, Clone)]
pub struct Song {
pub item: Arc<Item>,
/// Since the last time it was unpaused, what was the initial elapsed duration.
elapsed: Duration,
/// When the current song started playing.
started_at: Option<Instant>,
}
impl Song {
/// Create a new current song.
pub fn new(item: Arc<Item>, elapsed: Duration) -> Self {
Song {
item,
elapsed,
started_at: None,
}
}
/// Test if the two songs reference roughly the same song.
pub fn is_same(&self, song: &Song) -> bool {
if self.item.track_id != song.item.track_id {
return false;
}
let a = self.elapsed();
let b = song.elapsed();
let diff = if a > b { a - b } else { b - a };
if diff.as_secs() > 5 {
return false;
}
true
}
/// Convert a playback information into a Song struct.
pub fn from_playback(playback: &api::spotify::FullPlayingContext) -> Option<Self> {
let progress_ms = playback.progress_ms.unwrap_or_default();
let track = match playback.item.clone() {
Some(track) => track,
_ => {
log::warn!("No playback item in current playback");
return None;
}
};
let track_id = match &track.id {
Some(track_id) => track_id,
None => {
log::warn!("Current playback doesn't have a track id");
return None;
}
};
let track_id = match SpotifyId::from_base62(&track_id) {
Ok(spotify_id) => TrackId::Spotify(spotify_id),
Err(e) => {
log::warn!(
"Failed to parse track id from current playback: {}: {}",
track_id,
e
);
return None;
}
};
let elapsed = Duration::from_millis(progress_ms as u64);
let duration = Duration::from_millis(track.duration_ms.into());
let item = Arc::new(Item {
track_id,
track: Track::Spotify { track },
user: None,
duration,
});
let mut song = Song::new(item, elapsed);
if playback.is_playing {
song.play();
} else {
song.pause();
}
Some(song)
}
/// Get the deadline for when this song will end, assuming it is currently playing.
pub fn deadline(&self) -> Instant {
Instant::now() + self.remaining()
}
/// Duration of the current song.
pub fn duration(&self) -> Duration {
self.item.duration.clone()
}
/// Elapsed time on current song.
///
/// Elapsed need to take started at into account.
pub fn elapsed(&self) -> Duration {
let when = self
.started_at
.as_ref()
.and_then(|started_at| {
let now = Instant::now();
if now > *started_at {
Some(now - *started_at)
} else {
None
}
})
.unwrap_or_default();
when.checked_add(self.elapsed.clone()).unwrap_or_default()
}
/// Remaining time of the current song.
pub fn remaining(&self) -> Duration {
self.item
.duration
.checked_sub(self.elapsed())
.unwrap_or_default()
}
/// Get serializable data for this item.
pub fn data(&self, state: State) -> Result<CurrentData<'_>, Error> {
let artists = self.item.track.artists();
Ok(CurrentData {
paused: state != State::Playing,
track_id: &self.item.track_id,
name: self.item.track.name(),
artists,
user: self.item.user.as_ref().map(|s| s.as_str()),
duration: utils::digital_duration(&self.item.duration),
elapsed: utils::digital_duration(&self.elapsed()),
})
}
/// Check if the song is currently playing.
pub fn state(&self) -> State {
match self.started_at.is_some() {
true => State::Playing,
false => State::Paused,
}
}
/// Get the player kind for the current song.
pub fn player(&self) -> PlayerKind {
match self.item.track_id {
TrackId::Spotify(..) => PlayerKind::Spotify,
TrackId::YouTube(..) => PlayerKind::YouTube,
}
}
/// Set the started_at time to now.
/// For safety, update the current `elapsed` time based on any prior `started_at`.
pub fn play(&mut self) {
let duration = self.take_started_at();
self.elapsed += duration;
self.started_at = Some(Instant::now());
}
/// Update the elapsed time based on when this song was started.
pub fn pause(&mut self) {
let duration = self.take_started_at();
self.elapsed += duration;
}
/// Take the current started_at as a duration and leave it as None.
fn take_started_at(&mut self) -> Duration {
let started_at = match self.started_at.take() {
Some(started_at) => started_at,
None => return Default::default(),
};
let now = Instant::now();
if now < started_at {
return Default::default();
}
now - started_at
}
}
#[derive(Debug, Clone, serde::Serialize)]
pub struct CurrentData<'a> {
paused: bool,
track_id: &'a TrackId,
name: String,
artists: Option<String>,
user: Option<&'a str>,
duration: String,
elapsed: String,
}
/// Internal of the player.
pub struct PlayerInner {
device: self::connect::ConnectDevice,
queue: Queue,
connect_player: self::connect::ConnectPlayer,
youtube_player: self::youtube::YouTubePlayer,
max_queue_length: Arc<RwLock<u32>>,
max_songs_per_user: Arc<RwLock<u32>>,
duplicate_duration: Arc<RwLock<utils::Duration>>,
spotify: Arc<api::Spotify>,
youtube: Arc<api::YouTube>,
commands_tx: mpsc::UnboundedSender<Command>,
bus: EventBus,
/// Song song that is loaded.
song: Arc<RwLock<Option<Song>>>,
/// Theme songs.
themes: Arc<RwLock<Option<db::Themes>>>,
/// Player is closed for more requests.
closed: Arc<RwLock<Option<Option<Arc<String>>>>>,
}
/// All parts of a Player that can be shared between threads.
#[derive(Clone)]
pub struct Player {
/// Player internals. Wrapped to make cloning cheaper since Player is frequently shared.
inner: Arc<PlayerInner>,
}
impl Player {
/// Get a receiver for player events.
pub fn add_rx(&self) -> BusReader<Event> {
self.inner.bus.add_rx()
}
/// Synchronize playback with the given song.
fn play_sync(&self, song: Song) -> Result<(), Error> {
self.send(Command::Sync { song })
}
/// Get the current device.
pub fn current_device(&self) -> Option<String> {
self.inner.device.current_device()
}
/// List all available devices.
pub async fn list_devices(&self) -> Result<Vec<api::spotify::Device>, Error> {
self.inner.device.list_devices().await
}
/// External call to set device.
///
/// Should always notify the player to change.
pub fn set_device(&self, device: String) -> Result<(), Error> {
self.inner.device.set_device(Some(device))
}
/// Clear the current device.
pub fn clear_device(&self) -> Result<(), Error> {
self.inner.device.set_device(None)
}
/// Send the given command.
fn send(&self, command: Command) -> Result<(), Error> {
self.inner
.commands_tx
.unbounded_send(command)
.map_err(|_| format_err!("failed to send command"))
}
/// Get the next N songs in queue.
pub fn list(&self) -> Vec<Arc<Item>> {
let song = self.inner.song.read();
let queue = self.inner.queue.queue.read();
song.as_ref()
.map(|c| c.item.clone())
.into_iter()
.chain(queue.iter().cloned())
.collect()
}
/// Promote the given song to the head of the queue.
pub fn promote_song(&self, user: Option<&str>, n: usize) -> Option<Arc<Item>> {
let promoted = self.inner.queue.promote_song(user, n);
if promoted.is_some() {
self.modified();
}
promoted
}
/// Toggle playback.
pub fn toggle(&self) -> Result<(), Error> {
self.send(Command::Toggle(Source::Manual))
}
/// Start playback.
pub fn play(&self) -> Result<(), Error> {
self.send(Command::Play(Source::Manual))
}
/// Pause playback.
pub fn pause(&self) -> Result<(), Error> {
self.pause_with_source(Source::Manual)
}
/// Pause playback.
pub fn pause_with_source(&self, source: Source) -> Result<(), Error> {
self.send(Command::Pause(source))
}
/// Skip the current song.
pub fn skip(&self) -> Result<(), Error> {
self.send(Command::Skip(Source::Manual))
}
/// Update volume of the player.
pub fn volume(&self, modify: ModifyVolume) -> Result<Option<u32>, Error> {
let track_id = match self.inner.song.read().as_ref() {
Some(song) => song.item.track_id.clone(),
None => {
return Ok(None);
}
};
match track_id {
TrackId::Spotify(..) => match self.inner.connect_player.volume(modify) {
Err(self::connect::CommandError::NoDevice) => {
self.inner.bus.broadcast(Event::NotConfigured);
return Ok(None);
}
Err(e) => return Err(e.into()),
Ok(volume) => return Ok(Some(volume)),
},
TrackId::YouTube(..) => Ok(Some(self.inner.youtube_player.volume(modify)?)),
}
}
/// Get the current volume.
pub fn current_volume(&self) -> Option<u32> {
let track_id = match self.inner.song.read().as_ref() {
Some(song) => song.item.track_id.clone(),
None => {
return None;
}
};
match track_id {
TrackId::Spotify(..) => Some(self.inner.connect_player.current_volume()),
TrackId::YouTube(..) => Some(self.inner.youtube_player.current_volume()),
}
}
/// Close the player from more requests.
pub fn close(&self, reason: Option<String>) {
*self.inner.closed.write() = Some(reason.map(Arc::new));
}
/// Open the player.
pub fn open(&self) {
*self.inner.closed.write() = None;
}
/// Search for a track.
pub async fn search_track(&self, q: &str) -> Result<Option<TrackId>, Error> {
if q.starts_with("youtube:") {
let q = q.trim_start_matches("youtube:");
let results = self.inner.youtube.search(q).await?;
let result = results.items.into_iter().filter(|r| match r.id.kind {
api::youtube::Kind::Video => true,
_ => false,
});
let mut result = result.flat_map(|r| r.id.video_id);
return Ok(result.next().map(TrackId::YouTube));
}
let q = if q.starts_with("spotify:") {
q.trim_start_matches("spotify:")
} else {
q
};
let page = self.inner.spotify.search_track(q).await?;
match page.items.into_iter().next().and_then(|t| t.id) {
Some(track_id) => match SpotifyId::from_base62(&track_id) {
Ok(track_id) => Ok(Some(TrackId::Spotify(track_id))),
Err(_) => bail!("search result returned malformed id"),
},
None => Ok(None),
}
}
/// Play a theme track.
pub async fn play_theme(&self, channel: &str, name: &str) -> Result<(), PlayThemeError> {
let themes = match self.inner.themes.read().clone() {
Some(themes) => themes,
None => return Err(PlayThemeError::NotConfigured),
};
let theme = match themes.get(channel, name) {
Some(theme) => theme,
None => return Err(PlayThemeError::NoSuchTheme),
};
let duration = theme.end.clone().map(|o| o.as_duration());
let item = convert_item(
&*self.inner.spotify,
&*self.inner.youtube,
None,
&theme.track_id,
duration,
)
.await
.map_err(|e| PlayThemeError::Error(e.into()))?;
let item = match item {
Some(item) => item,
None => return Err(PlayThemeError::MissingAuth),
};
let item = Arc::new(item);
let duration = theme.start.as_duration();
self.inner
.commands_tx
.unbounded_send(Command::Inject(Source::Manual, item, duration))
.map_err(|e| PlayThemeError::Error(e.into()))?;
Ok(())
}
/// Add the given track to the queue.
///
/// Returns the item added.
pub async fn add_track(
&self,
user: &str,
track_id: TrackId,
bypass_constraints: bool,
max_duration: Option<utils::Duration>,
) -> Result<(usize, Arc<Item>), AddTrackError> {
let (user_count, len) = {
let queue_inner = self.inner.queue.queue.read();
let len = queue_inner.len();
if !bypass_constraints {
if let Some(reason) = self.inner.closed.read().as_ref() {
return Err(AddTrackError::PlayerClosed(reason.clone()));
}
let max_queue_length = *self.inner.max_queue_length.read();
// NB: moderator is allowed to violate max queue length.
if len >= max_queue_length as usize {
return Err(AddTrackError::QueueFull);
}
let duplicate_duration = self.inner.duplicate_duration.read().clone();
if !duplicate_duration.is_empty() {
if let Some(last) = self
.inner
.queue
.last_song_within(&track_id, duplicate_duration.clone())
.map_err(AddTrackError::Error)?
{
let added_at = DateTime::from_utc(last.added_at, Utc);
return Err(AddTrackError::Duplicate(
added_at,
last.user,
duplicate_duration.as_std(),
));
}
}
}
let mut user_count = 0;
for (index, i) in queue_inner.iter().enumerate() {
if i.track_id == track_id {
return Err(AddTrackError::QueueContainsTrack(index));
}
if i.user.as_ref().map(|u| *u == user).unwrap_or_default() {
user_count += 1;
}
}
(user_count, len)
};
let max_songs_per_user = *self.inner.max_songs_per_user.read();
// NB: moderator is allowed to add more songs.
if !bypass_constraints && user_count >= max_songs_per_user {
return Err(AddTrackError::TooManyUserTracks(max_songs_per_user));
}
let item = convert_item(
&*self.inner.spotify,
&*self.inner.youtube,
Some(user),
&track_id,
None,
)
.await
.map_err(|e| AddTrackError::Error(e.into()))?;
let mut item = match item {
Some(item) => item,
None => return Err(AddTrackError::MissingAuth),
};
if let Some(max_duration) = max_duration {
let max_duration = max_duration.as_std();
if item.duration > max_duration {
item.duration = max_duration;
}
}
let item = Arc::new(item);
self.inner
.queue
.push_back(item.clone())
.await
.map_err(|e| AddTrackError::Error(e.into()))?;
self.inner
.commands_tx
.unbounded_send(Command::Modified(Source::Manual))
.map_err(|e| AddTrackError::Error(e.into()))?;
Ok((len, item))
}
/// Remove the first track in the queue.
pub fn remove_first(&self) -> Result<Option<Arc<Item>>, Error> {
Ok(None)
}
pub fn purge(&self) -> Result<Vec<Arc<Item>>, Error> {
let purged = self.inner.queue.purge()?;
if !purged.is_empty() {
self.modified();
}
Ok(purged)
}
/// Remove the item at the given position.
pub fn remove_at(&self, n: usize) -> Result<Option<Arc<Item>>, Error> {
let removed = self.inner.queue.remove_at(n)?;
if removed.is_some() {
self.modified();
}
Ok(removed)
}
/// Remove the first track in the queue.
pub fn remove_last(&self) -> Result<Option<Arc<Item>>, Error> {
let removed = self.inner.queue.remove_last()?;
if removed.is_some() {
self.modified();
}
Ok(removed)
}
/// Remove the last track by the given user.
pub fn remove_last_by_user(&self, user: &str) -> Result<Option<Arc<Item>>, Error> {
let removed = self.inner.queue.remove_last_by_user(user)?;
if removed.is_some() {
self.modified();
}
Ok(removed)
}
/// Find the next item that matches the given predicate and how long until it plays.
pub fn find(&self, mut predicate: impl FnMut(&Item) -> bool) -> Option<(Duration, Arc<Item>)> {
let mut duration = Duration::default();
if let Some(c) = self.inner.song.read().as_ref() {
if predicate(&c.item) {
return Some((Default::default(), c.item.clone()));
}
duration += c.remaining();
}
let queue = self.inner.queue.queue.read();
for item in &*queue {
if predicate(item) {
return Some((duration, item.clone()));
}
duration += item.duration;
}
None
}
/// Get the length in number of items and total number of seconds in queue.
pub fn length(&self) -> (usize, Duration) {
let mut count = 0;
let mut duration = Duration::default();
if let Some(item) = self.inner.song.read().as_ref() {
duration += item.remaining();
count += 1;
}
let queue = self.inner.queue.queue.read();
for item in &*queue {
duration += item.duration;
}
count += queue.len();
(count, duration)
}
/// Get the current song, if it is set.
pub fn current(&self) -> Option<Song> {
self.inner.song.read().clone()
}
/// Indicate that the queue has been modified.
fn modified(&self) {
if let Err(e) = self
.inner
.commands_tx
.unbounded_send(Command::Modified(Source::Manual))
{
log::error!("failed to send queue modified notification: {}", e);
}
}