stations.js 72 KB

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