stations.js 82 KB

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