stations.js 75 KB

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