stations.js 104 KB

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