stations.js 90 KB

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