stations.js 103 KB

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