stations.js 38 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517
  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_SONG_POSITIONS", { 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. .forEach(song => {
  464. if (
  465. songsToAdd.length < songsStillNeeded &&
  466. currentSongIds.indexOf(song._id.toString()) === -1
  467. )
  468. songsToAdd.push(song);
  469. });
  470. next(null, [...currentSongs, ...songsToAdd]);
  471. },
  472. (newPlaylist, next) => {
  473. StationsModule.stationModel.updateOne(
  474. { _id: stationId },
  475. { $set: { playlist: newPlaylist } },
  476. { runValidators: true },
  477. () => {
  478. StationsModule.runJob(
  479. "UPDATE_STATION",
  480. {
  481. stationId
  482. },
  483. this
  484. )
  485. .then(() => {
  486. next(null);
  487. })
  488. .catch(next);
  489. }
  490. );
  491. }
  492. ],
  493. err => {
  494. if (err) reject(err);
  495. else resolve();
  496. }
  497. );
  498. });
  499. }
  500. /**
  501. * Gets next official station song
  502. *
  503. * @param {object} payload - object that contains the payload
  504. * @param {string} payload.stationId - the id of the station
  505. * @returns {Promise} - returns a promise (resolve, reject)
  506. */
  507. GET_NEXT_OFFICIAL_STATION_SONG(payload) {
  508. return new Promise((resolve, reject) => {
  509. const { stationId } = payload;
  510. async.waterfall(
  511. [
  512. next => {
  513. StationsModule.runJob("GET_STATION", { stationId }, this)
  514. .then(station => {
  515. next(null, station);
  516. })
  517. .catch(next);
  518. },
  519. (station, next) => {
  520. if (station.playlist.length === 0) next("No songs available.");
  521. else {
  522. next(null, station.playlist[0]);
  523. }
  524. },
  525. (song, next) => {
  526. console.log(44444, song, song._id);
  527. SongsModule.runJob("GET_SONG", { id: song._id }, this)
  528. .then(response => {
  529. const { song } = response;
  530. if (song) {
  531. const newSong = {
  532. _id: song._id,
  533. songId: song.songId,
  534. title: song.title,
  535. artists: song.artists,
  536. duration: song.duration,
  537. thumbnail: song.thumbnail,
  538. requestedAt: song.requestedAt
  539. };
  540. next(null, newSong);
  541. } else {
  542. next(null, song);
  543. }
  544. })
  545. .catch(next);
  546. }
  547. ],
  548. (err, song) => {
  549. if (err) console.log(33333, err, payload);
  550. if (err) reject(err);
  551. else resolve({ song });
  552. }
  553. );
  554. });
  555. }
  556. /**
  557. * Removes first official playlist queue song
  558. *
  559. * @param {object} payload - object that contains the payload
  560. * @param {string} payload.stationId - the id of the station
  561. * @returns {Promise} - returns a promise (resolve, reject)
  562. */
  563. REMOVE_FIRST_OFFICIAL_PLAYLIST_QUEUE_SONG(payload) {
  564. return new Promise((resolve, reject) => {
  565. const { stationId } = payload;
  566. async.waterfall(
  567. [
  568. next => {
  569. StationsModule.stationModel.updateOne(
  570. { _id: stationId },
  571. { $pop: { playlist: -1 } },
  572. { runValidators: true },
  573. err => {
  574. if (err) next(err);
  575. else
  576. StationsModule.runJob(
  577. "UPDATE_STATION",
  578. {
  579. stationId
  580. },
  581. this
  582. )
  583. .then(() => {
  584. next(null);
  585. })
  586. .catch(next);
  587. }
  588. );
  589. }
  590. ],
  591. err => {
  592. if (err) reject(err);
  593. else resolve();
  594. }
  595. );
  596. });
  597. }
  598. /**
  599. * Skips a station
  600. *
  601. * @param {object} payload - object that contains the payload
  602. * @param {string} payload.stationId - the id of the station to skip
  603. * @returns {Promise} - returns a promise (resolve, reject)
  604. */
  605. SKIP_STATION(payload) {
  606. return new Promise((resolve, reject) => {
  607. StationsModule.log("INFO", `Skipping station ${payload.stationId}.`);
  608. StationsModule.log("STATION_ISSUE", `SKIP_STATION_CB - Station ID: ${payload.stationId}.`);
  609. async.waterfall(
  610. [
  611. next => {
  612. NotificationsModule.runJob("UNSCHEDULE", {
  613. name: `stations.nextSong?id=${payload.stationId}`
  614. })
  615. .then(() => {
  616. next();
  617. })
  618. .catch(next);
  619. },
  620. next => {
  621. StationsModule.runJob(
  622. "GET_STATION",
  623. {
  624. stationId: payload.stationId
  625. },
  626. this
  627. )
  628. .then(station => {
  629. next(null, station);
  630. })
  631. .catch(() => {});
  632. },
  633. // eslint-disable-next-line consistent-return
  634. (station, next) => {
  635. if (!station) return next("Station not found.");
  636. if (station.type === "community" && station.partyMode && station.queue.length === 0)
  637. return next(null, null, -11, station); // Community station with party mode enabled and no songs in the queue
  638. if (station.type === "community" && station.partyMode && station.queue.length > 0) {
  639. // Community station with party mode enabled and songs in the queue
  640. if (station.paused) return next(null, null, -19, station);
  641. return StationsModule.stationModel.updateOne(
  642. { _id: payload.stationId },
  643. {
  644. $pull: {
  645. queue: {
  646. _id: station.queue[0]._id
  647. }
  648. }
  649. },
  650. err => {
  651. if (err) return next(err);
  652. return next(null, station.queue[0], -12, station);
  653. }
  654. );
  655. }
  656. if (station.type === "community" && !station.partyMode) {
  657. return DBModule.runJob("GET_MODEL", { modelName: "playlist" }, this).then(playlistModel =>
  658. playlistModel.findOne({ _id: station.privatePlaylist }, (err, playlist) => {
  659. if (err) return next(err);
  660. if (!playlist) return next(null, null, -13, station);
  661. playlist = playlist.songs;
  662. if (playlist.length > 0) {
  663. let currentSongIndex;
  664. if (station.currentSongIndex < playlist.length - 1)
  665. currentSongIndex = station.currentSongIndex + 1;
  666. else currentSongIndex = 0;
  667. const callback = (err, song) => {
  668. if (err) return next(err);
  669. if (song) return next(null, song, currentSongIndex, station);
  670. const currentSong = {
  671. songId: playlist[currentSongIndex].songId,
  672. title: playlist[currentSongIndex].title,
  673. duration: playlist[currentSongIndex].duration,
  674. likes: -1,
  675. dislikes: -1,
  676. requestedAt: playlist[currentSongIndex].requestedAt
  677. };
  678. return next(null, currentSong, currentSongIndex, station);
  679. };
  680. if (mongoose.Types.ObjectId.isValid(playlist[currentSongIndex]._id))
  681. return SongsModule.runJob(
  682. "GET_SONG",
  683. {
  684. id: playlist[currentSongIndex]._id
  685. },
  686. this
  687. )
  688. .then(response => callback(null, response.song))
  689. .catch(callback);
  690. return SongsModule.runJob(
  691. "GET_SONG_FROM_ID",
  692. {
  693. songId: playlist[currentSongIndex].songId
  694. },
  695. this
  696. )
  697. .then(response => callback(null, response.song))
  698. .catch(callback);
  699. }
  700. return next(null, null, -14, station);
  701. })
  702. );
  703. }
  704. if (station.type === "official") {
  705. StationsModule.runJob(
  706. "REMOVE_FIRST_OFFICIAL_PLAYLIST_QUEUE_SONG",
  707. { stationId: station._id },
  708. this
  709. )
  710. .then(() => {
  711. StationsModule.runJob(
  712. "FILL_UP_OFFICIAL_STATION_PLAYLIST_QUEUE",
  713. { stationId: station._id },
  714. this
  715. )
  716. .then(() => {
  717. StationsModule.runJob(
  718. "GET_NEXT_OFFICIAL_STATION_SONG",
  719. { stationId: station._id },
  720. this
  721. )
  722. .then(response => {
  723. next(null, response.song, 0, station);
  724. })
  725. .catch(err => {
  726. if (err === "No songs available.") next(null, null, 0, station);
  727. else next(err);
  728. });
  729. })
  730. .catch(next);
  731. })
  732. .catch(next);
  733. }
  734. },
  735. (song, currentSongIndex, station, next) => {
  736. const $set = {};
  737. if (song === null) $set.currentSong = null;
  738. else if (song.likes === -1 && song.dislikes === -1) {
  739. $set.currentSong = {
  740. songId: song.songId,
  741. title: song.title,
  742. duration: song.duration,
  743. skipDuration: 0,
  744. likes: -1,
  745. dislikes: -1,
  746. requestedAt: song.requestedAt
  747. };
  748. } else {
  749. $set.currentSong = {
  750. _id: song._id,
  751. songId: song.songId,
  752. title: song.title,
  753. artists: song.artists,
  754. duration: song.duration,
  755. likes: song.likes,
  756. dislikes: song.dislikes,
  757. skipDuration: song.skipDuration,
  758. thumbnail: song.thumbnail,
  759. requestedAt: song.requestedAt
  760. };
  761. }
  762. if (currentSongIndex >= 0) $set.currentSongIndex = currentSongIndex;
  763. $set.startedAt = Date.now();
  764. $set.timePaused = 0;
  765. if (station.paused) $set.pausedAt = Date.now();
  766. next(null, $set, station);
  767. },
  768. ($set, station, next) => {
  769. StationsModule.stationModel.updateOne({ _id: station._id }, { $set }, err => {
  770. if (err) return next(err);
  771. return StationsModule.runJob(
  772. "UPDATE_STATION",
  773. {
  774. stationId: station._id
  775. },
  776. this
  777. )
  778. .then(station => {
  779. if (station.type === "community" && station.partyMode === true)
  780. CacheModule.runJob("PUB", {
  781. channel: "station.queueUpdate",
  782. value: payload.stationId
  783. })
  784. .then()
  785. .catch();
  786. next(null, station);
  787. })
  788. .catch(next);
  789. });
  790. }
  791. ],
  792. async (err, station) => {
  793. if (err) {
  794. console.log(123, err);
  795. err = await UtilsModule.runJob(
  796. "GET_ERROR",
  797. {
  798. error: err
  799. },
  800. this
  801. );
  802. StationsModule.log("ERROR", `Skipping station "${payload.stationId}" failed. "${err}"`);
  803. reject(new Error(err));
  804. } else {
  805. if (station.currentSong !== null && station.currentSong.songId !== undefined) {
  806. station.currentSong.skipVotes = 0;
  807. }
  808. // TODO Pub/Sub this
  809. WSModule.runJob("EMIT_TO_ROOM", {
  810. room: `station.${station._id}`,
  811. args: [
  812. "event:songs.next",
  813. {
  814. currentSong: station.currentSong,
  815. startedAt: station.startedAt,
  816. paused: station.paused,
  817. timePaused: 0
  818. }
  819. ]
  820. })
  821. .then()
  822. .catch();
  823. if (station.privacy === "public") {
  824. WSModule.runJob("EMIT_TO_ROOM", {
  825. room: "home",
  826. args: ["event:station.nextSong", station._id, station.currentSong]
  827. })
  828. .then()
  829. .catch();
  830. } else {
  831. const sockets = await WSModule.runJob("GET_SOCKETS_FOR_ROOM", { room: "home" }, this);
  832. sockets.forEach(async socketId => {
  833. const socket = await WSModule.runJob("SOCKET_FROM_SOCKET_ID", { socketId }, this);
  834. const { session } = socket;
  835. if (session.sessionId) {
  836. CacheModule.runJob(
  837. "HGET",
  838. { table: "sessions", key: session.sessionId },
  839. this
  840. // eslint-disable-next-line no-loop-func
  841. ).then(session => {
  842. if (session) {
  843. DBModule.runJob("GET_MODEL", { modelName: "user" }, this).then(
  844. userModel => {
  845. userModel.findOne(
  846. {
  847. _id: session.userId
  848. },
  849. (err, user) => {
  850. if (!err && user) {
  851. if (user.role === "admin")
  852. socket.dispatch(
  853. "event:station.nextSong",
  854. station._id,
  855. station.currentSong
  856. );
  857. else if (
  858. station.type === "community" &&
  859. station.owner === session.userId
  860. )
  861. socket.dispatch(
  862. "event:station.nextSong",
  863. station._id,
  864. station.currentSong
  865. );
  866. }
  867. }
  868. );
  869. }
  870. );
  871. }
  872. });
  873. }
  874. });
  875. }
  876. WSModule.runJob("GET_SOCKETS_FOR_ROOM", { room: `station.${station._id}` }).then(sockets => {
  877. if (station.currentSong !== null && station.currentSong.songId !== undefined) {
  878. WSModule.runJob("SOCKETS_JOIN_SONG_ROOM", {
  879. sockets,
  880. room: `song.${station.currentSong.songId}`
  881. });
  882. if (!station.paused) {
  883. NotificationsModule.runJob("SCHEDULE", {
  884. name: `stations.nextSong?id=${station._id}`,
  885. time: station.currentSong.duration * 1000,
  886. station
  887. });
  888. }
  889. } else {
  890. WSModule.runJob("SOCKETS_LEAVE_SONG_ROOMS", {
  891. sockets
  892. });
  893. }
  894. });
  895. resolve({ station });
  896. }
  897. }
  898. );
  899. });
  900. }
  901. /**
  902. * Checks if a user can view/access a station
  903. *
  904. * @param {object} payload - object that contains the payload
  905. * @param {object} payload.station - the station object of the station in question
  906. * @param {string} payload.userId - the id of the user in question
  907. * @param {boolean} payload.hideUnlisted - whether the user is allowed to see unlisted stations or not
  908. * @returns {Promise} - returns a promise (resolve, reject)
  909. */
  910. CAN_USER_VIEW_STATION(payload) {
  911. return new Promise((resolve, reject) => {
  912. async.waterfall(
  913. [
  914. next => {
  915. if (payload.station.privacy === "public") return next(true);
  916. if (payload.station.privacy === "unlisted")
  917. if (payload.hideUnlisted === true) return next();
  918. else return next(true);
  919. if (!payload.userId) return next("Not allowed");
  920. return next();
  921. },
  922. next => {
  923. DBModule.runJob("GET_MODEL", { modelName: "user" }, this).then(userModel => {
  924. userModel.findOne({ _id: payload.userId }, next);
  925. });
  926. },
  927. (user, next) => {
  928. if (!user) return next("Not allowed");
  929. if (user.role === "admin") return next(true);
  930. if (payload.station.type === "official") return next("Not allowed");
  931. if (payload.station.owner === payload.userId) return next(true);
  932. return next("Not allowed");
  933. }
  934. ],
  935. async errOrResult => {
  936. if (errOrResult !== true && errOrResult !== "Not allowed") {
  937. errOrResult = await UtilsModule.runJob(
  938. "GET_ERROR",
  939. {
  940. error: errOrResult
  941. },
  942. this
  943. );
  944. reject(new Error(errOrResult));
  945. } else {
  946. resolve(errOrResult === true);
  947. }
  948. }
  949. );
  950. });
  951. }
  952. /**
  953. * Checks if a user has favorited a station or not
  954. *
  955. * @param {object} payload - object that contains the payload
  956. * @param {object} payload.stationId - the id of the station in question
  957. * @param {string} payload.userId - the id of the user in question
  958. * @returns {Promise} - returns a promise (resolve, reject)
  959. */
  960. HAS_USER_FAVORITED_STATION(payload) {
  961. return new Promise((resolve, reject) => {
  962. async.waterfall(
  963. [
  964. next => {
  965. DBModule.runJob("GET_MODEL", { modelName: "user" }, this).then(userModel => {
  966. userModel.findOne({ _id: payload.userId }, next);
  967. });
  968. },
  969. (user, next) => {
  970. if (!user) return next("User not found.");
  971. if (user.favoriteStations.indexOf(payload.stationId) !== -1) return next(null, true);
  972. return next(null, false);
  973. }
  974. ],
  975. async (err, isStationFavorited) => {
  976. if (err && err !== true) {
  977. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  978. return reject(new Error(err));
  979. }
  980. return resolve(isStationFavorited);
  981. }
  982. );
  983. });
  984. }
  985. /**
  986. * Returns a list of sockets in a room that can and can't know about a station
  987. *
  988. * @param {object} payload - the payload object
  989. * @param {object} payload.station - the station object
  990. * @param {string} payload.room - the websockets room to get the sockets from
  991. * @returns {Promise} - returns a promise (resolve, reject)
  992. */
  993. GET_SOCKETS_THAT_CAN_KNOW_ABOUT_STATION(payload) {
  994. return new Promise((resolve, reject) => {
  995. WSModule.runJob("GET_SOCKETS_FOR_ROOM", { room: payload.room }, this)
  996. .then(socketsObject => {
  997. const sockets = Object.keys(socketsObject).map(socketKey => socketsObject[socketKey]);
  998. let socketsThatCan = [];
  999. const socketsThatCannot = [];
  1000. if (payload.station.privacy === "public") {
  1001. socketsThatCan = sockets;
  1002. resolve({ socketsThatCan, socketsThatCannot });
  1003. } else {
  1004. async.eachLimit(
  1005. sockets,
  1006. 1,
  1007. (socket, next) => {
  1008. const { session } = socket;
  1009. async.waterfall(
  1010. [
  1011. next => {
  1012. if (!session.sessionId) next("No session id");
  1013. else next();
  1014. },
  1015. next => {
  1016. CacheModule.runJob(
  1017. "HGET",
  1018. {
  1019. table: "sessions",
  1020. key: session.sessionId
  1021. },
  1022. this
  1023. )
  1024. .then(response => {
  1025. next(null, response);
  1026. })
  1027. .catch(next);
  1028. },
  1029. (session, next) => {
  1030. if (!session) next("No session");
  1031. else {
  1032. DBModule.runJob("GET_MODEL", { modelName: "user" }, this)
  1033. .then(userModel => {
  1034. next(null, userModel);
  1035. })
  1036. .catch(next);
  1037. }
  1038. },
  1039. (userModel, next) => {
  1040. if (!userModel) next("No user model");
  1041. else
  1042. userModel.findOne(
  1043. {
  1044. _id: session.userId
  1045. },
  1046. next
  1047. );
  1048. },
  1049. (user, next) => {
  1050. if (!user) next("No user found");
  1051. else if (user.role === "admin") {
  1052. socketsThatCan.push(socket);
  1053. next();
  1054. } else if (
  1055. payload.station.type === "community" &&
  1056. payload.station.owner === session.userId
  1057. ) {
  1058. socketsThatCan.push(socket);
  1059. next();
  1060. }
  1061. }
  1062. ],
  1063. err => {
  1064. if (err) socketsThatCannot.push(socket);
  1065. next();
  1066. }
  1067. );
  1068. },
  1069. err => {
  1070. if (err) reject(err);
  1071. else resolve({ socketsThatCan, socketsThatCannot });
  1072. }
  1073. );
  1074. }
  1075. })
  1076. .catch(reject);
  1077. });
  1078. }
  1079. /**
  1080. * Adds a playlist to be included in a station
  1081. *
  1082. * @param {object} payload - object that contains the payload
  1083. * @param {object} payload.stationId - the id of the station to include the playlist in
  1084. * @param {object} payload.playlistId - the id of the playlist to be included
  1085. * @returns {Promise} - returns a promise (resolve, reject)
  1086. */
  1087. INCLUDE_PLAYLIST(payload) {
  1088. return new Promise((resolve, reject) => {
  1089. async.waterfall(
  1090. [
  1091. next => {
  1092. if (!payload.stationId) next("Please specify a station id");
  1093. else if (!payload.playlistId) next("Please specify a playlist id");
  1094. else next();
  1095. },
  1096. next => {
  1097. StationsModule.runJob("GET_STATION", { stationId: payload.stationId }, this)
  1098. .then(station => {
  1099. next(null, station);
  1100. })
  1101. .catch(next);
  1102. },
  1103. (station, next) => {
  1104. if (station.playlist2 === payload.playlistId) next("You cannot include the station playlist");
  1105. else if (station.includedPlaylists.indexOf(payload.playlistId) !== -1)
  1106. next("This playlist is already included");
  1107. else if (station.excludedPlaylists.indexOf(payload.playlistId) !== -1)
  1108. next(
  1109. "This playlist is currently excluded, please remove it from there before including it"
  1110. );
  1111. else
  1112. PlaylistsModule.runJob("GET_PLAYLIST", { playlistId: payload.playlistId }, this)
  1113. .then(() => {
  1114. next(null);
  1115. })
  1116. .catch(next);
  1117. },
  1118. next => {
  1119. DBModule.runJob(
  1120. "GET_MODEL",
  1121. {
  1122. modelName: "station"
  1123. },
  1124. this
  1125. ).then(stationModel => {
  1126. stationModel.updateOne(
  1127. { _id: payload.stationId },
  1128. { $push: { includedPlaylists: payload.playlistId } },
  1129. next
  1130. );
  1131. });
  1132. },
  1133. (res, next) => {
  1134. StationsModule.runJob(
  1135. "UPDATE_STATION",
  1136. {
  1137. stationId: payload.stationId
  1138. },
  1139. this
  1140. )
  1141. .then(() => {
  1142. next();
  1143. })
  1144. .catch(next);
  1145. }
  1146. ],
  1147. async err => {
  1148. if (err && err !== true) {
  1149. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1150. return reject(new Error(err));
  1151. }
  1152. return resolve();
  1153. }
  1154. );
  1155. });
  1156. }
  1157. /**
  1158. * Removes a playlist that is included in a station
  1159. *
  1160. * @param {object} payload - object that contains the payload
  1161. * @param {object} payload.stationId - the id of the station
  1162. * @param {object} payload.playlistId - the id of the playlist
  1163. * @returns {Promise} - returns a promise (resolve, reject)
  1164. */
  1165. REMOVE_INCLUDED_PLAYLIST(payload) {
  1166. return new Promise((resolve, reject) => {
  1167. async.waterfall(
  1168. [
  1169. next => {
  1170. if (!payload.stationId) next("Please specify a station id");
  1171. else if (!payload.playlistId) next("Please specify a playlist id");
  1172. else next();
  1173. },
  1174. next => {
  1175. StationsModule.runJob("GET_STATION", { stationId: payload.stationId }, this)
  1176. .then(station => {
  1177. next(null, station);
  1178. })
  1179. .catch(next);
  1180. },
  1181. (station, next) => {
  1182. if (station.includedPlaylists.indexOf(payload.playlistId) === -1)
  1183. next("This playlist isn't included");
  1184. else next();
  1185. },
  1186. next => {
  1187. DBModule.runJob(
  1188. "GET_MODEL",
  1189. {
  1190. modelName: "station"
  1191. },
  1192. this
  1193. ).then(stationModel => {
  1194. stationModel.updateOne(
  1195. { _id: payload.stationId },
  1196. { $pull: { includedPlaylists: payload.playlistId } },
  1197. next
  1198. );
  1199. });
  1200. },
  1201. (res, next) => {
  1202. StationsModule.runJob(
  1203. "UPDATE_STATION",
  1204. {
  1205. stationId: payload.stationId
  1206. },
  1207. this
  1208. )
  1209. .then(() => {
  1210. next();
  1211. })
  1212. .catch(next);
  1213. }
  1214. ],
  1215. async err => {
  1216. if (err && err !== true) {
  1217. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1218. return reject(new Error(err));
  1219. }
  1220. return resolve();
  1221. }
  1222. );
  1223. });
  1224. }
  1225. /**
  1226. * Adds a playlist to be excluded in a station
  1227. *
  1228. * @param {object} payload - object that contains the payload
  1229. * @param {object} payload.stationId - the id of the station
  1230. * @param {object} payload.playlistId - the id of the playlist
  1231. * @returns {Promise} - returns a promise (resolve, reject)
  1232. */
  1233. EXCLUDE_PLAYLIST(payload) {
  1234. return new Promise((resolve, reject) => {
  1235. async.waterfall(
  1236. [
  1237. next => {
  1238. if (!payload.stationId) next("Please specify a station id");
  1239. else if (!payload.playlistId) next("Please specify a playlist id");
  1240. else next();
  1241. },
  1242. next => {
  1243. StationsModule.runJob("GET_STATION", { stationId: payload.stationId }, this)
  1244. .then(station => {
  1245. next(null, station);
  1246. })
  1247. .catch(next);
  1248. },
  1249. (station, next) => {
  1250. if (station.playlist2 === payload.playlistId) next("You cannot exclude the station playlist");
  1251. else if (station.excludedPlaylists.indexOf(payload.playlistId) !== -1)
  1252. next("This playlist is already excluded");
  1253. else if (station.includedPlaylists.indexOf(payload.playlistId) !== -1)
  1254. next(
  1255. "This playlist is currently included, please remove it from there before excluding it"
  1256. );
  1257. else
  1258. PlaylistsModule.runJob("GET_PLAYLIST", { playlistId: payload.playlistId }, this)
  1259. .then(() => {
  1260. next(null);
  1261. })
  1262. .catch(next);
  1263. },
  1264. next => {
  1265. DBModule.runJob(
  1266. "GET_MODEL",
  1267. {
  1268. modelName: "station"
  1269. },
  1270. this
  1271. ).then(stationModel => {
  1272. stationModel.updateOne(
  1273. { _id: payload.stationId },
  1274. { $push: { excludedPlaylists: payload.playlistId } },
  1275. next
  1276. );
  1277. });
  1278. },
  1279. (res, next) => {
  1280. StationsModule.runJob(
  1281. "UPDATE_STATION",
  1282. {
  1283. stationId: payload.stationId
  1284. },
  1285. this
  1286. )
  1287. .then(() => {
  1288. next();
  1289. })
  1290. .catch(next);
  1291. }
  1292. ],
  1293. async err => {
  1294. if (err && err !== true) {
  1295. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1296. return reject(new Error(err));
  1297. }
  1298. return resolve();
  1299. }
  1300. );
  1301. });
  1302. }
  1303. /**
  1304. * Removes a playlist that is excluded in a station
  1305. *
  1306. * @param {object} payload - object that contains the payload
  1307. * @param {object} payload.stationId - the id of the station
  1308. * @param {object} payload.playlistId - the id of the playlist
  1309. * @returns {Promise} - returns a promise (resolve, reject)
  1310. */
  1311. REMOVE_EXCLUDED_PLAYLIST(payload) {
  1312. return new Promise((resolve, reject) => {
  1313. console.log(112, payload);
  1314. async.waterfall(
  1315. [
  1316. next => {
  1317. if (!payload.stationId) next("Please specify a station id");
  1318. else if (!payload.playlistId) next("Please specify a playlist id");
  1319. else next();
  1320. },
  1321. next => {
  1322. StationsModule.runJob("GET_STATION", { stationId: payload.stationId }, this)
  1323. .then(station => {
  1324. next(null, station);
  1325. })
  1326. .catch(next);
  1327. },
  1328. (station, next) => {
  1329. if (station.excludedPlaylists.indexOf(payload.playlistId) === -1)
  1330. next("This playlist isn't excluded");
  1331. else next();
  1332. },
  1333. next => {
  1334. DBModule.runJob(
  1335. "GET_MODEL",
  1336. {
  1337. modelName: "station"
  1338. },
  1339. this
  1340. ).then(stationModel => {
  1341. stationModel.updateOne(
  1342. { _id: payload.stationId },
  1343. { $pull: { excludedPlaylists: payload.playlistId } },
  1344. next
  1345. );
  1346. });
  1347. },
  1348. (res, next) => {
  1349. StationsModule.runJob(
  1350. "UPDATE_STATION",
  1351. {
  1352. stationId: payload.stationId
  1353. },
  1354. this
  1355. )
  1356. .then(() => {
  1357. next();
  1358. })
  1359. .catch(next);
  1360. }
  1361. ],
  1362. async err => {
  1363. if (err && err !== true) {
  1364. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1365. return reject(new Error(err));
  1366. }
  1367. return resolve();
  1368. }
  1369. );
  1370. });
  1371. }
  1372. /**
  1373. * Gets stations that include or exclude a specific playlist
  1374. *
  1375. * @param {object} payload - object that contains the payload
  1376. * @param {string} payload.playlistId - the playlist id
  1377. * @returns {Promise} - returns promise (reject, resolve)
  1378. */
  1379. GET_STATIONS_THAT_INCLUDE_OR_EXCLUDE_PLAYLIST(payload) {
  1380. return new Promise((resolve, reject) => {
  1381. DBModule.runJob(
  1382. "GET_MODEL",
  1383. {
  1384. modelName: "station"
  1385. },
  1386. this
  1387. ).then(stationModel => {
  1388. stationModel.find(
  1389. { $or: [{ includedPlaylists: payload.playlistId }, { excludedPlaylists: payload.playlistId }] },
  1390. (err, stations) => {
  1391. if (err) reject(err);
  1392. else resolve({ stationIds: stations.map(station => station._id) });
  1393. }
  1394. );
  1395. });
  1396. });
  1397. }
  1398. }
  1399. export default new _StationsModule();