stations.js 51 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994
  1. import async from "async";
  2. import CoreClass from "../core";
  3. let StationsModule;
  4. let CacheModule;
  5. let DBModule;
  6. let UtilsModule;
  7. let WSModule;
  8. let SongsModule;
  9. let PlaylistsModule;
  10. let NotificationsModule;
  11. class _StationsModule extends CoreClass {
  12. // eslint-disable-next-line require-jsdoc
  13. constructor() {
  14. super("stations");
  15. StationsModule = this;
  16. }
  17. /**
  18. * Initialises the stations module
  19. *
  20. * @returns {Promise} - returns promise (reject, resolve)
  21. */
  22. async initialize() {
  23. CacheModule = this.moduleManager.modules.cache;
  24. DBModule = this.moduleManager.modules.db;
  25. UtilsModule = this.moduleManager.modules.utils;
  26. WSModule = this.moduleManager.modules.ws;
  27. SongsModule = this.moduleManager.modules.songs;
  28. PlaylistsModule = this.moduleManager.modules.playlists;
  29. NotificationsModule = this.moduleManager.modules.notifications;
  30. this.userList = {};
  31. this.usersPerStation = {};
  32. this.usersPerStationCount = {};
  33. // TEMP
  34. CacheModule.runJob("SUB", {
  35. channel: "station.pause",
  36. cb: async stationId => {
  37. NotificationsModule.runJob("REMOVE", {
  38. subscription: `stations.nextSong?id=${stationId}`
  39. }).then();
  40. }
  41. });
  42. CacheModule.runJob("SUB", {
  43. channel: "station.resume",
  44. cb: async stationId => {
  45. StationsModule.runJob("INITIALIZE_STATION", { stationId }).then();
  46. }
  47. });
  48. CacheModule.runJob("SUB", {
  49. channel: "station.queueUpdate",
  50. cb: async stationId => {
  51. StationsModule.runJob("GET_STATION", { stationId }).then(station => {
  52. if (!station.currentSong && station.queue.length > 0) {
  53. StationsModule.runJob("INITIALIZE_STATION", {
  54. stationId
  55. }).then();
  56. }
  57. WSModule.runJob("EMIT_TO_ROOM", {
  58. room: `station.${stationId}`,
  59. args: ["event:station.queue.updated", { data: { queue: station.queue } }]
  60. });
  61. WSModule.runJob("EMIT_TO_ROOM", {
  62. room: `manage-station.${stationId}`,
  63. args: ["event:manageStation.queue.updated", { data: { stationId, queue: station.queue } }]
  64. });
  65. });
  66. }
  67. });
  68. const stationModel = (this.stationModel = await DBModule.runJob("GET_MODEL", { modelName: "station" }));
  69. const stationSchema = (this.stationSchema = await CacheModule.runJob("GET_SCHEMA", { schemaName: "station" }));
  70. return new Promise((resolve, reject) => {
  71. async.waterfall(
  72. [
  73. next => {
  74. this.setStage(2);
  75. CacheModule.runJob("HGETALL", { table: "stations" })
  76. .then(stations => {
  77. next(null, stations);
  78. })
  79. .catch(next);
  80. },
  81. (stations, next) => {
  82. this.setStage(3);
  83. if (!stations) return next();
  84. const stationIds = Object.keys(stations);
  85. return async.each(
  86. stationIds,
  87. (stationId, next) => {
  88. stationModel.findOne({ _id: stationId }, (err, station) => {
  89. if (err) next(err);
  90. else if (!station) {
  91. CacheModule.runJob("HDEL", {
  92. table: "stations",
  93. key: stationId
  94. })
  95. .then(() => {
  96. next();
  97. })
  98. .catch(next);
  99. } else next();
  100. });
  101. },
  102. next
  103. );
  104. },
  105. next => {
  106. this.setStage(4);
  107. stationModel.find({}, next);
  108. },
  109. (stations, next) => {
  110. this.setStage(5);
  111. async.each(
  112. stations,
  113. (station, next2) => {
  114. async.waterfall(
  115. [
  116. next => {
  117. CacheModule.runJob("HSET", {
  118. table: "stations",
  119. key: station._id,
  120. value: stationSchema(station)
  121. })
  122. .then(station => next(null, station))
  123. .catch(next);
  124. },
  125. (station, next) => {
  126. StationsModule.runJob(
  127. "INITIALIZE_STATION",
  128. {
  129. stationId: station._id
  130. },
  131. null,
  132. -1
  133. )
  134. .then(() => {
  135. next();
  136. })
  137. .catch(next);
  138. }
  139. ],
  140. err => {
  141. next2(err);
  142. }
  143. );
  144. },
  145. next
  146. );
  147. }
  148. ],
  149. async err => {
  150. if (err) {
  151. err = await UtilsModule.runJob("GET_ERROR", {
  152. error: err
  153. });
  154. reject(new Error(err));
  155. } else {
  156. resolve();
  157. }
  158. }
  159. );
  160. });
  161. }
  162. /**
  163. * Initialises a station
  164. *
  165. * @param {object} payload - object that contains the payload
  166. * @param {string} payload.stationId - id of the station to initialise
  167. * @returns {Promise} - returns a promise (resolve, reject)
  168. */
  169. INITIALIZE_STATION(payload) {
  170. return new Promise((resolve, reject) => {
  171. async.waterfall(
  172. [
  173. next => {
  174. StationsModule.runJob(
  175. "GET_STATION",
  176. {
  177. stationId: payload.stationId
  178. },
  179. this
  180. )
  181. .then(station => {
  182. next(null, station);
  183. })
  184. .catch(next);
  185. },
  186. (station, next) => {
  187. if (!station) return next("Station not found.");
  188. return NotificationsModule.runJob(
  189. "UNSCHEDULE",
  190. {
  191. name: `stations.nextSong?id=${station._id}`
  192. },
  193. this
  194. )
  195. .then()
  196. .catch()
  197. .finally(() => {
  198. NotificationsModule.runJob("SUBSCRIBE", {
  199. name: `stations.nextSong?id=${station._id}`,
  200. cb: () =>
  201. StationsModule.runJob("SKIP_STATION", {
  202. stationId: station._id,
  203. natural: true
  204. }),
  205. unique: true,
  206. station
  207. })
  208. .then()
  209. .catch();
  210. if (station.paused) return next(true, station);
  211. return next(null, station);
  212. });
  213. },
  214. (station, next) => {
  215. if (!station.currentSong) {
  216. return StationsModule.runJob(
  217. "SKIP_STATION",
  218. {
  219. stationId: station._id,
  220. natural: false
  221. },
  222. this
  223. )
  224. .then(station => {
  225. next(true, station);
  226. })
  227. .catch(next)
  228. .finally(() => {});
  229. }
  230. let timeLeft =
  231. station.currentSong.duration * 1000 - (Date.now() - station.startedAt - station.timePaused);
  232. if (Number.isNaN(timeLeft)) timeLeft = -1;
  233. if (station.currentSong.duration * 1000 < timeLeft || timeLeft < 0) {
  234. return StationsModule.runJob(
  235. "SKIP_STATION",
  236. {
  237. stationId: station._id,
  238. natural: false
  239. },
  240. this
  241. )
  242. .then(station => {
  243. next(null, station);
  244. })
  245. .catch(next);
  246. }
  247. // name, time, cb, station
  248. NotificationsModule.runJob("SCHEDULE", {
  249. name: `stations.nextSong?id=${station._id}`,
  250. time: timeLeft,
  251. station
  252. });
  253. return next(null, station);
  254. }
  255. ],
  256. async (err, station) => {
  257. if (err && err !== true) {
  258. err = await UtilsModule.runJob(
  259. "GET_ERROR",
  260. {
  261. error: err
  262. },
  263. this
  264. );
  265. reject(new Error(err));
  266. } else resolve(station);
  267. }
  268. );
  269. });
  270. }
  271. /**
  272. * Attempts to get the station from Redis. If it's not in Redis, get it from Mongo and add it to Redis.
  273. *
  274. * @param {object} payload - object that contains the payload
  275. * @param {string} payload.stationId - id of the station
  276. * @returns {Promise} - returns a promise (resolve, reject)
  277. */
  278. GET_STATION(payload) {
  279. return new Promise((resolve, reject) => {
  280. async.waterfall(
  281. [
  282. next => {
  283. CacheModule.runJob("HGET", { table: "stations", key: payload.stationId }, this)
  284. .then(station => next(null, station))
  285. .catch(next);
  286. },
  287. (station, next) => {
  288. if (station) return next(true, station);
  289. return StationsModule.stationModel.findOne({ _id: payload.stationId }, next);
  290. },
  291. (station, next) => {
  292. if (station) {
  293. station = StationsModule.stationSchema(station);
  294. CacheModule.runJob("HSET", {
  295. table: "stations",
  296. key: payload.stationId,
  297. value: station
  298. })
  299. .then()
  300. .catch();
  301. next(true, station);
  302. } else next("Station not found");
  303. }
  304. ],
  305. async (err, station) => {
  306. if (err && err !== true) {
  307. err = await UtilsModule.runJob(
  308. "GET_ERROR",
  309. {
  310. error: err
  311. },
  312. this
  313. );
  314. reject(new Error(err));
  315. } else resolve(station);
  316. }
  317. );
  318. });
  319. }
  320. /**
  321. * Attempts to get a station by name, firstly from Redis. If it's not in Redis, get it from Mongo and add it to Redis.
  322. *
  323. * @param {object} payload - object that contains the payload
  324. * @param {string} payload.stationName - the unique name of the station
  325. * @returns {Promise} - returns a promise (resolve, reject)
  326. */
  327. async GET_STATION_BY_NAME(payload) {
  328. return new Promise((resolve, reject) => {
  329. async.waterfall(
  330. [
  331. next => {
  332. StationsModule.stationModel.findOne({ name: payload.stationName }, next);
  333. },
  334. (station, next) => {
  335. if (station) {
  336. station = StationsModule.stationSchema(station);
  337. CacheModule.runJob("HSET", {
  338. table: "stations",
  339. key: station._id,
  340. value: station
  341. });
  342. next(true, station);
  343. } else next("Station not found");
  344. }
  345. ],
  346. (err, station) => {
  347. if (err && err !== true) return reject(new Error(err));
  348. return resolve(station);
  349. }
  350. );
  351. });
  352. }
  353. /**
  354. * Updates the station in cache from mongo or deletes station in cache if no longer in mongo.
  355. *
  356. * @param {object} payload - object that contains the payload
  357. * @param {string} payload.stationId - the id of the station to update
  358. * @returns {Promise} - returns a promise (resolve, reject)
  359. */
  360. UPDATE_STATION(payload) {
  361. return new Promise((resolve, reject) => {
  362. async.waterfall(
  363. [
  364. next => {
  365. StationsModule.stationModel.findOne({ _id: payload.stationId }, next);
  366. },
  367. (station, next) => {
  368. if (!station) {
  369. CacheModule.runJob("HDEL", {
  370. table: "stations",
  371. key: payload.stationId
  372. })
  373. .then()
  374. .catch();
  375. return next("Station not found");
  376. }
  377. return CacheModule.runJob(
  378. "HSET",
  379. {
  380. table: "stations",
  381. key: payload.stationId,
  382. value: station
  383. },
  384. this
  385. )
  386. .then(station => {
  387. next(null, station);
  388. })
  389. .catch(next);
  390. }
  391. ],
  392. async (err, station) => {
  393. if (err && err !== true) {
  394. err = await UtilsModule.runJob(
  395. "GET_ERROR",
  396. {
  397. error: err
  398. },
  399. this
  400. );
  401. reject(new Error(err));
  402. } else resolve(station);
  403. }
  404. );
  405. });
  406. }
  407. /**
  408. * Autofill station queue from station playlist
  409. *
  410. * @param {object} payload - object that contains the payload
  411. * @param {string} payload.stationId - the id of the station
  412. * @param {string} payload.ignoreExistingQueue - ignore the existing queue songs, replacing the old queue with a completely fresh one
  413. * @returns {Promise} - returns a promise (resolve, reject)
  414. */
  415. AUTOFILL_STATION(payload) {
  416. return new Promise((resolve, reject) => {
  417. const { stationId, ignoreExistingQueue } = payload;
  418. async.waterfall(
  419. [
  420. next => {
  421. PlaylistsModule.runJob("GET_STATION_PLAYLIST", { stationId, includeSongs: true }, this)
  422. .then(response => {
  423. next(null, response.playlist);
  424. })
  425. .catch(next);
  426. },
  427. (playlist, next) => {
  428. StationsModule.runJob("GET_STATION", { stationId }, this)
  429. .then(station => {
  430. if (!station.autofill.enabled) return next("Autofill is disabled in this station");
  431. if (
  432. !ignoreExistingQueue &&
  433. station.autofill.limit <= station.queue.filter(song => !song.requestedBy).length
  434. )
  435. return next("Autofill limit reached");
  436. if (ignoreExistingQueue) station.queue = [];
  437. return next(null, playlist, station);
  438. })
  439. .catch(next);
  440. },
  441. (playlist, station, next) => {
  442. if (station.autofill.mode === "random") {
  443. UtilsModule.runJob("SHUFFLE", { array: playlist.songs }, this)
  444. .then(response => {
  445. next(null, response.array, station);
  446. })
  447. .catch(next);
  448. } else next(null, playlist.songs, station);
  449. },
  450. (_playlistSongs, station, next) => {
  451. let playlistSongs = JSON.parse(JSON.stringify(_playlistSongs));
  452. if (station.autofill.mode === "sequential") {
  453. if (station.currentSongIndex <= playlistSongs.length) {
  454. const songsToAddToEnd = playlistSongs.splice(0, station.currentSongIndex);
  455. playlistSongs = [...playlistSongs, ...songsToAddToEnd];
  456. }
  457. }
  458. const currentRequests = station.queue.filter(song => !song.requestedBy).length;
  459. const songsStillNeeded = station.autofill.limit - currentRequests;
  460. const currentSongs = station.queue;
  461. const currentYoutubeIds = station.queue.map(song => song.youtubeId);
  462. const songsToAdd = [];
  463. let lastSongAdded = null;
  464. if (station.currentSong && station.currentSong.youtubeId)
  465. currentYoutubeIds.push(station.currentSong.youtubeId);
  466. playlistSongs.every(song => {
  467. if (
  468. songsToAdd.length < songsStillNeeded &&
  469. currentYoutubeIds.indexOf(song.youtubeId) === -1
  470. ) {
  471. lastSongAdded = song;
  472. songsToAdd.push(song);
  473. return true;
  474. }
  475. if (songsToAdd.length >= songsStillNeeded) return false;
  476. return true;
  477. });
  478. let { currentSongIndex } = station;
  479. if (station.autofill.mode === "sequential" && lastSongAdded) {
  480. const indexOfLastSong = _playlistSongs
  481. .map(song => song.youtubeId)
  482. .indexOf(lastSongAdded.youtubeId);
  483. if (indexOfLastSong !== -1) currentSongIndex = indexOfLastSong;
  484. }
  485. next(null, currentSongs, songsToAdd, currentSongIndex);
  486. },
  487. (currentSongs, songsToAdd, currentSongIndex, next) => {
  488. const songs = [];
  489. async.eachLimit(
  490. songsToAdd.map(song => song.youtubeId),
  491. 2,
  492. (youtubeId, next) => {
  493. SongsModule.runJob("ENSURE_SONG_EXISTS_BY_YOUTUBE_ID", { youtubeId }, this)
  494. .then(response => {
  495. const { song } = response;
  496. const { _id, title, artists, thumbnail, duration, skipDuration, verified } =
  497. song;
  498. songs.push({
  499. _id,
  500. youtubeId,
  501. title,
  502. artists,
  503. thumbnail,
  504. duration,
  505. skipDuration,
  506. verified
  507. });
  508. next();
  509. })
  510. .catch(next);
  511. },
  512. err => {
  513. if (err) next(err);
  514. else {
  515. const newSongsToAdd = songsToAdd.map(song =>
  516. songs.find(newSong => newSong._id.toString() === song._id.toString())
  517. );
  518. next(null, currentSongs, newSongsToAdd, currentSongIndex);
  519. }
  520. }
  521. );
  522. },
  523. (currentSongs, songsToAdd, currentSongIndex, next) => {
  524. const newPlaylist = [...currentSongs, ...songsToAdd].map(song => {
  525. if (!song._id) song._id = null;
  526. if (!song.requestedAt) song.requestedAt = Date.now();
  527. return song;
  528. });
  529. next(null, newPlaylist, currentSongIndex);
  530. },
  531. (newPlaylist, currentSongIndex, next) => {
  532. StationsModule.stationModel.updateOne(
  533. { _id: stationId },
  534. { $set: { queue: newPlaylist, currentSongIndex } },
  535. { runValidators: true },
  536. err => {
  537. if (err) next(err);
  538. else
  539. StationsModule.runJob(
  540. "UPDATE_STATION",
  541. {
  542. stationId
  543. },
  544. this
  545. )
  546. .then(() => {
  547. next(null);
  548. })
  549. .catch(next);
  550. }
  551. );
  552. }
  553. ],
  554. err => {
  555. if (err) reject(err);
  556. else resolve();
  557. }
  558. );
  559. });
  560. }
  561. /**
  562. * Gets next station song
  563. *
  564. * @param {object} payload - object that contains the payload
  565. * @param {string} payload.stationId - the id of the station
  566. * @returns {Promise} - returns a promise (resolve, reject)
  567. */
  568. GET_NEXT_STATION_SONG(payload) {
  569. return new Promise((resolve, reject) => {
  570. const { stationId } = payload;
  571. async.waterfall(
  572. [
  573. next => {
  574. StationsModule.runJob("GET_STATION", { stationId }, this)
  575. .then(station => {
  576. next(null, station);
  577. })
  578. .catch(next);
  579. },
  580. (station, next) => {
  581. if (station.queue.length === 0) next("No songs available.");
  582. else {
  583. next(null, station.queue[0]);
  584. }
  585. },
  586. (queueSong, next) => {
  587. SongsModule.runJob(
  588. "ENSURE_SONG_EXISTS_BY_YOUTUBE_ID",
  589. {
  590. youtubeId: queueSong.youtubeId,
  591. userId: null,
  592. automaticallyRequested: true
  593. },
  594. this
  595. )
  596. .then(response => {
  597. const { song } = response;
  598. const { _id, youtubeId, title, skipDuration, artists, thumbnail, duration, verified } =
  599. song;
  600. next(null, {
  601. _id,
  602. youtubeId,
  603. title,
  604. skipDuration,
  605. artists,
  606. thumbnail,
  607. duration,
  608. verified,
  609. requestedAt: queueSong.requestedAt,
  610. requestedBy: queueSong.requestedBy,
  611. likes: song.likes || 0,
  612. dislikes: song.dislikes || 0
  613. });
  614. })
  615. .catch(next);
  616. }
  617. ],
  618. (err, song) => {
  619. if (err) reject(err);
  620. else resolve({ song });
  621. }
  622. );
  623. });
  624. }
  625. /**
  626. * Removes first station queue song
  627. *
  628. * @param {object} payload - object that contains the payload
  629. * @param {string} payload.stationId - the id of the station
  630. * @returns {Promise} - returns a promise (resolve, reject)
  631. */
  632. REMOVE_FIRST_QUEUE_SONG(payload) {
  633. return new Promise((resolve, reject) => {
  634. const { stationId } = payload;
  635. async.waterfall(
  636. [
  637. next => {
  638. StationsModule.stationModel.updateOne(
  639. { _id: stationId },
  640. { $pop: { queue: -1 } },
  641. { runValidators: true },
  642. err => {
  643. if (err) next(err);
  644. else
  645. StationsModule.runJob(
  646. "UPDATE_STATION",
  647. {
  648. stationId
  649. },
  650. this
  651. )
  652. .then(() => {
  653. next(null);
  654. })
  655. .catch(next);
  656. }
  657. );
  658. }
  659. ],
  660. err => {
  661. if (err) reject(err);
  662. else resolve();
  663. }
  664. );
  665. });
  666. }
  667. /**
  668. * Process vote to skips for a station
  669. *
  670. * @param {object} payload - object that contains the payload
  671. * @param {string} payload.stationId - the id of the station to process
  672. * @returns {Promise} - returns a promise (resolve, reject)
  673. */
  674. PROCESS_VOTE_SKIPS(payload) {
  675. return new Promise((resolve, reject) => {
  676. StationsModule.log("INFO", `Processing vote skips for station ${payload.stationId}.`);
  677. async.waterfall(
  678. [
  679. next => {
  680. StationsModule.runJob(
  681. "GET_STATION",
  682. {
  683. stationId: payload.stationId
  684. },
  685. this
  686. )
  687. .then(station => next(null, station))
  688. .catch(next);
  689. },
  690. (station, next) => {
  691. if (!station) return next("Station not found.");
  692. return next(null, station);
  693. },
  694. (station, next) => {
  695. WSModule.runJob("GET_SOCKETS_FOR_ROOM", { room: `station.${station._id}` }, this)
  696. .then(sockets => next(null, station, sockets))
  697. .catch(next);
  698. },
  699. (station, sockets, next) => {
  700. const skipVotes = station.currentSong.skipVotes.length;
  701. let shouldSkip = false;
  702. if (sockets.length <= skipVotes) {
  703. if (!station.paused) shouldSkip = true;
  704. return next(null, shouldSkip);
  705. }
  706. const users = [];
  707. return async.each(
  708. sockets,
  709. (socketId, next) => {
  710. WSModule.runJob("SOCKET_FROM_SOCKET_ID", { socketId }, this)
  711. .then(socket => {
  712. if (socket && socket.session && socket.session.userId) {
  713. if (!users.includes(socket.session.userId))
  714. users.push(socket.session.userId);
  715. }
  716. return next();
  717. })
  718. .catch(next);
  719. },
  720. err => {
  721. if (err) return next(err);
  722. if (!station.paused && users.length <= skipVotes) shouldSkip = true;
  723. return next(null, shouldSkip);
  724. }
  725. );
  726. },
  727. (shouldSkip, next) => {
  728. if (shouldSkip)
  729. StationsModule.runJob(
  730. "SKIP_STATION",
  731. {
  732. stationId: payload.stationId,
  733. natural: false
  734. },
  735. this
  736. )
  737. .then(() => next())
  738. .catch(next);
  739. else next();
  740. }
  741. ],
  742. err => {
  743. if (err) reject(err);
  744. else resolve();
  745. }
  746. );
  747. });
  748. }
  749. /**
  750. * Skips a station
  751. *
  752. * @param {object} payload - object that contains the payload
  753. * @param {string} payload.stationId - the id of the station to skip
  754. * @param {string} payload.natural - whether to skip naturally or forcefully
  755. * @returns {Promise} - returns a promise (resolve, reject)
  756. */
  757. SKIP_STATION(payload) {
  758. return new Promise((resolve, reject) => {
  759. StationsModule.log("INFO", `Skipping station ${payload.stationId}.`);
  760. StationsModule.log("STATION_ISSUE", `SKIP_STATION_CB - Station ID: ${payload.stationId}.`);
  761. async.waterfall(
  762. [
  763. // Clears up any existing timers that would skip the station if the song ends
  764. next => {
  765. NotificationsModule.runJob("UNSCHEDULE", {
  766. name: `stations.nextSong?id=${payload.stationId}`
  767. })
  768. .then(() => {
  769. next();
  770. })
  771. .catch(next);
  772. },
  773. // Gets the station object
  774. next => {
  775. StationsModule.runJob(
  776. "GET_STATION",
  777. {
  778. stationId: payload.stationId
  779. },
  780. this
  781. )
  782. .then(station => next(null, station))
  783. .catch(next);
  784. },
  785. (station, next) => {
  786. if (!station) return next("Station not found.");
  787. if (station.autofill.enabled)
  788. return StationsModule.runJob("AUTOFILL_STATION", { stationId: station._id }, this)
  789. .then(() => next(null, station))
  790. .catch(err => {
  791. if (
  792. err === "Autofill is disabled in this station" ||
  793. err === "Autofill limit reached"
  794. )
  795. return next(null, station);
  796. return next(err);
  797. });
  798. return next(null, station);
  799. },
  800. (station, next) => {
  801. StationsModule.runJob("GET_NEXT_STATION_SONG", { stationId: station._id }, this)
  802. .then(response => {
  803. StationsModule.runJob("REMOVE_FIRST_QUEUE_SONG", { stationId: station._id }, this)
  804. .then(() => {
  805. next(null, response.song, station);
  806. })
  807. .catch(next);
  808. })
  809. .catch(err => {
  810. if (err === "No songs available.") next(null, null, station);
  811. else next(err);
  812. });
  813. },
  814. (song, station, next) => {
  815. const $set = {};
  816. if (song === null) $set.currentSong = null;
  817. else {
  818. $set.currentSong = {
  819. _id: song._id,
  820. youtubeId: song.youtubeId,
  821. title: song.title,
  822. artists: song.artists,
  823. duration: song.duration,
  824. skipDuration: song.skipDuration,
  825. thumbnail: song.thumbnail,
  826. requestedAt: song.requestedAt,
  827. requestedBy: song.requestedBy,
  828. verified: song.verified
  829. };
  830. }
  831. $set.startedAt = Date.now();
  832. $set.timePaused = 0;
  833. if (station.paused) $set.pausedAt = Date.now();
  834. next(null, $set, station);
  835. },
  836. ($set, station, next) => {
  837. StationsModule.stationModel.updateOne({ _id: station._id }, { $set }, err => {
  838. if (err) return next(err);
  839. return StationsModule.runJob("UPDATE_STATION", { stationId: station._id }, this)
  840. .then(station => {
  841. next(null, station);
  842. })
  843. .catch(next);
  844. });
  845. },
  846. (station, next) => {
  847. if (station.currentSong !== null && station.currentSong.youtubeId !== undefined) {
  848. station.currentSong.skipVotes = 0;
  849. }
  850. next(null, station);
  851. },
  852. (station, next) => {
  853. if (station.autofill.enabled)
  854. return StationsModule.runJob("AUTOFILL_STATION", { stationId: station._id }, this)
  855. .then(() => next(null, station))
  856. .catch(err => {
  857. if (
  858. err === "Autofill is disabled in this station" ||
  859. err === "Autofill limit reached"
  860. )
  861. return next(null, station);
  862. return next(err);
  863. });
  864. return next(null, station);
  865. },
  866. (station, next) =>
  867. StationsModule.runJob("UPDATE_STATION", { stationId: station._id }, this)
  868. .then(station => {
  869. CacheModule.runJob("PUB", {
  870. channel: "station.queueUpdate",
  871. value: payload.stationId
  872. })
  873. .then()
  874. .catch();
  875. next(null, station);
  876. })
  877. .catch(next)
  878. ],
  879. async (err, station) => {
  880. if (err === "Autofill limit reached") return resolve({ station });
  881. if (err) {
  882. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  883. StationsModule.log("ERROR", `Skipping station "${payload.stationId}" failed. "${err}"`);
  884. return reject(new Error(err));
  885. }
  886. // TODO Pub/Sub this
  887. const { currentSong } = station;
  888. WSModule.runJob("EMIT_TO_ROOM", {
  889. room: `station.${station._id}`,
  890. args: [
  891. "event:station.nextSong",
  892. {
  893. data: {
  894. currentSong,
  895. startedAt: station.startedAt,
  896. paused: station.paused,
  897. timePaused: 0,
  898. natural: payload.natural
  899. }
  900. }
  901. ]
  902. });
  903. WSModule.runJob("EMIT_TO_ROOM", {
  904. room: `manage-station.${station._id}`,
  905. args: ["event:station.nextSong", { data: { stationId: station._id, currentSong } }]
  906. });
  907. if (station.privacy === "public")
  908. WSModule.runJob("EMIT_TO_ROOM", {
  909. room: "home",
  910. args: ["event:station.nextSong", { data: { stationId: station._id, currentSong } }]
  911. });
  912. else {
  913. const sockets = await WSModule.runJob("GET_SOCKETS_FOR_ROOM", { room: "home" }, this);
  914. sockets.forEach(async socketId => {
  915. const socket = await WSModule.runJob("SOCKET_FROM_SOCKET_ID", { socketId });
  916. if (!socket) return;
  917. const { session } = socket;
  918. if (session.sessionId) {
  919. CacheModule.runJob("HGET", { table: "sessions", key: session.sessionId }).then(
  920. session => {
  921. if (session) {
  922. DBModule.runJob("GET_MODEL", { modelName: "user" }).then(userModel => {
  923. userModel.findOne({ _id: session.userId }, (err, user) => {
  924. if (!err && user) {
  925. if (user.role === "admin")
  926. socket.dispatch("event:station.nextSong", {
  927. data: {
  928. stationId: station._id,
  929. currentSong
  930. }
  931. });
  932. else if (
  933. station.type === "community" &&
  934. station.owner === session.userId
  935. )
  936. socket.dispatch("event:station.nextSong", {
  937. data: {
  938. stationId: station._id,
  939. currentSong
  940. }
  941. });
  942. }
  943. });
  944. });
  945. }
  946. }
  947. );
  948. }
  949. });
  950. }
  951. WSModule.runJob("GET_SOCKETS_FOR_ROOM", { room: `station.${station._id}` }).then(sockets => {
  952. if (station.currentSong !== null && station.currentSong.youtubeId !== undefined) {
  953. WSModule.runJob("SOCKETS_JOIN_SONG_ROOM", {
  954. sockets,
  955. room: `song.${station.currentSong.youtubeId}`
  956. });
  957. if (!station.paused) {
  958. NotificationsModule.runJob("SCHEDULE", {
  959. name: `stations.nextSong?id=${station._id}`,
  960. time: station.currentSong.duration * 1000,
  961. station
  962. });
  963. }
  964. } else WSModule.runJob("SOCKETS_LEAVE_SONG_ROOMS", { sockets });
  965. });
  966. return resolve({ station });
  967. }
  968. );
  969. });
  970. }
  971. /**
  972. * Checks if a user can view/access a station
  973. *
  974. * @param {object} payload - object that contains the payload
  975. * @param {object} payload.station - the station object of the station in question
  976. * @param {string} payload.userId - the id of the user in question
  977. * @returns {Promise} - returns a promise (resolve, reject)
  978. */
  979. CAN_USER_VIEW_STATION(payload) {
  980. return new Promise((resolve, reject) => {
  981. async.waterfall(
  982. [
  983. next => {
  984. if (payload.station.privacy === "public" || payload.station.privacy === "unlisted")
  985. return next(true);
  986. if (!payload.userId) return next("Not allowed");
  987. return next();
  988. },
  989. next => {
  990. DBModule.runJob("GET_MODEL", { modelName: "user" }, this).then(userModel => {
  991. userModel.findOne({ _id: payload.userId }, next);
  992. });
  993. },
  994. (user, next) => {
  995. if (!user) return next("Not allowed");
  996. if (user.role === "admin" || payload.station.owner === payload.userId) return next(true);
  997. if (payload.station.type === "official") return next("Not allowed");
  998. return next("Not allowed");
  999. }
  1000. ],
  1001. async errOrResult => {
  1002. if (errOrResult !== true && errOrResult !== "Not allowed") {
  1003. errOrResult = await UtilsModule.runJob(
  1004. "GET_ERROR",
  1005. {
  1006. error: errOrResult
  1007. },
  1008. this
  1009. );
  1010. reject(new Error(errOrResult));
  1011. } else {
  1012. resolve(errOrResult === true);
  1013. }
  1014. }
  1015. );
  1016. });
  1017. }
  1018. /**
  1019. * Checks if a user has favorited a station or not
  1020. *
  1021. * @param {object} payload - object that contains the payload
  1022. * @param {object} payload.stationId - the id of the station in question
  1023. * @param {string} payload.userId - the id of the user in question
  1024. * @returns {Promise} - returns a promise (resolve, reject)
  1025. */
  1026. HAS_USER_FAVORITED_STATION(payload) {
  1027. return new Promise((resolve, reject) => {
  1028. async.waterfall(
  1029. [
  1030. next => {
  1031. DBModule.runJob("GET_MODEL", { modelName: "user" }, this).then(userModel => {
  1032. userModel.findOne({ _id: payload.userId }, next);
  1033. });
  1034. },
  1035. (user, next) => {
  1036. if (!user) return next("User not found.");
  1037. if (user.favoriteStations.indexOf(payload.stationId) !== -1) return next(null, true);
  1038. return next(null, false);
  1039. }
  1040. ],
  1041. async (err, isStationFavorited) => {
  1042. if (err && err !== true) {
  1043. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1044. return reject(new Error(err));
  1045. }
  1046. return resolve(isStationFavorited);
  1047. }
  1048. );
  1049. });
  1050. }
  1051. /**
  1052. * Returns a list of sockets in a room that can and can't know about a station
  1053. *
  1054. * @param {object} payload - the payload object
  1055. * @param {object} payload.station - the station object
  1056. * @param {string} payload.room - the websockets room to get the sockets from
  1057. * @returns {Promise} - returns a promise (resolve, reject)
  1058. */
  1059. GET_SOCKETS_THAT_CAN_KNOW_ABOUT_STATION(payload) {
  1060. return new Promise((resolve, reject) => {
  1061. WSModule.runJob("GET_SOCKETS_FOR_ROOM", { room: payload.room }, this)
  1062. .then(socketIds => {
  1063. const sockets = [];
  1064. async.eachLimit(
  1065. socketIds,
  1066. 1,
  1067. (socketId, next) => {
  1068. WSModule.runJob("SOCKET_FROM_SOCKET_ID", { socketId }, this)
  1069. .then(socket => {
  1070. if (socket) sockets.push(socket);
  1071. next();
  1072. })
  1073. .catch(err => {
  1074. reject(err);
  1075. });
  1076. },
  1077. err => {
  1078. if (err) reject(err);
  1079. else {
  1080. let socketsThatCan = [];
  1081. const socketsThatCannot = [];
  1082. if (payload.station.privacy === "public") {
  1083. socketsThatCan = sockets;
  1084. resolve({ socketsThatCan, socketsThatCannot });
  1085. } else {
  1086. async.eachLimit(
  1087. sockets,
  1088. 1,
  1089. (socket, next) => {
  1090. const { session } = socket;
  1091. async.waterfall(
  1092. [
  1093. next => {
  1094. if (!session.sessionId) next("No session id");
  1095. else next();
  1096. },
  1097. next => {
  1098. CacheModule.runJob(
  1099. "HGET",
  1100. {
  1101. table: "sessions",
  1102. key: session.sessionId
  1103. },
  1104. this
  1105. )
  1106. .then(response => {
  1107. next(null, response);
  1108. })
  1109. .catch(next);
  1110. },
  1111. (session, next) => {
  1112. if (!session) next("No session");
  1113. else {
  1114. DBModule.runJob("GET_MODEL", { modelName: "user" }, this)
  1115. .then(userModel => {
  1116. next(null, userModel);
  1117. })
  1118. .catch(next);
  1119. }
  1120. },
  1121. (userModel, next) => {
  1122. if (!userModel) next("No user model");
  1123. else
  1124. userModel.findOne(
  1125. {
  1126. _id: session.userId
  1127. },
  1128. next
  1129. );
  1130. },
  1131. (user, next) => {
  1132. if (!user) next("No user found");
  1133. else if (user.role === "admin") {
  1134. socketsThatCan.push(socket);
  1135. next();
  1136. } else if (
  1137. payload.station.type === "community" &&
  1138. payload.station.owner === session.userId
  1139. ) {
  1140. socketsThatCan.push(socket);
  1141. next();
  1142. }
  1143. }
  1144. ],
  1145. err => {
  1146. if (err) socketsThatCannot.push(socket);
  1147. next();
  1148. }
  1149. );
  1150. },
  1151. err => {
  1152. if (err) reject(err);
  1153. else resolve({ socketsThatCan, socketsThatCannot });
  1154. }
  1155. );
  1156. }
  1157. }
  1158. }
  1159. );
  1160. })
  1161. .catch(reject);
  1162. });
  1163. }
  1164. /**
  1165. * Adds a playlist to autofill a station
  1166. *
  1167. * @param {object} payload - object that contains the payload
  1168. * @param {object} payload.stationId - the id of the station
  1169. * @param {object} payload.playlistId - the id of the playlist
  1170. * @returns {Promise} - returns a promise (resolve, reject)
  1171. */
  1172. AUTOFILL_PLAYLIST(payload) {
  1173. return new Promise((resolve, reject) => {
  1174. async.waterfall(
  1175. [
  1176. next => {
  1177. if (!payload.stationId) next("Please specify a station id");
  1178. else if (!payload.playlistId) next("Please specify a playlist id");
  1179. else next();
  1180. },
  1181. next => {
  1182. StationsModule.runJob("GET_STATION", { stationId: payload.stationId }, this)
  1183. .then(station => {
  1184. next(null, station);
  1185. })
  1186. .catch(next);
  1187. },
  1188. (station, next) => {
  1189. if (station.playlist === payload.playlistId) next("You cannot autofill the station playlist");
  1190. else if (station.autofill.playlists.indexOf(payload.playlistId) !== -1)
  1191. next("This playlist is already autofilling");
  1192. else if (station.blacklist.indexOf(payload.playlistId) !== -1)
  1193. next("This playlist is currently blacklisted");
  1194. else
  1195. PlaylistsModule.runJob("GET_PLAYLIST", { playlistId: payload.playlistId }, this)
  1196. .then(() => {
  1197. next(null);
  1198. })
  1199. .catch(next);
  1200. },
  1201. next => {
  1202. StationsModule.stationModel.updateOne(
  1203. { _id: payload.stationId },
  1204. { $push: { "autofill.playlists": payload.playlistId } },
  1205. next
  1206. );
  1207. },
  1208. (res, next) => {
  1209. StationsModule.runJob(
  1210. "UPDATE_STATION",
  1211. {
  1212. stationId: payload.stationId
  1213. },
  1214. this
  1215. )
  1216. .then(() => {
  1217. next();
  1218. })
  1219. .catch(next);
  1220. }
  1221. ],
  1222. async err => {
  1223. if (err && err !== true) {
  1224. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1225. return reject(new Error(err));
  1226. }
  1227. return resolve();
  1228. }
  1229. );
  1230. });
  1231. }
  1232. /**
  1233. * Removes a playlist from autofill
  1234. *
  1235. * @param {object} payload - object that contains the payload
  1236. * @param {object} payload.stationId - the id of the station
  1237. * @param {object} payload.playlistId - the id of the playlist
  1238. * @returns {Promise} - returns a promise (resolve, reject)
  1239. */
  1240. REMOVE_AUTOFILL_PLAYLIST(payload) {
  1241. return new Promise((resolve, reject) => {
  1242. async.waterfall(
  1243. [
  1244. next => {
  1245. if (!payload.stationId) next("Please specify a station id");
  1246. else if (!payload.playlistId) next("Please specify a playlist id");
  1247. else next();
  1248. },
  1249. next => {
  1250. StationsModule.runJob("GET_STATION", { stationId: payload.stationId }, this)
  1251. .then(station => {
  1252. next(null, station);
  1253. })
  1254. .catch(next);
  1255. },
  1256. (station, next) => {
  1257. if (station.autofill.playlists.indexOf(payload.playlistId) === -1)
  1258. next("This playlist isn't autofilling");
  1259. else next();
  1260. },
  1261. next => {
  1262. StationsModule.stationModel.updateOne(
  1263. { _id: payload.stationId },
  1264. { $pull: { "autofill.playlists": payload.playlistId } },
  1265. next
  1266. );
  1267. },
  1268. (res, next) => {
  1269. StationsModule.runJob(
  1270. "UPDATE_STATION",
  1271. {
  1272. stationId: payload.stationId
  1273. },
  1274. this
  1275. )
  1276. .then(() => {
  1277. next();
  1278. })
  1279. .catch(next);
  1280. }
  1281. ],
  1282. async err => {
  1283. if (err && err !== true) {
  1284. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1285. return reject(new Error(err));
  1286. }
  1287. return resolve();
  1288. }
  1289. );
  1290. });
  1291. }
  1292. /**
  1293. * Add a playlist to station blacklist
  1294. *
  1295. * @param {object} payload - object that contains the payload
  1296. * @param {object} payload.stationId - the id of the station
  1297. * @param {object} payload.playlistId - the id of the playlist
  1298. * @returns {Promise} - returns a promise (resolve, reject)
  1299. */
  1300. BLACKLIST_PLAYLIST(payload) {
  1301. return new Promise((resolve, reject) => {
  1302. async.waterfall(
  1303. [
  1304. next => {
  1305. if (!payload.stationId) next("Please specify a station id");
  1306. else if (!payload.playlistId) next("Please specify a playlist id");
  1307. else next();
  1308. },
  1309. next => {
  1310. StationsModule.runJob("GET_STATION", { stationId: payload.stationId }, this)
  1311. .then(station => {
  1312. next(null, station);
  1313. })
  1314. .catch(next);
  1315. },
  1316. (station, next) => {
  1317. if (station.playlist === payload.playlistId) next("You cannot blacklist the station playlist");
  1318. else if (station.blacklist.indexOf(payload.playlistId) !== -1)
  1319. next("This playlist is already blacklisted");
  1320. else if (station.autofill.playlists.indexOf(payload.playlistId) !== -1)
  1321. next(
  1322. "This playlist is currently autofilling, please remove it from there before blacklisting it"
  1323. );
  1324. else
  1325. PlaylistsModule.runJob("GET_PLAYLIST", { playlistId: payload.playlistId }, this)
  1326. .then(() => {
  1327. next(null);
  1328. })
  1329. .catch(next);
  1330. },
  1331. next => {
  1332. StationsModule.stationModel.updateOne(
  1333. { _id: payload.stationId },
  1334. { $push: { blacklist: payload.playlistId } },
  1335. next
  1336. );
  1337. },
  1338. (res, next) => {
  1339. StationsModule.runJob(
  1340. "UPDATE_STATION",
  1341. {
  1342. stationId: payload.stationId
  1343. },
  1344. this
  1345. )
  1346. .then(() => {
  1347. next();
  1348. })
  1349. .catch(next);
  1350. }
  1351. ],
  1352. async err => {
  1353. if (err && err !== true) {
  1354. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1355. return reject(new Error(err));
  1356. }
  1357. return resolve();
  1358. }
  1359. );
  1360. });
  1361. }
  1362. /**
  1363. * Remove a playlist from station blacklist
  1364. *
  1365. * @param {object} payload - object that contains the payload
  1366. * @param {object} payload.stationId - the id of the station
  1367. * @param {object} payload.playlistId - the id of the playlist
  1368. * @returns {Promise} - returns a promise (resolve, reject)
  1369. */
  1370. REMOVE_BLACKLISTED_PLAYLIST(payload) {
  1371. return new Promise((resolve, reject) => {
  1372. async.waterfall(
  1373. [
  1374. next => {
  1375. if (!payload.stationId) next("Please specify a station id");
  1376. else if (!payload.playlistId) next("Please specify a playlist id");
  1377. else next();
  1378. },
  1379. next => {
  1380. StationsModule.runJob("GET_STATION", { stationId: payload.stationId }, this)
  1381. .then(station => {
  1382. next(null, station);
  1383. })
  1384. .catch(next);
  1385. },
  1386. (station, next) => {
  1387. if (station.blacklist.indexOf(payload.playlistId) === -1)
  1388. next("This playlist isn't blacklisted");
  1389. else next();
  1390. },
  1391. next => {
  1392. StationsModule.stationModel.updateOne(
  1393. { _id: payload.stationId },
  1394. { $pull: { blacklist: payload.playlistId } },
  1395. next
  1396. );
  1397. },
  1398. (res, next) => {
  1399. StationsModule.runJob(
  1400. "UPDATE_STATION",
  1401. {
  1402. stationId: payload.stationId
  1403. },
  1404. this
  1405. )
  1406. .then(() => {
  1407. next();
  1408. })
  1409. .catch(next);
  1410. }
  1411. ],
  1412. async err => {
  1413. if (err && err !== true) {
  1414. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1415. return reject(new Error(err));
  1416. }
  1417. return resolve();
  1418. }
  1419. );
  1420. });
  1421. }
  1422. /**
  1423. * Removes autofilled or blacklisted playlist from a station
  1424. *
  1425. * @param {object} payload - object that contains the payload
  1426. * @param {string} payload.playlistId - the playlist id
  1427. * @returns {Promise} - returns promise (reject, resolve)
  1428. */
  1429. REMOVE_AUTOFILLED_OR_BLACKLISTED_PLAYLIST_FROM_STATIONS(payload) {
  1430. return new Promise((resolve, reject) => {
  1431. async.waterfall(
  1432. [
  1433. next => {
  1434. if (!payload.playlistId) next("Please specify a playlist id");
  1435. else next();
  1436. },
  1437. next => {
  1438. StationsModule.stationModel.updateMany(
  1439. {
  1440. $or: [{ "autofill.playlists": payload.playlistId }, { blacklist: payload.playlistId }]
  1441. },
  1442. {
  1443. $pull: {
  1444. "autofill.playlists": payload.playlistId,
  1445. blacklist: payload.playlistId
  1446. }
  1447. },
  1448. err => {
  1449. if (err) next(err);
  1450. else next();
  1451. }
  1452. );
  1453. }
  1454. ],
  1455. async err => {
  1456. if (err && err !== true) {
  1457. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1458. return reject(new Error(err));
  1459. }
  1460. return resolve();
  1461. }
  1462. );
  1463. });
  1464. }
  1465. /**
  1466. * Gets stations that autofill or blacklist a specific playlist
  1467. *
  1468. * @param {object} payload - object that contains the payload
  1469. * @param {string} payload.playlistId - the playlist id
  1470. * @returns {Promise} - returns promise (reject, resolve)
  1471. */
  1472. GET_STATIONS_THAT_AUTOFILL_OR_BLACKLIST_PLAYLIST(payload) {
  1473. return new Promise((resolve, reject) => {
  1474. DBModule.runJob(
  1475. "GET_MODEL",
  1476. {
  1477. modelName: "station"
  1478. },
  1479. this
  1480. ).then(stationModel => {
  1481. stationModel.find(
  1482. {
  1483. $or: [{ "autofill.playlists": payload.playlistId }, { blacklist: payload.playlistId }]
  1484. },
  1485. (err, stations) => {
  1486. if (err) reject(err);
  1487. else resolve({ stationIds: stations.map(station => station._id) });
  1488. }
  1489. );
  1490. });
  1491. });
  1492. }
  1493. /**
  1494. * Clears every queue
  1495. *
  1496. * @returns {Promise} - returns a promise (resolve, reject)
  1497. */
  1498. CLEAR_EVERY_STATION_QUEUE() {
  1499. return new Promise((resolve, reject) => {
  1500. async.waterfall(
  1501. [
  1502. next => {
  1503. StationsModule.stationModel.updateMany({}, { $set: { queue: [] } }, err => {
  1504. if (err) next(err);
  1505. else {
  1506. StationsModule.stationModel.find({}, (err, stations) => {
  1507. if (err) next(err);
  1508. else {
  1509. async.eachLimit(
  1510. stations,
  1511. 1,
  1512. (station, next) => {
  1513. StationsModule.runJob("UPDATE_STATION", {
  1514. stationId: station._id
  1515. })
  1516. .then(() => next())
  1517. .catch(next);
  1518. CacheModule.runJob("PUB", {
  1519. channel: "station.queueUpdate",
  1520. value: station._id
  1521. })
  1522. .then()
  1523. .catch();
  1524. },
  1525. next
  1526. );
  1527. }
  1528. });
  1529. }
  1530. });
  1531. }
  1532. ],
  1533. err => {
  1534. if (err) reject(err);
  1535. else resolve();
  1536. }
  1537. );
  1538. });
  1539. }
  1540. /**
  1541. * Resets a station queue
  1542. *
  1543. * @param {object} payload - object that contains the payload
  1544. * @param {string} payload.stationId - the station id
  1545. * @returns {Promise} - returns a promise (resolve, reject)
  1546. */
  1547. RESET_QUEUE(payload) {
  1548. return new Promise((resolve, reject) => {
  1549. async.waterfall(
  1550. [
  1551. next => {
  1552. StationsModule.runJob(
  1553. "AUTOFILL_STATION",
  1554. { stationId: payload.stationId, ignoreExistingQueue: true },
  1555. this
  1556. )
  1557. .then(() => {
  1558. CacheModule.runJob("PUB", {
  1559. channel: "station.queueUpdate",
  1560. value: payload.stationId
  1561. })
  1562. .then()
  1563. .catch();
  1564. next();
  1565. })
  1566. .catch(err => {
  1567. if (err === "Autofill is disabled in this station" || err === "Autofill limit reached")
  1568. StationsModule.stationModel
  1569. .updateOne({ _id: payload.stationId }, { $set: { queue: [] } }, this)
  1570. .then(() => next())
  1571. .catch(next);
  1572. else next(err);
  1573. });
  1574. },
  1575. next => {
  1576. StationsModule.runJob("UPDATE_STATION", { stationId: payload.stationId }, this)
  1577. .then(() => next())
  1578. .catch(next);
  1579. },
  1580. next => {
  1581. CacheModule.runJob("PUB", {
  1582. channel: "station.queueUpdate",
  1583. value: payload.stationId
  1584. })
  1585. .then(() => next())
  1586. .catch(next);
  1587. }
  1588. ],
  1589. err => {
  1590. if (err) reject(err);
  1591. else resolve();
  1592. }
  1593. );
  1594. });
  1595. }
  1596. /**
  1597. * Add to a station queue
  1598. *
  1599. * @param {object} payload - object that contains the payload
  1600. * @param {string} payload.stationId - the station id
  1601. * @param {string} payload.youtubeId - the youtube id
  1602. * @param {string} payload.requestUser - the requesting user id
  1603. * @returns {Promise} - returns a promise (resolve, reject)
  1604. */
  1605. ADD_TO_QUEUE(payload) {
  1606. return new Promise((resolve, reject) => {
  1607. const { stationId, youtubeId, requestUser } = payload;
  1608. async.waterfall(
  1609. [
  1610. next => {
  1611. StationsModule.runJob("GET_STATION", { stationId }, this)
  1612. .then(station => {
  1613. next(null, station);
  1614. })
  1615. .catch(next);
  1616. },
  1617. (station, next) => {
  1618. if (!station) return next("Station not found.");
  1619. if (!station.requests.enabled) return next("Requests are disabled in this station.");
  1620. if (station.currentSong && station.currentSong.youtubeId === youtubeId)
  1621. return next("That song is currently playing.");
  1622. if (station.queue.find(song => song.youtubeId === youtubeId))
  1623. return next("That song is already in the queue.");
  1624. return next(null, station);
  1625. },
  1626. (station, next) => {
  1627. SongsModule.runJob("ENSURE_SONG_EXISTS_BY_YOUTUBE_ID", { youtubeId }, this)
  1628. .then(response => {
  1629. const { song } = response;
  1630. const { _id, title, skipDuration, artists, thumbnail, duration, verified } = song;
  1631. next(
  1632. null,
  1633. {
  1634. _id,
  1635. youtubeId,
  1636. title,
  1637. skipDuration,
  1638. artists,
  1639. thumbnail,
  1640. duration,
  1641. verified
  1642. },
  1643. station
  1644. );
  1645. })
  1646. .catch(next);
  1647. },
  1648. (song, station, next) => {
  1649. const blacklist = [];
  1650. async.eachLimit(
  1651. station.blacklist,
  1652. 1,
  1653. (playlistId, next) => {
  1654. PlaylistsModule.runJob("GET_PLAYLIST", { playlistId }, this)
  1655. .then(playlist => {
  1656. blacklist.push(playlist);
  1657. next();
  1658. })
  1659. .catch(next);
  1660. },
  1661. err => {
  1662. next(err, song, station, blacklist);
  1663. }
  1664. );
  1665. },
  1666. (song, station, blacklist, next) => {
  1667. const blacklistedSongs = blacklist
  1668. .flatMap(blacklistedPlaylist => blacklistedPlaylist.songs)
  1669. .reduce(
  1670. (items, item) =>
  1671. items.find(x => x.youtubeId === item.youtubeId) ? [...items] : [...items, item],
  1672. []
  1673. );
  1674. if (blacklistedSongs.find(blacklistedSong => blacklistedSong.youtubeId === song.youtubeId))
  1675. next("That song is in an blacklisted playlist and cannot be played.");
  1676. else next(null, song, station);
  1677. },
  1678. (song, station, next) => {
  1679. song.requestedBy = requestUser;
  1680. song.requestedAt = Date.now();
  1681. if (station.queue.length === 0) return next(null, song);
  1682. if (
  1683. requestUser &&
  1684. station.queue.filter(queueSong => queueSong.requestedBy === song.requestedBy).length >=
  1685. station.requests.limit
  1686. )
  1687. return next(`The max amount of songs per user is ${station.requests.limit}.`);
  1688. return next(null, song);
  1689. },
  1690. // (song, station, next) => {
  1691. // song.requestedBy = session.userId;
  1692. // song.requestedAt = Date.now();
  1693. // let totalDuration = 0;
  1694. // station.queue.forEach(song => {
  1695. // totalDuration += song.duration;
  1696. // });
  1697. // if (totalDuration >= 3600 * 3) return next("The max length of the queue is 3 hours.");
  1698. // return next(null, song, station);
  1699. // },
  1700. // (song, station, next) => {
  1701. // if (station.queue.length === 0) return next(null, song, station);
  1702. // let totalDuration = 0;
  1703. // const userId = station.queue[station.queue.length - 1].requestedBy;
  1704. // station.queue.forEach(song => {
  1705. // if (userId === song.requestedBy) {
  1706. // totalDuration += song.duration;
  1707. // }
  1708. // });
  1709. // if (totalDuration >= 900) return next("The max length of songs per user is 15 minutes.");
  1710. // return next(null, song, station);
  1711. // },
  1712. // (song, station, next) => {
  1713. // if (station.queue.length === 0) return next(null, song);
  1714. // let totalSongs = 0;
  1715. // const userId = station.queue[station.queue.length - 1].requestedBy;
  1716. // station.queue.forEach(song => {
  1717. // if (userId === song.requestedBy) {
  1718. // totalSongs += 1;
  1719. // }
  1720. // });
  1721. // if (totalSongs <= 2) return next(null, song);
  1722. // if (totalSongs > 3)
  1723. // return next("The max amount of songs per user is 3, and only 2 in a row is allowed.");
  1724. // if (
  1725. // station.queue[station.queue.length - 2].requestedBy !== userId ||
  1726. // station.queue[station.queue.length - 3] !== userId
  1727. // )
  1728. // return next("The max amount of songs per user is 3, and only 2 in a row is allowed.");
  1729. // return next(null, song);
  1730. // },
  1731. (song, next) => {
  1732. StationsModule.stationModel.updateOne(
  1733. { _id: stationId },
  1734. { $push: { queue: song } },
  1735. { runValidators: true },
  1736. next
  1737. );
  1738. },
  1739. (res, next) => {
  1740. StationsModule.runJob("UPDATE_STATION", { stationId }, this)
  1741. .then(() => next())
  1742. .catch(next);
  1743. },
  1744. next => {
  1745. CacheModule.runJob(
  1746. "PUB",
  1747. {
  1748. channel: "station.queueUpdate",
  1749. value: stationId
  1750. },
  1751. this
  1752. )
  1753. .then(() => next())
  1754. .catch(next);
  1755. }
  1756. ],
  1757. err => {
  1758. if (err) reject(err);
  1759. else resolve();
  1760. }
  1761. );
  1762. });
  1763. }
  1764. /**
  1765. * Remove from a station queue
  1766. *
  1767. * @param {object} payload - object that contains the payload
  1768. * @param {string} payload.stationId - the station id
  1769. * @param {string} payload.youtubeId - the youtube id
  1770. * @returns {Promise} - returns a promise (resolve, reject)
  1771. */
  1772. REMOVE_FROM_QUEUE(payload) {
  1773. return new Promise((resolve, reject) => {
  1774. const { stationId, youtubeId } = payload;
  1775. async.waterfall(
  1776. [
  1777. next => {
  1778. StationsModule.runJob("GET_STATION", { stationId }, this)
  1779. .then(station => {
  1780. next(null, station);
  1781. })
  1782. .catch(next);
  1783. },
  1784. (station, next) => {
  1785. if (!station) return next("Station not found.");
  1786. if (!station.queue.find(song => song.youtubeId === youtubeId))
  1787. return next("That song is not currently in the queue.");
  1788. return StationsModule.stationModel.updateOne(
  1789. { _id: stationId },
  1790. { $pull: { queue: { youtubeId } } },
  1791. next
  1792. );
  1793. },
  1794. (res, next) => {
  1795. StationsModule.runJob("UPDATE_STATION", { stationId }, this)
  1796. .then(station => {
  1797. if (station.autofill.enabled)
  1798. StationsModule.runJob("AUTOFILL_STATION", { stationId }, this)
  1799. .then(() => next())
  1800. .catch(err => {
  1801. if (
  1802. err === "Autofill is disabled in this station" ||
  1803. err === "Autofill limit reached"
  1804. )
  1805. return next();
  1806. return next(err);
  1807. });
  1808. else next();
  1809. })
  1810. .catch(next);
  1811. },
  1812. next =>
  1813. CacheModule.runJob(
  1814. "PUB",
  1815. {
  1816. channel: "station.queueUpdate",
  1817. value: stationId
  1818. },
  1819. this
  1820. )
  1821. .then(() => next())
  1822. .catch(next)
  1823. ],
  1824. err => {
  1825. if (err) reject(err);
  1826. else resolve();
  1827. }
  1828. );
  1829. });
  1830. }
  1831. }
  1832. export default new _StationsModule();