stations.js 68 KB

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