stations.js 98 KB

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