stations.js 75 KB

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