stations.js 103 KB

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