stations.js 49 KB

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