stations.js 86 KB

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