stations.js 75 KB

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