stations.js 72 KB

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