stations.js 72 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795
  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. const { name, displayName, description, privacy, requests, autofill, theme } = newStation;
  1219. const { enabled, limit, mode } = autofill;
  1220. // This object makes sure only certain properties can be changed by a user
  1221. const setObject = {
  1222. name,
  1223. displayName,
  1224. description,
  1225. privacy,
  1226. requests,
  1227. "autofill.enabled": enabled,
  1228. "autofill.limit": limit,
  1229. "autofill.mode": mode,
  1230. theme
  1231. };
  1232. stationModel.updateOne({ _id: stationId }, { $set: setObject }, { runValidators: true }, err => {
  1233. next(err, previousStation);
  1234. });
  1235. },
  1236. (previousStation, next) => {
  1237. StationsModule.runJob("UPDATE_STATION", { stationId }, this)
  1238. .then(station => next(null, station, previousStation))
  1239. .catch(next);
  1240. },
  1241. (station, previousStation, next) => {
  1242. if (
  1243. newStation.autofill.enabled &&
  1244. JSON.stringify(newStation.autofill) !== JSON.stringify(previousStation.autofill)
  1245. )
  1246. StationsModule.runJob("AUTOFILL_STATION", { stationId }, this)
  1247. .then(() => {
  1248. CacheModule.runJob("PUB", {
  1249. channel: "station.queueUpdate",
  1250. value: stationId
  1251. })
  1252. .then(() => next(null, station, previousStation))
  1253. .catch(next);
  1254. })
  1255. .catch(err => {
  1256. if (err === "Autofill is disabled in this station" || err === "Autofill limit reached")
  1257. next(null, station, previousStation);
  1258. else next(err);
  1259. });
  1260. else next(null, station, previousStation);
  1261. },
  1262. (station, previousStation, next) => {
  1263. playlistModel.updateOne(
  1264. { _id: station.playlist },
  1265. { $set: { displayName: `Station - ${station.displayName}` } },
  1266. err => {
  1267. next(err, station, previousStation);
  1268. }
  1269. );
  1270. }
  1271. ],
  1272. async (err, station, previousStation) => {
  1273. if (err) {
  1274. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1275. this.log("ERROR", "STATIONS_UPDATE", `Updating station "${stationId}" failed. "${err}"`);
  1276. return cb({ status: "error", message: err });
  1277. }
  1278. this.log("SUCCESS", "STATIONS_UPDATE", `Updated station "${stationId}" successfully.`);
  1279. CacheModule.runJob("PUB", {
  1280. channel: "station.updated",
  1281. value: { stationId, previousStation }
  1282. });
  1283. return cb({
  1284. status: "success",
  1285. message: "Successfully updated the station."
  1286. });
  1287. }
  1288. );
  1289. }),
  1290. /**
  1291. * Pauses a station
  1292. *
  1293. * @param session
  1294. * @param stationId - the station id
  1295. * @param cb
  1296. */
  1297. pause: isOwnerRequired(async function pause(session, stationId, cb) {
  1298. const stationModel = await DBModule.runJob(
  1299. "GET_MODEL",
  1300. {
  1301. modelName: "station"
  1302. },
  1303. this
  1304. );
  1305. async.waterfall(
  1306. [
  1307. next => {
  1308. StationsModule.runJob("GET_STATION", { stationId }, this)
  1309. .then(station => {
  1310. next(null, station);
  1311. })
  1312. .catch(next);
  1313. },
  1314. (station, next) => {
  1315. if (!station) return next("Station not found.");
  1316. if (station.paused) return next("That station was already paused.");
  1317. return stationModel.updateOne(
  1318. { _id: stationId },
  1319. { $set: { paused: true, pausedAt: Date.now() } },
  1320. next
  1321. );
  1322. },
  1323. (res, next) => {
  1324. StationsModule.runJob("UPDATE_STATION", { stationId }, this)
  1325. .then(station => {
  1326. next(null, station);
  1327. })
  1328. .catch(next);
  1329. }
  1330. ],
  1331. async err => {
  1332. if (err) {
  1333. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1334. this.log("ERROR", "STATIONS_PAUSE", `Pausing station "${stationId}" failed. "${err}"`);
  1335. return cb({ status: "error", message: err });
  1336. }
  1337. this.log("SUCCESS", "STATIONS_PAUSE", `Paused station "${stationId}" successfully.`);
  1338. CacheModule.runJob("PUB", {
  1339. channel: "station.pause",
  1340. value: stationId
  1341. });
  1342. NotificationsModule.runJob("UNSCHEDULE", {
  1343. name: `stations.nextSong?id=${stationId}`
  1344. });
  1345. return cb({
  1346. status: "success",
  1347. message: "Successfully paused."
  1348. });
  1349. }
  1350. );
  1351. }),
  1352. /**
  1353. * Resumes a station
  1354. *
  1355. * @param session
  1356. * @param stationId - the station id
  1357. * @param cb
  1358. */
  1359. resume: isOwnerRequired(async function resume(session, stationId, cb) {
  1360. const stationModel = await DBModule.runJob(
  1361. "GET_MODEL",
  1362. {
  1363. modelName: "station"
  1364. },
  1365. this
  1366. );
  1367. async.waterfall(
  1368. [
  1369. next => {
  1370. StationsModule.runJob("GET_STATION", { stationId }, this)
  1371. .then(station => {
  1372. next(null, station);
  1373. })
  1374. .catch(next);
  1375. },
  1376. (station, next) => {
  1377. if (!station) return next("Station not found.");
  1378. if (!station.paused) return next("That station is not paused.");
  1379. station.timePaused += Date.now() - station.pausedAt;
  1380. return stationModel.updateOne(
  1381. { _id: stationId },
  1382. {
  1383. $set: { paused: false },
  1384. $inc: { timePaused: Date.now() - station.pausedAt }
  1385. },
  1386. next
  1387. );
  1388. },
  1389. (res, next) => {
  1390. StationsModule.runJob("UPDATE_STATION", { stationId }, this)
  1391. .then(station => {
  1392. next(null, station);
  1393. })
  1394. .catch(next);
  1395. }
  1396. ],
  1397. async err => {
  1398. if (err) {
  1399. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1400. this.log("ERROR", "STATIONS_RESUME", `Resuming station "${stationId}" failed. "${err}"`);
  1401. return cb({ status: "error", message: err });
  1402. }
  1403. this.log("SUCCESS", "STATIONS_RESUME", `Resuming station "${stationId}" successfully.`);
  1404. CacheModule.runJob("PUB", {
  1405. channel: "station.resume",
  1406. value: stationId
  1407. });
  1408. return cb({
  1409. status: "success",
  1410. message: "Successfully resumed."
  1411. });
  1412. }
  1413. );
  1414. }),
  1415. /**
  1416. * Removes a station
  1417. *
  1418. * @param session
  1419. * @param stationId - the station id
  1420. * @param cb
  1421. */
  1422. remove: isOwnerRequired(async function remove(session, stationId, cb) {
  1423. const stationModel = await DBModule.runJob("GET_MODEL", { modelName: "station" }, this);
  1424. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  1425. async.waterfall(
  1426. [
  1427. next => {
  1428. stationModel.findById(stationId, (err, station) => {
  1429. if (err) return next(err);
  1430. return next(null, station);
  1431. });
  1432. },
  1433. (station, next) => {
  1434. stationModel.deleteOne({ _id: stationId }, err => next(err, station));
  1435. },
  1436. (station, next) => {
  1437. CacheModule.runJob("HDEL", { table: "stations", key: stationId }, this)
  1438. .then(() => next(null, station))
  1439. .catch(next);
  1440. },
  1441. // remove the playlist for the station
  1442. (station, next) => {
  1443. if (station.playlist)
  1444. PlaylistsModule.runJob("DELETE_PLAYLIST", { playlistId: station.playlist })
  1445. .then(() => {})
  1446. .catch(next);
  1447. next(null, station);
  1448. },
  1449. // remove reference to the station id in any array of a user's favorite stations
  1450. (station, next) => {
  1451. userModel.updateMany(
  1452. { favoriteStations: stationId },
  1453. { $pull: { favoriteStations: stationId } },
  1454. err => next(err, station)
  1455. );
  1456. }
  1457. ],
  1458. async (err, station) => {
  1459. if (err) {
  1460. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1461. this.log("ERROR", "STATIONS_REMOVE", `Removing station "${stationId}" failed. "${err}"`);
  1462. return cb({ status: "error", message: err });
  1463. }
  1464. this.log("SUCCESS", "STATIONS_REMOVE", `Removing station "${stationId}" successfully.`);
  1465. CacheModule.runJob("PUB", {
  1466. channel: "station.remove",
  1467. value: stationId
  1468. });
  1469. ActivitiesModule.runJob("ADD_ACTIVITY", {
  1470. userId: session.userId,
  1471. type: "station__remove",
  1472. payload: { message: `Removed a station named ${station.displayName}` }
  1473. });
  1474. ActivitiesModule.runJob("REMOVE_ACTIVITY_REFERENCES", { type: "stationId", stationId });
  1475. return cb({
  1476. status: "success",
  1477. message: "Successfully removed."
  1478. });
  1479. }
  1480. );
  1481. }),
  1482. /**
  1483. * Create a station
  1484. *
  1485. * @param session
  1486. * @param data - the station data
  1487. * @param cb
  1488. */
  1489. create: isLoginRequired(async function create(session, data, cb) {
  1490. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  1491. const stationModel = await DBModule.runJob("GET_MODEL", { modelName: "station" }, this);
  1492. const playlistModel = await DBModule.runJob("GET_MODEL", { modelName: "playlist" }, this);
  1493. data.name = data.name.toLowerCase();
  1494. let blacklist = [
  1495. "about",
  1496. "support",
  1497. "staff",
  1498. "help",
  1499. "news",
  1500. "terms",
  1501. "privacy",
  1502. "profile",
  1503. "c",
  1504. "community",
  1505. "tos",
  1506. "login",
  1507. "register",
  1508. "p",
  1509. "official",
  1510. "o",
  1511. "faq",
  1512. "team",
  1513. "donate",
  1514. "buy",
  1515. "shop",
  1516. "forums",
  1517. "explore",
  1518. "settings",
  1519. "admin",
  1520. "auth",
  1521. "reset_password",
  1522. "backend",
  1523. "api",
  1524. "songs",
  1525. "playlists",
  1526. "playlist",
  1527. "albums",
  1528. "artists",
  1529. "artist",
  1530. "station"
  1531. ];
  1532. if (data.type === "community" && config.has("blacklistedCommunityStationNames"))
  1533. blacklist = [...blacklist, ...config.get("blacklistedCommunityStationNames")];
  1534. async.waterfall(
  1535. [
  1536. next => {
  1537. if (!data) return next("Invalid data.");
  1538. return next();
  1539. },
  1540. next => {
  1541. stationModel.findOne(
  1542. {
  1543. $or: [{ name: data.name }, { displayName: new RegExp(`^${data.displayName}$`, "i") }]
  1544. },
  1545. next
  1546. );
  1547. },
  1548. (station, next) => {
  1549. this.log(station);
  1550. if (station) return next("A station with that name or display name already exists.");
  1551. if (blacklist.indexOf(data.name) !== -1)
  1552. return next("That name is blacklisted. Please use a different name.");
  1553. if (data.type === "official") {
  1554. return userModel.findOne({ _id: session.userId }, (err, user) => {
  1555. if (err) return next(err);
  1556. if (!user) return next("User not found.");
  1557. if (user.role !== "admin") return next("Admin required.");
  1558. return next();
  1559. });
  1560. }
  1561. return next();
  1562. },
  1563. next => {
  1564. const stationId = mongoose.Types.ObjectId();
  1565. playlistModel.create(
  1566. {
  1567. displayName: `Station - ${data.name}`,
  1568. songs: [],
  1569. createdBy: data.type === "official" ? "Musare" : session.userId,
  1570. createdFor: `${stationId}`,
  1571. createdAt: Date.now(),
  1572. type: "station"
  1573. },
  1574. (err, playlist) => {
  1575. next(err, playlist, stationId);
  1576. }
  1577. );
  1578. },
  1579. (playlist, stationId, next) => {
  1580. const { name, displayName, description, type } = data;
  1581. if (type === "official") {
  1582. stationModel.create(
  1583. {
  1584. _id: stationId,
  1585. name,
  1586. displayName,
  1587. description,
  1588. playlist: playlist._id,
  1589. type,
  1590. privacy: "private",
  1591. queue: [],
  1592. currentSong: null
  1593. },
  1594. next
  1595. );
  1596. } else {
  1597. stationModel.create(
  1598. {
  1599. _id: stationId,
  1600. name,
  1601. displayName,
  1602. description,
  1603. playlist: playlist._id,
  1604. type,
  1605. privacy: "private",
  1606. owner: session.userId,
  1607. queue: [],
  1608. currentSong: null
  1609. },
  1610. next
  1611. );
  1612. }
  1613. }
  1614. ],
  1615. async (err, station) => {
  1616. if (err) {
  1617. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1618. this.log("ERROR", "STATIONS_CREATE", `Creating station failed. "${err}"`);
  1619. cb({ status: "error", message: err });
  1620. } else {
  1621. this.log("SUCCESS", "STATIONS_CREATE", `Created station "${station._id}" successfully.`);
  1622. CacheModule.runJob("PUB", {
  1623. channel: "station.create",
  1624. value: station._id
  1625. });
  1626. ActivitiesModule.runJob("ADD_ACTIVITY", {
  1627. userId: session.userId,
  1628. type: "station__create",
  1629. payload: {
  1630. message: `Created a station named <stationId>${station.displayName}</stationId>`,
  1631. stationId: station._id
  1632. }
  1633. });
  1634. cb({
  1635. status: "success",
  1636. message: "Successfully created station."
  1637. });
  1638. }
  1639. }
  1640. );
  1641. }),
  1642. /**
  1643. * Adds song to station queue
  1644. *
  1645. * @param session
  1646. * @param stationId - the station id
  1647. * @param youtubeId - the song id
  1648. * @param cb
  1649. */
  1650. addToQueue: isLoginRequired(async function addToQueue(session, stationId, youtubeId, cb) {
  1651. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  1652. const stationModel = await DBModule.runJob(
  1653. "GET_MODEL",
  1654. {
  1655. modelName: "station"
  1656. },
  1657. this
  1658. );
  1659. async.waterfall(
  1660. [
  1661. next => {
  1662. StationsModule.runJob("GET_STATION", { stationId }, this)
  1663. .then(station => {
  1664. next(null, station);
  1665. })
  1666. .catch(next);
  1667. },
  1668. (station, next) => {
  1669. if (!station) return next("Station not found.");
  1670. if (!station.requests.enabled) return next("Requests are disabled in this station.");
  1671. if (
  1672. station.requests.access === "owner" ||
  1673. (station.requests.access === "user" && station.privacy === "private")
  1674. ) {
  1675. return userModel.findOne({ _id: session.userId }, (err, user) => {
  1676. if (err) return next(err);
  1677. if (user.role !== "admin" && station.owner !== session.userId)
  1678. return next("You do not have permission to add songs to queue.");
  1679. return next(null, station);
  1680. });
  1681. }
  1682. return next(null, station);
  1683. },
  1684. (station, next) =>
  1685. StationsModule.runJob(
  1686. "CAN_USER_VIEW_STATION",
  1687. {
  1688. station,
  1689. userId: session.userId
  1690. },
  1691. this
  1692. )
  1693. .then(canView => {
  1694. if (canView) return next(null, station);
  1695. return next("Insufficient permissions.");
  1696. })
  1697. .catch(err => next(err)),
  1698. (station, next) => {
  1699. if (station.currentSong && station.currentSong.youtubeId === youtubeId)
  1700. return next("That song is currently playing.");
  1701. return async.each(
  1702. station.queue,
  1703. (queueSong, next) => {
  1704. if (queueSong.youtubeId === youtubeId) return next("That song is already in the queue.");
  1705. return next();
  1706. },
  1707. err => next(err, station)
  1708. );
  1709. },
  1710. (station, next) => {
  1711. DBModule.runJob("GET_MODEL", { modelName: "user" }, this)
  1712. .then(UserModel => {
  1713. UserModel.findOne(
  1714. { _id: session.userId },
  1715. { "preferences.anonymousSongRequests": 1 },
  1716. (err, user) => next(err, station, user)
  1717. );
  1718. })
  1719. .catch(next);
  1720. },
  1721. (station, user, next) => {
  1722. SongsModule.runJob(
  1723. "ENSURE_SONG_EXISTS_BY_YOUTUBE_ID",
  1724. {
  1725. youtubeId,
  1726. userId: user.preferences.anonymousSongRequests ? null : session.userId,
  1727. automaticallyRequested: true
  1728. },
  1729. this
  1730. )
  1731. .then(response => {
  1732. const { song } = response;
  1733. const { _id, title, skipDuration, artists, thumbnail, duration, verified } = song;
  1734. next(
  1735. null,
  1736. {
  1737. _id,
  1738. youtubeId,
  1739. title,
  1740. skipDuration,
  1741. artists,
  1742. thumbnail,
  1743. duration,
  1744. verified
  1745. },
  1746. station
  1747. );
  1748. })
  1749. .catch(next);
  1750. },
  1751. (song, station, next) => {
  1752. const blacklist = [];
  1753. async.eachLimit(
  1754. station.blacklist,
  1755. 1,
  1756. (playlistId, next) => {
  1757. PlaylistsModule.runJob("GET_PLAYLIST", { playlistId }, this)
  1758. .then(playlist => {
  1759. blacklist.push(playlist);
  1760. next();
  1761. })
  1762. .catch(next);
  1763. },
  1764. err => {
  1765. next(err, song, station, blacklist);
  1766. }
  1767. );
  1768. },
  1769. (song, station, blacklist, next) => {
  1770. const blacklistedSongs = blacklist
  1771. .flatMap(blacklistedPlaylist => blacklistedPlaylist.songs)
  1772. .reduce(
  1773. (items, item) =>
  1774. items.find(x => x.youtubeId === item.youtubeId) ? [...items] : [...items, item],
  1775. []
  1776. );
  1777. if (
  1778. blacklistedSongs.find(blacklistedSong => blacklistedSong._id.toString() === song._id.toString())
  1779. )
  1780. next("That song is in an blacklisted playlist and cannot be played.");
  1781. else next(null, song, station);
  1782. },
  1783. (song, station, next) => {
  1784. song.requestedBy = session.userId;
  1785. song.requestedAt = Date.now();
  1786. return next(null, song, station);
  1787. },
  1788. (song, station, next) => {
  1789. if (station.queue.length === 0) return next(null, song);
  1790. let totalSongs = 0;
  1791. station.queue.forEach(song => {
  1792. if (session.userId === song.requestedBy) {
  1793. totalSongs += 1;
  1794. }
  1795. });
  1796. if (totalSongs >= station.requests.limit)
  1797. return next(`The max amount of songs per user is ${station.requests.limit}.`);
  1798. return next(null, song);
  1799. },
  1800. // (song, station, next) => {
  1801. // song.requestedBy = session.userId;
  1802. // song.requestedAt = Date.now();
  1803. // let totalDuration = 0;
  1804. // station.queue.forEach(song => {
  1805. // totalDuration += song.duration;
  1806. // });
  1807. // if (totalDuration >= 3600 * 3) return next("The max length of the queue is 3 hours.");
  1808. // return next(null, song, station);
  1809. // },
  1810. // (song, station, next) => {
  1811. // if (station.queue.length === 0) return next(null, song, station);
  1812. // let totalDuration = 0;
  1813. // const userId = station.queue[station.queue.length - 1].requestedBy;
  1814. // station.queue.forEach(song => {
  1815. // if (userId === song.requestedBy) {
  1816. // totalDuration += song.duration;
  1817. // }
  1818. // });
  1819. // if (totalDuration >= 900) return next("The max length of songs per user is 15 minutes.");
  1820. // return next(null, song, station);
  1821. // },
  1822. // (song, station, next) => {
  1823. // if (station.queue.length === 0) return next(null, song);
  1824. // let totalSongs = 0;
  1825. // const userId = station.queue[station.queue.length - 1].requestedBy;
  1826. // station.queue.forEach(song => {
  1827. // if (userId === song.requestedBy) {
  1828. // totalSongs += 1;
  1829. // }
  1830. // });
  1831. // if (totalSongs <= 2) return next(null, song);
  1832. // if (totalSongs > 3)
  1833. // return next("The max amount of songs per user is 3, and only 2 in a row is allowed.");
  1834. // if (
  1835. // station.queue[station.queue.length - 2].requestedBy !== userId ||
  1836. // station.queue[station.queue.length - 3] !== userId
  1837. // )
  1838. // return next("The max amount of songs per user is 3, and only 2 in a row is allowed.");
  1839. // return next(null, song);
  1840. // },
  1841. (song, next) => {
  1842. stationModel.updateOne(
  1843. { _id: stationId },
  1844. { $push: { queue: song } },
  1845. { runValidators: true },
  1846. next
  1847. );
  1848. },
  1849. (res, next) => {
  1850. StationsModule.runJob("UPDATE_STATION", { stationId }, this)
  1851. .then(station => next(null, station))
  1852. .catch(next);
  1853. }
  1854. ],
  1855. async err => {
  1856. if (err) {
  1857. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1858. this.log(
  1859. "ERROR",
  1860. "STATIONS_ADD_SONG_TO_QUEUE",
  1861. `Adding song "${youtubeId}" to station "${stationId}" queue failed. "${err}"`
  1862. );
  1863. return cb({ status: "error", message: err });
  1864. }
  1865. this.log(
  1866. "SUCCESS",
  1867. "STATIONS_ADD_SONG_TO_QUEUE",
  1868. `Added song "${youtubeId}" to station "${stationId}" successfully.`
  1869. );
  1870. CacheModule.runJob("PUB", {
  1871. channel: "station.queueUpdate",
  1872. value: stationId
  1873. });
  1874. return cb({
  1875. status: "success",
  1876. message: "Successfully added song to queue."
  1877. });
  1878. }
  1879. );
  1880. }),
  1881. /**
  1882. * Removes song from station queue
  1883. *
  1884. * @param session
  1885. * @param stationId - the station id
  1886. * @param youtubeId - the youtube id
  1887. * @param cb
  1888. */
  1889. removeFromQueue: isOwnerRequired(async function removeFromQueue(session, stationId, youtubeId, cb) {
  1890. const stationModel = await DBModule.runJob("GET_MODEL", { modelName: "station" }, this);
  1891. async.waterfall(
  1892. [
  1893. next => {
  1894. if (!youtubeId) return next("Invalid youtube id.");
  1895. return StationsModule.runJob("GET_STATION", { stationId }, this)
  1896. .then(station => next(null, station))
  1897. .catch(next);
  1898. },
  1899. (station, next) => {
  1900. if (!station) return next("Station not found.");
  1901. return async.each(
  1902. station.queue,
  1903. (queueSong, next) => {
  1904. if (queueSong.youtubeId === youtubeId) return next(true);
  1905. return next();
  1906. },
  1907. err => {
  1908. if (err === true) return next();
  1909. return next("Song is not currently in the queue.");
  1910. }
  1911. );
  1912. },
  1913. next => {
  1914. stationModel.updateOne({ _id: stationId }, { $pull: { queue: { youtubeId } } }, next);
  1915. },
  1916. (res, next) => {
  1917. StationsModule.runJob("UPDATE_STATION", { stationId }, this)
  1918. .then(station => next(null, station))
  1919. .catch(next);
  1920. }
  1921. ],
  1922. async err => {
  1923. if (err) {
  1924. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1925. this.log(
  1926. "ERROR",
  1927. "STATIONS_REMOVE_SONG_TO_QUEUE",
  1928. `Removing song "${youtubeId}" from station "${stationId}" queue failed. "${err}"`
  1929. );
  1930. return cb({ status: "error", message: err });
  1931. }
  1932. this.log(
  1933. "SUCCESS",
  1934. "STATIONS_REMOVE_SONG_TO_QUEUE",
  1935. `Removed song "${youtubeId}" from station "${stationId}" successfully.`
  1936. );
  1937. CacheModule.runJob("PUB", {
  1938. channel: "station.queueUpdate",
  1939. value: stationId
  1940. });
  1941. return cb({
  1942. status: "success",
  1943. message: "Successfully removed song from queue."
  1944. });
  1945. }
  1946. );
  1947. }),
  1948. /**
  1949. * Gets the queue from a station
  1950. *
  1951. * @param {object} session - user session
  1952. * @param {string} stationId - the station id
  1953. * @param {Function} cb - callback
  1954. */
  1955. getQueue(session, stationId, cb) {
  1956. async.waterfall(
  1957. [
  1958. next => {
  1959. StationsModule.runJob("GET_STATION", { stationId }, this)
  1960. .then(station => next(null, station))
  1961. .catch(next);
  1962. },
  1963. (station, next) => {
  1964. if (!station) return next("Station not found.");
  1965. return next(null, station);
  1966. },
  1967. (station, next) => {
  1968. StationsModule.runJob("CAN_USER_VIEW_STATION", { station, userId: session.userId }, this)
  1969. .then(canView => {
  1970. if (canView) return next(null, station);
  1971. return next("Insufficient permissions.");
  1972. })
  1973. .catch(err => next(err));
  1974. },
  1975. (station, next) => next(null, station.queue)
  1976. ],
  1977. async (err, queue) => {
  1978. if (err) {
  1979. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1980. this.log(
  1981. "ERROR",
  1982. "STATIONS_GET_QUEUE",
  1983. `Getting queue for station "${stationId}" failed. "${err}"`
  1984. );
  1985. return cb({ status: "error", message: err });
  1986. }
  1987. this.log("SUCCESS", "STATIONS_GET_QUEUE", `Got queue for station "${stationId}" successfully.`);
  1988. return cb({
  1989. status: "success",
  1990. message: "Successfully got queue.",
  1991. data: { queue }
  1992. });
  1993. }
  1994. );
  1995. },
  1996. /**
  1997. * Reposition a song in station queue
  1998. *
  1999. * @param {object} session - user session
  2000. * @param {object} song - contains details about the song that is to be repositioned
  2001. * @param {string} song.youtubeId - the youtube id of the song
  2002. * @param {number} song.newIndex - the new position for the song in the queue
  2003. * @param {number} song.oldIndex - the old position of the song in the queue
  2004. * @param {string} stationId - the station id
  2005. * @param {Function} cb - callback
  2006. */
  2007. repositionSongInQueue: isOwnerRequired(async function repositionQueue(session, stationId, song, cb) {
  2008. const stationModel = await DBModule.runJob("GET_MODEL", { modelName: "station" }, this);
  2009. async.waterfall(
  2010. [
  2011. next => {
  2012. if (!song || !song.youtubeId) return next("You must provide a song to reposition.");
  2013. return next();
  2014. },
  2015. // remove song from queue
  2016. next => {
  2017. stationModel.updateOne(
  2018. { _id: stationId },
  2019. { $pull: { queue: { youtubeId: song.youtubeId } } },
  2020. next
  2021. );
  2022. },
  2023. // add song back to queue (in new position)
  2024. (res, next) => {
  2025. stationModel.updateOne(
  2026. { _id: stationId },
  2027. { $push: { queue: { $each: [song], $position: song.newIndex } } },
  2028. err => next(err)
  2029. );
  2030. },
  2031. // update the cache representation of the station
  2032. next => {
  2033. StationsModule.runJob("UPDATE_STATION", { stationId }, this)
  2034. .then(station => next(null, station))
  2035. .catch(next);
  2036. }
  2037. ],
  2038. async err => {
  2039. if (err) {
  2040. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  2041. this.log(
  2042. "ERROR",
  2043. "STATIONS_REPOSITION_SONG_IN_QUEUE",
  2044. `Repositioning song ${song.youtubeId} in queue of station "${stationId}" failed. "${err}"`
  2045. );
  2046. return cb({ status: "error", message: err });
  2047. }
  2048. this.log(
  2049. "SUCCESS",
  2050. "STATIONS_REPOSITION_SONG_IN_QUEUE",
  2051. `Repositioned song ${song.youtubeId} in queue of station "${stationId}" successfully.`
  2052. );
  2053. CacheModule.runJob("PUB", {
  2054. channel: "station.repositionSongInQueue",
  2055. value: {
  2056. song: {
  2057. youtubeId: song.youtubeId,
  2058. oldIndex: song.oldIndex,
  2059. newIndex: song.newIndex
  2060. },
  2061. stationId
  2062. }
  2063. });
  2064. return cb({
  2065. status: "success",
  2066. message: "Successfully repositioned song in queue."
  2067. });
  2068. }
  2069. );
  2070. }),
  2071. /**
  2072. * Autofill a playlist in a station
  2073. *
  2074. * @param session
  2075. * @param stationId - the station id
  2076. * @param playlistId - the playlist id
  2077. * @param cb
  2078. */
  2079. autofillPlaylist: isOwnerRequired(async function autofillPlaylist(session, stationId, playlistId, cb) {
  2080. async.waterfall(
  2081. [
  2082. next => {
  2083. StationsModule.runJob("GET_STATION", { stationId }, this)
  2084. .then(station => next(null, station))
  2085. .catch(next);
  2086. },
  2087. (station, next) => {
  2088. if (!station) return next("Station not found.");
  2089. if (station.autofill.playlists.indexOf(playlistId) !== -1)
  2090. return next("That playlist is already autofilling.");
  2091. if (station.autofill.mode === "sequential" && station.autofill.playlists.length > 0)
  2092. return next("Error: Only 1 playlist can be autofilling in sequential mode.");
  2093. return next();
  2094. },
  2095. next => {
  2096. StationsModule.runJob("AUTOFILL_PLAYLIST", { stationId, playlistId }, this)
  2097. .then(() => {
  2098. next();
  2099. })
  2100. .catch(next);
  2101. }
  2102. ],
  2103. async err => {
  2104. if (err) {
  2105. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  2106. this.log(
  2107. "ERROR",
  2108. "STATIONS_AUTOFILL_PLAYLIST",
  2109. `Including playlist "${playlistId}" for station "${stationId}" failed. "${err}"`
  2110. );
  2111. return cb({ status: "error", message: err });
  2112. }
  2113. this.log(
  2114. "SUCCESS",
  2115. "STATIONS_AUTOFILL_PLAYLIST",
  2116. `Including playlist "${playlistId}" for station "${stationId}" successfully.`
  2117. );
  2118. PlaylistsModule.runJob("AUTOFILL_STATION_PLAYLIST", { stationId }).then().catch();
  2119. CacheModule.runJob("PUB", {
  2120. channel: "station.autofillPlaylist",
  2121. value: {
  2122. playlistId,
  2123. stationId
  2124. }
  2125. });
  2126. return cb({
  2127. status: "success",
  2128. message: "Successfully added autofill playlist."
  2129. });
  2130. }
  2131. );
  2132. }),
  2133. /**
  2134. * Remove autofilled playlist from a station
  2135. *
  2136. * @param session
  2137. * @param stationId - the station id
  2138. * @param playlistId - the playlist id
  2139. * @param cb
  2140. */
  2141. removeAutofillPlaylist: isOwnerRequired(async function removeAutofillPlaylist(session, stationId, playlistId, cb) {
  2142. async.waterfall(
  2143. [
  2144. next => {
  2145. StationsModule.runJob("GET_STATION", { stationId }, this)
  2146. .then(station => next(null, station))
  2147. .catch(next);
  2148. },
  2149. (station, next) => {
  2150. if (!station) return next("Station not found.");
  2151. if (station.autofill.playlists.indexOf(playlistId) === -1)
  2152. return next("That playlist is not autofilling.");
  2153. return next();
  2154. },
  2155. next => {
  2156. StationsModule.runJob("REMOVE_AUTOFILL_PLAYLIST", { stationId, playlistId }, this)
  2157. .then(() => {
  2158. next();
  2159. })
  2160. .catch(next);
  2161. }
  2162. ],
  2163. async err => {
  2164. if (err) {
  2165. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  2166. this.log(
  2167. "ERROR",
  2168. "STATIONS_REMOVE_AUTOFILL_PLAYLIST",
  2169. `Removing autofill playlist "${playlistId}" for station "${stationId}" failed. "${err}"`
  2170. );
  2171. return cb({ status: "error", message: err });
  2172. }
  2173. this.log(
  2174. "SUCCESS",
  2175. "STATIONS_REMOVE_AUTOFILL_PLAYLIST",
  2176. `Removing autofill playlist "${playlistId}" for station "${stationId}" successfully.`
  2177. );
  2178. PlaylistsModule.runJob("AUTOFILL_STATION_PLAYLIST", { stationId }).then().catch();
  2179. CacheModule.runJob("PUB", {
  2180. channel: "station.removedAutofillPlaylist",
  2181. value: {
  2182. playlistId,
  2183. stationId
  2184. }
  2185. });
  2186. return cb({
  2187. status: "success",
  2188. message: "Successfully removed autofill playlist."
  2189. });
  2190. }
  2191. );
  2192. }),
  2193. /**
  2194. * Blacklist a playlist in a station
  2195. *
  2196. * @param session
  2197. * @param stationId - the station id
  2198. * @param playlistId - the playlist id
  2199. * @param cb
  2200. */
  2201. blacklistPlaylist: isOwnerRequired(async function blacklistPlaylist(session, stationId, playlistId, cb) {
  2202. async.waterfall(
  2203. [
  2204. next => {
  2205. StationsModule.runJob("GET_STATION", { stationId }, this)
  2206. .then(station => next(null, station))
  2207. .catch(next);
  2208. },
  2209. (station, next) => {
  2210. if (!station) return next("Station not found.");
  2211. if (station.blacklist.indexOf(playlistId) !== -1)
  2212. return next("That playlist is already blacklisted.");
  2213. return next();
  2214. },
  2215. next => {
  2216. StationsModule.runJob("BLACKLIST_PLAYLIST", { stationId, playlistId }, this)
  2217. .then(() => {
  2218. next();
  2219. })
  2220. .catch(next);
  2221. }
  2222. ],
  2223. async err => {
  2224. if (err) {
  2225. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  2226. this.log(
  2227. "ERROR",
  2228. "STATIONS_BLACKLIST_PLAYLIST",
  2229. `Blacklisting playlist "${playlistId}" for station "${stationId}" failed. "${err}"`
  2230. );
  2231. return cb({ status: "error", message: err });
  2232. }
  2233. this.log(
  2234. "SUCCESS",
  2235. "STATIONS_BLACKLIST_PLAYLIST",
  2236. `Blacklisting playlist "${playlistId}" for station "${stationId}" successfully.`
  2237. );
  2238. PlaylistsModule.runJob("AUTOFILL_STATION_PLAYLIST", { stationId }).then().catch();
  2239. CacheModule.runJob("PUB", {
  2240. channel: "station.blacklistedPlaylist",
  2241. value: {
  2242. playlistId,
  2243. stationId
  2244. }
  2245. });
  2246. return cb({
  2247. status: "success",
  2248. message: "Successfully blacklisted playlist."
  2249. });
  2250. }
  2251. );
  2252. }),
  2253. /**
  2254. * Remove blacklisted a playlist from a station
  2255. *
  2256. * @param session
  2257. * @param stationId - the station id
  2258. * @param playlistId - the playlist id
  2259. * @param cb
  2260. */
  2261. removeBlacklistedPlaylist: isOwnerRequired(async function removeBlacklistedPlaylist(
  2262. session,
  2263. stationId,
  2264. playlistId,
  2265. cb
  2266. ) {
  2267. async.waterfall(
  2268. [
  2269. next => {
  2270. StationsModule.runJob("GET_STATION", { stationId }, this)
  2271. .then(station => next(null, station))
  2272. .catch(next);
  2273. },
  2274. (station, next) => {
  2275. if (!station) return next("Station not found.");
  2276. if (station.blacklist.indexOf(playlistId) === -1) return next("That playlist is not blacklisted.");
  2277. return next();
  2278. },
  2279. next => {
  2280. StationsModule.runJob("REMOVE_BLACKLISTED_PLAYLIST", { stationId, playlistId }, this)
  2281. .then(() => {
  2282. next();
  2283. })
  2284. .catch(next);
  2285. }
  2286. ],
  2287. async err => {
  2288. if (err) {
  2289. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  2290. this.log(
  2291. "ERROR",
  2292. "STATIONS_REMOVE_BLACKLISTED_PLAYLIST",
  2293. `Removing blacklisted playlist "${playlistId}" for station "${stationId}" failed. "${err}"`
  2294. );
  2295. return cb({ status: "error", message: err });
  2296. }
  2297. this.log(
  2298. "SUCCESS",
  2299. "STATIONS_REMOVE_BLACKLISTED_PLAYLIST",
  2300. `Removing blacklisted playlist "${playlistId}" for station "${stationId}" successfully.`
  2301. );
  2302. PlaylistsModule.runJob("AUTOFILL_STATION_PLAYLIST", { stationId }).then().catch();
  2303. CacheModule.runJob("PUB", {
  2304. channel: "station.removedBlacklistedPlaylist",
  2305. value: {
  2306. playlistId,
  2307. stationId
  2308. }
  2309. });
  2310. return cb({
  2311. status: "success",
  2312. message: "Successfully removed blacklisted playlist."
  2313. });
  2314. }
  2315. );
  2316. }),
  2317. favoriteStation: isLoginRequired(async function favoriteStation(session, stationId, cb) {
  2318. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  2319. async.waterfall(
  2320. [
  2321. next => {
  2322. StationsModule.runJob("GET_STATION", { stationId }, this)
  2323. .then(station => next(null, station))
  2324. .catch(next);
  2325. },
  2326. (station, next) => {
  2327. if (!station) return next("Station not found.");
  2328. return StationsModule.runJob("CAN_USER_VIEW_STATION", { station, userId: session.userId }, this)
  2329. .then(canView => {
  2330. if (canView) return next(null, station);
  2331. return next("Insufficient permissions.");
  2332. })
  2333. .catch(err => next(err));
  2334. },
  2335. (station, next) => {
  2336. userModel.updateOne(
  2337. { _id: session.userId },
  2338. { $addToSet: { favoriteStations: stationId } },
  2339. (err, res) => next(err, station, res)
  2340. );
  2341. },
  2342. (station, res, next) => {
  2343. if (res.nModified === 0) return next("The station was already favorited.");
  2344. return next(null, station);
  2345. }
  2346. ],
  2347. async (err, station) => {
  2348. if (err) {
  2349. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  2350. this.log("ERROR", "FAVORITE_STATION", `Favoriting station "${stationId}" failed. "${err}"`);
  2351. return cb({ status: "error", message: err });
  2352. }
  2353. this.log("SUCCESS", "FAVORITE_STATION", `Favorited station "${stationId}" successfully.`);
  2354. CacheModule.runJob("PUB", {
  2355. channel: "user.favoritedStation",
  2356. value: {
  2357. userId: session.userId,
  2358. stationId
  2359. }
  2360. });
  2361. ActivitiesModule.runJob("ADD_ACTIVITY", {
  2362. userId: session.userId,
  2363. type: "station__favorite",
  2364. payload: {
  2365. message: `Favorited station <stationId>${station.displayName}</stationId>`,
  2366. stationId
  2367. }
  2368. });
  2369. return cb({
  2370. status: "success",
  2371. message: "Succesfully favorited station."
  2372. });
  2373. }
  2374. );
  2375. }),
  2376. unfavoriteStation: isLoginRequired(async function unfavoriteStation(session, stationId, cb) {
  2377. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  2378. async.waterfall(
  2379. [
  2380. next => {
  2381. userModel.updateOne({ _id: session.userId }, { $pull: { favoriteStations: stationId } }, next);
  2382. },
  2383. (res, next) => {
  2384. if (res.nModified === 0) return next("The station wasn't favorited.");
  2385. return next();
  2386. },
  2387. next => {
  2388. StationsModule.runJob("GET_STATION", { stationId }, this)
  2389. .then(station => next(null, station))
  2390. .catch(next);
  2391. }
  2392. ],
  2393. async (err, station) => {
  2394. if (err) {
  2395. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  2396. this.log("ERROR", "UNFAVORITE_STATION", `Unfavoriting station "${stationId}" failed. "${err}"`);
  2397. return cb({ status: "error", message: err });
  2398. }
  2399. this.log("SUCCESS", "UNFAVORITE_STATION", `Unfavorited station "${stationId}" successfully.`);
  2400. CacheModule.runJob("PUB", {
  2401. channel: "user.unfavoritedStation",
  2402. value: {
  2403. userId: session.userId,
  2404. stationId
  2405. }
  2406. });
  2407. ActivitiesModule.runJob("ADD_ACTIVITY", {
  2408. userId: session.userId,
  2409. type: "station__unfavorite",
  2410. payload: {
  2411. message: `Unfavorited station <stationId>${station.displayName}</stationId>`,
  2412. stationId
  2413. }
  2414. });
  2415. return cb({
  2416. status: "success",
  2417. message: "Succesfully unfavorited station."
  2418. });
  2419. }
  2420. );
  2421. }),
  2422. /**
  2423. * Clears every station queue
  2424. *
  2425. * @param {object} session - the session object automatically added by socket.io
  2426. * @param {Function} cb - gets called with the result
  2427. */
  2428. clearEveryStationQueue: isAdminRequired(async function clearEveryStationQueue(session, cb) {
  2429. async.waterfall(
  2430. [
  2431. next => {
  2432. StationsModule.runJob("CLEAR_EVERY_STATION_QUEUE", {}, this)
  2433. .then(() => next())
  2434. .catch(next);
  2435. }
  2436. ],
  2437. async err => {
  2438. if (err) {
  2439. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  2440. this.log("ERROR", "CLEAR_EVERY_STATION_QUEUE", `Clearing every station queue failed. "${err}"`);
  2441. return cb({ status: "error", message: err });
  2442. }
  2443. this.log("SUCCESS", "CLEAR_EVERY_STATION_QUEUE", "Clearing every station queue was successful.");
  2444. return cb({ status: "success", message: "Successfully cleared every station queue." });
  2445. }
  2446. );
  2447. }),
  2448. /**
  2449. * Reset a station queue
  2450. *
  2451. * @param {object} session - the session object automatically added by socket.io
  2452. * @param {string} stationId - the station id
  2453. * @param {Function} cb - gets called with the result
  2454. */
  2455. resetQueue: isAdminRequired(async function resetQueue(session, stationId, cb) {
  2456. async.waterfall(
  2457. [
  2458. next => {
  2459. StationsModule.runJob("RESET_QUEUE", { stationId }, this)
  2460. .then(() => next())
  2461. .catch(next);
  2462. }
  2463. ],
  2464. async err => {
  2465. if (err) {
  2466. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  2467. this.log("ERROR", "RESET_QUEUE", `Resetting station queue failed. "${err}"`);
  2468. return cb({ status: "error", message: err });
  2469. }
  2470. this.log("SUCCESS", "RESET_QUEUE", "Resetting station queue was successful.");
  2471. return cb({ status: "success", message: "Successfully reset station queue." });
  2472. }
  2473. );
  2474. }),
  2475. /**
  2476. * Gets skip votes for a station
  2477. *
  2478. * @param session
  2479. * @param stationId - the station id
  2480. * @param stationId - the song id to get skipvotes for
  2481. * @param cb
  2482. */
  2483. getSkipVotes: isLoginRequired(async function getSkipVotes(session, stationId, songId, cb) {
  2484. async.waterfall(
  2485. [
  2486. next => {
  2487. StationsModule.runJob("GET_STATION", { stationId }, this)
  2488. .then(res => next(null, res.currentSong))
  2489. .catch(console.log);
  2490. },
  2491. (currentSong, next) => {
  2492. if (currentSong && currentSong._id === songId)
  2493. next(null, {
  2494. skipVotes: currentSong.skipVotes.length,
  2495. skipVotesCurrent: true
  2496. });
  2497. else
  2498. next(null, {
  2499. skipVotes: 0,
  2500. skipVotesCurrent: false
  2501. });
  2502. }
  2503. ],
  2504. async (err, data) => {
  2505. if (err) {
  2506. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  2507. this.log(
  2508. "ERROR",
  2509. "STATIONS_GET_SKIP_VOTES",
  2510. `User "${session.userId}" failed to get skip votes for ${stationId}. "${err}"`
  2511. );
  2512. return cb({ status: "error", message: err });
  2513. }
  2514. const { skipVotes, skipVotesCurrent } = data;
  2515. return cb({
  2516. status: "success",
  2517. data: {
  2518. skipVotes,
  2519. skipVotesCurrent
  2520. }
  2521. });
  2522. }
  2523. );
  2524. })
  2525. };