stations.js 102 KB

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