stations.js 71 KB

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