stations.js 70 KB

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