stations.js 103 KB

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