stations.js 83 KB

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