stations.js 54 KB

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