stations.js 72 KB

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