stations.js 71 KB

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