stations.js 74 KB

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