stations.js 67 KB

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