stations.js 104 KB

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