stations.js 83 KB

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