stations.js 73 KB

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