stations.js 71 KB

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