stations.js 67 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641
  1. import async from "async";
  2. import mongoose from "mongoose";
  3. import config from "config";
  4. import { hasPermission, useHasPermission, getUserPermissions } 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. "admin.view.stations",
  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. (data, next) => {
  782. getUserPermissions(session.userId, data._id)
  783. .then(permissions => {
  784. data.permissions = permissions;
  785. next(null, data);
  786. })
  787. .catch(() => {
  788. data.permissions = {};
  789. next(null, data);
  790. });
  791. }
  792. ],
  793. async (err, data) => {
  794. if (err) {
  795. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  796. this.log("ERROR", "STATIONS_JOIN", `Joining station "${stationIdentifier}" failed. "${err}"`);
  797. return cb({ status: "error", message: err });
  798. }
  799. this.log("SUCCESS", "STATIONS_JOIN", `Joined station "${data._id}" successfully.`);
  800. return cb({ status: "success", data });
  801. }
  802. );
  803. },
  804. /**
  805. * Gets a station by id
  806. *
  807. * @param {object} session - user session
  808. * @param {string} stationId - the station id
  809. * @param {Function} cb - callback
  810. */
  811. getStationById(session, stationId, cb) {
  812. async.waterfall(
  813. [
  814. next => {
  815. StationsModule.runJob("GET_STATION", { stationId }, this)
  816. .then(station => {
  817. next(null, station);
  818. })
  819. .catch(next);
  820. },
  821. (station, next) => {
  822. if (!station) return next("Station not found.");
  823. return StationsModule.runJob(
  824. "CAN_USER_VIEW_STATION",
  825. {
  826. station,
  827. userId: session.userId
  828. },
  829. this
  830. )
  831. .then(canView => {
  832. if (!canView) next("Not allowed to get station.");
  833. else next(null, station);
  834. })
  835. .catch(err => next(err));
  836. },
  837. (station, next) => {
  838. // only relevant if user logged in
  839. if (session.userId) {
  840. return StationsModule.runJob(
  841. "HAS_USER_FAVORITED_STATION",
  842. {
  843. userId: session.userId,
  844. stationId
  845. },
  846. this
  847. )
  848. .then(isStationFavorited => {
  849. station.isFavorited = isStationFavorited;
  850. return next(null, station);
  851. })
  852. .catch(err => next(err));
  853. }
  854. return next(null, station);
  855. },
  856. (station, next) => {
  857. const data = {
  858. _id: station._id,
  859. type: station.type,
  860. description: station.description,
  861. displayName: station.displayName,
  862. name: station.name,
  863. privacy: station.privacy,
  864. requests: station.requests,
  865. autofill: station.autofill,
  866. owner: station.owner,
  867. theme: station.theme,
  868. paused: station.paused,
  869. currentSong: station.currentSong,
  870. isFavorited: station.isFavorited
  871. };
  872. next(null, data);
  873. },
  874. (data, next) => {
  875. getUserPermissions(session.userId, data._id)
  876. .then(permissions => {
  877. data.permissions = permissions;
  878. next(null, data);
  879. })
  880. .catch(() => {
  881. data.permissions = {};
  882. next(null, data);
  883. });
  884. }
  885. ],
  886. async (err, data) => {
  887. if (err) {
  888. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  889. this.log("ERROR", "GET_STATION_BY_ID", `Getting station "${stationId}" failed. "${err}"`);
  890. return cb({ status: "error", message: err });
  891. }
  892. this.log("SUCCESS", "GET_STATION_BY_ID", `Got station "${stationId}" successfully.`);
  893. return cb({ status: "success", data: { station: data } });
  894. }
  895. );
  896. },
  897. getStationAutofillPlaylistsById(session, stationId, cb) {
  898. async.waterfall(
  899. [
  900. next => {
  901. StationsModule.runJob("GET_STATION", { stationId }, this)
  902. .then(station => {
  903. next(null, station);
  904. })
  905. .catch(next);
  906. },
  907. (station, next) => {
  908. if (!station) return next("Station not found.");
  909. return StationsModule.runJob(
  910. "CAN_USER_VIEW_STATION",
  911. {
  912. station,
  913. userId: session.userId
  914. },
  915. this
  916. )
  917. .then(canView => {
  918. if (!canView) next("Not allowed to get station.");
  919. else next(null, station);
  920. })
  921. .catch(err => next(err));
  922. },
  923. (station, next) => {
  924. const playlists = [];
  925. async.eachLimit(
  926. station.autofill.playlists,
  927. 1,
  928. (playlistId, next) => {
  929. PlaylistsModule.runJob("GET_PLAYLIST", { playlistId }, this)
  930. .then(playlist => {
  931. playlists.push(playlist);
  932. next();
  933. })
  934. .catch(() => {
  935. playlists.push(null);
  936. next();
  937. });
  938. },
  939. err => {
  940. next(err, playlists);
  941. }
  942. );
  943. }
  944. ],
  945. async (err, playlists) => {
  946. if (err) {
  947. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  948. this.log(
  949. "ERROR",
  950. "GET_STATION_AUTOFILL_PLAYLISTS_BY_ID",
  951. `Getting station "${stationId}"'s autofilling playlists failed. "${err}"`
  952. );
  953. return cb({ status: "error", message: err });
  954. }
  955. this.log(
  956. "SUCCESS",
  957. "GET_STATION_AUTOFILL_PLAYLISTS_BY_ID",
  958. `Got station "${stationId}"'s autofilling playlists successfully.`
  959. );
  960. return cb({ status: "success", data: { playlists } });
  961. }
  962. );
  963. },
  964. getStationBlacklistById(session, stationId, cb) {
  965. async.waterfall(
  966. [
  967. next => {
  968. StationsModule.runJob("GET_STATION", { stationId }, this)
  969. .then(station => {
  970. next(null, station);
  971. })
  972. .catch(next);
  973. },
  974. (station, next) => {
  975. if (!station) return next("Station not found.");
  976. return StationsModule.runJob(
  977. "CAN_USER_VIEW_STATION",
  978. {
  979. station,
  980. userId: session.userId
  981. },
  982. this
  983. )
  984. .then(canView => {
  985. if (!canView) next("Not allowed to get station.");
  986. else next(null, station);
  987. })
  988. .catch(err => next(err));
  989. },
  990. (station, next) => {
  991. const playlists = [];
  992. async.eachLimit(
  993. station.blacklist,
  994. 1,
  995. (playlistId, next) => {
  996. PlaylistsModule.runJob("GET_PLAYLIST", { playlistId }, this)
  997. .then(playlist => {
  998. playlists.push(playlist);
  999. next();
  1000. })
  1001. .catch(() => {
  1002. playlists.push(null);
  1003. next();
  1004. });
  1005. },
  1006. err => {
  1007. next(err, playlists);
  1008. }
  1009. );
  1010. }
  1011. ],
  1012. async (err, playlists) => {
  1013. if (err) {
  1014. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1015. this.log(
  1016. "ERROR",
  1017. "GET_STATION_BLACKLIST_BY_ID",
  1018. `Getting station "${stationId}"'s blacklist failed. "${err}"`
  1019. );
  1020. return cb({ status: "error", message: err });
  1021. }
  1022. this.log(
  1023. "SUCCESS",
  1024. "GET_STATION_BLACKLIST_BY_ID",
  1025. `Got station "${stationId}"'s blacklist successfully.`
  1026. );
  1027. return cb({ status: "success", data: { playlists } });
  1028. }
  1029. );
  1030. },
  1031. /**
  1032. * Votes to skip a station
  1033. *
  1034. * @param session
  1035. * @param stationId - the station id
  1036. * @param cb
  1037. */
  1038. voteSkip: isLoginRequired(async function voteSkip(session, stationId, cb) {
  1039. const stationModel = await DBModule.runJob("GET_MODEL", { modelName: "station" }, this);
  1040. async.waterfall(
  1041. [
  1042. next => {
  1043. StationsModule.runJob("GET_STATION", { stationId }, this)
  1044. .then(station => next(null, station))
  1045. .catch(next);
  1046. },
  1047. (station, next) => {
  1048. if (!station) return next("Station not found.");
  1049. return StationsModule.runJob("CAN_USER_VIEW_STATION", { station, userId: session.userId }, this)
  1050. .then(canView => {
  1051. if (canView) return next(null, station);
  1052. return next("Insufficient permissions.");
  1053. })
  1054. .catch(err => next(err));
  1055. },
  1056. (station, next) => {
  1057. if (!station.currentSong) return next("There is currently no song to skip.");
  1058. if (station.currentSong.skipVotes.indexOf(session.userId) !== -1)
  1059. return next("You have already voted to skip this song.");
  1060. return next(null, station);
  1061. },
  1062. (station, next) => {
  1063. stationModel.updateOne(
  1064. { _id: stationId },
  1065. { $push: { "currentSong.skipVotes": session.userId } },
  1066. next
  1067. );
  1068. },
  1069. (res, next) => {
  1070. StationsModule.runJob("UPDATE_STATION", { stationId }, this)
  1071. .then(station => {
  1072. next(null, station);
  1073. })
  1074. .catch(next);
  1075. },
  1076. (station, next) => {
  1077. if (!station) return next("Station not found.");
  1078. return StationsModule.runJob("PROCESS_VOTE_SKIPS", { stationId }, this)
  1079. .then(() => next())
  1080. .catch(next);
  1081. }
  1082. ],
  1083. async err => {
  1084. if (err) {
  1085. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1086. this.log("ERROR", "STATIONS_VOTE_SKIP", `Vote skipping station "${stationId}" failed. "${err}"`);
  1087. return cb({ status: "error", message: err });
  1088. }
  1089. this.log("SUCCESS", "STATIONS_VOTE_SKIP", `Vote skipping "${stationId}" successful.`);
  1090. CacheModule.runJob("PUB", {
  1091. channel: "station.voteSkipSong",
  1092. value: stationId
  1093. });
  1094. return cb({
  1095. status: "success",
  1096. message: "Successfully voted to skip the song."
  1097. });
  1098. }
  1099. );
  1100. }),
  1101. /**
  1102. * Force skips a station
  1103. *
  1104. * @param session
  1105. * @param stationId - the station id
  1106. * @param cb
  1107. */
  1108. forceSkip(session, stationId, cb) {
  1109. async.waterfall(
  1110. [
  1111. next => {
  1112. hasPermission("stations.skip", session, stationId)
  1113. .then(() => next())
  1114. .catch(next);
  1115. },
  1116. next => {
  1117. StationsModule.runJob("GET_STATION", { stationId }, this)
  1118. .then(station => {
  1119. next(null, station);
  1120. })
  1121. .catch(next);
  1122. },
  1123. (station, next) => {
  1124. if (!station) return next("Station not found.");
  1125. return next();
  1126. }
  1127. ],
  1128. async err => {
  1129. if (err) {
  1130. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1131. this.log("ERROR", "STATIONS_FORCE_SKIP", `Force skipping station "${stationId}" failed. "${err}"`);
  1132. return cb({ status: "error", message: err });
  1133. }
  1134. StationsModule.runJob("SKIP_STATION", { stationId, natural: false });
  1135. this.log("SUCCESS", "STATIONS_FORCE_SKIP", `Force skipped station "${stationId}" successfully.`);
  1136. return cb({
  1137. status: "success",
  1138. message: "Successfully skipped station."
  1139. });
  1140. }
  1141. );
  1142. },
  1143. /**
  1144. * Leaves the user's current station
  1145. *
  1146. * @param {object} session - user session
  1147. * @param {string} stationId - id of station to leave
  1148. * @param {Function} cb - callback
  1149. */
  1150. leave(session, stationId, cb) {
  1151. async.waterfall(
  1152. [
  1153. next => {
  1154. StationsModule.runJob("GET_STATION", { stationId }, this)
  1155. .then(station => next(null, station))
  1156. .catch(next);
  1157. },
  1158. (station, next) => {
  1159. if (!station) return next("Station not found.");
  1160. return next();
  1161. }
  1162. ],
  1163. async (err, userCount) => {
  1164. if (err) {
  1165. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1166. this.log("ERROR", "STATIONS_LEAVE", `Leaving station "${stationId}" failed. "${err}"`);
  1167. return cb({ status: "error", message: err });
  1168. }
  1169. this.log("SUCCESS", "STATIONS_LEAVE", `Left station "${stationId}" successfully.`);
  1170. WSModule.runJob("SOCKET_LEAVE_ROOM", { socketId: session.socketId, room: `station.${stationId}` });
  1171. WSModule.runJob("SOCKETS_LEAVE_SONG_ROOMS", { sockets: [session.socketId] });
  1172. delete StationsModule.userList[session.socketId];
  1173. return cb({
  1174. status: "success",
  1175. message: "Successfully left station.",
  1176. data: { userCount }
  1177. });
  1178. }
  1179. );
  1180. },
  1181. /**
  1182. * Updates a station's settings
  1183. *
  1184. * @param session
  1185. * @param stationId - the station id
  1186. * @param station - updated station object
  1187. * @param newStation
  1188. * @param cb
  1189. */
  1190. async update(session, stationId, newStation, cb) {
  1191. const stationModel = await DBModule.runJob("GET_MODEL", { modelName: "station" }, this);
  1192. const playlistModel = await DBModule.runJob("GET_MODEL", { modelName: "playlist" }, this);
  1193. async.waterfall(
  1194. [
  1195. next => {
  1196. hasPermission("stations.update", session, stationId)
  1197. .then(() => next())
  1198. .catch(next);
  1199. },
  1200. next => {
  1201. stationModel.findOne({ _id: stationId }, next);
  1202. },
  1203. (previousStation, next) => {
  1204. const { name, displayName, description, privacy, requests, autofill, theme } = newStation;
  1205. const { enabled, limit, mode } = autofill;
  1206. // This object makes sure only certain properties can be changed by a user
  1207. const setObject = {
  1208. name,
  1209. displayName,
  1210. description,
  1211. privacy,
  1212. requests,
  1213. "autofill.enabled": enabled,
  1214. "autofill.limit": limit,
  1215. "autofill.mode": mode,
  1216. theme
  1217. };
  1218. stationModel.updateOne({ _id: stationId }, { $set: setObject }, { runValidators: true }, err => {
  1219. next(err, previousStation);
  1220. });
  1221. },
  1222. (previousStation, next) => {
  1223. StationsModule.runJob("UPDATE_STATION", { stationId }, this)
  1224. .then(station => next(null, station, previousStation))
  1225. .catch(next);
  1226. },
  1227. (station, previousStation, next) => {
  1228. if (
  1229. newStation.autofill.enabled &&
  1230. JSON.stringify(newStation.autofill) !== JSON.stringify(previousStation.autofill)
  1231. )
  1232. StationsModule.runJob("AUTOFILL_STATION", { stationId }, this)
  1233. .then(() => {
  1234. CacheModule.runJob("PUB", {
  1235. channel: "station.queueUpdate",
  1236. value: stationId
  1237. })
  1238. .then(() => next(null, station, previousStation))
  1239. .catch(next);
  1240. })
  1241. .catch(err => {
  1242. if (err === "Autofill is disabled in this station" || err === "Autofill limit reached")
  1243. next(null, station, previousStation);
  1244. else next(err);
  1245. });
  1246. else next(null, station, previousStation);
  1247. },
  1248. (station, previousStation, next) => {
  1249. playlistModel.updateOne(
  1250. { _id: station.playlist },
  1251. { $set: { displayName: `Station - ${station.displayName}` } },
  1252. err => {
  1253. next(err, station, previousStation);
  1254. }
  1255. );
  1256. }
  1257. ],
  1258. async (err, station, previousStation) => {
  1259. if (err) {
  1260. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1261. this.log("ERROR", "STATIONS_UPDATE", `Updating station "${stationId}" failed. "${err}"`);
  1262. return cb({ status: "error", message: err });
  1263. }
  1264. this.log("SUCCESS", "STATIONS_UPDATE", `Updated station "${stationId}" successfully.`);
  1265. CacheModule.runJob("PUB", {
  1266. channel: "station.updated",
  1267. value: { stationId, previousStation }
  1268. });
  1269. return cb({
  1270. status: "success",
  1271. message: "Successfully updated the station."
  1272. });
  1273. }
  1274. );
  1275. },
  1276. /**
  1277. * Pauses a station
  1278. *
  1279. * @param session
  1280. * @param stationId - the station id
  1281. * @param cb
  1282. */
  1283. async pause(session, stationId, cb) {
  1284. const stationModel = await DBModule.runJob(
  1285. "GET_MODEL",
  1286. {
  1287. modelName: "station"
  1288. },
  1289. this
  1290. );
  1291. async.waterfall(
  1292. [
  1293. next => {
  1294. hasPermission("stations.playback.toggle", session, stationId)
  1295. .then(() => next())
  1296. .catch(next);
  1297. },
  1298. next => {
  1299. StationsModule.runJob("GET_STATION", { stationId }, this)
  1300. .then(station => {
  1301. next(null, station);
  1302. })
  1303. .catch(next);
  1304. },
  1305. (station, next) => {
  1306. if (!station) return next("Station not found.");
  1307. if (station.paused) return next("That station was already paused.");
  1308. return stationModel.updateOne(
  1309. { _id: stationId },
  1310. { $set: { paused: true, pausedAt: Date.now() } },
  1311. next
  1312. );
  1313. },
  1314. (res, next) => {
  1315. StationsModule.runJob("UPDATE_STATION", { stationId }, this)
  1316. .then(() => next())
  1317. .catch(next);
  1318. }
  1319. ],
  1320. async err => {
  1321. if (err) {
  1322. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1323. this.log("ERROR", "STATIONS_PAUSE", `Pausing station "${stationId}" failed. "${err}"`);
  1324. return cb({ status: "error", message: err });
  1325. }
  1326. this.log("SUCCESS", "STATIONS_PAUSE", `Paused station "${stationId}" successfully.`);
  1327. CacheModule.runJob("PUB", {
  1328. channel: "station.pause",
  1329. value: stationId
  1330. });
  1331. NotificationsModule.runJob("UNSCHEDULE", {
  1332. name: `stations.nextSong?id=${stationId}`
  1333. });
  1334. return cb({
  1335. status: "success",
  1336. message: "Successfully paused."
  1337. });
  1338. }
  1339. );
  1340. },
  1341. /**
  1342. * Resumes a station
  1343. *
  1344. * @param session
  1345. * @param stationId - the station id
  1346. * @param cb
  1347. */
  1348. async resume(session, stationId, cb) {
  1349. const stationModel = await DBModule.runJob(
  1350. "GET_MODEL",
  1351. {
  1352. modelName: "station"
  1353. },
  1354. this
  1355. );
  1356. async.waterfall(
  1357. [
  1358. next => {
  1359. hasPermission("stations.playback.toggle", session, stationId)
  1360. .then(() => next())
  1361. .catch(next);
  1362. },
  1363. next => {
  1364. StationsModule.runJob("GET_STATION", { stationId }, this)
  1365. .then(station => {
  1366. next(null, station);
  1367. })
  1368. .catch(next);
  1369. },
  1370. (station, next) => {
  1371. if (!station) return next("Station not found.");
  1372. if (!station.paused) return next("That station is not paused.");
  1373. station.timePaused += Date.now() - station.pausedAt;
  1374. return stationModel.updateOne(
  1375. { _id: stationId },
  1376. {
  1377. $set: { paused: false },
  1378. $inc: { timePaused: Date.now() - station.pausedAt }
  1379. },
  1380. next
  1381. );
  1382. },
  1383. (res, next) => {
  1384. StationsModule.runJob("UPDATE_STATION", { stationId }, this)
  1385. .then(() => next())
  1386. .catch(next);
  1387. },
  1388. next => {
  1389. StationsModule.runJob("PROCESS_VOTE_SKIPS", { stationId }, this)
  1390. .then(() => next())
  1391. .catch(next);
  1392. }
  1393. ],
  1394. async err => {
  1395. if (err) {
  1396. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1397. this.log("ERROR", "STATIONS_RESUME", `Resuming station "${stationId}" failed. "${err}"`);
  1398. return cb({ status: "error", message: err });
  1399. }
  1400. this.log("SUCCESS", "STATIONS_RESUME", `Resuming station "${stationId}" successfully.`);
  1401. CacheModule.runJob("PUB", {
  1402. channel: "station.resume",
  1403. value: stationId
  1404. });
  1405. return cb({
  1406. status: "success",
  1407. message: "Successfully resumed."
  1408. });
  1409. }
  1410. );
  1411. },
  1412. /**
  1413. * Removes a station
  1414. *
  1415. * @param session
  1416. * @param stationId - the station id
  1417. * @param cb
  1418. */
  1419. async remove(session, stationId, cb) {
  1420. const stationModel = await DBModule.runJob("GET_MODEL", { modelName: "station" }, this);
  1421. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  1422. async.waterfall(
  1423. [
  1424. next => {
  1425. hasPermission("stations.remove", session, stationId)
  1426. .then(() => next())
  1427. .catch(next);
  1428. },
  1429. next => {
  1430. stationModel.findById(stationId, (err, station) => {
  1431. if (err) return next(err);
  1432. return next(null, station);
  1433. });
  1434. },
  1435. (station, next) => {
  1436. stationModel.deleteOne({ _id: stationId }, err => next(err, station));
  1437. },
  1438. (station, next) => {
  1439. CacheModule.runJob("HDEL", { table: "stations", key: stationId }, this)
  1440. .then(() => next(null, station))
  1441. .catch(next);
  1442. },
  1443. // remove the playlist for the station
  1444. (station, next) => {
  1445. if (station.playlist)
  1446. PlaylistsModule.runJob("DELETE_PLAYLIST", { playlistId: station.playlist })
  1447. .then(() => {})
  1448. .catch(next);
  1449. next(null, station);
  1450. },
  1451. // remove reference to the station id in any array of a user's favorite stations
  1452. (station, next) => {
  1453. userModel.updateMany(
  1454. { favoriteStations: stationId },
  1455. { $pull: { favoriteStations: stationId } },
  1456. err => next(err, station)
  1457. );
  1458. }
  1459. ],
  1460. async (err, station) => {
  1461. if (err) {
  1462. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1463. this.log("ERROR", "STATIONS_REMOVE", `Removing station "${stationId}" failed. "${err}"`);
  1464. return cb({ status: "error", message: err });
  1465. }
  1466. this.log("SUCCESS", "STATIONS_REMOVE", `Removing station "${stationId}" successfully.`);
  1467. CacheModule.runJob("PUB", {
  1468. channel: "station.remove",
  1469. value: stationId
  1470. });
  1471. ActivitiesModule.runJob("ADD_ACTIVITY", {
  1472. userId: session.userId,
  1473. type: "station__remove",
  1474. payload: { message: `Removed a station named ${station.displayName}` }
  1475. });
  1476. ActivitiesModule.runJob("REMOVE_ACTIVITY_REFERENCES", { type: "stationId", stationId });
  1477. return cb({
  1478. status: "success",
  1479. message: "Successfully removed."
  1480. });
  1481. }
  1482. );
  1483. },
  1484. /**
  1485. * Create a station
  1486. *
  1487. * @param session
  1488. * @param data - the station data
  1489. * @param cb
  1490. */
  1491. create: isLoginRequired(async function create(session, data, cb) {
  1492. const stationModel = await DBModule.runJob("GET_MODEL", { modelName: "station" }, this);
  1493. const playlistModel = await DBModule.runJob("GET_MODEL", { modelName: "playlist" }, this);
  1494. data.name = data.name.toLowerCase();
  1495. let blacklist = [
  1496. "about",
  1497. "support",
  1498. "staff",
  1499. "help",
  1500. "news",
  1501. "terms",
  1502. "privacy",
  1503. "profile",
  1504. "c",
  1505. "community",
  1506. "tos",
  1507. "login",
  1508. "register",
  1509. "p",
  1510. "official",
  1511. "o",
  1512. "faq",
  1513. "team",
  1514. "donate",
  1515. "buy",
  1516. "shop",
  1517. "forums",
  1518. "explore",
  1519. "settings",
  1520. "admin",
  1521. "auth",
  1522. "reset_password",
  1523. "backend",
  1524. "api",
  1525. "songs",
  1526. "playlists",
  1527. "playlist",
  1528. "albums",
  1529. "artists",
  1530. "artist",
  1531. "station"
  1532. ];
  1533. if (data.type === "community" && config.has("blacklistedCommunityStationNames"))
  1534. blacklist = [...blacklist, ...config.get("blacklistedCommunityStationNames")];
  1535. async.waterfall(
  1536. [
  1537. next => {
  1538. if (!data) return next("Invalid data.");
  1539. return next();
  1540. },
  1541. next => {
  1542. stationModel.findOne(
  1543. {
  1544. $or: [{ name: data.name }, { displayName: new RegExp(`^${data.displayName}$`, "i") }]
  1545. },
  1546. next
  1547. );
  1548. },
  1549. (station, next) => {
  1550. this.log(station);
  1551. if (station) return next("A station with that name or display name already exists.");
  1552. if (blacklist.indexOf(data.name) !== -1)
  1553. return next("That name is blacklisted. Please use a different name.");
  1554. if (data.type === "official")
  1555. return hasPermission("stations.create.official", session)
  1556. .then(() => next())
  1557. .catch(() => next("Insufficient permissions."));
  1558. return next();
  1559. },
  1560. next => {
  1561. const stationId = mongoose.Types.ObjectId();
  1562. playlistModel.create(
  1563. {
  1564. displayName: `Station - ${data.name}`,
  1565. songs: [],
  1566. createdBy: data.type === "official" ? "Musare" : session.userId,
  1567. createdFor: `${stationId}`,
  1568. createdAt: Date.now(),
  1569. type: "station"
  1570. },
  1571. (err, playlist) => {
  1572. next(err, playlist, stationId);
  1573. }
  1574. );
  1575. },
  1576. (playlist, stationId, next) => {
  1577. const { name, displayName, description, type } = data;
  1578. if (type === "official") {
  1579. stationModel.create(
  1580. {
  1581. _id: stationId,
  1582. name,
  1583. displayName,
  1584. description,
  1585. playlist: playlist._id,
  1586. type,
  1587. privacy: "private",
  1588. queue: [],
  1589. currentSong: null
  1590. },
  1591. next
  1592. );
  1593. } else {
  1594. stationModel.create(
  1595. {
  1596. _id: stationId,
  1597. name,
  1598. displayName,
  1599. description,
  1600. playlist: playlist._id,
  1601. type,
  1602. privacy: "private",
  1603. owner: session.userId,
  1604. queue: [],
  1605. currentSong: null
  1606. },
  1607. next
  1608. );
  1609. }
  1610. }
  1611. ],
  1612. async (err, station) => {
  1613. if (err) {
  1614. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1615. this.log("ERROR", "STATIONS_CREATE", `Creating station failed. "${err}"`);
  1616. cb({ status: "error", message: err });
  1617. } else {
  1618. this.log("SUCCESS", "STATIONS_CREATE", `Created station "${station._id}" successfully.`);
  1619. CacheModule.runJob("PUB", {
  1620. channel: "station.create",
  1621. value: station._id
  1622. });
  1623. ActivitiesModule.runJob("ADD_ACTIVITY", {
  1624. userId: session.userId,
  1625. type: "station__create",
  1626. payload: {
  1627. message: `Created a station named <stationId>${station.displayName}</stationId>`,
  1628. stationId: station._id
  1629. }
  1630. });
  1631. cb({
  1632. status: "success",
  1633. message: "Successfully created station."
  1634. });
  1635. }
  1636. }
  1637. );
  1638. }),
  1639. /**
  1640. * Adds song to station queue
  1641. *
  1642. * @param session
  1643. * @param stationId - the station id
  1644. * @param youtubeId - the song id
  1645. * @param cb
  1646. */
  1647. addToQueue: isLoginRequired(async function addToQueue(session, stationId, youtubeId, cb) {
  1648. async.waterfall(
  1649. [
  1650. next => {
  1651. StationsModule.runJob("GET_STATION", { stationId }, this)
  1652. .then(station => {
  1653. next(null, station);
  1654. })
  1655. .catch(next);
  1656. },
  1657. (station, next) => {
  1658. if (!station) return next("Station not found.");
  1659. if (!station.requests.enabled) return next("Requests are disabled in this station.");
  1660. if (
  1661. station.requests.access === "owner" ||
  1662. (station.requests.access === "user" && station.privacy === "private")
  1663. ) {
  1664. return hasPermission("stations.request", session, stationId)
  1665. .then(() => next(null, station))
  1666. .catch(() => next("You do not have permission to add songs to queue."));
  1667. }
  1668. return next(null, station);
  1669. },
  1670. (station, next) =>
  1671. StationsModule.runJob(
  1672. "CAN_USER_VIEW_STATION",
  1673. {
  1674. station,
  1675. userId: session.userId
  1676. },
  1677. this
  1678. )
  1679. .then(canView => {
  1680. if (canView) return next();
  1681. return next("Insufficient permissions.");
  1682. })
  1683. .catch(err => next(err)),
  1684. next =>
  1685. StationsModule.runJob(
  1686. "ADD_TO_QUEUE",
  1687. {
  1688. stationId,
  1689. youtubeId,
  1690. requestUser: session.userId
  1691. },
  1692. this
  1693. )
  1694. .then(() => next())
  1695. .catch(next)
  1696. ],
  1697. async err => {
  1698. if (err) {
  1699. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1700. this.log(
  1701. "ERROR",
  1702. "STATIONS_ADD_SONG_TO_QUEUE",
  1703. `Adding song "${youtubeId}" to station "${stationId}" queue failed. "${err}"`
  1704. );
  1705. return cb({ status: "error", message: err });
  1706. }
  1707. this.log(
  1708. "SUCCESS",
  1709. "STATIONS_ADD_SONG_TO_QUEUE",
  1710. `Added song "${youtubeId}" to station "${stationId}" successfully.`
  1711. );
  1712. return cb({
  1713. status: "success",
  1714. message: "Successfully added song to queue."
  1715. });
  1716. }
  1717. );
  1718. }),
  1719. /**
  1720. * Removes song from station queue
  1721. *
  1722. * @param session
  1723. * @param stationId - the station id
  1724. * @param youtubeId - the youtube id
  1725. * @param cb
  1726. */
  1727. async removeFromQueue(session, stationId, youtubeId, cb) {
  1728. async.waterfall(
  1729. [
  1730. next => {
  1731. hasPermission("stations.queue.remove", session, stationId)
  1732. .then(() => next())
  1733. .catch(next);
  1734. },
  1735. next => {
  1736. if (!youtubeId) return next("Invalid youtube id.");
  1737. return StationsModule.runJob("REMOVE_FROM_QUEUE", { stationId, youtubeId }, this)
  1738. .then(() => next())
  1739. .catch(next);
  1740. }
  1741. ],
  1742. async err => {
  1743. if (err) {
  1744. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1745. this.log(
  1746. "ERROR",
  1747. "STATIONS_REMOVE_SONG_TO_QUEUE",
  1748. `Removing song "${youtubeId}" from station "${stationId}" queue failed. "${err}"`
  1749. );
  1750. return cb({ status: "error", message: err });
  1751. }
  1752. this.log(
  1753. "SUCCESS",
  1754. "STATIONS_REMOVE_SONG_TO_QUEUE",
  1755. `Removed song "${youtubeId}" from station "${stationId}" successfully.`
  1756. );
  1757. return cb({
  1758. status: "success",
  1759. message: "Successfully removed song from queue."
  1760. });
  1761. }
  1762. );
  1763. },
  1764. /**
  1765. * Gets the queue from a station
  1766. *
  1767. * @param {object} session - user session
  1768. * @param {string} stationId - the station id
  1769. * @param {Function} cb - callback
  1770. */
  1771. getQueue(session, stationId, cb) {
  1772. async.waterfall(
  1773. [
  1774. next => {
  1775. StationsModule.runJob("GET_STATION", { stationId }, this)
  1776. .then(station => next(null, station))
  1777. .catch(next);
  1778. },
  1779. (station, next) => {
  1780. if (!station) return next("Station not found.");
  1781. return next(null, station);
  1782. },
  1783. (station, next) => {
  1784. StationsModule.runJob("CAN_USER_VIEW_STATION", { station, userId: session.userId }, this)
  1785. .then(canView => {
  1786. if (canView) return next(null, station);
  1787. return next("Insufficient permissions.");
  1788. })
  1789. .catch(err => next(err));
  1790. },
  1791. (station, next) => next(null, station.queue)
  1792. ],
  1793. async (err, queue) => {
  1794. if (err) {
  1795. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1796. this.log(
  1797. "ERROR",
  1798. "STATIONS_GET_QUEUE",
  1799. `Getting queue for station "${stationId}" failed. "${err}"`
  1800. );
  1801. return cb({ status: "error", message: err });
  1802. }
  1803. this.log("SUCCESS", "STATIONS_GET_QUEUE", `Got queue for station "${stationId}" successfully.`);
  1804. return cb({
  1805. status: "success",
  1806. message: "Successfully got queue.",
  1807. data: { queue }
  1808. });
  1809. }
  1810. );
  1811. },
  1812. /**
  1813. * Reposition a song in station queue
  1814. *
  1815. * @param {object} session - user session
  1816. * @param {object} song - contains details about the song that is to be repositioned
  1817. * @param {string} song.youtubeId - the youtube id of the song
  1818. * @param {number} song.newIndex - the new position for the song in the queue
  1819. * @param {number} song.oldIndex - the old position of the song in the queue
  1820. * @param {string} stationId - the station id
  1821. * @param {Function} cb - callback
  1822. */
  1823. async repositionSongInQueue(session, stationId, song, cb) {
  1824. const stationModel = await DBModule.runJob("GET_MODEL", { modelName: "station" }, this);
  1825. async.waterfall(
  1826. [
  1827. next => {
  1828. hasPermission("stations.queue.reposition", session, stationId)
  1829. .then(() => next())
  1830. .catch(next);
  1831. },
  1832. next => {
  1833. if (!song || !song.youtubeId) return next("You must provide a song to reposition.");
  1834. return next();
  1835. },
  1836. // remove song from queue
  1837. next => {
  1838. stationModel.updateOne(
  1839. { _id: stationId },
  1840. { $pull: { queue: { youtubeId: song.youtubeId } } },
  1841. next
  1842. );
  1843. },
  1844. // add song back to queue (in new position)
  1845. (res, next) => {
  1846. stationModel.updateOne(
  1847. { _id: stationId },
  1848. { $push: { queue: { $each: [song], $position: song.newIndex } } },
  1849. err => next(err)
  1850. );
  1851. },
  1852. // update the cache representation of the station
  1853. next => {
  1854. StationsModule.runJob("UPDATE_STATION", { stationId }, this)
  1855. .then(station => next(null, station))
  1856. .catch(next);
  1857. }
  1858. ],
  1859. async err => {
  1860. if (err) {
  1861. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1862. this.log(
  1863. "ERROR",
  1864. "STATIONS_REPOSITION_SONG_IN_QUEUE",
  1865. `Repositioning song ${song.youtubeId} in queue of station "${stationId}" failed. "${err}"`
  1866. );
  1867. return cb({ status: "error", message: err });
  1868. }
  1869. this.log(
  1870. "SUCCESS",
  1871. "STATIONS_REPOSITION_SONG_IN_QUEUE",
  1872. `Repositioned song ${song.youtubeId} in queue of station "${stationId}" successfully.`
  1873. );
  1874. CacheModule.runJob("PUB", {
  1875. channel: "station.repositionSongInQueue",
  1876. value: {
  1877. song: {
  1878. youtubeId: song.youtubeId,
  1879. oldIndex: song.oldIndex,
  1880. newIndex: song.newIndex
  1881. },
  1882. stationId
  1883. }
  1884. });
  1885. return cb({
  1886. status: "success",
  1887. message: "Successfully repositioned song in queue."
  1888. });
  1889. }
  1890. );
  1891. },
  1892. /**
  1893. * Autofill a playlist in a station
  1894. *
  1895. * @param session
  1896. * @param stationId - the station id
  1897. * @param playlistId - the playlist id
  1898. * @param cb
  1899. */
  1900. async autofillPlaylist(session, stationId, playlistId, cb) {
  1901. async.waterfall(
  1902. [
  1903. next => {
  1904. hasPermission("stations.autofill", session, stationId)
  1905. .then(() => next())
  1906. .catch(next);
  1907. },
  1908. next => {
  1909. StationsModule.runJob("GET_STATION", { stationId }, this)
  1910. .then(station => next(null, station))
  1911. .catch(next);
  1912. },
  1913. (station, next) => {
  1914. if (!station) return next("Station not found.");
  1915. if (station.autofill.playlists.indexOf(playlistId) !== -1)
  1916. return next("That playlist is already autofilling.");
  1917. if (station.autofill.mode === "sequential" && station.autofill.playlists.length > 0)
  1918. return next("Error: Only 1 playlist can be autofilling in sequential mode.");
  1919. return next();
  1920. },
  1921. next => {
  1922. StationsModule.runJob("AUTOFILL_PLAYLIST", { stationId, playlistId }, this)
  1923. .then(() => {
  1924. next();
  1925. })
  1926. .catch(next);
  1927. }
  1928. ],
  1929. async err => {
  1930. if (err) {
  1931. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1932. this.log(
  1933. "ERROR",
  1934. "STATIONS_AUTOFILL_PLAYLIST",
  1935. `Including playlist "${playlistId}" for station "${stationId}" failed. "${err}"`
  1936. );
  1937. return cb({ status: "error", message: err });
  1938. }
  1939. this.log(
  1940. "SUCCESS",
  1941. "STATIONS_AUTOFILL_PLAYLIST",
  1942. `Including playlist "${playlistId}" for station "${stationId}" successfully.`
  1943. );
  1944. PlaylistsModule.runJob("AUTOFILL_STATION_PLAYLIST", { stationId }).then().catch();
  1945. CacheModule.runJob("PUB", {
  1946. channel: "station.autofillPlaylist",
  1947. value: {
  1948. playlistId,
  1949. stationId
  1950. }
  1951. });
  1952. return cb({
  1953. status: "success",
  1954. message: "Successfully added autofill playlist."
  1955. });
  1956. }
  1957. );
  1958. },
  1959. /**
  1960. * Remove autofilled playlist from a station
  1961. *
  1962. * @param session
  1963. * @param stationId - the station id
  1964. * @param playlistId - the playlist id
  1965. * @param cb
  1966. */
  1967. async removeAutofillPlaylist(session, stationId, playlistId, cb) {
  1968. async.waterfall(
  1969. [
  1970. next => {
  1971. hasPermission("stations.autofill", session, stationId)
  1972. .then(() => next())
  1973. .catch(next);
  1974. },
  1975. next => {
  1976. StationsModule.runJob("GET_STATION", { stationId }, this)
  1977. .then(station => next(null, station))
  1978. .catch(next);
  1979. },
  1980. (station, next) => {
  1981. if (!station) return next("Station not found.");
  1982. if (station.autofill.playlists.indexOf(playlistId) === -1)
  1983. return next("That playlist is not autofilling.");
  1984. return next();
  1985. },
  1986. next => {
  1987. StationsModule.runJob("REMOVE_AUTOFILL_PLAYLIST", { stationId, playlistId }, this)
  1988. .then(() => {
  1989. next();
  1990. })
  1991. .catch(next);
  1992. }
  1993. ],
  1994. async err => {
  1995. if (err) {
  1996. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1997. this.log(
  1998. "ERROR",
  1999. "STATIONS_REMOVE_AUTOFILL_PLAYLIST",
  2000. `Removing autofill playlist "${playlistId}" for station "${stationId}" failed. "${err}"`
  2001. );
  2002. return cb({ status: "error", message: err });
  2003. }
  2004. this.log(
  2005. "SUCCESS",
  2006. "STATIONS_REMOVE_AUTOFILL_PLAYLIST",
  2007. `Removing autofill playlist "${playlistId}" for station "${stationId}" successfully.`
  2008. );
  2009. PlaylistsModule.runJob("AUTOFILL_STATION_PLAYLIST", { stationId }).then().catch();
  2010. CacheModule.runJob("PUB", {
  2011. channel: "station.removedAutofillPlaylist",
  2012. value: {
  2013. playlistId,
  2014. stationId
  2015. }
  2016. });
  2017. return cb({
  2018. status: "success",
  2019. message: "Successfully removed autofill playlist."
  2020. });
  2021. }
  2022. );
  2023. },
  2024. /**
  2025. * Blacklist a playlist in a station
  2026. *
  2027. * @param session
  2028. * @param stationId - the station id
  2029. * @param playlistId - the playlist id
  2030. * @param cb
  2031. */
  2032. async blacklistPlaylist(session, stationId, playlistId, cb) {
  2033. async.waterfall(
  2034. [
  2035. next => {
  2036. hasPermission("stations.blacklist", session, stationId)
  2037. .then(() => next())
  2038. .catch(next);
  2039. },
  2040. next => {
  2041. StationsModule.runJob("GET_STATION", { stationId }, this)
  2042. .then(station => next(null, station))
  2043. .catch(next);
  2044. },
  2045. (station, next) => {
  2046. if (!station) return next("Station not found.");
  2047. if (station.blacklist.indexOf(playlistId) !== -1)
  2048. return next("That playlist is already blacklisted.");
  2049. return next();
  2050. },
  2051. next => {
  2052. StationsModule.runJob("BLACKLIST_PLAYLIST", { stationId, playlistId }, this)
  2053. .then(() => {
  2054. next();
  2055. })
  2056. .catch(next);
  2057. }
  2058. ],
  2059. async err => {
  2060. if (err) {
  2061. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  2062. this.log(
  2063. "ERROR",
  2064. "STATIONS_BLACKLIST_PLAYLIST",
  2065. `Blacklisting playlist "${playlistId}" for station "${stationId}" failed. "${err}"`
  2066. );
  2067. return cb({ status: "error", message: err });
  2068. }
  2069. this.log(
  2070. "SUCCESS",
  2071. "STATIONS_BLACKLIST_PLAYLIST",
  2072. `Blacklisting playlist "${playlistId}" for station "${stationId}" successfully.`
  2073. );
  2074. PlaylistsModule.runJob("AUTOFILL_STATION_PLAYLIST", { stationId }).then().catch();
  2075. CacheModule.runJob("PUB", {
  2076. channel: "station.blacklistedPlaylist",
  2077. value: {
  2078. playlistId,
  2079. stationId
  2080. }
  2081. });
  2082. return cb({
  2083. status: "success",
  2084. message: "Successfully blacklisted playlist."
  2085. });
  2086. }
  2087. );
  2088. },
  2089. /**
  2090. * Remove blacklisted a playlist from a station
  2091. *
  2092. * @param session
  2093. * @param stationId - the station id
  2094. * @param playlistId - the playlist id
  2095. * @param cb
  2096. */
  2097. async removeBlacklistedPlaylist(session, stationId, playlistId, cb) {
  2098. async.waterfall(
  2099. [
  2100. next => {
  2101. hasPermission("stations.blacklist", session, stationId)
  2102. .then(() => next())
  2103. .catch(next);
  2104. },
  2105. next => {
  2106. StationsModule.runJob("GET_STATION", { stationId }, this)
  2107. .then(station => next(null, station))
  2108. .catch(next);
  2109. },
  2110. (station, next) => {
  2111. if (!station) return next("Station not found.");
  2112. if (station.blacklist.indexOf(playlistId) === -1) return next("That playlist is not blacklisted.");
  2113. return next();
  2114. },
  2115. next => {
  2116. StationsModule.runJob("REMOVE_BLACKLISTED_PLAYLIST", { stationId, playlistId }, this)
  2117. .then(() => {
  2118. next();
  2119. })
  2120. .catch(next);
  2121. }
  2122. ],
  2123. async err => {
  2124. if (err) {
  2125. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  2126. this.log(
  2127. "ERROR",
  2128. "STATIONS_REMOVE_BLACKLISTED_PLAYLIST",
  2129. `Removing blacklisted playlist "${playlistId}" for station "${stationId}" failed. "${err}"`
  2130. );
  2131. return cb({ status: "error", message: err });
  2132. }
  2133. this.log(
  2134. "SUCCESS",
  2135. "STATIONS_REMOVE_BLACKLISTED_PLAYLIST",
  2136. `Removing blacklisted playlist "${playlistId}" for station "${stationId}" successfully.`
  2137. );
  2138. PlaylistsModule.runJob("AUTOFILL_STATION_PLAYLIST", { stationId }).then().catch();
  2139. CacheModule.runJob("PUB", {
  2140. channel: "station.removedBlacklistedPlaylist",
  2141. value: {
  2142. playlistId,
  2143. stationId
  2144. }
  2145. });
  2146. return cb({
  2147. status: "success",
  2148. message: "Successfully removed blacklisted playlist."
  2149. });
  2150. }
  2151. );
  2152. },
  2153. favoriteStation: isLoginRequired(async function favoriteStation(session, stationId, cb) {
  2154. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  2155. async.waterfall(
  2156. [
  2157. next => {
  2158. StationsModule.runJob("GET_STATION", { stationId }, this)
  2159. .then(station => next(null, station))
  2160. .catch(next);
  2161. },
  2162. (station, next) => {
  2163. if (!station) return next("Station not found.");
  2164. return StationsModule.runJob("CAN_USER_VIEW_STATION", { station, userId: session.userId }, this)
  2165. .then(canView => {
  2166. if (canView) return next(null, station);
  2167. return next("Insufficient permissions.");
  2168. })
  2169. .catch(err => next(err));
  2170. },
  2171. (station, next) => {
  2172. userModel.updateOne(
  2173. { _id: session.userId },
  2174. { $addToSet: { favoriteStations: stationId } },
  2175. (err, res) => next(err, station, res)
  2176. );
  2177. },
  2178. (station, res, next) => {
  2179. if (res.nModified === 0) return next("The station was already favorited.");
  2180. return next(null, station);
  2181. }
  2182. ],
  2183. async (err, station) => {
  2184. if (err) {
  2185. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  2186. this.log("ERROR", "FAVORITE_STATION", `Favoriting station "${stationId}" failed. "${err}"`);
  2187. return cb({ status: "error", message: err });
  2188. }
  2189. this.log("SUCCESS", "FAVORITE_STATION", `Favorited station "${stationId}" successfully.`);
  2190. CacheModule.runJob("PUB", {
  2191. channel: "user.favoritedStation",
  2192. value: {
  2193. userId: session.userId,
  2194. stationId
  2195. }
  2196. });
  2197. ActivitiesModule.runJob("ADD_ACTIVITY", {
  2198. userId: session.userId,
  2199. type: "station__favorite",
  2200. payload: {
  2201. message: `Favorited station <stationId>${station.displayName}</stationId>`,
  2202. stationId
  2203. }
  2204. });
  2205. return cb({
  2206. status: "success",
  2207. message: "Succesfully favorited station."
  2208. });
  2209. }
  2210. );
  2211. }),
  2212. unfavoriteStation: isLoginRequired(async function unfavoriteStation(session, stationId, cb) {
  2213. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  2214. async.waterfall(
  2215. [
  2216. next => {
  2217. userModel.updateOne({ _id: session.userId }, { $pull: { favoriteStations: stationId } }, next);
  2218. },
  2219. (res, next) => {
  2220. if (res.nModified === 0) return next("The station wasn't favorited.");
  2221. return next();
  2222. },
  2223. next => {
  2224. StationsModule.runJob("GET_STATION", { stationId }, this)
  2225. .then(station => next(null, station))
  2226. .catch(next);
  2227. }
  2228. ],
  2229. async (err, station) => {
  2230. if (err) {
  2231. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  2232. this.log("ERROR", "UNFAVORITE_STATION", `Unfavoriting station "${stationId}" failed. "${err}"`);
  2233. return cb({ status: "error", message: err });
  2234. }
  2235. this.log("SUCCESS", "UNFAVORITE_STATION", `Unfavorited station "${stationId}" successfully.`);
  2236. CacheModule.runJob("PUB", {
  2237. channel: "user.unfavoritedStation",
  2238. value: {
  2239. userId: session.userId,
  2240. stationId
  2241. }
  2242. });
  2243. ActivitiesModule.runJob("ADD_ACTIVITY", {
  2244. userId: session.userId,
  2245. type: "station__unfavorite",
  2246. payload: {
  2247. message: `Unfavorited station <stationId>${station.displayName}</stationId>`,
  2248. stationId
  2249. }
  2250. });
  2251. return cb({
  2252. status: "success",
  2253. message: "Succesfully unfavorited station."
  2254. });
  2255. }
  2256. );
  2257. }),
  2258. /**
  2259. * Clears every station queue
  2260. *
  2261. * @param {object} session - the session object automatically added by socket.io
  2262. * @param {Function} cb - gets called with the result
  2263. */
  2264. clearEveryStationQueue: useHasPermission(
  2265. "stations.clearEveryStationQueue",
  2266. async function clearEveryStationQueue(session, cb) {
  2267. this.keepLongJob();
  2268. this.publishProgress({
  2269. status: "started",
  2270. title: "Clear every station queue",
  2271. message: "Clearing every station queue.",
  2272. id: this.toString()
  2273. });
  2274. await CacheModule.runJob("RPUSH", { key: `longJobs.${session.userId}`, value: this.toString() }, this);
  2275. await CacheModule.runJob(
  2276. "PUB",
  2277. {
  2278. channel: "longJob.added",
  2279. value: { jobId: this.toString(), userId: session.userId }
  2280. },
  2281. this
  2282. );
  2283. async.waterfall(
  2284. [
  2285. next => {
  2286. StationsModule.runJob("CLEAR_EVERY_STATION_QUEUE", {}, this)
  2287. .then(() => next())
  2288. .catch(next);
  2289. }
  2290. ],
  2291. async err => {
  2292. if (err) {
  2293. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  2294. this.log("ERROR", "CLEAR_EVERY_STATION_QUEUE", `Clearing every station queue failed. "${err}"`);
  2295. this.publishProgress({
  2296. status: "error",
  2297. message: err
  2298. });
  2299. return cb({ status: "error", message: err });
  2300. }
  2301. this.log("SUCCESS", "CLEAR_EVERY_STATION_QUEUE", "Clearing every station queue was successful.");
  2302. this.publishProgress({
  2303. status: "success",
  2304. message: "Successfully cleared every station queue."
  2305. });
  2306. return cb({ status: "success", message: "Successfully cleared every station queue." });
  2307. }
  2308. );
  2309. }
  2310. ),
  2311. /**
  2312. * Reset a station queue
  2313. *
  2314. * @param {object} session - the session object automatically added by socket.io
  2315. * @param {string} stationId - the station id
  2316. * @param {Function} cb - gets called with the result
  2317. */
  2318. resetQueue: useHasPermission("stations.queue.reset", async function resetQueue(session, stationId, cb) {
  2319. async.waterfall(
  2320. [
  2321. next => {
  2322. StationsModule.runJob("RESET_QUEUE", { stationId }, this)
  2323. .then(() => next())
  2324. .catch(next);
  2325. }
  2326. ],
  2327. async err => {
  2328. if (err) {
  2329. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  2330. this.log("ERROR", "RESET_QUEUE", `Resetting station queue failed. "${err}"`);
  2331. return cb({ status: "error", message: err });
  2332. }
  2333. this.log("SUCCESS", "RESET_QUEUE", "Resetting station queue was successful.");
  2334. return cb({ status: "success", message: "Successfully reset station queue." });
  2335. }
  2336. );
  2337. }),
  2338. /**
  2339. * Gets skip votes for a station
  2340. *
  2341. * @param session
  2342. * @param stationId - the station id
  2343. * @param stationId - the song id to get skipvotes for
  2344. * @param cb
  2345. */
  2346. getSkipVotes: isLoginRequired(async function getSkipVotes(session, stationId, songId, cb) {
  2347. async.waterfall(
  2348. [
  2349. next => {
  2350. StationsModule.runJob("GET_STATION", { stationId }, this)
  2351. .then(res => next(null, res.currentSong))
  2352. .catch(console.log);
  2353. },
  2354. (currentSong, next) => {
  2355. if (currentSong && currentSong._id === songId)
  2356. next(null, {
  2357. skipVotes: currentSong.skipVotes.length,
  2358. skipVotesCurrent: true
  2359. });
  2360. else
  2361. next(null, {
  2362. skipVotes: 0,
  2363. skipVotesCurrent: false
  2364. });
  2365. }
  2366. ],
  2367. async (err, data) => {
  2368. if (err) {
  2369. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  2370. this.log(
  2371. "ERROR",
  2372. "STATIONS_GET_SKIP_VOTES",
  2373. `User "${session.userId}" failed to get skip votes for ${stationId}. "${err}"`
  2374. );
  2375. return cb({ status: "error", message: err });
  2376. }
  2377. const { skipVotes, skipVotesCurrent } = data;
  2378. return cb({
  2379. status: "success",
  2380. data: {
  2381. skipVotes,
  2382. skipVotesCurrent
  2383. }
  2384. });
  2385. }
  2386. );
  2387. })
  2388. };