stations.js 69 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709
  1. import async from "async";
  2. import mongoose from "mongoose";
  3. import config from "config";
  4. import { hasPermission, useHasPermission } from "../hooks/hasPermission";
  5. import isLoginRequired from "../hooks/loginRequired";
  6. // eslint-disable-next-line
  7. import moduleManager from "../../index";
  8. const DBModule = moduleManager.modules.db;
  9. const UtilsModule = moduleManager.modules.utils;
  10. const WSModule = moduleManager.modules.ws;
  11. const PlaylistsModule = moduleManager.modules.playlists;
  12. const CacheModule = moduleManager.modules.cache;
  13. const NotificationsModule = moduleManager.modules.notifications;
  14. const StationsModule = moduleManager.modules.stations;
  15. const ActivitiesModule = moduleManager.modules.activities;
  16. CacheModule.runJob("SUB", {
  17. channel: "station.updateUsers",
  18. cb: ({ stationId, usersPerStation }) => {
  19. WSModule.runJob("EMIT_TO_ROOM", {
  20. room: `station.${stationId}`,
  21. args: ["event:station.users.updated", { data: { users: usersPerStation } }]
  22. });
  23. }
  24. });
  25. CacheModule.runJob("SUB", {
  26. channel: "station.updateUserCount",
  27. cb: ({ stationId, usersPerStationCount }) => {
  28. const count = usersPerStationCount || 0;
  29. WSModule.runJob("EMIT_TO_ROOM", {
  30. room: `station.${stationId}`,
  31. args: ["event:station.userCount.updated", { data: { userCount: count } }]
  32. });
  33. StationsModule.runJob("GET_STATION", { stationId }).then(async station => {
  34. if (station.privacy === "public")
  35. WSModule.runJob("EMIT_TO_ROOM", {
  36. room: "home",
  37. args: ["event:station.userCount.updated", { data: { stationId, userCount: count } }]
  38. });
  39. else {
  40. const sockets = await WSModule.runJob("GET_SOCKETS_FOR_ROOM", {
  41. room: "home"
  42. });
  43. sockets.forEach(async socketId => {
  44. const socket = await WSModule.runJob("SOCKET_FROM_SOCKET_ID", { socketId }, this);
  45. if (!socket) return;
  46. const { session } = socket;
  47. hasPermission("stations.view", session, stationId)
  48. .then(() => {
  49. socket.dispatch("event:station.userCount.updated", {
  50. data: { stationId, count }
  51. });
  52. })
  53. .catch(() => {});
  54. });
  55. }
  56. });
  57. }
  58. });
  59. CacheModule.runJob("SUB", {
  60. channel: "station.autofillPlaylist",
  61. cb: data => {
  62. const { stationId, playlistId } = data;
  63. PlaylistsModule.runJob("GET_PLAYLIST", { playlistId }).then(playlist =>
  64. WSModule.runJob("EMIT_TO_ROOMS", {
  65. rooms: [`station.${stationId}`, `manage-station.${stationId}`],
  66. args: ["event:station.autofillPlaylist", { data: { stationId, playlist } }]
  67. })
  68. );
  69. }
  70. });
  71. CacheModule.runJob("SUB", {
  72. channel: "station.blacklistedPlaylist",
  73. cb: data => {
  74. const { stationId, playlistId } = data;
  75. PlaylistsModule.runJob("GET_PLAYLIST", { playlistId }).then(playlist =>
  76. WSModule.runJob("EMIT_TO_ROOMS", {
  77. rooms: [`station.${stationId}`, `manage-station.${stationId}`],
  78. args: ["event:station.blacklistedPlaylist", { data: { stationId, playlist } }]
  79. })
  80. );
  81. }
  82. });
  83. CacheModule.runJob("SUB", {
  84. channel: "station.removedAutofillPlaylist",
  85. cb: data => {
  86. const { stationId, playlistId } = data;
  87. WSModule.runJob("EMIT_TO_ROOMS", {
  88. rooms: [`station.${stationId}`, `manage-station.${stationId}`],
  89. args: ["event:station.removedAutofillPlaylist", { data: { stationId, playlistId } }]
  90. });
  91. }
  92. });
  93. CacheModule.runJob("SUB", {
  94. channel: "station.removedBlacklistedPlaylist",
  95. cb: data => {
  96. const { stationId, playlistId } = data;
  97. WSModule.runJob("EMIT_TO_ROOMS", {
  98. rooms: [`station.${stationId}`, `manage-station.${stationId}`],
  99. args: ["event:station.removedBlacklistedPlaylist", { data: { stationId, playlistId } }]
  100. });
  101. }
  102. });
  103. CacheModule.runJob("SUB", {
  104. channel: "station.pause",
  105. cb: stationId => {
  106. StationsModule.runJob("GET_STATION", { stationId }).then(station => {
  107. WSModule.runJob("EMIT_TO_ROOM", {
  108. room: `station.${stationId}`,
  109. args: ["event:station.pause", { data: { pausedAt: station.pausedAt } }]
  110. });
  111. WSModule.runJob("EMIT_TO_ROOM", {
  112. room: `manage-station.${stationId}`,
  113. args: ["event:station.pause", { data: { stationId, pausedAt: station.pausedAt } }]
  114. });
  115. StationsModule.runJob("GET_SOCKETS_THAT_CAN_KNOW_ABOUT_STATION", {
  116. room: `home`,
  117. station
  118. }).then(response => {
  119. const { socketsThatCan } = response;
  120. socketsThatCan.forEach(socket => {
  121. socket.dispatch("event:station.pause", { data: { stationId } });
  122. });
  123. });
  124. });
  125. }
  126. });
  127. CacheModule.runJob("SUB", {
  128. channel: "station.resume",
  129. cb: stationId => {
  130. StationsModule.runJob("GET_STATION", { stationId }).then(station => {
  131. WSModule.runJob("EMIT_TO_ROOM", {
  132. room: `station.${stationId}`,
  133. args: ["event:station.resume", { data: { timePaused: station.timePaused } }]
  134. });
  135. WSModule.runJob("EMIT_TO_ROOM", {
  136. room: `manage-station.${stationId}`,
  137. args: ["event:station.resume", { data: { stationId, timePaused: station.timePaused } }]
  138. });
  139. StationsModule.runJob("GET_SOCKETS_THAT_CAN_KNOW_ABOUT_STATION", {
  140. room: `home`,
  141. station
  142. })
  143. .then(response => {
  144. const { socketsThatCan } = response;
  145. socketsThatCan.forEach(socket => {
  146. socket.dispatch("event:station.resume", { data: { stationId } });
  147. });
  148. })
  149. .catch(console.log);
  150. });
  151. }
  152. });
  153. CacheModule.runJob("SUB", {
  154. channel: "station.queueUpdate",
  155. cb: stationId => {
  156. StationsModule.runJob("GET_STATION", { stationId }).then(station => {
  157. if (!station.currentSong && station.queue.length > 0) {
  158. StationsModule.runJob("INITIALIZE_STATION", {
  159. stationId
  160. }).then();
  161. }
  162. WSModule.runJob("EMIT_TO_ROOM", {
  163. room: `station.${stationId}`,
  164. args: ["event:station.queue.updated", { data: { queue: station.queue } }]
  165. });
  166. WSModule.runJob("EMIT_TO_ROOM", {
  167. room: `manage-station.${stationId}`,
  168. args: ["event:manageStation.queue.updated", { data: { stationId, queue: station.queue } }]
  169. });
  170. });
  171. }
  172. });
  173. CacheModule.runJob("SUB", {
  174. channel: "station.repositionSongInQueue",
  175. cb: res => {
  176. WSModule.runJob("EMIT_TO_ROOM", {
  177. room: `station.${res.stationId}`,
  178. args: ["event:station.queue.song.repositioned", { data: { song: res.song } }]
  179. });
  180. WSModule.runJob("EMIT_TO_ROOM", {
  181. room: `manage-station.${res.stationId}`,
  182. args: [
  183. "event:manageStation.queue.song.repositioned",
  184. { data: { stationId: res.stationId, song: res.song } }
  185. ]
  186. });
  187. }
  188. });
  189. CacheModule.runJob("SUB", {
  190. channel: "station.voteSkipSong",
  191. cb: stationId => {
  192. WSModule.runJob("EMIT_TO_ROOM", {
  193. room: `station.${stationId}`,
  194. args: ["event:station.voteSkipSong"]
  195. });
  196. }
  197. });
  198. CacheModule.runJob("SUB", {
  199. channel: "station.remove",
  200. cb: stationId => {
  201. WSModule.runJob("EMIT_TO_ROOM", {
  202. room: `station.${stationId}`,
  203. args: ["event:station.deleted"]
  204. });
  205. WSModule.runJob("EMIT_TO_ROOM", {
  206. room: `manage-station.${stationId}`,
  207. args: ["event:station.deleted"]
  208. });
  209. WSModule.runJob("EMIT_TO_ROOM", {
  210. room: `home`,
  211. args: ["event:station.deleted", { data: { stationId } }]
  212. });
  213. WSModule.runJob("EMIT_TO_ROOM", {
  214. room: "admin.stations",
  215. args: ["event:admin.station.deleted", { data: { stationId } }]
  216. });
  217. }
  218. });
  219. CacheModule.runJob("SUB", {
  220. channel: "station.create",
  221. cb: async stationId => {
  222. StationsModule.runJob("INITIALIZE_STATION", { stationId }).then(async res => {
  223. const { station } = res;
  224. station.userCount = StationsModule.usersPerStationCount[stationId] || 0;
  225. WSModule.runJob("EMIT_TO_ROOM", {
  226. room: "admin.stations",
  227. args: ["event:admin.station.created", { data: { station } }]
  228. });
  229. if (station.privacy === "public")
  230. WSModule.runJob("EMIT_TO_ROOM", {
  231. room: "home",
  232. args: ["event:station.created", { data: { station } }]
  233. });
  234. else {
  235. const sockets = await WSModule.runJob("GET_SOCKETS_FOR_ROOM", {
  236. room: "home"
  237. });
  238. sockets.forEach(async socketId => {
  239. const socket = await WSModule.runJob("SOCKET_FROM_SOCKET_ID", { socketId }, this);
  240. if (!socket) return;
  241. const { session } = socket;
  242. hasPermission("stations.view", session, stationId)
  243. .then(() => {
  244. socket.dispatch("event:station.created", { data: { station } });
  245. })
  246. .catch(() => {});
  247. });
  248. }
  249. });
  250. }
  251. });
  252. CacheModule.runJob("SUB", {
  253. channel: "station.updated",
  254. cb: async data => {
  255. const stationModel = await DBModule.runJob("GET_MODEL", {
  256. modelName: "station"
  257. });
  258. const { stationId } = data;
  259. stationModel.findOne(
  260. { _id: stationId },
  261. ["_id", "name", "displayName", "description", "type", "privacy", "owner", "requests", "autofill", "theme"],
  262. (err, station) => {
  263. WSModule.runJob("EMIT_TO_ROOMS", {
  264. rooms: [`station.${stationId}`, `manage-station.${stationId}`, "admin.stations"],
  265. args: ["event:station.updated", { data: { station } }]
  266. });
  267. StationsModule.runJob("GET_SOCKETS_THAT_CAN_KNOW_ABOUT_STATION", {
  268. room: `home`,
  269. station
  270. }).then(response => {
  271. const { socketsThatCan } = response;
  272. socketsThatCan.forEach(socket => {
  273. socket.dispatch("event:station.updated", { data: { station } });
  274. });
  275. });
  276. if (data.previousStation && data.previousStation.privacy !== station.privacy) {
  277. if (station.privacy === "public") {
  278. // Station became public
  279. WSModule.runJob("EMIT_TO_ROOM", {
  280. room: "home",
  281. args: ["event:station.created", { data: { station } }]
  282. });
  283. } else if (data.previousStation.privacy === "public") {
  284. // Station became hidden
  285. StationsModule.runJob("GET_SOCKETS_THAT_CAN_KNOW_ABOUT_STATION", {
  286. room: `home`,
  287. station
  288. }).then(response => {
  289. const { socketsThatCannot } = response;
  290. socketsThatCannot.forEach(socket => {
  291. socket.dispatch("event:station.deleted", { data: { stationId } });
  292. });
  293. });
  294. }
  295. }
  296. }
  297. );
  298. }
  299. });
  300. export default {
  301. /**
  302. * Get a list of all the stations
  303. *
  304. * @param {object} session - user session
  305. * @param {boolean} adminFilter - whether to filter out stations admins do not own
  306. * @param {Function} cb - callback
  307. */
  308. async index(session, adminFilter, cb) {
  309. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" });
  310. async.waterfall(
  311. [
  312. // get array of the ids of the user's favorite stations
  313. next => {
  314. if (session.userId)
  315. return userModel.findById(session.userId).select({ favoriteStations: -1 }).exec(next);
  316. return next(null, { favoriteStations: [] });
  317. },
  318. (user, next) => {
  319. const favoriteStations = user ? user.favoriteStations : [];
  320. CacheModule.runJob("HGETALL", { table: "stations" }, this).then(stations =>
  321. next(null, stations, favoriteStations)
  322. );
  323. },
  324. (stations, favorited, next) => {
  325. const filteredStations = [];
  326. async.eachLimit(
  327. stations,
  328. 1,
  329. (station, nextStation) => {
  330. async.waterfall(
  331. [
  332. callback => {
  333. // only relevant if user logged in
  334. if (session.userId) {
  335. if (favorited.indexOf(station._id) !== -1) station.isFavorited = true;
  336. return callback();
  337. }
  338. return callback();
  339. },
  340. callback => {
  341. StationsModule.runJob(
  342. "CAN_USER_VIEW_STATION",
  343. {
  344. station,
  345. userId: session.userId
  346. },
  347. this
  348. )
  349. .then(exists => callback(null, exists))
  350. .catch(callback);
  351. },
  352. (exists, callback) => {
  353. if (!exists) callback(null, false, false);
  354. else if (station.privacy === "public") callback(null, true, true);
  355. else
  356. hasPermission("stations.index", session.userId, station._id)
  357. .then(() => callback(null, true, true))
  358. .catch(() => callback(null, true, false));
  359. },
  360. (exists, canIndex, callback) => {
  361. if (!exists) callback(null, false);
  362. else if (!canIndex && !adminFilter)
  363. hasPermission("stations.index.other", session.userId)
  364. .then(() => callback(null, true))
  365. .catch(() => callback(null, false));
  366. else callback(null, canIndex);
  367. }
  368. ],
  369. (err, exists) => {
  370. if (err) return this.log("ERROR", "STATIONS_INDEX", err);
  371. station.userCount = StationsModule.usersPerStationCount[station._id] || 0;
  372. if (exists) filteredStations.push(station);
  373. return nextStation();
  374. }
  375. );
  376. },
  377. () => next(null, filteredStations, favorited)
  378. );
  379. }
  380. ],
  381. async (err, stations, favorited) => {
  382. if (err) {
  383. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  384. this.log("ERROR", "STATIONS_INDEX", `Indexing stations failed. "${err}"`);
  385. return cb({ status: "error", message: err });
  386. }
  387. this.log("SUCCESS", "STATIONS_INDEX", `Indexing stations successful.`, false);
  388. return cb({ status: "success", data: { stations, favorited } });
  389. }
  390. );
  391. },
  392. /**
  393. * Gets stations, used in the admin stations page by the AdvancedTable component
  394. *
  395. * @param {object} session - the session object automatically added by the websocket
  396. * @param page - the page
  397. * @param pageSize - the size per page
  398. * @param properties - the properties to return for each station
  399. * @param sort - the sort object
  400. * @param queries - the queries array
  401. * @param operator - the operator for queries
  402. * @param cb
  403. */
  404. getData: useHasPermission(
  405. "admin.view.stations",
  406. async function getSet(session, page, pageSize, properties, sort, queries, operator, cb) {
  407. async.waterfall(
  408. [
  409. next => {
  410. DBModule.runJob(
  411. "GET_DATA",
  412. {
  413. page,
  414. pageSize,
  415. properties,
  416. sort,
  417. queries,
  418. operator,
  419. modelName: "station",
  420. blacklistedProperties: [],
  421. specialProperties: {
  422. owner: [
  423. {
  424. $addFields: {
  425. ownerOID: {
  426. $convert: {
  427. input: "$owner",
  428. to: "objectId",
  429. onError: "unknown",
  430. onNull: "unknown"
  431. }
  432. }
  433. }
  434. },
  435. {
  436. $lookup: {
  437. from: "users",
  438. localField: "ownerOID",
  439. foreignField: "_id",
  440. as: "ownerUser"
  441. }
  442. },
  443. {
  444. $unwind: {
  445. path: "$ownerUser",
  446. preserveNullAndEmptyArrays: true
  447. }
  448. },
  449. {
  450. $addFields: {
  451. ownerUsername: {
  452. $cond: [
  453. { $eq: [{ $type: "$owner" }, "string"] },
  454. { $ifNull: ["$ownerUser.username", "unknown"] },
  455. "none"
  456. ]
  457. }
  458. }
  459. },
  460. {
  461. $project: {
  462. ownerOID: 0,
  463. ownerUser: 0
  464. }
  465. }
  466. ]
  467. },
  468. specialQueries: {
  469. owner: newQuery => ({ $or: [newQuery, { ownerUsername: newQuery.owner }] })
  470. }
  471. },
  472. this
  473. )
  474. .then(response => {
  475. next(null, response);
  476. })
  477. .catch(err => {
  478. next(err);
  479. });
  480. }
  481. ],
  482. async (err, response) => {
  483. if (err) {
  484. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  485. this.log("ERROR", "STATIONS_GET_DATA", `Failed to get data from stations. "${err}"`);
  486. return cb({ status: "error", message: err });
  487. }
  488. this.log("SUCCESS", "STATIONS_GET_DATA", `Got data from stations successfully.`);
  489. return cb({ status: "success", message: "Successfully got data from stations.", data: response });
  490. }
  491. );
  492. }
  493. ),
  494. /**
  495. * Obtains basic metadata of a station in order to format an activity
  496. *
  497. * @param {object} session - user session
  498. * @param {string} stationId - the station id
  499. * @param {Function} cb - callback
  500. */
  501. getStationForActivity(session, stationId, cb) {
  502. async.waterfall(
  503. [
  504. next => {
  505. StationsModule.runJob("GET_STATION", { stationId }, this)
  506. .then(station => {
  507. next(null, station);
  508. })
  509. .catch(next);
  510. }
  511. ],
  512. async (err, station) => {
  513. if (err) {
  514. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  515. this.log(
  516. "ERROR",
  517. "STATIONS_GET_STATION_FOR_ACTIVITY",
  518. `Failed to obtain metadata of station ${stationId} for activity formatting. "${err}"`
  519. );
  520. return cb({ status: "error", message: err });
  521. }
  522. this.log(
  523. "SUCCESS",
  524. "STATIONS_GET_STATION_FOR_ACTIVITY",
  525. `Obtained metadata of station ${stationId} for activity formatting successfully.`
  526. );
  527. return cb({
  528. status: "success",
  529. data: {
  530. title: station.displayName,
  531. thumbnail: station.currentSong ? station.currentSong.thumbnail : ""
  532. }
  533. });
  534. }
  535. );
  536. },
  537. /**
  538. * Verifies that a station exists from its name
  539. *
  540. * @param {object} session - user session
  541. * @param {string} stationName - the station name
  542. * @param {Function} cb - callback
  543. */
  544. existsByName(session, stationName, cb) {
  545. async.waterfall(
  546. [
  547. next => {
  548. StationsModule.runJob("GET_STATION_BY_NAME", { stationName }, this)
  549. .then(station => next(null, station))
  550. .catch(next);
  551. },
  552. (station, next) => {
  553. if (!station) return next(null, false);
  554. return StationsModule.runJob("CAN_USER_VIEW_STATION", { station, userId: session.userId }, this)
  555. .then(exists => next(null, exists))
  556. .catch(next);
  557. }
  558. ],
  559. async (err, exists) => {
  560. if (err) {
  561. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  562. this.log(
  563. "ERROR",
  564. "STATION_EXISTS_BY_NAME",
  565. `Checking if station "${stationName}" exists failed. "${err}"`
  566. );
  567. return cb({ status: "error", message: err });
  568. }
  569. this.log(
  570. "SUCCESS",
  571. "STATION_EXISTS_BY_NAME",
  572. `Station "${stationName}" exists successfully.` /* , false */
  573. );
  574. return cb({ status: "success", data: { exists } });
  575. }
  576. );
  577. },
  578. /**
  579. * Verifies that a station exists from its id
  580. *
  581. * @param {object} session - user session
  582. * @param {string} stationId - the station id
  583. * @param {Function} cb - callback
  584. */
  585. existsById(session, stationId, cb) {
  586. async.waterfall(
  587. [
  588. next => {
  589. StationsModule.runJob("GET_STATION", { stationId }, this)
  590. .then(station => next(null, station))
  591. .catch(next);
  592. },
  593. (station, next) => {
  594. if (!station) return next(null, false);
  595. return StationsModule.runJob("CAN_USER_VIEW_STATION", { station, userId: session.userId }, this)
  596. .then(exists => next(null, exists))
  597. .catch(next);
  598. }
  599. ],
  600. async (err, exists) => {
  601. if (err) {
  602. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  603. this.log(
  604. "ERROR",
  605. "STATION_EXISTS_BY_ID",
  606. `Checking if station "${stationId}" exists failed. "${err}"`
  607. );
  608. return cb({ status: "error", message: err });
  609. }
  610. this.log(
  611. "SUCCESS",
  612. "STATION_EXISTS_BY_ID",
  613. `Station "${stationId}" exists successfully.` /* , false */
  614. );
  615. return cb({ status: "success", data: { exists } });
  616. }
  617. );
  618. },
  619. /**
  620. * Gets the official playlist for a station
  621. *
  622. * @param {object} session - user session
  623. * @param {string} stationId - the station id
  624. * @param {Function} cb - callback
  625. */
  626. getPlaylist(session, stationId, cb) {
  627. async.waterfall(
  628. [
  629. next => {
  630. StationsModule.runJob("GET_STATION", { stationId }, this)
  631. .then(station => {
  632. next(null, station);
  633. })
  634. .catch(next);
  635. },
  636. (station, next) => {
  637. StationsModule.runJob(
  638. "CAN_USER_VIEW_STATION",
  639. {
  640. station,
  641. userId: session.userId
  642. },
  643. this
  644. )
  645. .then(canView => {
  646. if (canView) return next(null, station);
  647. return next("Insufficient permissions.");
  648. })
  649. .catch(err => next(err));
  650. },
  651. (station, next) => {
  652. if (!station) return next("Station not found.");
  653. if (station.type !== "official") return next("This is not an official station.");
  654. return next();
  655. },
  656. next => {
  657. CacheModule.runJob(
  658. "HGET",
  659. {
  660. table: "officialPlaylists",
  661. key: stationId
  662. },
  663. this
  664. )
  665. .then(playlist => {
  666. next(null, playlist);
  667. })
  668. .catch(next);
  669. },
  670. (playlist, next) => {
  671. if (!playlist) return next("Playlist not found.");
  672. return next(null, playlist);
  673. }
  674. ],
  675. async (err, playlist) => {
  676. if (err) {
  677. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  678. this.log(
  679. "ERROR",
  680. "STATIONS_GET_PLAYLIST",
  681. `Getting playlist for station "${stationId}" failed. "${err}"`
  682. );
  683. return cb({ status: "error", message: err });
  684. }
  685. this.log(
  686. "SUCCESS",
  687. "STATIONS_GET_PLAYLIST",
  688. `Got playlist for station "${stationId}" successfully.`,
  689. false
  690. );
  691. return cb({ status: "success", data: { songs: playlist.songs } });
  692. }
  693. );
  694. },
  695. /**
  696. * Joins the station by its name
  697. *
  698. * @param {object} session - user session
  699. * @param {string} stationIdentifier - the station name or station id
  700. * @param {Function} cb - callback
  701. */
  702. async join(session, stationIdentifier, cb) {
  703. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" });
  704. async.waterfall(
  705. [
  706. next => {
  707. StationsModule.runJob("GET_STATION_BY_NAME", { stationName: stationIdentifier }, this)
  708. .then(station => next(null, station))
  709. .catch(() =>
  710. // station identifier may be using stationid instead
  711. StationsModule.runJob("GET_STATION", { stationId: stationIdentifier }, this)
  712. .then(station => next(null, station))
  713. .catch(next)
  714. );
  715. },
  716. (station, next) => {
  717. if (!station) return next("Station not found.");
  718. return StationsModule.runJob("CAN_USER_VIEW_STATION", { station, userId: session.userId }, this)
  719. .then(canView => {
  720. if (!canView) next("Not allowed to join station.");
  721. else next(null, station);
  722. })
  723. .catch(err => next(err));
  724. },
  725. (station, next) => {
  726. WSModule.runJob("SOCKET_JOIN_ROOM", {
  727. socketId: session.socketId,
  728. room: `station.${station._id}`
  729. });
  730. const data = {
  731. _id: station._id,
  732. type: station.type,
  733. currentSong: station.currentSong,
  734. startedAt: station.startedAt,
  735. paused: station.paused,
  736. timePaused: station.timePaused,
  737. pausedAt: station.pausedAt,
  738. description: station.description,
  739. displayName: station.displayName,
  740. name: station.name,
  741. privacy: station.privacy,
  742. requests: station.requests,
  743. autofill: station.autofill,
  744. owner: station.owner,
  745. blacklist: station.blacklist,
  746. theme: station.theme,
  747. djs: station.djs
  748. };
  749. StationsModule.userList[session.socketId] = station._id;
  750. next(null, data);
  751. },
  752. (data, next) => {
  753. userModel.find({ _id: { $in: data.djs } }, (err, users) => {
  754. if (err) next(err);
  755. else {
  756. data.djs = users.map(user => {
  757. const { _id, name, username, avatar } = user._doc;
  758. return { _id, name, username, avatar };
  759. });
  760. next(null, data);
  761. }
  762. });
  763. },
  764. (data, next) => {
  765. data = JSON.parse(JSON.stringify(data));
  766. data.userCount = StationsModule.usersPerStationCount[data._id] || 0;
  767. data.users = StationsModule.usersPerStation[data._id] || [];
  768. if (!data.currentSong || !data.currentSong.title) return next(null, data);
  769. WSModule.runJob("SOCKET_JOIN_SONG_ROOM", {
  770. socketId: session.socketId,
  771. room: `song.${data.currentSong.youtubeId}`
  772. });
  773. data.currentSong.skipVotes = data.currentSong.skipVotes.length;
  774. return next(null, data);
  775. },
  776. (data, next) => {
  777. // only relevant if user logged in
  778. if (session.userId) {
  779. return StationsModule.runJob(
  780. "HAS_USER_FAVORITED_STATION",
  781. {
  782. userId: session.userId,
  783. stationId: data._id
  784. },
  785. this
  786. )
  787. .then(isStationFavorited => {
  788. data.isFavorited = isStationFavorited;
  789. return next(null, data);
  790. })
  791. .catch(err => next(err));
  792. }
  793. return next(null, data);
  794. }
  795. ],
  796. async (err, data) => {
  797. if (err) {
  798. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  799. this.log("ERROR", "STATIONS_JOIN", `Joining station "${stationIdentifier}" failed. "${err}"`);
  800. return cb({ status: "error", message: err });
  801. }
  802. this.log("SUCCESS", "STATIONS_JOIN", `Joined station "${data._id}" successfully.`);
  803. return cb({ status: "success", data });
  804. }
  805. );
  806. },
  807. /**
  808. * Gets a station by id
  809. *
  810. * @param {object} session - user session
  811. * @param {string} stationId - the station id
  812. * @param {Function} cb - callback
  813. */
  814. getStationById(session, stationId, cb) {
  815. async.waterfall(
  816. [
  817. next => {
  818. StationsModule.runJob("GET_STATION", { stationId }, this)
  819. .then(station => {
  820. next(null, station);
  821. })
  822. .catch(next);
  823. },
  824. (station, next) => {
  825. if (!station) return next("Station not found.");
  826. return StationsModule.runJob(
  827. "CAN_USER_VIEW_STATION",
  828. {
  829. station,
  830. userId: session.userId
  831. },
  832. this
  833. )
  834. .then(canView => {
  835. if (!canView) next("Not allowed to get station.");
  836. else next(null, station);
  837. })
  838. .catch(err => next(err));
  839. },
  840. (station, next) => {
  841. // only relevant if user logged in
  842. if (session.userId) {
  843. return StationsModule.runJob(
  844. "HAS_USER_FAVORITED_STATION",
  845. {
  846. userId: session.userId,
  847. stationId
  848. },
  849. this
  850. )
  851. .then(isStationFavorited => {
  852. station.isFavorited = isStationFavorited;
  853. return next(null, station);
  854. })
  855. .catch(err => next(err));
  856. }
  857. return next(null, station);
  858. },
  859. (station, next) => {
  860. const data = {
  861. _id: station._id,
  862. type: station.type,
  863. description: station.description,
  864. displayName: station.displayName,
  865. name: station.name,
  866. privacy: station.privacy,
  867. requests: station.requests,
  868. autofill: station.autofill,
  869. owner: station.owner,
  870. theme: station.theme,
  871. paused: station.paused,
  872. currentSong: station.currentSong,
  873. isFavorited: station.isFavorited,
  874. djs: station.djs
  875. };
  876. next(null, data);
  877. }
  878. ],
  879. async (err, data) => {
  880. if (err) {
  881. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  882. this.log("ERROR", "GET_STATION_BY_ID", `Getting station "${stationId}" failed. "${err}"`);
  883. return cb({ status: "error", message: err });
  884. }
  885. this.log("SUCCESS", "GET_STATION_BY_ID", `Got station "${stationId}" successfully.`);
  886. return cb({ status: "success", data: { station: data } });
  887. }
  888. );
  889. },
  890. getStationAutofillPlaylistsById(session, stationId, cb) {
  891. async.waterfall(
  892. [
  893. next => {
  894. StationsModule.runJob("GET_STATION", { stationId }, this)
  895. .then(station => {
  896. next(null, station);
  897. })
  898. .catch(next);
  899. },
  900. (station, next) => {
  901. if (!station) return next("Station not found.");
  902. return StationsModule.runJob(
  903. "CAN_USER_VIEW_STATION",
  904. {
  905. station,
  906. userId: session.userId
  907. },
  908. this
  909. )
  910. .then(canView => {
  911. if (!canView) next("Not allowed to get station.");
  912. else next(null, station);
  913. })
  914. .catch(err => next(err));
  915. },
  916. (station, next) => {
  917. const playlists = [];
  918. async.eachLimit(
  919. station.autofill.playlists,
  920. 1,
  921. (playlistId, next) => {
  922. PlaylistsModule.runJob("GET_PLAYLIST", { playlistId }, this)
  923. .then(playlist => {
  924. playlists.push(playlist);
  925. next();
  926. })
  927. .catch(() => {
  928. playlists.push(null);
  929. next();
  930. });
  931. },
  932. err => {
  933. next(err, playlists);
  934. }
  935. );
  936. }
  937. ],
  938. async (err, playlists) => {
  939. if (err) {
  940. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  941. this.log(
  942. "ERROR",
  943. "GET_STATION_AUTOFILL_PLAYLISTS_BY_ID",
  944. `Getting station "${stationId}"'s autofilling playlists failed. "${err}"`
  945. );
  946. return cb({ status: "error", message: err });
  947. }
  948. this.log(
  949. "SUCCESS",
  950. "GET_STATION_AUTOFILL_PLAYLISTS_BY_ID",
  951. `Got station "${stationId}"'s autofilling playlists successfully.`
  952. );
  953. return cb({ status: "success", data: { playlists } });
  954. }
  955. );
  956. },
  957. getStationBlacklistById(session, stationId, cb) {
  958. async.waterfall(
  959. [
  960. next => {
  961. StationsModule.runJob("GET_STATION", { stationId }, this)
  962. .then(station => {
  963. next(null, station);
  964. })
  965. .catch(next);
  966. },
  967. (station, next) => {
  968. if (!station) return next("Station not found.");
  969. return StationsModule.runJob(
  970. "CAN_USER_VIEW_STATION",
  971. {
  972. station,
  973. userId: session.userId
  974. },
  975. this
  976. )
  977. .then(canView => {
  978. if (!canView) next("Not allowed to get station.");
  979. else next(null, station);
  980. })
  981. .catch(err => next(err));
  982. },
  983. (station, next) => {
  984. const playlists = [];
  985. async.eachLimit(
  986. station.blacklist,
  987. 1,
  988. (playlistId, next) => {
  989. PlaylistsModule.runJob("GET_PLAYLIST", { playlistId }, this)
  990. .then(playlist => {
  991. playlists.push(playlist);
  992. next();
  993. })
  994. .catch(() => {
  995. playlists.push(null);
  996. next();
  997. });
  998. },
  999. err => {
  1000. next(err, playlists);
  1001. }
  1002. );
  1003. }
  1004. ],
  1005. async (err, playlists) => {
  1006. if (err) {
  1007. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1008. this.log(
  1009. "ERROR",
  1010. "GET_STATION_BLACKLIST_BY_ID",
  1011. `Getting station "${stationId}"'s blacklist failed. "${err}"`
  1012. );
  1013. return cb({ status: "error", message: err });
  1014. }
  1015. this.log(
  1016. "SUCCESS",
  1017. "GET_STATION_BLACKLIST_BY_ID",
  1018. `Got station "${stationId}"'s blacklist successfully.`
  1019. );
  1020. return cb({ status: "success", data: { playlists } });
  1021. }
  1022. );
  1023. },
  1024. /**
  1025. * Votes to skip a station
  1026. *
  1027. * @param session
  1028. * @param stationId - the station id
  1029. * @param cb
  1030. */
  1031. voteSkip: isLoginRequired(async function voteSkip(session, stationId, cb) {
  1032. const stationModel = await DBModule.runJob("GET_MODEL", { modelName: "station" }, this);
  1033. async.waterfall(
  1034. [
  1035. next => {
  1036. StationsModule.runJob("GET_STATION", { stationId }, this)
  1037. .then(station => next(null, station))
  1038. .catch(next);
  1039. },
  1040. (station, next) => {
  1041. if (!station) return next("Station not found.");
  1042. return StationsModule.runJob("CAN_USER_VIEW_STATION", { station, userId: session.userId }, this)
  1043. .then(canView => {
  1044. if (canView) return next(null, station);
  1045. return next("Insufficient permissions.");
  1046. })
  1047. .catch(err => next(err));
  1048. },
  1049. (station, next) => {
  1050. if (!station.currentSong) return next("There is currently no song to skip.");
  1051. if (station.currentSong.skipVotes.indexOf(session.userId) !== -1)
  1052. return next("You have already voted to skip this song.");
  1053. return next(null, station);
  1054. },
  1055. (station, next) => {
  1056. stationModel.updateOne(
  1057. { _id: stationId },
  1058. { $push: { "currentSong.skipVotes": session.userId } },
  1059. next
  1060. );
  1061. },
  1062. (res, next) => {
  1063. StationsModule.runJob("UPDATE_STATION", { stationId }, this)
  1064. .then(station => {
  1065. next(null, station);
  1066. })
  1067. .catch(next);
  1068. },
  1069. (station, next) => {
  1070. if (!station) return next("Station not found.");
  1071. return StationsModule.runJob("PROCESS_VOTE_SKIPS", { stationId }, this)
  1072. .then(() => next())
  1073. .catch(next);
  1074. }
  1075. ],
  1076. async err => {
  1077. if (err) {
  1078. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1079. this.log("ERROR", "STATIONS_VOTE_SKIP", `Vote skipping station "${stationId}" failed. "${err}"`);
  1080. return cb({ status: "error", message: err });
  1081. }
  1082. this.log("SUCCESS", "STATIONS_VOTE_SKIP", `Vote skipping "${stationId}" successful.`);
  1083. CacheModule.runJob("PUB", {
  1084. channel: "station.voteSkipSong",
  1085. value: stationId
  1086. });
  1087. return cb({
  1088. status: "success",
  1089. message: "Successfully voted to skip the song."
  1090. });
  1091. }
  1092. );
  1093. }),
  1094. /**
  1095. * Force skips a station
  1096. *
  1097. * @param session
  1098. * @param stationId - the station id
  1099. * @param cb
  1100. */
  1101. forceSkip(session, stationId, cb) {
  1102. async.waterfall(
  1103. [
  1104. next => {
  1105. hasPermission("stations.skip", session, stationId)
  1106. .then(() => next())
  1107. .catch(next);
  1108. },
  1109. next => {
  1110. StationsModule.runJob("GET_STATION", { stationId }, this)
  1111. .then(station => {
  1112. next(null, station);
  1113. })
  1114. .catch(next);
  1115. },
  1116. (station, next) => {
  1117. if (!station) return next("Station not found.");
  1118. return next();
  1119. }
  1120. ],
  1121. async err => {
  1122. if (err) {
  1123. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1124. this.log("ERROR", "STATIONS_FORCE_SKIP", `Force skipping station "${stationId}" failed. "${err}"`);
  1125. return cb({ status: "error", message: err });
  1126. }
  1127. StationsModule.runJob("SKIP_STATION", { stationId, natural: false });
  1128. this.log("SUCCESS", "STATIONS_FORCE_SKIP", `Force skipped station "${stationId}" successfully.`);
  1129. return cb({
  1130. status: "success",
  1131. message: "Successfully skipped station."
  1132. });
  1133. }
  1134. );
  1135. },
  1136. /**
  1137. * Leaves the user's current station
  1138. *
  1139. * @param {object} session - user session
  1140. * @param {string} stationId - id of station to leave
  1141. * @param {Function} cb - callback
  1142. */
  1143. leave(session, stationId, cb) {
  1144. async.waterfall(
  1145. [
  1146. next => {
  1147. StationsModule.runJob("GET_STATION", { stationId }, this)
  1148. .then(station => next(null, station))
  1149. .catch(next);
  1150. },
  1151. (station, next) => {
  1152. if (!station) return next("Station not found.");
  1153. return next();
  1154. }
  1155. ],
  1156. async (err, userCount) => {
  1157. if (err) {
  1158. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1159. this.log("ERROR", "STATIONS_LEAVE", `Leaving station "${stationId}" failed. "${err}"`);
  1160. return cb({ status: "error", message: err });
  1161. }
  1162. this.log("SUCCESS", "STATIONS_LEAVE", `Left station "${stationId}" successfully.`);
  1163. WSModule.runJob("SOCKET_LEAVE_ROOM", { socketId: session.socketId, room: `station.${stationId}` });
  1164. WSModule.runJob("SOCKETS_LEAVE_SONG_ROOMS", { sockets: [session.socketId] });
  1165. delete StationsModule.userList[session.socketId];
  1166. return cb({
  1167. status: "success",
  1168. message: "Successfully left station.",
  1169. data: { userCount }
  1170. });
  1171. }
  1172. );
  1173. },
  1174. /**
  1175. * Updates a station's settings
  1176. *
  1177. * @param session
  1178. * @param stationId - the station id
  1179. * @param station - updated station object
  1180. * @param newStation
  1181. * @param cb
  1182. */
  1183. async update(session, stationId, newStation, cb) {
  1184. const stationModel = await DBModule.runJob("GET_MODEL", { modelName: "station" }, this);
  1185. const playlistModel = await DBModule.runJob("GET_MODEL", { modelName: "playlist" }, this);
  1186. async.waterfall(
  1187. [
  1188. next => {
  1189. hasPermission("stations.update", session, stationId)
  1190. .then(() => next())
  1191. .catch(next);
  1192. },
  1193. next => {
  1194. stationModel.findOne({ _id: stationId }, next);
  1195. },
  1196. (previousStation, next) => {
  1197. const { name, displayName, description, privacy, requests, autofill, theme } = newStation;
  1198. const { enabled, limit, mode } = autofill;
  1199. // This object makes sure only certain properties can be changed by a user
  1200. const setObject = {
  1201. name,
  1202. displayName,
  1203. description,
  1204. privacy,
  1205. requests,
  1206. "autofill.enabled": enabled,
  1207. "autofill.limit": limit,
  1208. "autofill.mode": mode,
  1209. theme
  1210. };
  1211. stationModel.updateOne({ _id: stationId }, { $set: setObject }, { runValidators: true }, err => {
  1212. next(err, previousStation);
  1213. });
  1214. },
  1215. (previousStation, next) => {
  1216. StationsModule.runJob("UPDATE_STATION", { stationId }, this)
  1217. .then(station => next(null, station, previousStation))
  1218. .catch(next);
  1219. },
  1220. (station, previousStation, next) => {
  1221. if (
  1222. newStation.autofill.enabled &&
  1223. JSON.stringify(newStation.autofill) !== JSON.stringify(previousStation.autofill)
  1224. )
  1225. StationsModule.runJob("AUTOFILL_STATION", { stationId }, this)
  1226. .then(() => {
  1227. CacheModule.runJob("PUB", {
  1228. channel: "station.queueUpdate",
  1229. value: stationId
  1230. })
  1231. .then(() => next(null, station, previousStation))
  1232. .catch(next);
  1233. })
  1234. .catch(err => {
  1235. if (err === "Autofill is disabled in this station" || err === "Autofill limit reached")
  1236. next(null, station, previousStation);
  1237. else next(err);
  1238. });
  1239. else next(null, station, previousStation);
  1240. },
  1241. (station, previousStation, next) => {
  1242. playlistModel.updateOne(
  1243. { _id: station.playlist },
  1244. { $set: { displayName: `Station - ${station.displayName}` } },
  1245. err => {
  1246. next(err, station, previousStation);
  1247. }
  1248. );
  1249. }
  1250. ],
  1251. async (err, station, previousStation) => {
  1252. if (err) {
  1253. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1254. this.log("ERROR", "STATIONS_UPDATE", `Updating station "${stationId}" failed. "${err}"`);
  1255. return cb({ status: "error", message: err });
  1256. }
  1257. this.log("SUCCESS", "STATIONS_UPDATE", `Updated station "${stationId}" successfully.`);
  1258. CacheModule.runJob("PUB", {
  1259. channel: "station.updated",
  1260. value: { stationId, previousStation }
  1261. });
  1262. return cb({
  1263. status: "success",
  1264. message: "Successfully updated the station."
  1265. });
  1266. }
  1267. );
  1268. },
  1269. /**
  1270. * Pauses a station
  1271. *
  1272. * @param session
  1273. * @param stationId - the station id
  1274. * @param cb
  1275. */
  1276. async pause(session, stationId, cb) {
  1277. const stationModel = await DBModule.runJob(
  1278. "GET_MODEL",
  1279. {
  1280. modelName: "station"
  1281. },
  1282. this
  1283. );
  1284. async.waterfall(
  1285. [
  1286. next => {
  1287. hasPermission("stations.playback.toggle", session, stationId)
  1288. .then(() => next())
  1289. .catch(next);
  1290. },
  1291. next => {
  1292. StationsModule.runJob("GET_STATION", { stationId }, this)
  1293. .then(station => {
  1294. next(null, station);
  1295. })
  1296. .catch(next);
  1297. },
  1298. (station, next) => {
  1299. if (!station) return next("Station not found.");
  1300. if (station.paused) return next("That station was already paused.");
  1301. return stationModel.updateOne(
  1302. { _id: stationId },
  1303. { $set: { paused: true, pausedAt: Date.now() } },
  1304. next
  1305. );
  1306. },
  1307. (res, next) => {
  1308. StationsModule.runJob("UPDATE_STATION", { stationId }, this)
  1309. .then(() => next())
  1310. .catch(next);
  1311. }
  1312. ],
  1313. async err => {
  1314. if (err) {
  1315. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1316. this.log("ERROR", "STATIONS_PAUSE", `Pausing station "${stationId}" failed. "${err}"`);
  1317. return cb({ status: "error", message: err });
  1318. }
  1319. this.log("SUCCESS", "STATIONS_PAUSE", `Paused station "${stationId}" successfully.`);
  1320. CacheModule.runJob("PUB", {
  1321. channel: "station.pause",
  1322. value: stationId
  1323. });
  1324. NotificationsModule.runJob("UNSCHEDULE", {
  1325. name: `stations.nextSong?id=${stationId}`
  1326. });
  1327. return cb({
  1328. status: "success",
  1329. message: "Successfully paused."
  1330. });
  1331. }
  1332. );
  1333. },
  1334. /**
  1335. * Resumes a station
  1336. *
  1337. * @param session
  1338. * @param stationId - the station id
  1339. * @param cb
  1340. */
  1341. async resume(session, stationId, cb) {
  1342. const stationModel = await DBModule.runJob(
  1343. "GET_MODEL",
  1344. {
  1345. modelName: "station"
  1346. },
  1347. this
  1348. );
  1349. async.waterfall(
  1350. [
  1351. next => {
  1352. hasPermission("stations.playback.toggle", session, stationId)
  1353. .then(() => next())
  1354. .catch(next);
  1355. },
  1356. next => {
  1357. StationsModule.runJob("GET_STATION", { stationId }, this)
  1358. .then(station => {
  1359. next(null, station);
  1360. })
  1361. .catch(next);
  1362. },
  1363. (station, next) => {
  1364. if (!station) return next("Station not found.");
  1365. if (!station.paused) return next("That station is not paused.");
  1366. station.timePaused += Date.now() - station.pausedAt;
  1367. return stationModel.updateOne(
  1368. { _id: stationId },
  1369. {
  1370. $set: { paused: false },
  1371. $inc: { timePaused: Date.now() - station.pausedAt }
  1372. },
  1373. next
  1374. );
  1375. },
  1376. (res, next) => {
  1377. StationsModule.runJob("UPDATE_STATION", { stationId }, this)
  1378. .then(() => next())
  1379. .catch(next);
  1380. },
  1381. next => {
  1382. StationsModule.runJob("PROCESS_VOTE_SKIPS", { stationId }, this)
  1383. .then(() => next())
  1384. .catch(next);
  1385. }
  1386. ],
  1387. async err => {
  1388. if (err) {
  1389. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1390. this.log("ERROR", "STATIONS_RESUME", `Resuming station "${stationId}" failed. "${err}"`);
  1391. return cb({ status: "error", message: err });
  1392. }
  1393. this.log("SUCCESS", "STATIONS_RESUME", `Resuming station "${stationId}" successfully.`);
  1394. CacheModule.runJob("PUB", {
  1395. channel: "station.resume",
  1396. value: stationId
  1397. });
  1398. return cb({
  1399. status: "success",
  1400. message: "Successfully resumed."
  1401. });
  1402. }
  1403. );
  1404. },
  1405. /**
  1406. * Removes a station
  1407. *
  1408. * @param session
  1409. * @param stationId - the station id
  1410. * @param cb
  1411. */
  1412. async remove(session, stationId, cb) {
  1413. const stationModel = await DBModule.runJob("GET_MODEL", { modelName: "station" }, this);
  1414. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  1415. async.waterfall(
  1416. [
  1417. next => {
  1418. hasPermission("stations.remove", session, stationId)
  1419. .then(() => next())
  1420. .catch(next);
  1421. },
  1422. next => {
  1423. stationModel.findById(stationId, (err, station) => {
  1424. if (err) return next(err);
  1425. return next(null, station);
  1426. });
  1427. },
  1428. (station, next) => {
  1429. stationModel.deleteOne({ _id: stationId }, err => next(err, station));
  1430. },
  1431. (station, next) => {
  1432. CacheModule.runJob("HDEL", { table: "stations", key: stationId }, this)
  1433. .then(() => next(null, station))
  1434. .catch(next);
  1435. },
  1436. // remove the playlist for the station
  1437. (station, next) => {
  1438. if (station.playlist)
  1439. PlaylistsModule.runJob("DELETE_PLAYLIST", { playlistId: station.playlist })
  1440. .then(() => {})
  1441. .catch(next);
  1442. next(null, station);
  1443. },
  1444. // remove reference to the station id in any array of a user's favorite stations
  1445. (station, next) => {
  1446. userModel.updateMany(
  1447. { favoriteStations: stationId },
  1448. { $pull: { favoriteStations: stationId } },
  1449. err => next(err, station)
  1450. );
  1451. }
  1452. ],
  1453. async (err, station) => {
  1454. if (err) {
  1455. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1456. this.log("ERROR", "STATIONS_REMOVE", `Removing station "${stationId}" failed. "${err}"`);
  1457. return cb({ status: "error", message: err });
  1458. }
  1459. this.log("SUCCESS", "STATIONS_REMOVE", `Removing station "${stationId}" successfully.`);
  1460. CacheModule.runJob("PUB", {
  1461. channel: "station.remove",
  1462. value: stationId
  1463. });
  1464. ActivitiesModule.runJob("ADD_ACTIVITY", {
  1465. userId: session.userId,
  1466. type: "station__remove",
  1467. payload: { message: `Removed a station named ${station.displayName}` }
  1468. });
  1469. ActivitiesModule.runJob("REMOVE_ACTIVITY_REFERENCES", { type: "stationId", stationId });
  1470. return cb({
  1471. status: "success",
  1472. message: "Successfully removed."
  1473. });
  1474. }
  1475. );
  1476. },
  1477. /**
  1478. * Create a station
  1479. *
  1480. * @param session
  1481. * @param data - the station data
  1482. * @param cb
  1483. */
  1484. create: isLoginRequired(async function create(session, data, cb) {
  1485. const stationModel = await DBModule.runJob("GET_MODEL", { modelName: "station" }, this);
  1486. const playlistModel = await DBModule.runJob("GET_MODEL", { modelName: "playlist" }, this);
  1487. data.name = data.name.toLowerCase();
  1488. let blacklist = [
  1489. "about",
  1490. "support",
  1491. "staff",
  1492. "help",
  1493. "news",
  1494. "terms",
  1495. "privacy",
  1496. "profile",
  1497. "c",
  1498. "community",
  1499. "tos",
  1500. "login",
  1501. "register",
  1502. "p",
  1503. "official",
  1504. "o",
  1505. "faq",
  1506. "team",
  1507. "donate",
  1508. "buy",
  1509. "shop",
  1510. "forums",
  1511. "explore",
  1512. "settings",
  1513. "admin",
  1514. "auth",
  1515. "reset_password",
  1516. "backend",
  1517. "api",
  1518. "songs",
  1519. "playlists",
  1520. "playlist",
  1521. "albums",
  1522. "artists",
  1523. "artist",
  1524. "station"
  1525. ];
  1526. if (data.type === "community" && config.has("blacklistedCommunityStationNames"))
  1527. blacklist = [...blacklist, ...config.get("blacklistedCommunityStationNames")];
  1528. async.waterfall(
  1529. [
  1530. next => {
  1531. if (!data) return next("Invalid data.");
  1532. return next();
  1533. },
  1534. next => {
  1535. stationModel.findOne(
  1536. {
  1537. $or: [{ name: data.name }, { displayName: new RegExp(`^${data.displayName}$`, "i") }]
  1538. },
  1539. next
  1540. );
  1541. },
  1542. (station, next) => {
  1543. this.log(station);
  1544. if (station) return next("A station with that name or display name already exists.");
  1545. if (blacklist.indexOf(data.name) !== -1)
  1546. return next("That name is blacklisted. Please use a different name.");
  1547. if (data.type === "official")
  1548. return hasPermission("stations.create.official", session)
  1549. .then(() => next())
  1550. .catch(() => next("Insufficient permissions."));
  1551. return next();
  1552. },
  1553. next => {
  1554. const stationId = mongoose.Types.ObjectId();
  1555. playlistModel.create(
  1556. {
  1557. displayName: `Station - ${data.name}`,
  1558. songs: [],
  1559. createdBy: data.type === "official" ? "Musare" : session.userId,
  1560. createdFor: `${stationId}`,
  1561. createdAt: Date.now(),
  1562. type: "station"
  1563. },
  1564. (err, playlist) => {
  1565. next(err, playlist, stationId);
  1566. }
  1567. );
  1568. },
  1569. (playlist, stationId, next) => {
  1570. const { name, displayName, description, type } = data;
  1571. if (type === "official") {
  1572. stationModel.create(
  1573. {
  1574. _id: stationId,
  1575. name,
  1576. displayName,
  1577. description,
  1578. playlist: playlist._id,
  1579. type,
  1580. privacy: "private",
  1581. queue: [],
  1582. currentSong: null
  1583. },
  1584. next
  1585. );
  1586. } else {
  1587. stationModel.create(
  1588. {
  1589. _id: stationId,
  1590. name,
  1591. displayName,
  1592. description,
  1593. playlist: playlist._id,
  1594. type,
  1595. privacy: "private",
  1596. owner: session.userId,
  1597. queue: [],
  1598. currentSong: null
  1599. },
  1600. next
  1601. );
  1602. }
  1603. }
  1604. ],
  1605. async (err, station) => {
  1606. if (err) {
  1607. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1608. this.log("ERROR", "STATIONS_CREATE", `Creating station failed. "${err}"`);
  1609. cb({ status: "error", message: err });
  1610. } else {
  1611. this.log("SUCCESS", "STATIONS_CREATE", `Created station "${station._id}" successfully.`);
  1612. CacheModule.runJob("PUB", {
  1613. channel: "station.create",
  1614. value: station._id
  1615. });
  1616. ActivitiesModule.runJob("ADD_ACTIVITY", {
  1617. userId: session.userId,
  1618. type: "station__create",
  1619. payload: {
  1620. message: `Created a station named <stationId>${station.displayName}</stationId>`,
  1621. stationId: station._id
  1622. }
  1623. });
  1624. cb({
  1625. status: "success",
  1626. message: "Successfully created station."
  1627. });
  1628. }
  1629. }
  1630. );
  1631. }),
  1632. /**
  1633. * Adds song to station queue
  1634. *
  1635. * @param session
  1636. * @param stationId - the station id
  1637. * @param youtubeId - the song id
  1638. * @param cb
  1639. */
  1640. addToQueue: isLoginRequired(async function addToQueue(session, stationId, youtubeId, cb) {
  1641. async.waterfall(
  1642. [
  1643. next => {
  1644. StationsModule.runJob("GET_STATION", { stationId }, this)
  1645. .then(station => {
  1646. next(null, station);
  1647. })
  1648. .catch(next);
  1649. },
  1650. (station, next) => {
  1651. if (!station) return next("Station not found.");
  1652. if (!station.requests.enabled) return next("Requests are disabled in this station.");
  1653. if (
  1654. station.requests.access === "owner" ||
  1655. (station.requests.access === "user" && station.privacy === "private")
  1656. ) {
  1657. return hasPermission("stations.request", session, stationId)
  1658. .then(() => next(null, station))
  1659. .catch(() => next("You do not have permission to add songs to queue."));
  1660. }
  1661. return next(null, station);
  1662. },
  1663. (station, next) =>
  1664. StationsModule.runJob(
  1665. "CAN_USER_VIEW_STATION",
  1666. {
  1667. station,
  1668. userId: session.userId
  1669. },
  1670. this
  1671. )
  1672. .then(canView => {
  1673. if (canView) return next();
  1674. return next("Insufficient permissions.");
  1675. })
  1676. .catch(err => next(err)),
  1677. next =>
  1678. StationsModule.runJob(
  1679. "ADD_TO_QUEUE",
  1680. {
  1681. stationId,
  1682. youtubeId,
  1683. requestUser: session.userId
  1684. },
  1685. this
  1686. )
  1687. .then(() => next())
  1688. .catch(next)
  1689. ],
  1690. async err => {
  1691. if (err) {
  1692. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1693. this.log(
  1694. "ERROR",
  1695. "STATIONS_ADD_SONG_TO_QUEUE",
  1696. `Adding song "${youtubeId}" to station "${stationId}" queue failed. "${err}"`
  1697. );
  1698. return cb({ status: "error", message: err });
  1699. }
  1700. this.log(
  1701. "SUCCESS",
  1702. "STATIONS_ADD_SONG_TO_QUEUE",
  1703. `Added song "${youtubeId}" to station "${stationId}" successfully.`
  1704. );
  1705. return cb({
  1706. status: "success",
  1707. message: "Successfully added song to queue."
  1708. });
  1709. }
  1710. );
  1711. }),
  1712. /**
  1713. * Removes song from station queue
  1714. *
  1715. * @param session
  1716. * @param stationId - the station id
  1717. * @param youtubeId - the youtube id
  1718. * @param cb
  1719. */
  1720. async removeFromQueue(session, stationId, youtubeId, cb) {
  1721. async.waterfall(
  1722. [
  1723. next => {
  1724. hasPermission("stations.queue.remove", session, stationId)
  1725. .then(() => next())
  1726. .catch(next);
  1727. },
  1728. next => {
  1729. if (!youtubeId) return next("Invalid youtube id.");
  1730. return StationsModule.runJob("REMOVE_FROM_QUEUE", { stationId, youtubeId }, this)
  1731. .then(() => next())
  1732. .catch(next);
  1733. }
  1734. ],
  1735. async err => {
  1736. if (err) {
  1737. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1738. this.log(
  1739. "ERROR",
  1740. "STATIONS_REMOVE_SONG_TO_QUEUE",
  1741. `Removing song "${youtubeId}" from station "${stationId}" queue failed. "${err}"`
  1742. );
  1743. return cb({ status: "error", message: err });
  1744. }
  1745. this.log(
  1746. "SUCCESS",
  1747. "STATIONS_REMOVE_SONG_TO_QUEUE",
  1748. `Removed song "${youtubeId}" from station "${stationId}" successfully.`
  1749. );
  1750. return cb({
  1751. status: "success",
  1752. message: "Successfully removed song from queue."
  1753. });
  1754. }
  1755. );
  1756. },
  1757. /**
  1758. * Gets the queue from a station
  1759. *
  1760. * @param {object} session - user session
  1761. * @param {string} stationId - the station id
  1762. * @param {Function} cb - callback
  1763. */
  1764. getQueue(session, stationId, cb) {
  1765. async.waterfall(
  1766. [
  1767. next => {
  1768. StationsModule.runJob("GET_STATION", { stationId }, this)
  1769. .then(station => next(null, station))
  1770. .catch(next);
  1771. },
  1772. (station, next) => {
  1773. if (!station) return next("Station not found.");
  1774. return next(null, station);
  1775. },
  1776. (station, next) => {
  1777. StationsModule.runJob("CAN_USER_VIEW_STATION", { station, userId: session.userId }, this)
  1778. .then(canView => {
  1779. if (canView) return next(null, station);
  1780. return next("Insufficient permissions.");
  1781. })
  1782. .catch(err => next(err));
  1783. },
  1784. (station, next) => next(null, station.queue)
  1785. ],
  1786. async (err, queue) => {
  1787. if (err) {
  1788. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1789. this.log(
  1790. "ERROR",
  1791. "STATIONS_GET_QUEUE",
  1792. `Getting queue for station "${stationId}" failed. "${err}"`
  1793. );
  1794. return cb({ status: "error", message: err });
  1795. }
  1796. this.log("SUCCESS", "STATIONS_GET_QUEUE", `Got queue for station "${stationId}" successfully.`);
  1797. return cb({
  1798. status: "success",
  1799. message: "Successfully got queue.",
  1800. data: { queue }
  1801. });
  1802. }
  1803. );
  1804. },
  1805. /**
  1806. * Reposition a song in station queue
  1807. *
  1808. * @param {object} session - user session
  1809. * @param {object} song - contains details about the song that is to be repositioned
  1810. * @param {string} song.youtubeId - the youtube id of the song
  1811. * @param {number} song.newIndex - the new position for the song in the queue
  1812. * @param {number} song.oldIndex - the old position of the song in the queue
  1813. * @param {string} stationId - the station id
  1814. * @param {Function} cb - callback
  1815. */
  1816. async repositionSongInQueue(session, stationId, song, cb) {
  1817. const stationModel = await DBModule.runJob("GET_MODEL", { modelName: "station" }, this);
  1818. async.waterfall(
  1819. [
  1820. next => {
  1821. hasPermission("stations.queue.reposition", session, stationId)
  1822. .then(() => next())
  1823. .catch(next);
  1824. },
  1825. next => {
  1826. if (!song || !song.youtubeId) return next("You must provide a song to reposition.");
  1827. return next();
  1828. },
  1829. // remove song from queue
  1830. next => {
  1831. stationModel.updateOne(
  1832. { _id: stationId },
  1833. { $pull: { queue: { youtubeId: song.youtubeId } } },
  1834. next
  1835. );
  1836. },
  1837. // add song back to queue (in new position)
  1838. (res, next) => {
  1839. stationModel.updateOne(
  1840. { _id: stationId },
  1841. { $push: { queue: { $each: [song], $position: song.newIndex } } },
  1842. err => next(err)
  1843. );
  1844. },
  1845. // update the cache representation of the station
  1846. next => {
  1847. StationsModule.runJob("UPDATE_STATION", { stationId }, this)
  1848. .then(station => next(null, station))
  1849. .catch(next);
  1850. }
  1851. ],
  1852. async err => {
  1853. if (err) {
  1854. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1855. this.log(
  1856. "ERROR",
  1857. "STATIONS_REPOSITION_SONG_IN_QUEUE",
  1858. `Repositioning song ${song.youtubeId} in queue of station "${stationId}" failed. "${err}"`
  1859. );
  1860. return cb({ status: "error", message: err });
  1861. }
  1862. this.log(
  1863. "SUCCESS",
  1864. "STATIONS_REPOSITION_SONG_IN_QUEUE",
  1865. `Repositioned song ${song.youtubeId} in queue of station "${stationId}" successfully.`
  1866. );
  1867. CacheModule.runJob("PUB", {
  1868. channel: "station.repositionSongInQueue",
  1869. value: {
  1870. song: {
  1871. youtubeId: song.youtubeId,
  1872. oldIndex: song.oldIndex,
  1873. newIndex: song.newIndex
  1874. },
  1875. stationId
  1876. }
  1877. });
  1878. return cb({
  1879. status: "success",
  1880. message: "Successfully repositioned song in queue."
  1881. });
  1882. }
  1883. );
  1884. },
  1885. /**
  1886. * Autofill a playlist in a station
  1887. *
  1888. * @param session
  1889. * @param stationId - the station id
  1890. * @param playlistId - the playlist id
  1891. * @param cb
  1892. */
  1893. async autofillPlaylist(session, stationId, playlistId, cb) {
  1894. async.waterfall(
  1895. [
  1896. next => {
  1897. hasPermission("stations.autofill", session, stationId)
  1898. .then(() => next())
  1899. .catch(next);
  1900. },
  1901. next => {
  1902. StationsModule.runJob("GET_STATION", { stationId }, this)
  1903. .then(station => next(null, station))
  1904. .catch(next);
  1905. },
  1906. (station, next) => {
  1907. if (!station) return next("Station not found.");
  1908. if (station.autofill.playlists.indexOf(playlistId) !== -1)
  1909. return next("That playlist is already autofilling.");
  1910. if (station.autofill.mode === "sequential" && station.autofill.playlists.length > 0)
  1911. return next("Error: Only 1 playlist can be autofilling in sequential mode.");
  1912. return next();
  1913. },
  1914. next => {
  1915. StationsModule.runJob("AUTOFILL_PLAYLIST", { stationId, playlistId }, this)
  1916. .then(() => {
  1917. next();
  1918. })
  1919. .catch(next);
  1920. }
  1921. ],
  1922. async err => {
  1923. if (err) {
  1924. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1925. this.log(
  1926. "ERROR",
  1927. "STATIONS_AUTOFILL_PLAYLIST",
  1928. `Including playlist "${playlistId}" for station "${stationId}" failed. "${err}"`
  1929. );
  1930. return cb({ status: "error", message: err });
  1931. }
  1932. this.log(
  1933. "SUCCESS",
  1934. "STATIONS_AUTOFILL_PLAYLIST",
  1935. `Including playlist "${playlistId}" for station "${stationId}" successfully.`
  1936. );
  1937. PlaylistsModule.runJob("AUTOFILL_STATION_PLAYLIST", { stationId }).then().catch();
  1938. CacheModule.runJob("PUB", {
  1939. channel: "station.autofillPlaylist",
  1940. value: {
  1941. playlistId,
  1942. stationId
  1943. }
  1944. });
  1945. return cb({
  1946. status: "success",
  1947. message: "Successfully added autofill playlist."
  1948. });
  1949. }
  1950. );
  1951. },
  1952. /**
  1953. * Remove autofilled playlist from a station
  1954. *
  1955. * @param session
  1956. * @param stationId - the station id
  1957. * @param playlistId - the playlist id
  1958. * @param cb
  1959. */
  1960. async removeAutofillPlaylist(session, stationId, playlistId, cb) {
  1961. async.waterfall(
  1962. [
  1963. next => {
  1964. hasPermission("stations.autofill", session, stationId)
  1965. .then(() => next())
  1966. .catch(next);
  1967. },
  1968. next => {
  1969. StationsModule.runJob("GET_STATION", { stationId }, this)
  1970. .then(station => next(null, station))
  1971. .catch(next);
  1972. },
  1973. (station, next) => {
  1974. if (!station) return next("Station not found.");
  1975. if (station.autofill.playlists.indexOf(playlistId) === -1)
  1976. return next("That playlist is not autofilling.");
  1977. return next();
  1978. },
  1979. next => {
  1980. StationsModule.runJob("REMOVE_AUTOFILL_PLAYLIST", { stationId, playlistId }, this)
  1981. .then(() => {
  1982. next();
  1983. })
  1984. .catch(next);
  1985. }
  1986. ],
  1987. async err => {
  1988. if (err) {
  1989. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1990. this.log(
  1991. "ERROR",
  1992. "STATIONS_REMOVE_AUTOFILL_PLAYLIST",
  1993. `Removing autofill playlist "${playlistId}" for station "${stationId}" failed. "${err}"`
  1994. );
  1995. return cb({ status: "error", message: err });
  1996. }
  1997. this.log(
  1998. "SUCCESS",
  1999. "STATIONS_REMOVE_AUTOFILL_PLAYLIST",
  2000. `Removing autofill playlist "${playlistId}" for station "${stationId}" successfully.`
  2001. );
  2002. PlaylistsModule.runJob("AUTOFILL_STATION_PLAYLIST", { stationId }).then().catch();
  2003. CacheModule.runJob("PUB", {
  2004. channel: "station.removedAutofillPlaylist",
  2005. value: {
  2006. playlistId,
  2007. stationId
  2008. }
  2009. });
  2010. return cb({
  2011. status: "success",
  2012. message: "Successfully removed autofill playlist."
  2013. });
  2014. }
  2015. );
  2016. },
  2017. /**
  2018. * Blacklist a playlist in a station
  2019. *
  2020. * @param session
  2021. * @param stationId - the station id
  2022. * @param playlistId - the playlist id
  2023. * @param cb
  2024. */
  2025. async blacklistPlaylist(session, stationId, playlistId, cb) {
  2026. async.waterfall(
  2027. [
  2028. next => {
  2029. hasPermission("stations.blacklist", session, stationId)
  2030. .then(() => next())
  2031. .catch(next);
  2032. },
  2033. next => {
  2034. StationsModule.runJob("GET_STATION", { stationId }, this)
  2035. .then(station => next(null, station))
  2036. .catch(next);
  2037. },
  2038. (station, next) => {
  2039. if (!station) return next("Station not found.");
  2040. if (station.blacklist.indexOf(playlistId) !== -1)
  2041. return next("That playlist is already blacklisted.");
  2042. return next();
  2043. },
  2044. next => {
  2045. StationsModule.runJob("BLACKLIST_PLAYLIST", { stationId, playlistId }, this)
  2046. .then(() => {
  2047. next();
  2048. })
  2049. .catch(next);
  2050. }
  2051. ],
  2052. async err => {
  2053. if (err) {
  2054. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  2055. this.log(
  2056. "ERROR",
  2057. "STATIONS_BLACKLIST_PLAYLIST",
  2058. `Blacklisting playlist "${playlistId}" for station "${stationId}" failed. "${err}"`
  2059. );
  2060. return cb({ status: "error", message: err });
  2061. }
  2062. this.log(
  2063. "SUCCESS",
  2064. "STATIONS_BLACKLIST_PLAYLIST",
  2065. `Blacklisting playlist "${playlistId}" for station "${stationId}" successfully.`
  2066. );
  2067. PlaylistsModule.runJob("AUTOFILL_STATION_PLAYLIST", { stationId }).then().catch();
  2068. CacheModule.runJob("PUB", {
  2069. channel: "station.blacklistedPlaylist",
  2070. value: {
  2071. playlistId,
  2072. stationId
  2073. }
  2074. });
  2075. return cb({
  2076. status: "success",
  2077. message: "Successfully blacklisted playlist."
  2078. });
  2079. }
  2080. );
  2081. },
  2082. /**
  2083. * Remove blacklisted a playlist from a station
  2084. *
  2085. * @param session
  2086. * @param stationId - the station id
  2087. * @param playlistId - the playlist id
  2088. * @param cb
  2089. */
  2090. async removeBlacklistedPlaylist(session, stationId, playlistId, cb) {
  2091. async.waterfall(
  2092. [
  2093. next => {
  2094. hasPermission("stations.blacklist", session, stationId)
  2095. .then(() => next())
  2096. .catch(next);
  2097. },
  2098. next => {
  2099. StationsModule.runJob("GET_STATION", { stationId }, this)
  2100. .then(station => next(null, station))
  2101. .catch(next);
  2102. },
  2103. (station, next) => {
  2104. if (!station) return next("Station not found.");
  2105. if (station.blacklist.indexOf(playlistId) === -1) return next("That playlist is not blacklisted.");
  2106. return next();
  2107. },
  2108. next => {
  2109. StationsModule.runJob("REMOVE_BLACKLISTED_PLAYLIST", { stationId, playlistId }, this)
  2110. .then(() => {
  2111. next();
  2112. })
  2113. .catch(next);
  2114. }
  2115. ],
  2116. async err => {
  2117. if (err) {
  2118. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  2119. this.log(
  2120. "ERROR",
  2121. "STATIONS_REMOVE_BLACKLISTED_PLAYLIST",
  2122. `Removing blacklisted playlist "${playlistId}" for station "${stationId}" failed. "${err}"`
  2123. );
  2124. return cb({ status: "error", message: err });
  2125. }
  2126. this.log(
  2127. "SUCCESS",
  2128. "STATIONS_REMOVE_BLACKLISTED_PLAYLIST",
  2129. `Removing blacklisted playlist "${playlistId}" for station "${stationId}" successfully.`
  2130. );
  2131. PlaylistsModule.runJob("AUTOFILL_STATION_PLAYLIST", { stationId }).then().catch();
  2132. CacheModule.runJob("PUB", {
  2133. channel: "station.removedBlacklistedPlaylist",
  2134. value: {
  2135. playlistId,
  2136. stationId
  2137. }
  2138. });
  2139. return cb({
  2140. status: "success",
  2141. message: "Successfully removed blacklisted playlist."
  2142. });
  2143. }
  2144. );
  2145. },
  2146. favoriteStation: isLoginRequired(async function favoriteStation(session, stationId, cb) {
  2147. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  2148. async.waterfall(
  2149. [
  2150. next => {
  2151. StationsModule.runJob("GET_STATION", { stationId }, this)
  2152. .then(station => next(null, station))
  2153. .catch(next);
  2154. },
  2155. (station, next) => {
  2156. if (!station) return next("Station not found.");
  2157. return StationsModule.runJob("CAN_USER_VIEW_STATION", { station, userId: session.userId }, this)
  2158. .then(canView => {
  2159. if (canView) return next(null, station);
  2160. return next("Insufficient permissions.");
  2161. })
  2162. .catch(err => next(err));
  2163. },
  2164. (station, next) => {
  2165. userModel.updateOne(
  2166. { _id: session.userId },
  2167. { $addToSet: { favoriteStations: stationId } },
  2168. (err, res) => next(err, station, res)
  2169. );
  2170. },
  2171. (station, res, next) => {
  2172. if (res.nModified === 0) return next("The station was already favorited.");
  2173. return next(null, station);
  2174. }
  2175. ],
  2176. async (err, station) => {
  2177. if (err) {
  2178. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  2179. this.log("ERROR", "FAVORITE_STATION", `Favoriting station "${stationId}" failed. "${err}"`);
  2180. return cb({ status: "error", message: err });
  2181. }
  2182. this.log("SUCCESS", "FAVORITE_STATION", `Favorited station "${stationId}" successfully.`);
  2183. CacheModule.runJob("PUB", {
  2184. channel: "user.favoritedStation",
  2185. value: {
  2186. userId: session.userId,
  2187. stationId
  2188. }
  2189. });
  2190. ActivitiesModule.runJob("ADD_ACTIVITY", {
  2191. userId: session.userId,
  2192. type: "station__favorite",
  2193. payload: {
  2194. message: `Favorited station <stationId>${station.displayName}</stationId>`,
  2195. stationId
  2196. }
  2197. });
  2198. return cb({
  2199. status: "success",
  2200. message: "Succesfully favorited station."
  2201. });
  2202. }
  2203. );
  2204. }),
  2205. unfavoriteStation: isLoginRequired(async function unfavoriteStation(session, stationId, cb) {
  2206. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  2207. async.waterfall(
  2208. [
  2209. next => {
  2210. userModel.updateOne({ _id: session.userId }, { $pull: { favoriteStations: stationId } }, next);
  2211. },
  2212. (res, next) => {
  2213. if (res.nModified === 0) return next("The station wasn't favorited.");
  2214. return next();
  2215. },
  2216. next => {
  2217. StationsModule.runJob("GET_STATION", { stationId }, this)
  2218. .then(station => next(null, station))
  2219. .catch(next);
  2220. }
  2221. ],
  2222. async (err, station) => {
  2223. if (err) {
  2224. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  2225. this.log("ERROR", "UNFAVORITE_STATION", `Unfavoriting station "${stationId}" failed. "${err}"`);
  2226. return cb({ status: "error", message: err });
  2227. }
  2228. this.log("SUCCESS", "UNFAVORITE_STATION", `Unfavorited station "${stationId}" successfully.`);
  2229. CacheModule.runJob("PUB", {
  2230. channel: "user.unfavoritedStation",
  2231. value: {
  2232. userId: session.userId,
  2233. stationId
  2234. }
  2235. });
  2236. ActivitiesModule.runJob("ADD_ACTIVITY", {
  2237. userId: session.userId,
  2238. type: "station__unfavorite",
  2239. payload: {
  2240. message: `Unfavorited station <stationId>${station.displayName}</stationId>`,
  2241. stationId
  2242. }
  2243. });
  2244. return cb({
  2245. status: "success",
  2246. message: "Succesfully unfavorited station."
  2247. });
  2248. }
  2249. );
  2250. }),
  2251. /**
  2252. * Clears every station queue
  2253. *
  2254. * @param {object} session - the session object automatically added by socket.io
  2255. * @param {Function} cb - gets called with the result
  2256. */
  2257. clearEveryStationQueue: useHasPermission(
  2258. "stations.clearEveryStationQueue",
  2259. async function clearEveryStationQueue(session, cb) {
  2260. this.keepLongJob();
  2261. this.publishProgress({
  2262. status: "started",
  2263. title: "Clear every station queue",
  2264. message: "Clearing every station queue.",
  2265. id: this.toString()
  2266. });
  2267. await CacheModule.runJob("RPUSH", { key: `longJobs.${session.userId}`, value: this.toString() }, this);
  2268. await CacheModule.runJob(
  2269. "PUB",
  2270. {
  2271. channel: "longJob.added",
  2272. value: { jobId: this.toString(), userId: session.userId }
  2273. },
  2274. this
  2275. );
  2276. async.waterfall(
  2277. [
  2278. next => {
  2279. StationsModule.runJob("CLEAR_EVERY_STATION_QUEUE", {}, this)
  2280. .then(() => next())
  2281. .catch(next);
  2282. }
  2283. ],
  2284. async err => {
  2285. if (err) {
  2286. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  2287. this.log("ERROR", "CLEAR_EVERY_STATION_QUEUE", `Clearing every station queue failed. "${err}"`);
  2288. this.publishProgress({
  2289. status: "error",
  2290. message: err
  2291. });
  2292. return cb({ status: "error", message: err });
  2293. }
  2294. this.log("SUCCESS", "CLEAR_EVERY_STATION_QUEUE", "Clearing every station queue was successful.");
  2295. this.publishProgress({
  2296. status: "success",
  2297. message: "Successfully cleared every station queue."
  2298. });
  2299. return cb({ status: "success", message: "Successfully cleared every station queue." });
  2300. }
  2301. );
  2302. }
  2303. ),
  2304. /**
  2305. * Reset a station queue
  2306. *
  2307. * @param {object} session - the session object automatically added by socket.io
  2308. * @param {string} stationId - the station id
  2309. * @param {Function} cb - gets called with the result
  2310. */
  2311. async resetQueue(session, stationId, cb) {
  2312. async.waterfall(
  2313. [
  2314. next => {
  2315. hasPermission("stations.queue.reset", session, stationId)
  2316. .then(() => next())
  2317. .catch(next);
  2318. },
  2319. next => {
  2320. StationsModule.runJob("RESET_QUEUE", { stationId }, this)
  2321. .then(() => next())
  2322. .catch(next);
  2323. }
  2324. ],
  2325. async err => {
  2326. if (err) {
  2327. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  2328. this.log("ERROR", "RESET_QUEUE", `Resetting station queue failed. "${err}"`);
  2329. return cb({ status: "error", message: err });
  2330. }
  2331. this.log("SUCCESS", "RESET_QUEUE", "Resetting station queue was successful.");
  2332. return cb({ status: "success", message: "Successfully reset station queue." });
  2333. }
  2334. );
  2335. },
  2336. /**
  2337. * Gets skip votes for a station
  2338. *
  2339. * @param session
  2340. * @param stationId - the station id
  2341. * @param stationId - the song id to get skipvotes for
  2342. * @param cb
  2343. */
  2344. getSkipVotes: isLoginRequired(async function getSkipVotes(session, stationId, songId, cb) {
  2345. async.waterfall(
  2346. [
  2347. next => {
  2348. StationsModule.runJob("GET_STATION", { stationId }, this)
  2349. .then(res => next(null, res.currentSong))
  2350. .catch(console.log);
  2351. },
  2352. (currentSong, next) => {
  2353. if (currentSong && currentSong._id === songId)
  2354. next(null, {
  2355. skipVotes: currentSong.skipVotes.length,
  2356. skipVotesCurrent: true
  2357. });
  2358. else
  2359. next(null, {
  2360. skipVotes: 0,
  2361. skipVotesCurrent: false
  2362. });
  2363. }
  2364. ],
  2365. async (err, data) => {
  2366. if (err) {
  2367. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  2368. this.log(
  2369. "ERROR",
  2370. "STATIONS_GET_SKIP_VOTES",
  2371. `User "${session.userId}" failed to get skip votes for ${stationId}. "${err}"`
  2372. );
  2373. return cb({ status: "error", message: err });
  2374. }
  2375. const { skipVotes, skipVotesCurrent } = data;
  2376. return cb({
  2377. status: "success",
  2378. data: {
  2379. skipVotes,
  2380. skipVotesCurrent
  2381. }
  2382. });
  2383. }
  2384. );
  2385. }),
  2386. /**
  2387. * Add DJ to station
  2388. *
  2389. * @param {object} session - the session object automatically added by socket.io
  2390. * @param {string} stationId - the station id
  2391. * @param {string} userId - the dj user id
  2392. * @param {Function} cb - gets called with the result
  2393. */
  2394. async addDj(session, stationId, userId, cb) {
  2395. async.waterfall(
  2396. [
  2397. next => {
  2398. hasPermission("stations.djs.add", session, stationId)
  2399. .then(() => next())
  2400. .catch(next);
  2401. },
  2402. next => {
  2403. StationsModule.runJob("ADD_DJ", { stationId, userId }, this)
  2404. .then(() => next())
  2405. .catch(next);
  2406. }
  2407. ],
  2408. async err => {
  2409. if (err) {
  2410. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  2411. this.log("ERROR", "ADD_DJ", `Adding DJ failed. "${err}"`);
  2412. return cb({ status: "error", message: err });
  2413. }
  2414. this.log("SUCCESS", "ADD_DJ", "Adding DJ was successful.");
  2415. return cb({ status: "success", message: "Successfully added DJ." });
  2416. }
  2417. );
  2418. },
  2419. /**
  2420. * Remove DJ from station
  2421. *
  2422. * @param {object} session - the session object automatically added by socket.io
  2423. * @param {string} stationId - the station id
  2424. * @param {string} userId - the dj user id
  2425. * @param {Function} cb - gets called with the result
  2426. */
  2427. async removeDj(session, stationId, userId, cb) {
  2428. async.waterfall(
  2429. [
  2430. next => {
  2431. hasPermission("stations.djs.remove", session, stationId)
  2432. .then(() => next())
  2433. .catch(next);
  2434. },
  2435. next => {
  2436. StationsModule.runJob("REMOVE_DJ", { stationId, userId }, this)
  2437. .then(() => next())
  2438. .catch(next);
  2439. }
  2440. ],
  2441. async err => {
  2442. if (err) {
  2443. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  2444. this.log("ERROR", "REMOVE_DJ", `Removing DJ failed. "${err}"`);
  2445. return cb({ status: "error", message: err });
  2446. }
  2447. this.log("SUCCESS", "REMOVE_DJ", "Removing DJ was successful.");
  2448. return cb({ status: "success", message: "Successfully removed DJ." });
  2449. }
  2450. );
  2451. }
  2452. };