stations.js 99 KB

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