stations.js 72 KB

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