stations.js 74 KB

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