stations.js 99 KB

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