stations.js 69 KB

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