stations.js 73 KB

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