stations.js 73 KB

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