stations.js 55 KB

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