song_queue.rs 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  1. use super::song::Song;
  2. use rand::seq::SliceRandom;
  3. use serenity::model::id::UserId;
  4. use std::collections::HashMap;
  5. use std::{cmp::min, collections::VecDeque};
  6. #[derive(Clone)]
  7. pub struct SongQueue {
  8. queues: HashMap<UserId, VecDeque<Song>>,
  9. users: VecDeque<UserId>,
  10. }
  11. impl SongQueue {
  12. pub fn new() -> SongQueue {
  13. SongQueue {
  14. queues: HashMap::new(),
  15. users: VecDeque::new(),
  16. }
  17. }
  18. fn new_user_queue(&mut self, user: UserId) {
  19. if self.queues.get(&user).is_none() {
  20. self.queues.insert(user, VecDeque::new());
  21. }
  22. if !self.users.contains(&user) {
  23. self.users.push_back(user);
  24. }
  25. }
  26. pub fn push(&mut self, songs: Vec<Song>) {
  27. for song in songs.into_iter() {
  28. self.new_user_queue(song.queuer.id);
  29. let deque = self.queues.get_mut(&song.queuer.id).unwrap();
  30. deque.push_back(song);
  31. }
  32. }
  33. pub fn peek(&self) -> Option<Song> {
  34. let user = match self.users.front() {
  35. Some(user) => user,
  36. None => return None,
  37. };
  38. let deque = self.queues.get(&user).unwrap();
  39. deque.front().cloned()
  40. }
  41. pub fn pop(&mut self) -> Option<Song> {
  42. let user = match self.users.pop_front() {
  43. Some(user) => user,
  44. None => return None,
  45. };
  46. let deque = self.queues.get_mut(&user).unwrap();
  47. let song = deque.pop_front();
  48. if deque.len() > 0 {
  49. self.users.push_back(user);
  50. }
  51. song
  52. }
  53. pub fn shuffle(&mut self) -> Result<(), String> {
  54. if self.users.len() == 0 {
  55. return Err("queue is empty".to_string());
  56. }
  57. for deque in self.queues.values_mut() {
  58. deque.make_contiguous().shuffle(&mut rand::thread_rng());
  59. }
  60. Ok(())
  61. }
  62. pub fn clear(&mut self) -> Result<(), String> {
  63. if self.users.len() == 0 {
  64. return Err("queue is empty".to_string());
  65. };
  66. self.queues.clear();
  67. self.users.clear();
  68. Ok(())
  69. }
  70. pub fn get_string(&self) -> String {
  71. if self.users.len() == 0 {
  72. return "*empty*".to_string();
  73. };
  74. let mut s = String::new();
  75. let queue = self.as_vec();
  76. s.push_str(&format!(
  77. "*Showing {} of {} songs*\n",
  78. min(20, queue.len()),
  79. queue.len()
  80. ));
  81. for (i, song) in queue.iter().take(20).enumerate() {
  82. s += &format!(
  83. "{}: {} (queued by {})\n",
  84. i + 1,
  85. &song.get_string(),
  86. song.queuer.name
  87. );
  88. }
  89. s
  90. }
  91. fn as_vec(&self) -> Vec<Song> {
  92. let mut clone = self.clone();
  93. let mut queue = vec![];
  94. while let Some(song) = clone.pop() {
  95. queue.push(song);
  96. }
  97. queue
  98. }
  99. }