stations.js 101 KB

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