stations.js 85 KB

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