stations.js 38 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520
  1. import async from "async";
  2. import mongoose from "mongoose";
  3. import CoreClass from "../core";
  4. let StationsModule;
  5. let CacheModule;
  6. let DBModule;
  7. let UtilsModule;
  8. let WSModule;
  9. let SongsModule;
  10. let PlaylistsModule;
  11. let NotificationsModule;
  12. class _StationsModule extends CoreClass {
  13. // eslint-disable-next-line require-jsdoc
  14. constructor() {
  15. super("stations");
  16. StationsModule = this;
  17. }
  18. /**
  19. * Initialises the stations module
  20. *
  21. * @returns {Promise} - returns promise (reject, resolve)
  22. */
  23. async initialize() {
  24. CacheModule = this.moduleManager.modules.cache;
  25. DBModule = this.moduleManager.modules.db;
  26. UtilsModule = this.moduleManager.modules.utils;
  27. WSModule = this.moduleManager.modules.ws;
  28. SongsModule = this.moduleManager.modules.songs;
  29. PlaylistsModule = this.moduleManager.modules.playlists;
  30. NotificationsModule = this.moduleManager.modules.notifications;
  31. this.defaultSong = {
  32. songId: "60ItHLz5WEA",
  33. title: "Faded - Alan Walker",
  34. duration: 212,
  35. skipDuration: 0,
  36. likes: -1,
  37. dislikes: -1,
  38. requestedAt: Date.now()
  39. };
  40. this.userList = {};
  41. this.usersPerStation = {};
  42. this.usersPerStationCount = {};
  43. // TEMP
  44. CacheModule.runJob("SUB", {
  45. channel: "station.pause",
  46. cb: async stationId => {
  47. NotificationsModule.runJob("REMOVE", {
  48. subscription: `stations.nextSong?id=${stationId}`
  49. }).then();
  50. }
  51. });
  52. CacheModule.runJob("SUB", {
  53. channel: "station.resume",
  54. cb: async stationId => {
  55. StationsModule.runJob("INITIALIZE_STATION", { stationId }).then();
  56. }
  57. });
  58. CacheModule.runJob("SUB", {
  59. channel: "station.queueUpdate",
  60. cb: async stationId => {
  61. StationsModule.runJob("GET_STATION", { stationId }).then(station => {
  62. if (!station.currentSong && station.queue.length > 0) {
  63. StationsModule.runJob("INITIALIZE_STATION", {
  64. stationId
  65. }).then();
  66. }
  67. });
  68. }
  69. });
  70. CacheModule.runJob("SUB", {
  71. channel: "station.newOfficialPlaylist",
  72. cb: async stationId => {
  73. CacheModule.runJob("HGET", {
  74. table: "officialPlaylists",
  75. key: stationId
  76. }).then(playlistObj => {
  77. if (playlistObj) {
  78. WSModule.runJob("EMIT_TO_ROOM", {
  79. room: `station.${stationId}`,
  80. args: ["event:newOfficialPlaylist", playlistObj.songs]
  81. });
  82. }
  83. });
  84. }
  85. });
  86. const stationModel = (this.stationModel = await DBModule.runJob("GET_MODEL", { modelName: "station" }));
  87. const stationSchema = (this.stationSchema = await CacheModule.runJob("GET_SCHEMA", { schemaName: "station" }));
  88. return new Promise((resolve, reject) =>
  89. async.waterfall(
  90. [
  91. next => {
  92. this.setStage(2);
  93. CacheModule.runJob("HGETALL", { table: "stations" })
  94. .then(stations => {
  95. next(null, stations);
  96. })
  97. .catch(next);
  98. },
  99. (stations, next) => {
  100. this.setStage(3);
  101. if (!stations) return next();
  102. const stationIds = Object.keys(stations);
  103. return async.each(
  104. stationIds,
  105. (stationId, next) => {
  106. stationModel.findOne({ _id: stationId }, (err, station) => {
  107. if (err) next(err);
  108. else if (!station) {
  109. CacheModule.runJob("HDEL", {
  110. table: "stations",
  111. key: stationId
  112. })
  113. .then(() => {
  114. next();
  115. })
  116. .catch(next);
  117. } else next();
  118. });
  119. },
  120. next
  121. );
  122. },
  123. next => {
  124. this.setStage(4);
  125. stationModel.find({}, next);
  126. },
  127. (stations, next) => {
  128. this.setStage(5);
  129. async.each(
  130. stations,
  131. (station, next2) => {
  132. async.waterfall(
  133. [
  134. next => {
  135. CacheModule.runJob("HSET", {
  136. table: "stations",
  137. key: station._id,
  138. value: stationSchema(station)
  139. })
  140. .then(station => next(null, station))
  141. .catch(next);
  142. },
  143. (station, next) => {
  144. StationsModule.runJob(
  145. "INITIALIZE_STATION",
  146. {
  147. stationId: station._id
  148. },
  149. null,
  150. -1
  151. )
  152. .then(() => {
  153. next();
  154. })
  155. .catch(next);
  156. }
  157. ],
  158. err => {
  159. next2(err);
  160. }
  161. );
  162. },
  163. next
  164. );
  165. }
  166. ],
  167. async err => {
  168. if (err) {
  169. err = await UtilsModule.runJob("GET_ERROR", {
  170. error: err
  171. });
  172. reject(new Error(err));
  173. } else {
  174. resolve();
  175. }
  176. }
  177. )
  178. );
  179. }
  180. /**
  181. * Initialises a station
  182. *
  183. * @param {object} payload - object that contains the payload
  184. * @param {string} payload.stationId - id of the station to initialise
  185. * @returns {Promise} - returns a promise (resolve, reject)
  186. */
  187. INITIALIZE_STATION(payload) {
  188. return new Promise((resolve, reject) => {
  189. // if (typeof cb !== 'function') cb = ()=>{};
  190. async.waterfall(
  191. [
  192. next => {
  193. StationsModule.runJob(
  194. "GET_STATION",
  195. {
  196. stationId: payload.stationId
  197. },
  198. this
  199. )
  200. .then(station => {
  201. next(null, station);
  202. })
  203. .catch(next);
  204. },
  205. (station, next) => {
  206. if (!station) return next("Station not found.");
  207. return NotificationsModule.runJob(
  208. "UNSCHEDULE",
  209. {
  210. name: `stations.nextSong?id=${station._id}`
  211. },
  212. this
  213. )
  214. .then()
  215. .catch()
  216. .finally(() => {
  217. NotificationsModule.runJob("SUBSCRIBE", {
  218. name: `stations.nextSong?id=${station._id}`,
  219. cb: () =>
  220. StationsModule.runJob("SKIP_STATION", {
  221. stationId: station._id
  222. }),
  223. unique: true,
  224. station
  225. })
  226. .then()
  227. .catch();
  228. if (station.paused) return next(true, station);
  229. return next(null, station);
  230. });
  231. },
  232. (station, next) => {
  233. if (!station.currentSong) {
  234. return StationsModule.runJob(
  235. "SKIP_STATION",
  236. {
  237. stationId: station._id
  238. },
  239. this
  240. )
  241. .then(station => {
  242. next(true, station);
  243. })
  244. .catch(next)
  245. .finally(() => {});
  246. }
  247. let timeLeft =
  248. station.currentSong.duration * 1000 - (Date.now() - station.startedAt - station.timePaused);
  249. if (Number.isNaN(timeLeft)) timeLeft = -1;
  250. if (station.currentSong.duration * 1000 < timeLeft || timeLeft < 0) {
  251. return StationsModule.runJob(
  252. "SKIP_STATION",
  253. {
  254. stationId: station._id
  255. },
  256. this
  257. )
  258. .then(station => {
  259. next(null, station);
  260. })
  261. .catch(next);
  262. }
  263. // name, time, cb, station
  264. NotificationsModule.runJob("SCHEDULE", {
  265. name: `stations.nextSong?id=${station._id}`,
  266. time: timeLeft,
  267. station
  268. });
  269. return next(null, station);
  270. }
  271. ],
  272. async (err, station) => {
  273. if (err && err !== true) {
  274. err = await UtilsModule.runJob(
  275. "GET_ERROR",
  276. {
  277. error: err
  278. },
  279. this
  280. );
  281. reject(new Error(err));
  282. } else resolve(station);
  283. }
  284. );
  285. });
  286. }
  287. /**
  288. * Attempts to get the station from Redis. If it's not in Redis, get it from Mongo and add it to Redis.
  289. *
  290. * @param {object} payload - object that contains the payload
  291. * @param {string} payload.stationId - id of the station
  292. * @returns {Promise} - returns a promise (resolve, reject)
  293. */
  294. GET_STATION(payload) {
  295. return new Promise((resolve, reject) => {
  296. async.waterfall(
  297. [
  298. next => {
  299. CacheModule.runJob("HGET", { table: "stations", key: payload.stationId }, this)
  300. .then(station => next(null, station))
  301. .catch(next);
  302. },
  303. (station, next) => {
  304. if (station) return next(true, station);
  305. return StationsModule.stationModel.findOne({ _id: payload.stationId }, next);
  306. },
  307. (station, next) => {
  308. if (station) {
  309. station = StationsModule.stationSchema(station);
  310. CacheModule.runJob("HSET", {
  311. table: "stations",
  312. key: payload.stationId,
  313. value: station
  314. })
  315. .then()
  316. .catch();
  317. next(true, station);
  318. } else next("Station not found");
  319. }
  320. ],
  321. async (err, station) => {
  322. if (err && err !== true) {
  323. err = await UtilsModule.runJob(
  324. "GET_ERROR",
  325. {
  326. error: err
  327. },
  328. this
  329. );
  330. reject(new Error(err));
  331. } else resolve(station);
  332. }
  333. );
  334. });
  335. }
  336. /**
  337. * 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.
  338. *
  339. * @param {object} payload - object that contains the payload
  340. * @param {string} payload.stationName - the unique name of the station
  341. * @returns {Promise} - returns a promise (resolve, reject)
  342. */
  343. async GET_STATION_BY_NAME(payload) {
  344. return new Promise((resolve, reject) =>
  345. async.waterfall(
  346. [
  347. next => {
  348. StationsModule.stationModel.findOne({ name: payload.stationName }, next);
  349. },
  350. (station, next) => {
  351. if (station) {
  352. station = StationsModule.stationSchema(station);
  353. CacheModule.runJob("HSET", {
  354. table: "stations",
  355. key: station._id,
  356. value: station
  357. });
  358. next(true, station);
  359. } else next("Station not found");
  360. }
  361. ],
  362. (err, station) => {
  363. if (err && err !== true) return reject(new Error(err));
  364. return resolve(station);
  365. }
  366. )
  367. );
  368. }
  369. /**
  370. * Updates the station in cache from mongo or deletes station in cache if no longer in mongo.
  371. *
  372. * @param {object} payload - object that contains the payload
  373. * @param {string} payload.stationId - the id of the station to update
  374. * @returns {Promise} - returns a promise (resolve, reject)
  375. */
  376. UPDATE_STATION(payload) {
  377. return new Promise((resolve, reject) => {
  378. async.waterfall(
  379. [
  380. next => {
  381. StationsModule.stationModel.findOne({ _id: payload.stationId }, next);
  382. },
  383. (station, next) => {
  384. if (!station) {
  385. CacheModule.runJob("HDEL", {
  386. table: "stations",
  387. key: payload.stationId
  388. })
  389. .then()
  390. .catch();
  391. return next("Station not found");
  392. }
  393. return CacheModule.runJob(
  394. "HSET",
  395. {
  396. table: "stations",
  397. key: payload.stationId,
  398. value: station
  399. },
  400. this
  401. )
  402. .then(station => {
  403. next(null, station);
  404. })
  405. .catch(next);
  406. }
  407. ],
  408. async (err, station) => {
  409. if (err && err !== true) {
  410. err = await UtilsModule.runJob(
  411. "GET_ERROR",
  412. {
  413. error: err
  414. },
  415. this
  416. );
  417. reject(new Error(err));
  418. } else resolve(station);
  419. }
  420. );
  421. });
  422. }
  423. /**
  424. * Fills up the official station playlist queue using the songs from the official station playlist
  425. *
  426. * @param {object} payload - object that contains the payload
  427. * @param {string} payload.stationId - the id of the station
  428. * @returns {Promise} - returns a promise (resolve, reject)
  429. */
  430. FILL_UP_OFFICIAL_STATION_PLAYLIST_QUEUE(payload) {
  431. return new Promise((resolve, reject) => {
  432. const { stationId } = payload;
  433. async.waterfall(
  434. [
  435. next => {
  436. PlaylistsModule.runJob("GET_STATION_PLAYLIST", { stationId, includeSongs: true }, this)
  437. .then(response => {
  438. next(null, response.playlist);
  439. })
  440. .catch(next);
  441. },
  442. (playlist, next) => {
  443. UtilsModule.runJob("SHUFFLE", { array: playlist.songs }, this)
  444. .then(response => {
  445. next(null, response.array);
  446. })
  447. .catch(next);
  448. },
  449. (playlistSongs, next) => {
  450. StationsModule.runJob("GET_STATION", { stationId }, this)
  451. .then(station => {
  452. next(null, playlistSongs, station);
  453. })
  454. .catch(next);
  455. },
  456. (playlistSongs, station, next) => {
  457. const songsStillNeeded = 50 - station.playlist.length;
  458. const currentSongs = station.playlist;
  459. const currentSongIds = station.playlist.map(song => song._id);
  460. const songsToAdd = [];
  461. playlistSongs
  462. .map(song => song._doc)
  463. .every(song => {
  464. if (
  465. songsToAdd.length < songsStillNeeded &&
  466. currentSongIds.indexOf(song._id.toString()) === -1
  467. ) {
  468. songsToAdd.push(song);
  469. return false;
  470. }
  471. return true;
  472. });
  473. next(null, [...currentSongs, ...songsToAdd]);
  474. },
  475. (newPlaylist, next) => {
  476. StationsModule.stationModel.updateOne(
  477. { _id: stationId },
  478. { $set: { playlist: newPlaylist } },
  479. { runValidators: true },
  480. () => {
  481. StationsModule.runJob(
  482. "UPDATE_STATION",
  483. {
  484. stationId
  485. },
  486. this
  487. )
  488. .then(() => {
  489. next(null);
  490. })
  491. .catch(next);
  492. }
  493. );
  494. }
  495. ],
  496. err => {
  497. if (err) reject(err);
  498. else resolve();
  499. }
  500. );
  501. });
  502. }
  503. /**
  504. * Gets next official station song
  505. *
  506. * @param {object} payload - object that contains the payload
  507. * @param {string} payload.stationId - the id of the station
  508. * @returns {Promise} - returns a promise (resolve, reject)
  509. */
  510. GET_NEXT_OFFICIAL_STATION_SONG(payload) {
  511. return new Promise((resolve, reject) => {
  512. const { stationId } = payload;
  513. async.waterfall(
  514. [
  515. next => {
  516. StationsModule.runJob("GET_STATION", { stationId }, this)
  517. .then(station => {
  518. next(null, station);
  519. })
  520. .catch(next);
  521. },
  522. (station, next) => {
  523. if (station.playlist.length === 0) next("No songs available.");
  524. else {
  525. next(null, station.playlist[0]);
  526. }
  527. },
  528. (song, next) => {
  529. console.log(44444, song, song._id);
  530. SongsModule.runJob("GET_SONG", { id: song._id }, this)
  531. .then(response => {
  532. const { song } = response;
  533. if (song) {
  534. const newSong = {
  535. _id: song._id,
  536. songId: song.songId,
  537. title: song.title,
  538. artists: song.artists,
  539. duration: song.duration,
  540. thumbnail: song.thumbnail,
  541. requestedAt: song.requestedAt
  542. };
  543. next(null, newSong);
  544. } else {
  545. next(null, song);
  546. }
  547. })
  548. .catch(next);
  549. }
  550. ],
  551. (err, song) => {
  552. if (err) console.log(33333, err, payload);
  553. if (err) reject(err);
  554. else resolve({ song });
  555. }
  556. );
  557. });
  558. }
  559. /**
  560. * Removes first official playlist queue song
  561. *
  562. * @param {object} payload - object that contains the payload
  563. * @param {string} payload.stationId - the id of the station
  564. * @returns {Promise} - returns a promise (resolve, reject)
  565. */
  566. REMOVE_FIRST_OFFICIAL_PLAYLIST_QUEUE_SONG(payload) {
  567. return new Promise((resolve, reject) => {
  568. const { stationId } = payload;
  569. async.waterfall(
  570. [
  571. next => {
  572. StationsModule.stationModel.updateOne(
  573. { _id: stationId },
  574. { $pop: { playlist: -1 } },
  575. { runValidators: true },
  576. err => {
  577. if (err) next(err);
  578. else
  579. StationsModule.runJob(
  580. "UPDATE_STATION",
  581. {
  582. stationId
  583. },
  584. this
  585. )
  586. .then(() => {
  587. next(null);
  588. })
  589. .catch(next);
  590. }
  591. );
  592. }
  593. ],
  594. err => {
  595. if (err) reject(err);
  596. else resolve();
  597. }
  598. );
  599. });
  600. }
  601. /**
  602. * Skips a station
  603. *
  604. * @param {object} payload - object that contains the payload
  605. * @param {string} payload.stationId - the id of the station to skip
  606. * @returns {Promise} - returns a promise (resolve, reject)
  607. */
  608. SKIP_STATION(payload) {
  609. return new Promise((resolve, reject) => {
  610. StationsModule.log("INFO", `Skipping station ${payload.stationId}.`);
  611. StationsModule.log("STATION_ISSUE", `SKIP_STATION_CB - Station ID: ${payload.stationId}.`);
  612. async.waterfall(
  613. [
  614. next => {
  615. NotificationsModule.runJob("UNSCHEDULE", {
  616. name: `stations.nextSong?id=${payload.stationId}`
  617. })
  618. .then(() => {
  619. next();
  620. })
  621. .catch(next);
  622. },
  623. next => {
  624. StationsModule.runJob(
  625. "GET_STATION",
  626. {
  627. stationId: payload.stationId
  628. },
  629. this
  630. )
  631. .then(station => {
  632. next(null, station);
  633. })
  634. .catch(() => {});
  635. },
  636. // eslint-disable-next-line consistent-return
  637. (station, next) => {
  638. if (!station) return next("Station not found.");
  639. if (station.type === "community" && station.partyMode && station.queue.length === 0)
  640. return next(null, null, -11, station); // Community station with party mode enabled and no songs in the queue
  641. if (station.type === "community" && station.partyMode && station.queue.length > 0) {
  642. // Community station with party mode enabled and songs in the queue
  643. if (station.paused) return next(null, null, -19, station);
  644. return StationsModule.stationModel.updateOne(
  645. { _id: payload.stationId },
  646. {
  647. $pull: {
  648. queue: {
  649. _id: station.queue[0]._id
  650. }
  651. }
  652. },
  653. err => {
  654. if (err) return next(err);
  655. return next(null, station.queue[0], -12, station);
  656. }
  657. );
  658. }
  659. if (station.type === "community" && !station.partyMode) {
  660. return DBModule.runJob("GET_MODEL", { modelName: "playlist" }, this).then(playlistModel =>
  661. playlistModel.findOne({ _id: station.privatePlaylist }, (err, playlist) => {
  662. if (err) return next(err);
  663. if (!playlist) return next(null, null, -13, station);
  664. playlist = playlist.songs;
  665. if (playlist.length > 0) {
  666. let currentSongIndex;
  667. if (station.currentSongIndex < playlist.length - 1)
  668. currentSongIndex = station.currentSongIndex + 1;
  669. else currentSongIndex = 0;
  670. const callback = (err, song) => {
  671. if (err) return next(err);
  672. if (song) return next(null, song, currentSongIndex, station);
  673. const currentSong = {
  674. songId: playlist[currentSongIndex].songId,
  675. title: playlist[currentSongIndex].title,
  676. duration: playlist[currentSongIndex].duration,
  677. likes: -1,
  678. dislikes: -1,
  679. requestedAt: playlist[currentSongIndex].requestedAt
  680. };
  681. return next(null, currentSong, currentSongIndex, station);
  682. };
  683. if (mongoose.Types.ObjectId.isValid(playlist[currentSongIndex]._id))
  684. return SongsModule.runJob(
  685. "GET_SONG",
  686. {
  687. id: playlist[currentSongIndex]._id
  688. },
  689. this
  690. )
  691. .then(response => callback(null, response.song))
  692. .catch(callback);
  693. return SongsModule.runJob(
  694. "GET_SONG_FROM_ID",
  695. {
  696. songId: playlist[currentSongIndex].songId
  697. },
  698. this
  699. )
  700. .then(response => callback(null, response.song))
  701. .catch(callback);
  702. }
  703. return next(null, null, -14, station);
  704. })
  705. );
  706. }
  707. if (station.type === "official") {
  708. StationsModule.runJob(
  709. "REMOVE_FIRST_OFFICIAL_PLAYLIST_QUEUE_SONG",
  710. { stationId: station._id },
  711. this
  712. )
  713. .then(() => {
  714. StationsModule.runJob(
  715. "FILL_UP_OFFICIAL_STATION_PLAYLIST_QUEUE",
  716. { stationId: station._id },
  717. this
  718. )
  719. .then(() => {
  720. StationsModule.runJob(
  721. "GET_NEXT_OFFICIAL_STATION_SONG",
  722. { stationId: station._id },
  723. this
  724. )
  725. .then(response => {
  726. next(null, response.song, 0, station);
  727. })
  728. .catch(err => {
  729. if (err === "No songs available.") next(null, null, 0, station);
  730. else next(err);
  731. });
  732. })
  733. .catch(next);
  734. })
  735. .catch(next);
  736. }
  737. },
  738. (song, currentSongIndex, station, next) => {
  739. const $set = {};
  740. if (song === null) $set.currentSong = null;
  741. else if (song.likes === -1 && song.dislikes === -1) {
  742. $set.currentSong = {
  743. songId: song.songId,
  744. title: song.title,
  745. duration: song.duration,
  746. skipDuration: 0,
  747. likes: -1,
  748. dislikes: -1,
  749. requestedAt: song.requestedAt
  750. };
  751. } else {
  752. $set.currentSong = {
  753. _id: song._id,
  754. songId: song.songId,
  755. title: song.title,
  756. artists: song.artists,
  757. duration: song.duration,
  758. likes: song.likes,
  759. dislikes: song.dislikes,
  760. skipDuration: song.skipDuration,
  761. thumbnail: song.thumbnail,
  762. requestedAt: song.requestedAt
  763. };
  764. }
  765. if (currentSongIndex >= 0) $set.currentSongIndex = currentSongIndex;
  766. $set.startedAt = Date.now();
  767. $set.timePaused = 0;
  768. if (station.paused) $set.pausedAt = Date.now();
  769. next(null, $set, station);
  770. },
  771. ($set, station, next) => {
  772. StationsModule.stationModel.updateOne({ _id: station._id }, { $set }, err => {
  773. if (err) return next(err);
  774. return StationsModule.runJob(
  775. "UPDATE_STATION",
  776. {
  777. stationId: station._id
  778. },
  779. this
  780. )
  781. .then(station => {
  782. if (station.type === "community" && station.partyMode === true)
  783. CacheModule.runJob("PUB", {
  784. channel: "station.queueUpdate",
  785. value: payload.stationId
  786. })
  787. .then()
  788. .catch();
  789. next(null, station);
  790. })
  791. .catch(next);
  792. });
  793. }
  794. ],
  795. async (err, station) => {
  796. if (err) {
  797. console.log(123, err);
  798. err = await UtilsModule.runJob(
  799. "GET_ERROR",
  800. {
  801. error: err
  802. },
  803. this
  804. );
  805. StationsModule.log("ERROR", `Skipping station "${payload.stationId}" failed. "${err}"`);
  806. reject(new Error(err));
  807. } else {
  808. if (station.currentSong !== null && station.currentSong.songId !== undefined) {
  809. station.currentSong.skipVotes = 0;
  810. }
  811. // TODO Pub/Sub this
  812. WSModule.runJob("EMIT_TO_ROOM", {
  813. room: `station.${station._id}`,
  814. args: [
  815. "event:songs.next",
  816. {
  817. currentSong: station.currentSong,
  818. startedAt: station.startedAt,
  819. paused: station.paused,
  820. timePaused: 0
  821. }
  822. ]
  823. })
  824. .then()
  825. .catch();
  826. if (station.privacy === "public") {
  827. WSModule.runJob("EMIT_TO_ROOM", {
  828. room: "home",
  829. args: ["event:station.nextSong", station._id, station.currentSong]
  830. })
  831. .then()
  832. .catch();
  833. } else {
  834. const sockets = await WSModule.runJob("GET_SOCKETS_FOR_ROOM", { room: "home" }, this);
  835. sockets.forEach(async socketId => {
  836. const socket = await WSModule.runJob("SOCKET_FROM_SOCKET_ID", { socketId }, this);
  837. const { session } = socket;
  838. if (session.sessionId) {
  839. CacheModule.runJob(
  840. "HGET",
  841. { table: "sessions", key: session.sessionId },
  842. this
  843. // eslint-disable-next-line no-loop-func
  844. ).then(session => {
  845. if (session) {
  846. DBModule.runJob("GET_MODEL", { modelName: "user" }, this).then(
  847. userModel => {
  848. userModel.findOne(
  849. {
  850. _id: session.userId
  851. },
  852. (err, user) => {
  853. if (!err && user) {
  854. if (user.role === "admin")
  855. socket.dispatch(
  856. "event:station.nextSong",
  857. station._id,
  858. station.currentSong
  859. );
  860. else if (
  861. station.type === "community" &&
  862. station.owner === session.userId
  863. )
  864. socket.dispatch(
  865. "event:station.nextSong",
  866. station._id,
  867. station.currentSong
  868. );
  869. }
  870. }
  871. );
  872. }
  873. );
  874. }
  875. });
  876. }
  877. });
  878. }
  879. WSModule.runJob("GET_SOCKETS_FOR_ROOM", { room: `station.${station._id}` }).then(sockets => {
  880. if (station.currentSong !== null && station.currentSong.songId !== undefined) {
  881. WSModule.runJob("SOCKETS_JOIN_SONG_ROOM", {
  882. sockets,
  883. room: `song.${station.currentSong.songId}`
  884. });
  885. if (!station.paused) {
  886. NotificationsModule.runJob("SCHEDULE", {
  887. name: `stations.nextSong?id=${station._id}`,
  888. time: station.currentSong.duration * 1000,
  889. station
  890. });
  891. }
  892. } else {
  893. WSModule.runJob("SOCKETS_LEAVE_SONG_ROOMS", {
  894. sockets
  895. });
  896. }
  897. });
  898. resolve({ station });
  899. }
  900. }
  901. );
  902. });
  903. }
  904. /**
  905. * Checks if a user can view/access a station
  906. *
  907. * @param {object} payload - object that contains the payload
  908. * @param {object} payload.station - the station object of the station in question
  909. * @param {string} payload.userId - the id of the user in question
  910. * @param {boolean} payload.hideUnlisted - whether the user is allowed to see unlisted stations or not
  911. * @returns {Promise} - returns a promise (resolve, reject)
  912. */
  913. CAN_USER_VIEW_STATION(payload) {
  914. return new Promise((resolve, reject) => {
  915. async.waterfall(
  916. [
  917. next => {
  918. if (payload.station.privacy === "public") return next(true);
  919. if (payload.station.privacy === "unlisted")
  920. if (payload.hideUnlisted === true) return next();
  921. else return next(true);
  922. if (!payload.userId) return next("Not allowed");
  923. return next();
  924. },
  925. next => {
  926. DBModule.runJob("GET_MODEL", { modelName: "user" }, this).then(userModel => {
  927. userModel.findOne({ _id: payload.userId }, next);
  928. });
  929. },
  930. (user, next) => {
  931. if (!user) return next("Not allowed");
  932. if (user.role === "admin") return next(true);
  933. if (payload.station.type === "official") return next("Not allowed");
  934. if (payload.station.owner === payload.userId) return next(true);
  935. return next("Not allowed");
  936. }
  937. ],
  938. async errOrResult => {
  939. if (errOrResult !== true && errOrResult !== "Not allowed") {
  940. errOrResult = await UtilsModule.runJob(
  941. "GET_ERROR",
  942. {
  943. error: errOrResult
  944. },
  945. this
  946. );
  947. reject(new Error(errOrResult));
  948. } else {
  949. resolve(errOrResult === true);
  950. }
  951. }
  952. );
  953. });
  954. }
  955. /**
  956. * Checks if a user has favorited a station or not
  957. *
  958. * @param {object} payload - object that contains the payload
  959. * @param {object} payload.stationId - the id of the station in question
  960. * @param {string} payload.userId - the id of the user in question
  961. * @returns {Promise} - returns a promise (resolve, reject)
  962. */
  963. HAS_USER_FAVORITED_STATION(payload) {
  964. return new Promise((resolve, reject) => {
  965. async.waterfall(
  966. [
  967. next => {
  968. DBModule.runJob("GET_MODEL", { modelName: "user" }, this).then(userModel => {
  969. userModel.findOne({ _id: payload.userId }, next);
  970. });
  971. },
  972. (user, next) => {
  973. if (!user) return next("User not found.");
  974. if (user.favoriteStations.indexOf(payload.stationId) !== -1) return next(null, true);
  975. return next(null, false);
  976. }
  977. ],
  978. async (err, isStationFavorited) => {
  979. if (err && err !== true) {
  980. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  981. return reject(new Error(err));
  982. }
  983. return resolve(isStationFavorited);
  984. }
  985. );
  986. });
  987. }
  988. /**
  989. * Returns a list of sockets in a room that can and can't know about a station
  990. *
  991. * @param {object} payload - the payload object
  992. * @param {object} payload.station - the station object
  993. * @param {string} payload.room - the websockets room to get the sockets from
  994. * @returns {Promise} - returns a promise (resolve, reject)
  995. */
  996. GET_SOCKETS_THAT_CAN_KNOW_ABOUT_STATION(payload) {
  997. return new Promise((resolve, reject) => {
  998. WSModule.runJob("GET_SOCKETS_FOR_ROOM", { room: payload.room }, this)
  999. .then(socketsObject => {
  1000. const sockets = Object.keys(socketsObject).map(socketKey => socketsObject[socketKey]);
  1001. let socketsThatCan = [];
  1002. const socketsThatCannot = [];
  1003. if (payload.station.privacy === "public") {
  1004. socketsThatCan = sockets;
  1005. resolve({ socketsThatCan, socketsThatCannot });
  1006. } else {
  1007. async.eachLimit(
  1008. sockets,
  1009. 1,
  1010. (socket, next) => {
  1011. const { session } = socket;
  1012. async.waterfall(
  1013. [
  1014. next => {
  1015. if (!session.sessionId) next("No session id");
  1016. else next();
  1017. },
  1018. next => {
  1019. CacheModule.runJob(
  1020. "HGET",
  1021. {
  1022. table: "sessions",
  1023. key: session.sessionId
  1024. },
  1025. this
  1026. )
  1027. .then(response => {
  1028. next(null, response);
  1029. })
  1030. .catch(next);
  1031. },
  1032. (session, next) => {
  1033. if (!session) next("No session");
  1034. else {
  1035. DBModule.runJob("GET_MODEL", { modelName: "user" }, this)
  1036. .then(userModel => {
  1037. next(null, userModel);
  1038. })
  1039. .catch(next);
  1040. }
  1041. },
  1042. (userModel, next) => {
  1043. if (!userModel) next("No user model");
  1044. else
  1045. userModel.findOne(
  1046. {
  1047. _id: session.userId
  1048. },
  1049. next
  1050. );
  1051. },
  1052. (user, next) => {
  1053. if (!user) next("No user found");
  1054. else if (user.role === "admin") {
  1055. socketsThatCan.push(socket);
  1056. next();
  1057. } else if (
  1058. payload.station.type === "community" &&
  1059. payload.station.owner === session.userId
  1060. ) {
  1061. socketsThatCan.push(socket);
  1062. next();
  1063. }
  1064. }
  1065. ],
  1066. err => {
  1067. if (err) socketsThatCannot.push(socket);
  1068. next();
  1069. }
  1070. );
  1071. },
  1072. err => {
  1073. if (err) reject(err);
  1074. else resolve({ socketsThatCan, socketsThatCannot });
  1075. }
  1076. );
  1077. }
  1078. })
  1079. .catch(reject);
  1080. });
  1081. }
  1082. /**
  1083. * Adds a playlist to be included in a station
  1084. *
  1085. * @param {object} payload - object that contains the payload
  1086. * @param {object} payload.stationId - the id of the station to include the playlist in
  1087. * @param {object} payload.playlistId - the id of the playlist to be included
  1088. * @returns {Promise} - returns a promise (resolve, reject)
  1089. */
  1090. INCLUDE_PLAYLIST(payload) {
  1091. return new Promise((resolve, reject) => {
  1092. async.waterfall(
  1093. [
  1094. next => {
  1095. if (!payload.stationId) next("Please specify a station id");
  1096. else if (!payload.playlistId) next("Please specify a playlist id");
  1097. else next();
  1098. },
  1099. next => {
  1100. StationsModule.runJob("GET_STATION", { stationId: payload.stationId }, this)
  1101. .then(station => {
  1102. next(null, station);
  1103. })
  1104. .catch(next);
  1105. },
  1106. (station, next) => {
  1107. if (station.playlist2 === payload.playlistId) next("You cannot include the station playlist");
  1108. else if (station.includedPlaylists.indexOf(payload.playlistId) !== -1)
  1109. next("This playlist is already included");
  1110. else if (station.excludedPlaylists.indexOf(payload.playlistId) !== -1)
  1111. next(
  1112. "This playlist is currently excluded, please remove it from there before including it"
  1113. );
  1114. else
  1115. PlaylistsModule.runJob("GET_PLAYLIST", { playlistId: payload.playlistId }, this)
  1116. .then(() => {
  1117. next(null);
  1118. })
  1119. .catch(next);
  1120. },
  1121. next => {
  1122. DBModule.runJob(
  1123. "GET_MODEL",
  1124. {
  1125. modelName: "station"
  1126. },
  1127. this
  1128. ).then(stationModel => {
  1129. stationModel.updateOne(
  1130. { _id: payload.stationId },
  1131. { $push: { includedPlaylists: payload.playlistId } },
  1132. next
  1133. );
  1134. });
  1135. },
  1136. (res, next) => {
  1137. StationsModule.runJob(
  1138. "UPDATE_STATION",
  1139. {
  1140. stationId: payload.stationId
  1141. },
  1142. this
  1143. )
  1144. .then(() => {
  1145. next();
  1146. })
  1147. .catch(next);
  1148. }
  1149. ],
  1150. async err => {
  1151. if (err && err !== true) {
  1152. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1153. return reject(new Error(err));
  1154. }
  1155. return resolve();
  1156. }
  1157. );
  1158. });
  1159. }
  1160. /**
  1161. * Removes a playlist that is included in a station
  1162. *
  1163. * @param {object} payload - object that contains the payload
  1164. * @param {object} payload.stationId - the id of the station
  1165. * @param {object} payload.playlistId - the id of the playlist
  1166. * @returns {Promise} - returns a promise (resolve, reject)
  1167. */
  1168. REMOVE_INCLUDED_PLAYLIST(payload) {
  1169. return new Promise((resolve, reject) => {
  1170. async.waterfall(
  1171. [
  1172. next => {
  1173. if (!payload.stationId) next("Please specify a station id");
  1174. else if (!payload.playlistId) next("Please specify a playlist id");
  1175. else next();
  1176. },
  1177. next => {
  1178. StationsModule.runJob("GET_STATION", { stationId: payload.stationId }, this)
  1179. .then(station => {
  1180. next(null, station);
  1181. })
  1182. .catch(next);
  1183. },
  1184. (station, next) => {
  1185. if (station.includedPlaylists.indexOf(payload.playlistId) === -1)
  1186. next("This playlist isn't included");
  1187. else next();
  1188. },
  1189. next => {
  1190. DBModule.runJob(
  1191. "GET_MODEL",
  1192. {
  1193. modelName: "station"
  1194. },
  1195. this
  1196. ).then(stationModel => {
  1197. stationModel.updateOne(
  1198. { _id: payload.stationId },
  1199. { $pull: { includedPlaylists: payload.playlistId } },
  1200. next
  1201. );
  1202. });
  1203. },
  1204. (res, next) => {
  1205. StationsModule.runJob(
  1206. "UPDATE_STATION",
  1207. {
  1208. stationId: payload.stationId
  1209. },
  1210. this
  1211. )
  1212. .then(() => {
  1213. next();
  1214. })
  1215. .catch(next);
  1216. }
  1217. ],
  1218. async err => {
  1219. if (err && err !== true) {
  1220. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1221. return reject(new Error(err));
  1222. }
  1223. return resolve();
  1224. }
  1225. );
  1226. });
  1227. }
  1228. /**
  1229. * Adds a playlist to be excluded in a station
  1230. *
  1231. * @param {object} payload - object that contains the payload
  1232. * @param {object} payload.stationId - the id of the station
  1233. * @param {object} payload.playlistId - the id of the playlist
  1234. * @returns {Promise} - returns a promise (resolve, reject)
  1235. */
  1236. EXCLUDE_PLAYLIST(payload) {
  1237. return new Promise((resolve, reject) => {
  1238. async.waterfall(
  1239. [
  1240. next => {
  1241. if (!payload.stationId) next("Please specify a station id");
  1242. else if (!payload.playlistId) next("Please specify a playlist id");
  1243. else next();
  1244. },
  1245. next => {
  1246. StationsModule.runJob("GET_STATION", { stationId: payload.stationId }, this)
  1247. .then(station => {
  1248. next(null, station);
  1249. })
  1250. .catch(next);
  1251. },
  1252. (station, next) => {
  1253. if (station.playlist2 === payload.playlistId) next("You cannot exclude the station playlist");
  1254. else if (station.excludedPlaylists.indexOf(payload.playlistId) !== -1)
  1255. next("This playlist is already excluded");
  1256. else if (station.includedPlaylists.indexOf(payload.playlistId) !== -1)
  1257. next(
  1258. "This playlist is currently included, please remove it from there before excluding it"
  1259. );
  1260. else
  1261. PlaylistsModule.runJob("GET_PLAYLIST", { playlistId: payload.playlistId }, this)
  1262. .then(() => {
  1263. next(null);
  1264. })
  1265. .catch(next);
  1266. },
  1267. next => {
  1268. DBModule.runJob(
  1269. "GET_MODEL",
  1270. {
  1271. modelName: "station"
  1272. },
  1273. this
  1274. ).then(stationModel => {
  1275. stationModel.updateOne(
  1276. { _id: payload.stationId },
  1277. { $push: { excludedPlaylists: payload.playlistId } },
  1278. next
  1279. );
  1280. });
  1281. },
  1282. (res, next) => {
  1283. StationsModule.runJob(
  1284. "UPDATE_STATION",
  1285. {
  1286. stationId: payload.stationId
  1287. },
  1288. this
  1289. )
  1290. .then(() => {
  1291. next();
  1292. })
  1293. .catch(next);
  1294. }
  1295. ],
  1296. async err => {
  1297. if (err && err !== true) {
  1298. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1299. return reject(new Error(err));
  1300. }
  1301. return resolve();
  1302. }
  1303. );
  1304. });
  1305. }
  1306. /**
  1307. * Removes a playlist that is excluded in a station
  1308. *
  1309. * @param {object} payload - object that contains the payload
  1310. * @param {object} payload.stationId - the id of the station
  1311. * @param {object} payload.playlistId - the id of the playlist
  1312. * @returns {Promise} - returns a promise (resolve, reject)
  1313. */
  1314. REMOVE_EXCLUDED_PLAYLIST(payload) {
  1315. return new Promise((resolve, reject) => {
  1316. console.log(112, payload);
  1317. async.waterfall(
  1318. [
  1319. next => {
  1320. if (!payload.stationId) next("Please specify a station id");
  1321. else if (!payload.playlistId) next("Please specify a playlist id");
  1322. else next();
  1323. },
  1324. next => {
  1325. StationsModule.runJob("GET_STATION", { stationId: payload.stationId }, this)
  1326. .then(station => {
  1327. next(null, station);
  1328. })
  1329. .catch(next);
  1330. },
  1331. (station, next) => {
  1332. if (station.excludedPlaylists.indexOf(payload.playlistId) === -1)
  1333. next("This playlist isn't excluded");
  1334. else next();
  1335. },
  1336. next => {
  1337. DBModule.runJob(
  1338. "GET_MODEL",
  1339. {
  1340. modelName: "station"
  1341. },
  1342. this
  1343. ).then(stationModel => {
  1344. stationModel.updateOne(
  1345. { _id: payload.stationId },
  1346. { $pull: { excludedPlaylists: payload.playlistId } },
  1347. next
  1348. );
  1349. });
  1350. },
  1351. (res, next) => {
  1352. StationsModule.runJob(
  1353. "UPDATE_STATION",
  1354. {
  1355. stationId: payload.stationId
  1356. },
  1357. this
  1358. )
  1359. .then(() => {
  1360. next();
  1361. })
  1362. .catch(next);
  1363. }
  1364. ],
  1365. async err => {
  1366. if (err && err !== true) {
  1367. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1368. return reject(new Error(err));
  1369. }
  1370. return resolve();
  1371. }
  1372. );
  1373. });
  1374. }
  1375. /**
  1376. * Gets stations that include or exclude a specific playlist
  1377. *
  1378. * @param {object} payload - object that contains the payload
  1379. * @param {string} payload.playlistId - the playlist id
  1380. * @returns {Promise} - returns promise (reject, resolve)
  1381. */
  1382. GET_STATIONS_THAT_INCLUDE_OR_EXCLUDE_PLAYLIST(payload) {
  1383. return new Promise((resolve, reject) => {
  1384. DBModule.runJob(
  1385. "GET_MODEL",
  1386. {
  1387. modelName: "station"
  1388. },
  1389. this
  1390. ).then(stationModel => {
  1391. stationModel.find(
  1392. { $or: [{ includedPlaylists: payload.playlistId }, { excludedPlaylists: payload.playlistId }] },
  1393. (err, stations) => {
  1394. if (err) reject(err);
  1395. else resolve({ stationIds: stations.map(station => station._id) });
  1396. }
  1397. );
  1398. });
  1399. });
  1400. }
  1401. }
  1402. export default new _StationsModule();