stations.js 49 KB

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