stations.js 67 KB

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