stations.js 73 KB

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