stations.js 83 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254
  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, queue: [] } },
  1805. { runValidators: true },
  1806. next
  1807. );
  1808. },
  1809. (res, next) => {
  1810. CacheModule.runJob("PUB", {
  1811. channel: "station.queueUpdate",
  1812. value: stationId
  1813. })
  1814. .then()
  1815. .catch();
  1816. StationsModule.runJob("UPDATE_STATION", { stationId }, this)
  1817. .then(station => {
  1818. next(null, station);
  1819. })
  1820. .catch(next);
  1821. }
  1822. ],
  1823. async err => {
  1824. if (err) {
  1825. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1826. this.log(
  1827. "ERROR",
  1828. "STATIONS_UPDATE_PARTY_MODE",
  1829. `Updating station "${stationId}" party mode to "${newPartyMode}" failed. "${err}"`
  1830. );
  1831. return cb({ status: "failure", message: err });
  1832. }
  1833. this.log(
  1834. "SUCCESS",
  1835. "STATIONS_UPDATE_PARTY_MODE",
  1836. `Updated station "${stationId}" party mode to "${newPartyMode}" successfully.`
  1837. );
  1838. CacheModule.runJob("PUB", {
  1839. channel: "station.updatePartyMode",
  1840. value: {
  1841. stationId,
  1842. partyMode: newPartyMode
  1843. }
  1844. });
  1845. StationsModule.runJob("SKIP_STATION", { stationId });
  1846. return cb({
  1847. status: "success",
  1848. message: "Successfully updated the party mode."
  1849. });
  1850. }
  1851. );
  1852. }),
  1853. /**
  1854. * Updates a station's theme
  1855. *
  1856. * @param session
  1857. * @param stationId - the station id
  1858. * @param newTheme - the new station theme
  1859. * @param cb
  1860. */
  1861. updateTheme: isOwnerRequired(async function updateTheme(session, stationId, newTheme, cb) {
  1862. const stationModel = await DBModule.runJob("GET_MODEL", { modelName: "station" }, this);
  1863. async.waterfall(
  1864. [
  1865. next => {
  1866. StationsModule.runJob("GET_STATION", { stationId }, this)
  1867. .then(station => {
  1868. next(null, station);
  1869. })
  1870. .catch(next);
  1871. },
  1872. (station, next) => {
  1873. if (!station) return next("Station not found.");
  1874. if (station.theme === newTheme) return next("No change in theme.");
  1875. return stationModel.updateOne(
  1876. { _id: stationId },
  1877. { $set: { theme: newTheme } },
  1878. { runValidators: true },
  1879. next
  1880. );
  1881. },
  1882. (res, next) => {
  1883. StationsModule.runJob("UPDATE_STATION", { stationId }, this)
  1884. .then(station => next(null, station))
  1885. .catch(next);
  1886. }
  1887. ],
  1888. async (err, station) => {
  1889. if (err) {
  1890. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1891. this.log(
  1892. "ERROR",
  1893. "STATIONS_UPDATE_THEME",
  1894. `Updating station "${stationId}" theme to "${newTheme}" failed. "${err}"`
  1895. );
  1896. return cb({ status: "failure", message: err });
  1897. }
  1898. this.log(
  1899. "SUCCESS",
  1900. "STATIONS_UPDATE_THEME",
  1901. `Updated station "${stationId}" theme to "${newTheme}" successfully.`
  1902. );
  1903. CacheModule.runJob("PUB", {
  1904. channel: "station.themeUpdate",
  1905. value: { stationId }
  1906. });
  1907. ActivitiesModule.runJob("ADD_ACTIVITY", {
  1908. userId: session.userId,
  1909. type: "station__edit_theme",
  1910. payload: {
  1911. message: `Changed theme of station <stationId>${station.displayName}</stationId> to ${newTheme}`,
  1912. stationId
  1913. }
  1914. });
  1915. return cb({
  1916. status: "success",
  1917. message: "Successfully updated the theme."
  1918. });
  1919. }
  1920. );
  1921. }),
  1922. /**
  1923. * Pauses a station
  1924. *
  1925. * @param session
  1926. * @param stationId - the station id
  1927. * @param cb
  1928. */
  1929. pause: isOwnerRequired(async function pause(session, stationId, cb) {
  1930. const stationModel = await DBModule.runJob(
  1931. "GET_MODEL",
  1932. {
  1933. modelName: "station"
  1934. },
  1935. this
  1936. );
  1937. async.waterfall(
  1938. [
  1939. next => {
  1940. StationsModule.runJob("GET_STATION", { stationId }, this)
  1941. .then(station => {
  1942. next(null, station);
  1943. })
  1944. .catch(next);
  1945. },
  1946. (station, next) => {
  1947. if (!station) return next("Station not found.");
  1948. if (station.paused) return next("That station was already paused.");
  1949. return stationModel.updateOne(
  1950. { _id: stationId },
  1951. { $set: { paused: true, pausedAt: Date.now() } },
  1952. next
  1953. );
  1954. },
  1955. (res, next) => {
  1956. StationsModule.runJob("UPDATE_STATION", { stationId }, this)
  1957. .then(station => {
  1958. next(null, station);
  1959. })
  1960. .catch(next);
  1961. }
  1962. ],
  1963. async err => {
  1964. if (err) {
  1965. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1966. this.log("ERROR", "STATIONS_PAUSE", `Pausing station "${stationId}" failed. "${err}"`);
  1967. return cb({ status: "failure", message: err });
  1968. }
  1969. this.log("SUCCESS", "STATIONS_PAUSE", `Paused station "${stationId}" successfully.`);
  1970. CacheModule.runJob("PUB", {
  1971. channel: "station.pause",
  1972. value: stationId
  1973. });
  1974. NotificationsModule.runJob("UNSCHEDULE", {
  1975. name: `stations.nextSong?id=${stationId}`
  1976. });
  1977. return cb({
  1978. status: "success",
  1979. message: "Successfully paused."
  1980. });
  1981. }
  1982. );
  1983. }),
  1984. /**
  1985. * Resumes a station
  1986. *
  1987. * @param session
  1988. * @param stationId - the station id
  1989. * @param cb
  1990. */
  1991. resume: isOwnerRequired(async function resume(session, stationId, cb) {
  1992. const stationModel = await DBModule.runJob(
  1993. "GET_MODEL",
  1994. {
  1995. modelName: "station"
  1996. },
  1997. this
  1998. );
  1999. async.waterfall(
  2000. [
  2001. next => {
  2002. StationsModule.runJob("GET_STATION", { stationId }, this)
  2003. .then(station => {
  2004. next(null, station);
  2005. })
  2006. .catch(next);
  2007. },
  2008. (station, next) => {
  2009. if (!station) return next("Station not found.");
  2010. if (!station.paused) return next("That station is not paused.");
  2011. station.timePaused += Date.now() - station.pausedAt;
  2012. return stationModel.updateOne(
  2013. { _id: stationId },
  2014. {
  2015. $set: { paused: false },
  2016. $inc: { timePaused: Date.now() - station.pausedAt }
  2017. },
  2018. next
  2019. );
  2020. },
  2021. (res, next) => {
  2022. StationsModule.runJob("UPDATE_STATION", { stationId }, this)
  2023. .then(station => {
  2024. next(null, station);
  2025. })
  2026. .catch(next);
  2027. }
  2028. ],
  2029. async err => {
  2030. if (err) {
  2031. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  2032. this.log("ERROR", "STATIONS_RESUME", `Resuming station "${stationId}" failed. "${err}"`);
  2033. return cb({ status: "failure", message: err });
  2034. }
  2035. this.log("SUCCESS", "STATIONS_RESUME", `Resuming station "${stationId}" successfully.`);
  2036. CacheModule.runJob("PUB", {
  2037. channel: "station.resume",
  2038. value: stationId
  2039. });
  2040. return cb({
  2041. status: "success",
  2042. message: "Successfully resumed."
  2043. });
  2044. }
  2045. );
  2046. }),
  2047. /**
  2048. * Removes a station
  2049. *
  2050. * @param session
  2051. * @param stationId - the station id
  2052. * @param cb
  2053. */
  2054. remove: isOwnerRequired(async function remove(session, stationId, cb) {
  2055. const stationModel = await DBModule.runJob("GET_MODEL", { modelName: "station" }, this);
  2056. async.waterfall(
  2057. [
  2058. next => {
  2059. stationModel.findById(stationId, (err, station) => {
  2060. if (err) return next(err);
  2061. return next(null, station);
  2062. });
  2063. },
  2064. (station, next) => {
  2065. stationModel.deleteOne({ _id: stationId }, err => next(err, station));
  2066. },
  2067. (station, next) => {
  2068. CacheModule.runJob("HDEL", { table: "stations", key: stationId }, this)
  2069. .then(() => next(null, station))
  2070. .catch(next);
  2071. },
  2072. (station, next) => {
  2073. if (station.playlist2)
  2074. PlaylistsModule.runJob("DELETE_PLAYLIST", { playlistId: station.playlist2 })
  2075. .then(() => {})
  2076. .catch(next);
  2077. next(null, station);
  2078. }
  2079. ],
  2080. async (err, station) => {
  2081. if (err) {
  2082. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  2083. this.log("ERROR", "STATIONS_REMOVE", `Removing station "${stationId}" failed. "${err}"`);
  2084. return cb({ status: "failure", message: err });
  2085. }
  2086. this.log("SUCCESS", "STATIONS_REMOVE", `Removing station "${stationId}" successfully.`);
  2087. CacheModule.runJob("PUB", {
  2088. channel: "station.remove",
  2089. value: stationId
  2090. });
  2091. ActivitiesModule.runJob("ADD_ACTIVITY", {
  2092. userId: session.userId,
  2093. type: "station__remove",
  2094. payload: { message: `Removed a station named ${station.displayName}` }
  2095. });
  2096. return cb({
  2097. status: "success",
  2098. message: "Successfully removed."
  2099. });
  2100. }
  2101. );
  2102. }),
  2103. /**
  2104. * Create a station
  2105. *
  2106. * @param session
  2107. * @param data - the station data
  2108. * @param cb
  2109. */
  2110. create: isLoginRequired(async function create(session, data, cb) {
  2111. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  2112. const stationModel = await DBModule.runJob("GET_MODEL", { modelName: "station" }, this);
  2113. const playlistModel = await DBModule.runJob("GET_MODEL", { modelName: "playlist" }, this);
  2114. data.name = data.name.toLowerCase();
  2115. const blacklist = [
  2116. "country",
  2117. "edm",
  2118. "musare",
  2119. "hip-hop",
  2120. "rap",
  2121. "top-hits",
  2122. "todays-hits",
  2123. "old-school",
  2124. "christmas",
  2125. "about",
  2126. "support",
  2127. "staff",
  2128. "help",
  2129. "news",
  2130. "terms",
  2131. "privacy",
  2132. "profile",
  2133. "c",
  2134. "community",
  2135. "tos",
  2136. "login",
  2137. "register",
  2138. "p",
  2139. "official",
  2140. "o",
  2141. "trap",
  2142. "faq",
  2143. "team",
  2144. "donate",
  2145. "buy",
  2146. "shop",
  2147. "forums",
  2148. "explore",
  2149. "settings",
  2150. "admin",
  2151. "auth",
  2152. "reset_password"
  2153. ];
  2154. async.waterfall(
  2155. [
  2156. next => {
  2157. if (!data) return next("Invalid data.");
  2158. return next();
  2159. },
  2160. next => {
  2161. stationModel.findOne(
  2162. {
  2163. $or: [
  2164. { name: data.name },
  2165. {
  2166. displayName: new RegExp(`^${data.displayName}$`, "i")
  2167. }
  2168. ]
  2169. },
  2170. next
  2171. );
  2172. },
  2173. // eslint-disable-next-line consistent-return
  2174. (station, next) => {
  2175. this.log(station);
  2176. if (station) return next("A station with that name or display name already exists.");
  2177. const { name, displayName, description, playlist, type, genres, blacklistedGenres } = data;
  2178. const stationId = mongoose.Types.ObjectId();
  2179. if (type === "official") {
  2180. return userModel.findOne({ _id: session.userId }, (err, user) => {
  2181. if (err) return next(err);
  2182. if (!user) return next("User not found.");
  2183. if (user.role !== "admin") return next("Admin required.");
  2184. return async.waterfall(
  2185. [
  2186. next => {
  2187. const playlists = [];
  2188. async.eachLimit(
  2189. genres,
  2190. 1,
  2191. (genre, next) => {
  2192. PlaylistsModule.runJob(
  2193. "GET_GENRE_PLAYLIST",
  2194. { genre, includeSongs: false },
  2195. this
  2196. )
  2197. .then(response => {
  2198. playlists.push(response.playlist);
  2199. next();
  2200. })
  2201. .catch(err => {
  2202. next(
  2203. `An error occurred when trying to get genre playlist for genre ${genre}. Error: ${err}.`
  2204. );
  2205. });
  2206. },
  2207. err => {
  2208. next(
  2209. err,
  2210. playlists.map(playlist => playlist._id.toString())
  2211. );
  2212. }
  2213. );
  2214. },
  2215. (genrePlaylistIds, next) => {
  2216. const playlists = [];
  2217. async.eachLimit(
  2218. blacklistedGenres,
  2219. 1,
  2220. (genre, next) => {
  2221. PlaylistsModule.runJob(
  2222. "GET_GENRE_PLAYLIST",
  2223. { genre, includeSongs: false },
  2224. this
  2225. )
  2226. .then(response => {
  2227. playlists.push(response.playlist);
  2228. next();
  2229. })
  2230. .catch(err => {
  2231. next(
  2232. `An error occurred when trying to get genre playlist for genre ${genre}. Error: ${err}.`
  2233. );
  2234. });
  2235. },
  2236. err => {
  2237. next(
  2238. err,
  2239. genrePlaylistIds,
  2240. playlists.map(playlist => playlist._id.toString())
  2241. );
  2242. }
  2243. );
  2244. },
  2245. (genrePlaylistIds, blacklistedGenrePlaylistIds, next) => {
  2246. const duplicateGenre =
  2247. genrePlaylistIds.length !== new Set(genrePlaylistIds).size;
  2248. const duplicateBlacklistedGenre =
  2249. genrePlaylistIds.length !== new Set(genrePlaylistIds).size;
  2250. const duplicateCross =
  2251. genrePlaylistIds.length + blacklistedGenrePlaylistIds.length !==
  2252. new Set([...genrePlaylistIds, ...blacklistedGenrePlaylistIds]).size;
  2253. if (duplicateGenre)
  2254. return next("You cannot have the same genre included twice.");
  2255. if (duplicateBlacklistedGenre)
  2256. return next("You cannot have the same blacklisted genre included twice.");
  2257. if (duplicateCross)
  2258. return next(
  2259. "You cannot have the same genre included and blacklisted at the same time."
  2260. );
  2261. return next(null, genrePlaylistIds, blacklistedGenrePlaylistIds);
  2262. }
  2263. ],
  2264. (err, genrePlaylistIds, blacklistedGenrePlaylistIds) => {
  2265. if (err) return next(err);
  2266. return playlistModel.create(
  2267. {
  2268. isUserModifiable: false,
  2269. displayName: `Station - ${displayName}`,
  2270. songs: [],
  2271. createdBy: "Musare",
  2272. createdFor: `${stationId}`,
  2273. createdAt: Date.now(),
  2274. type: "station"
  2275. },
  2276. (err, playlist2) => {
  2277. if (err) next(err);
  2278. else {
  2279. stationModel.create(
  2280. {
  2281. _id: stationId,
  2282. name,
  2283. displayName,
  2284. description,
  2285. type,
  2286. privacy: "private",
  2287. playlist2: playlist2._id,
  2288. playlist,
  2289. currentSong: StationsModule.defaultSong
  2290. },
  2291. (err, station) => {
  2292. next(
  2293. err,
  2294. station,
  2295. genrePlaylistIds,
  2296. blacklistedGenrePlaylistIds
  2297. );
  2298. }
  2299. );
  2300. }
  2301. }
  2302. );
  2303. }
  2304. );
  2305. });
  2306. }
  2307. if (type === "community") {
  2308. if (blacklist.indexOf(name) !== -1)
  2309. return next("That name is blacklisted. Please use a different name.");
  2310. return playlistModel.create(
  2311. {
  2312. isUserModifiable: false,
  2313. displayName: `Station - ${name}`,
  2314. songs: [],
  2315. createdBy: session.userId,
  2316. createdFor: `${stationId}`,
  2317. createdAt: Date.now(),
  2318. type: "station"
  2319. },
  2320. (err, playlist2) => {
  2321. if (err) next(err);
  2322. else {
  2323. stationModel.create(
  2324. {
  2325. _id: stationId,
  2326. name,
  2327. displayName,
  2328. description,
  2329. playlist2: playlist2._id,
  2330. type,
  2331. privacy: "private",
  2332. owner: session.userId,
  2333. queue: [],
  2334. currentSong: null
  2335. },
  2336. (err, station) => {
  2337. next(err, station, null, null);
  2338. }
  2339. );
  2340. }
  2341. }
  2342. );
  2343. }
  2344. },
  2345. (station, genrePlaylistIds, blacklistedGenrePlaylistIds, next) => {
  2346. if (station.type !== "official") return next(null, station);
  2347. const stationId = station._id;
  2348. console.log(111, station, genrePlaylistIds, blacklistedGenrePlaylistIds, next);
  2349. return async.waterfall(
  2350. [
  2351. next => {
  2352. async.eachLimit(
  2353. genrePlaylistIds,
  2354. 1,
  2355. (playlistId, next) => {
  2356. StationsModule.runJob("INCLUDE_PLAYLIST", { stationId, playlistId }, this)
  2357. .then(() => {
  2358. next();
  2359. })
  2360. .catch(next);
  2361. },
  2362. next
  2363. );
  2364. },
  2365. next => {
  2366. async.eachLimit(
  2367. blacklistedGenrePlaylistIds,
  2368. 1,
  2369. (playlistId, next) => {
  2370. StationsModule.runJob("EXCLUDE_PLAYLIST", { stationId, playlistId }, this)
  2371. .then(() => {
  2372. next();
  2373. })
  2374. .catch(next);
  2375. },
  2376. next
  2377. );
  2378. },
  2379. next => {
  2380. PlaylistsModule.runJob("AUTOFILL_STATION_PLAYLIST", { stationId }).then().catch();
  2381. next();
  2382. }
  2383. ],
  2384. async err => {
  2385. if (err) {
  2386. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  2387. this.log(
  2388. "ERROR",
  2389. "STATIONS_CREATE",
  2390. `Created station ${stationId} successfully, but an error occurred during playing including/excluding. Error: ${err}`
  2391. );
  2392. }
  2393. next(null, station, err);
  2394. }
  2395. );
  2396. }
  2397. ],
  2398. async (err, station, extraError) => {
  2399. if (err) {
  2400. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  2401. this.log("ERROR", "STATIONS_CREATE", `Creating station failed. "${err}"`);
  2402. cb({ status: "failure", message: err });
  2403. } else {
  2404. this.log("SUCCESS", "STATIONS_CREATE", `Created station "${station._id}" successfully.`);
  2405. CacheModule.runJob("PUB", {
  2406. channel: "station.create",
  2407. value: station._id
  2408. });
  2409. ActivitiesModule.runJob("ADD_ACTIVITY", {
  2410. userId: session.userId,
  2411. type: "station__create",
  2412. payload: {
  2413. message: `Created a station named <stationId>${station.displayName}</stationId>`,
  2414. stationId: station._id
  2415. }
  2416. });
  2417. if (!extraError) {
  2418. cb({
  2419. status: "success",
  2420. message: "Successfully created station."
  2421. });
  2422. } else {
  2423. cb({
  2424. status: "success",
  2425. message: `Successfully created station, but with one error at the end: ${extraError}`
  2426. });
  2427. }
  2428. }
  2429. }
  2430. );
  2431. }),
  2432. /**
  2433. * Adds song to station queue
  2434. *
  2435. * @param session
  2436. * @param stationId - the station id
  2437. * @param songId - the song id
  2438. * @param cb
  2439. */
  2440. addToQueue: isLoginRequired(async function addToQueue(session, stationId, songId, cb) {
  2441. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  2442. const stationModel = await DBModule.runJob(
  2443. "GET_MODEL",
  2444. {
  2445. modelName: "station"
  2446. },
  2447. this
  2448. );
  2449. async.waterfall(
  2450. [
  2451. next => {
  2452. StationsModule.runJob("GET_STATION", { stationId }, this)
  2453. .then(station => {
  2454. next(null, station);
  2455. })
  2456. .catch(next);
  2457. },
  2458. (station, next) => {
  2459. if (!station) return next("Station not found.");
  2460. if (!station.partyMode) return next("Station is not in party mode.");
  2461. if (station.locked) {
  2462. return userModel.findOne({ _id: session.userId }, (err, user) => {
  2463. if (user.role !== "admin" && station.owner !== session.userId)
  2464. return next("Only owners and admins can add songs to a locked queue.");
  2465. return next(null, station);
  2466. });
  2467. }
  2468. return next(null, station);
  2469. },
  2470. (station, next) => {
  2471. if (station.type !== "community") return next("That station is not a community station.");
  2472. return StationsModule.runJob(
  2473. "CAN_USER_VIEW_STATION",
  2474. {
  2475. station,
  2476. userId: session.userId
  2477. },
  2478. this
  2479. )
  2480. .then(canView => {
  2481. if (canView) return next(null, station);
  2482. return next("Insufficient permissions.");
  2483. })
  2484. .catch(err => next(err));
  2485. },
  2486. (station, next) => {
  2487. if (station.currentSong && station.currentSong.songId === songId)
  2488. return next("That song is currently playing.");
  2489. return async.each(
  2490. station.queue,
  2491. (queueSong, next) => {
  2492. if (queueSong.songId === songId) return next("That song is already in the queue.");
  2493. return next();
  2494. },
  2495. err => next(err, station)
  2496. );
  2497. },
  2498. (station, next) => {
  2499. SongsModule.runJob("GET_SONG_FROM_ID", { songId }, this)
  2500. .then(res => {
  2501. if (res.song) return next(null, res.song, station);
  2502. return YouTubeModule.runJob("GET_SONG", { songId }, this)
  2503. .then(response => {
  2504. const { song } = response;
  2505. song.artists = [];
  2506. song.skipDuration = 0;
  2507. song.likes = -1;
  2508. song.dislikes = -1;
  2509. song.thumbnail = "empty";
  2510. song.explicit = false;
  2511. return next(null, song, station);
  2512. })
  2513. .catch(err => {
  2514. next(err);
  2515. });
  2516. })
  2517. .catch(err => {
  2518. next(err);
  2519. });
  2520. },
  2521. (song, station, next) => {
  2522. song.requestedBy = session.userId;
  2523. song.requestedAt = Date.now();
  2524. song._id = null;
  2525. let totalDuration = 0;
  2526. station.queue.forEach(song => {
  2527. totalDuration += song.duration;
  2528. });
  2529. if (totalDuration >= 3600 * 3) return next("The max length of the queue is 3 hours.");
  2530. return next(null, song, station);
  2531. },
  2532. (song, station, next) => {
  2533. if (station.queue.length === 0) return next(null, song, station);
  2534. let totalDuration = 0;
  2535. const userId = station.queue[station.queue.length - 1].requestedBy;
  2536. station.queue.forEach(song => {
  2537. if (userId === song.requestedBy) {
  2538. totalDuration += song.duration;
  2539. }
  2540. });
  2541. if (totalDuration >= 900) return next("The max length of songs per user is 15 minutes.");
  2542. return next(null, song, station);
  2543. },
  2544. (song, station, next) => {
  2545. if (station.queue.length === 0) return next(null, song);
  2546. let totalSongs = 0;
  2547. const userId = station.queue[station.queue.length - 1].requestedBy;
  2548. station.queue.forEach(song => {
  2549. if (userId === song.requestedBy) {
  2550. totalSongs += 1;
  2551. }
  2552. });
  2553. if (totalSongs <= 2) return next(null, song);
  2554. if (totalSongs > 3)
  2555. return next("The max amount of songs per user is 3, and only 2 in a row is allowed.");
  2556. if (
  2557. station.queue[station.queue.length - 2].requestedBy !== userId ||
  2558. station.queue[station.queue.length - 3] !== userId
  2559. )
  2560. return next("The max amount of songs per user is 3, and only 2 in a row is allowed.");
  2561. return next(null, song);
  2562. },
  2563. (song, next) => {
  2564. stationModel.updateOne(
  2565. { _id: stationId },
  2566. { $push: { queue: song } },
  2567. { runValidators: true },
  2568. next
  2569. );
  2570. },
  2571. (res, next) => {
  2572. StationsModule.runJob("UPDATE_STATION", { stationId }, this)
  2573. .then(station => next(null, station))
  2574. .catch(next);
  2575. }
  2576. // (res, next) => {
  2577. // StationsModule.runJob("UPDATE_STATION", { stationId }, this)
  2578. // .then(station => {
  2579. // next(null, station);
  2580. // })
  2581. // .catch(next);
  2582. // }
  2583. ],
  2584. async err => {
  2585. if (err) {
  2586. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  2587. this.log(
  2588. "ERROR",
  2589. "STATIONS_ADD_SONG_TO_QUEUE",
  2590. `Adding song "${songId}" to station "${stationId}" queue failed. "${err}"`
  2591. );
  2592. return cb({ status: "failure", message: err });
  2593. }
  2594. this.log(
  2595. "SUCCESS",
  2596. "STATIONS_ADD_SONG_TO_QUEUE",
  2597. `Added song "${songId}" to station "${stationId}" successfully.`
  2598. );
  2599. CacheModule.runJob("PUB", {
  2600. channel: "station.queueUpdate",
  2601. value: stationId
  2602. });
  2603. return cb({
  2604. status: "success",
  2605. message: "Successfully added song to queue."
  2606. });
  2607. }
  2608. );
  2609. }),
  2610. /**
  2611. * Removes song from station queue
  2612. *
  2613. * @param session
  2614. * @param stationId - the station id
  2615. * @param songId - the song id
  2616. * @param cb
  2617. */
  2618. removeFromQueue: isOwnerRequired(async function removeFromQueue(session, stationId, songId, cb) {
  2619. const stationModel = await DBModule.runJob("GET_MODEL", { modelName: "station" }, this);
  2620. async.waterfall(
  2621. [
  2622. next => {
  2623. if (!songId) return next("Invalid song id.");
  2624. return StationsModule.runJob("GET_STATION", { stationId }, this)
  2625. .then(station => next(null, station))
  2626. .catch(next);
  2627. },
  2628. (station, next) => {
  2629. if (!station) return next("Station not found.");
  2630. if (station.type !== "community") return next("Station is not a community station.");
  2631. return async.each(
  2632. station.queue,
  2633. (queueSong, next) => {
  2634. if (queueSong.songId === songId) return next(true);
  2635. return next();
  2636. },
  2637. err => {
  2638. if (err === true) return next();
  2639. return next("Song is not currently in the queue.");
  2640. }
  2641. );
  2642. },
  2643. next => {
  2644. stationModel.updateOne({ _id: stationId }, { $pull: { queue: { songId } } }, next);
  2645. },
  2646. (res, next) => {
  2647. StationsModule.runJob("UPDATE_STATION", { stationId }, this)
  2648. .then(station => next(null, station))
  2649. .catch(next);
  2650. }
  2651. ],
  2652. async err => {
  2653. if (err) {
  2654. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  2655. this.log(
  2656. "ERROR",
  2657. "STATIONS_REMOVE_SONG_TO_QUEUE",
  2658. `Removing song "${songId}" from station "${stationId}" queue failed. "${err}"`
  2659. );
  2660. return cb({ status: "failure", message: err });
  2661. }
  2662. this.log(
  2663. "SUCCESS",
  2664. "STATIONS_REMOVE_SONG_TO_QUEUE",
  2665. `Removed song "${songId}" from station "${stationId}" successfully.`
  2666. );
  2667. CacheModule.runJob("PUB", {
  2668. channel: "station.queueUpdate",
  2669. value: stationId
  2670. });
  2671. return cb({
  2672. status: "success",
  2673. message: "Successfully removed song from queue."
  2674. });
  2675. }
  2676. );
  2677. }),
  2678. /**
  2679. * Gets the queue from a station
  2680. *
  2681. * @param {object} session - user session
  2682. * @param {string} stationId - the station id
  2683. * @param {Function} cb - callback
  2684. */
  2685. getQueue(session, stationId, cb) {
  2686. async.waterfall(
  2687. [
  2688. next => {
  2689. StationsModule.runJob("GET_STATION", { stationId }, this)
  2690. .then(station => next(null, station))
  2691. .catch(next);
  2692. },
  2693. (station, next) => {
  2694. if (!station) return next("Station not found.");
  2695. return next(null, station);
  2696. },
  2697. (station, next) => {
  2698. StationsModule.runJob("CAN_USER_VIEW_STATION", { station, userId: session.userId }, this)
  2699. .then(canView => {
  2700. if (canView) return next(null, station);
  2701. return next("Insufficient permissions.");
  2702. })
  2703. .catch(err => next(err));
  2704. },
  2705. (station, next) => {
  2706. if (station.type === "official") next(null, station.queue);
  2707. else next(null, station.queue);
  2708. }
  2709. ],
  2710. async (err, queue) => {
  2711. if (err) {
  2712. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  2713. this.log(
  2714. "ERROR",
  2715. "STATIONS_GET_QUEUE",
  2716. `Getting queue for station "${stationId}" failed. "${err}"`
  2717. );
  2718. return cb({ status: "failure", message: err });
  2719. }
  2720. this.log("SUCCESS", "STATIONS_GET_QUEUE", `Got queue for station "${stationId}" successfully.`);
  2721. return cb({
  2722. status: "success",
  2723. message: "Successfully got queue.",
  2724. queue
  2725. });
  2726. }
  2727. );
  2728. },
  2729. /**
  2730. * Selects a private playlist for a station
  2731. *
  2732. * @param session
  2733. * @param stationId - the station id
  2734. * @param playlistId - the private playlist id
  2735. * @param cb
  2736. */
  2737. selectPrivatePlaylist: isOwnerRequired(async function selectPrivatePlaylist(session, stationId, playlistId, cb) {
  2738. async.waterfall(
  2739. [
  2740. next => {
  2741. StationsModule.runJob("GET_STATION", { stationId }, this)
  2742. .then(station => next(null, station))
  2743. .catch(next);
  2744. },
  2745. (station, next) => {
  2746. if (!station) return next("Station not found.");
  2747. if (station.type !== "community") return next("Station is not a community station.");
  2748. if (station.includedPlaylists.indexOf(playlistId) !== -1)
  2749. return next("That playlist is already included.");
  2750. return next();
  2751. },
  2752. next => {
  2753. StationsModule.runJob("INCLUDE_PLAYLIST", { stationId, playlistId }, this)
  2754. .then(() => {
  2755. next();
  2756. })
  2757. .catch(next);
  2758. }
  2759. ],
  2760. async err => {
  2761. if (err) {
  2762. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  2763. this.log(
  2764. "ERROR",
  2765. "STATIONS_SELECT_PRIVATE_PLAYLIST",
  2766. `Selecting private playlist "${playlistId}" for station "${stationId}" failed. "${err}"`
  2767. );
  2768. return cb({ status: "failure", message: err });
  2769. }
  2770. this.log(
  2771. "SUCCESS",
  2772. "STATIONS_SELECT_PRIVATE_PLAYLIST",
  2773. `Selected private playlist "${playlistId}" for station "${stationId}" successfully.`
  2774. );
  2775. PlaylistsModule.runJob("AUTOFILL_STATION_PLAYLIST", { stationId }).then().catch();
  2776. // CacheModule.runJob("PUB", {
  2777. // channel: "privatePlaylist.selected",
  2778. // value: {
  2779. // playlistId,
  2780. // stationId
  2781. // }
  2782. // });
  2783. return cb({
  2784. status: "success",
  2785. message: "Successfully selected playlist."
  2786. });
  2787. }
  2788. );
  2789. }),
  2790. /**
  2791. * Deselects the private playlist selected in a station
  2792. *
  2793. * @param session
  2794. * @param stationId - the station id
  2795. * @param cb
  2796. */
  2797. deselectPrivatePlaylist: isOwnerRequired(async function deselectPrivatePlaylist(
  2798. session,
  2799. stationId,
  2800. playlistId,
  2801. cb
  2802. ) {
  2803. async.waterfall(
  2804. [
  2805. next => {
  2806. StationsModule.runJob("GET_STATION", { stationId }, this)
  2807. .then(station => {
  2808. next(null, station);
  2809. })
  2810. .catch(next);
  2811. },
  2812. (station, next) => {
  2813. if (!station) return next("Station not found.");
  2814. if (station.type !== "community") return next("Station is not a community station.");
  2815. if (station.includedPlaylists.indexOf(playlistId) === -1)
  2816. return next("That playlist is not included.");
  2817. return next();
  2818. },
  2819. next => {
  2820. StationsModule.runJob("REMOVE_INCLUDED_PLAYLIST", { stationId, playlistId }, this)
  2821. .then(() => {
  2822. next();
  2823. })
  2824. .catch(next);
  2825. }
  2826. ],
  2827. async err => {
  2828. if (err) {
  2829. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  2830. this.log(
  2831. "ERROR",
  2832. "STATIONS_DESELECT_PRIVATE_PLAYLIST",
  2833. `Deselecting private playlist for station "${stationId}" failed. "${err}"`
  2834. );
  2835. return cb({ status: "failure", message: err });
  2836. }
  2837. this.log(
  2838. "SUCCESS",
  2839. "STATIONS_DESELECT_PRIVATE_PLAYLIST",
  2840. `Deselected private playlist for station "${stationId}" successfully.`
  2841. );
  2842. PlaylistsModule.runJob("AUTOFILL_STATION_PLAYLIST", { stationId }).then().catch();
  2843. // CacheModule.runJob("PUB", {
  2844. // channel: "privatePlaylist.deselected",
  2845. // value: {
  2846. // stationId
  2847. // }
  2848. // });
  2849. return cb({
  2850. status: "success",
  2851. message: "Successfully deselected playlist."
  2852. });
  2853. }
  2854. );
  2855. }),
  2856. favoriteStation: isLoginRequired(async function favoriteStation(session, stationId, cb) {
  2857. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  2858. async.waterfall(
  2859. [
  2860. next => {
  2861. StationsModule.runJob("GET_STATION", { stationId }, this)
  2862. .then(station => next(null, station))
  2863. .catch(next);
  2864. },
  2865. (station, next) => {
  2866. if (!station) return next("Station not found.");
  2867. return StationsModule.runJob("CAN_USER_VIEW_STATION", { station, userId: session.userId }, this)
  2868. .then(canView => {
  2869. if (canView) return next(null, station);
  2870. return next("Insufficient permissions.");
  2871. })
  2872. .catch(err => next(err));
  2873. },
  2874. (station, next) => {
  2875. userModel.updateOne(
  2876. { _id: session.userId },
  2877. { $addToSet: { favoriteStations: stationId } },
  2878. (err, res) => next(err, station, res)
  2879. );
  2880. },
  2881. (station, res, next) => {
  2882. if (res.nModified === 0) return next("The station was already favorited.");
  2883. return next(null, station);
  2884. }
  2885. ],
  2886. async (err, station) => {
  2887. if (err) {
  2888. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  2889. this.log("ERROR", "FAVORITE_STATION", `Favoriting station "${stationId}" failed. "${err}"`);
  2890. return cb({ status: "failure", message: err });
  2891. }
  2892. this.log("SUCCESS", "FAVORITE_STATION", `Favorited station "${stationId}" successfully.`);
  2893. CacheModule.runJob("PUB", {
  2894. channel: "user.favoritedStation",
  2895. value: {
  2896. userId: session.userId,
  2897. stationId
  2898. }
  2899. });
  2900. ActivitiesModule.runJob("ADD_ACTIVITY", {
  2901. userId: session.userId,
  2902. type: "station__favorite",
  2903. payload: {
  2904. message: `Favorited station <stationId>${station.displayName}</stationId>`,
  2905. stationId
  2906. }
  2907. });
  2908. return cb({
  2909. status: "success",
  2910. message: "Succesfully favorited station."
  2911. });
  2912. }
  2913. );
  2914. }),
  2915. unfavoriteStation: isLoginRequired(async function unfavoriteStation(session, stationId, cb) {
  2916. const userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" }, this);
  2917. async.waterfall(
  2918. [
  2919. next => {
  2920. userModel.updateOne({ _id: session.userId }, { $pull: { favoriteStations: stationId } }, next);
  2921. },
  2922. (res, next) => {
  2923. if (res.nModified === 0) return next("The station wasn't favorited.");
  2924. return next();
  2925. },
  2926. next => {
  2927. StationsModule.runJob("GET_STATION", { stationId }, this)
  2928. .then(station => next(null, station))
  2929. .catch(next);
  2930. }
  2931. ],
  2932. async (err, station) => {
  2933. if (err) {
  2934. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  2935. this.log("ERROR", "UNFAVORITE_STATION", `Unfavoriting station "${stationId}" failed. "${err}"`);
  2936. return cb({ status: "failure", message: err });
  2937. }
  2938. this.log("SUCCESS", "UNFAVORITE_STATION", `Unfavorited station "${stationId}" successfully.`);
  2939. CacheModule.runJob("PUB", {
  2940. channel: "user.unfavoritedStation",
  2941. value: {
  2942. userId: session.userId,
  2943. stationId
  2944. }
  2945. });
  2946. ActivitiesModule.runJob("ADD_ACTIVITY", {
  2947. userId: session.userId,
  2948. type: "station__unfavorite",
  2949. payload: {
  2950. message: `Unfavorited station <stationId>${station.displayName}</stationId>`,
  2951. stationId
  2952. }
  2953. });
  2954. return cb({
  2955. status: "success",
  2956. message: "Succesfully unfavorited station."
  2957. });
  2958. }
  2959. );
  2960. })
  2961. };