stations.js 70 KB

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