apis.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447
  1. import config from "config";
  2. import async from "async";
  3. import axios from "axios";
  4. import isLoginRequired from "../hooks/loginRequired";
  5. import isLoginSometimesRequired from "../hooks/loginSometimesRequired";
  6. import { hasPermission, useHasPermission } from "../hooks/hasPermission";
  7. // eslint-disable-next-line
  8. import moduleManager from "../../index";
  9. const UtilsModule = moduleManager.modules.utils;
  10. const WSModule = moduleManager.modules.ws;
  11. const YouTubeModule = moduleManager.modules.youtube;
  12. const SpotifyModule = moduleManager.modules.spotify;
  13. export default {
  14. /**
  15. * Fetches a list of songs from Youtube's API
  16. * @param {object} session - user session
  17. * @param {string} query - the query we'll pass to youtubes api
  18. * @param {Function} cb - callback
  19. * @returns {{status: string, data: object}} - returns an object
  20. */
  21. searchYoutube: isLoginRequired(function searchYoutube(session, query, cb) {
  22. return YouTubeModule.runJob("SEARCH", { query }, this)
  23. .then(data => {
  24. this.log("SUCCESS", "APIS_SEARCH_YOUTUBE", `Searching YouTube successful with query "${query}".`);
  25. return cb({ status: "success", data });
  26. })
  27. .catch(async err => {
  28. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  29. this.log("ERROR", "APIS_SEARCH_YOUTUBE", `Searching youtube failed with query "${query}". "${err}"`);
  30. return cb({ status: "error", message: err });
  31. });
  32. }),
  33. /**
  34. * Fetches a specific page of search results from Youtube's API
  35. * @param {object} session - user session
  36. * @param {string} query - the query we'll pass to youtubes api
  37. * @param {string} pageToken - identifies a specific page in the result set that should be retrieved
  38. * @param {Function} cb - callback
  39. * @returns {{status: string, data: object}} - returns an object
  40. */
  41. searchYoutubeForPage: isLoginRequired(function searchYoutubeForPage(session, query, pageToken, cb) {
  42. return YouTubeModule.runJob("SEARCH", { query, pageToken }, this)
  43. .then(data => {
  44. this.log(
  45. "SUCCESS",
  46. "APIS_SEARCH_YOUTUBE_FOR_PAGE",
  47. `Searching YouTube successful with query "${query}".`
  48. );
  49. return cb({ status: "success", data });
  50. })
  51. .catch(async err => {
  52. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  53. this.log(
  54. "ERROR",
  55. "APIS_SEARCH_YOUTUBE_FOR_PAGE",
  56. `Searching youtube failed with query "${query}". "${err}"`
  57. );
  58. return cb({ status: "error", message: err });
  59. });
  60. }),
  61. /**
  62. * Gets Discogs data
  63. * @param session
  64. * @param query - the query
  65. * @param {Function} cb
  66. */
  67. searchDiscogs: useHasPermission("apis.searchDiscogs", function searchDiscogs(session, query, page, cb) {
  68. async.waterfall(
  69. [
  70. next => {
  71. const options = {
  72. params: { q: query, per_page: 20, page },
  73. headers: {
  74. "User-Agent": "Request",
  75. Authorization: `Discogs key=${config.get("apis.discogs.client")}, secret=${config.get(
  76. "apis.discogs.secret"
  77. )}`
  78. }
  79. };
  80. axios
  81. .get("https://api.discogs.com/database/search", options)
  82. .then(res => next(null, res.data))
  83. .catch(err => next(err));
  84. }
  85. ],
  86. async (err, body) => {
  87. if (err) {
  88. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  89. this.log(
  90. "ERROR",
  91. "APIS_SEARCH_DISCOGS",
  92. `Searching discogs failed with query "${query}". "${err}"`
  93. );
  94. return cb({ status: "error", message: err });
  95. }
  96. this.log(
  97. "SUCCESS",
  98. "APIS_SEARCH_DISCOGS",
  99. `User "${session.userId}" searched Discogs succesfully for query "${query}".`
  100. );
  101. return cb({
  102. status: "success",
  103. data: {
  104. results: body.results,
  105. pages: body.pagination.pages
  106. }
  107. });
  108. }
  109. );
  110. }),
  111. /**
  112. * Gets alternative media sources for list of Spotify tracks (media sources)
  113. * @param session
  114. * @param trackId - the trackId
  115. * @param {Function} cb
  116. */
  117. getAlternativeMediaSourcesForTracks: useHasPermission(
  118. "spotify.getAlternativeMediaSourcesForTracks",
  119. function getAlternativeMediaSourcesForTracks(session, mediaSources, collectAlternativeMediaSourcesOrigins, cb) {
  120. async.waterfall(
  121. [
  122. next => {
  123. if (!mediaSources) {
  124. next("Invalid mediaSources provided.");
  125. return;
  126. }
  127. next();
  128. },
  129. next => {
  130. this.keepLongJob();
  131. this.publishProgress({
  132. status: "started",
  133. title: "Getting alternative media sources for Spotify tracks",
  134. message: "Starting up",
  135. id: this.toString()
  136. });
  137. SpotifyModule.runJob(
  138. "GET_ALTERNATIVE_MEDIA_SOURCES_FOR_TRACKS",
  139. {
  140. mediaSources,
  141. collectAlternativeMediaSourcesOrigins
  142. },
  143. this
  144. )
  145. .then(() => next())
  146. .catch(next);
  147. }
  148. ],
  149. async err => {
  150. if (err) {
  151. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  152. this.log(
  153. "ERROR",
  154. "APIS_GET_ALTERNATIVE_SOURCES",
  155. `Getting alternative sources failed for "${mediaSources.join(", ")}". "${err}"`
  156. );
  157. return cb({ status: "error", message: err });
  158. }
  159. this.log(
  160. "SUCCESS",
  161. "APIS_GET_ALTERNATIVE_SOURCES",
  162. `User "${session.userId}" started getting alternatives for "${mediaSources.join(", ")}".`
  163. );
  164. return cb({
  165. status: "success"
  166. });
  167. }
  168. );
  169. }
  170. ),
  171. /**
  172. * Gets alternative album sources (such as YouTube playlists) for a list of Spotify album ids
  173. * @param session
  174. * @param trackId - the trackId
  175. * @param {Function} cb
  176. */
  177. getAlternativeAlbumSourcesForAlbums: useHasPermission(
  178. "spotify.getAlternativeAlbumSourcesForAlbums",
  179. function getAlternativeAlbumSourcesForAlbums(session, albumIds, collectAlternativeAlbumSourcesOrigins, cb) {
  180. async.waterfall(
  181. [
  182. next => {
  183. if (!albumIds) {
  184. next("Invalid albumIds provided.");
  185. return;
  186. }
  187. next();
  188. },
  189. next => {
  190. this.keepLongJob();
  191. this.publishProgress({
  192. status: "started",
  193. title: "Getting alternative album sources for Spotify albums",
  194. message: "Starting up",
  195. id: this.toString()
  196. });
  197. SpotifyModule.runJob(
  198. "GET_ALTERNATIVE_ALBUM_SOURCES_FOR_ALBUMS",
  199. { albumIds, collectAlternativeAlbumSourcesOrigins },
  200. this
  201. )
  202. .then(() => next())
  203. .catch(next);
  204. }
  205. ],
  206. async err => {
  207. if (err) {
  208. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  209. this.log(
  210. "ERROR",
  211. "APIS_GET_ALTERNATIVE_ALBUM_SOURCES",
  212. `Getting alternative album sources failed for "${albumIds.join(", ")}". "${err}"`
  213. );
  214. return cb({ status: "error", message: err });
  215. }
  216. this.log(
  217. "SUCCESS",
  218. "APIS_GET_ALTERNATIVE_ALBUM_SOURCES",
  219. `User "${session.userId}" started getting alternative album spirces for "${albumIds.join(
  220. ", "
  221. )}".`
  222. );
  223. return cb({
  224. status: "success"
  225. });
  226. }
  227. );
  228. }
  229. ),
  230. /**
  231. * Gets a list of alternative artist sources (such as YouTube channels) for a list of Spotify artist ids
  232. * @param session
  233. * @param trackId - the trackId
  234. * @param {Function} cb
  235. */
  236. getAlternativeArtistSourcesForArtists: useHasPermission(
  237. "spotify.getAlternativeArtistSourcesForArtists",
  238. function getAlternativeArtistSourcesForArtists(session, artistIds, collectAlternativeArtistSourcesOrigins, cb) {
  239. async.waterfall(
  240. [
  241. next => {
  242. if (!artistIds) {
  243. next("Invalid artistIds provided.");
  244. return;
  245. }
  246. next();
  247. },
  248. next => {
  249. this.keepLongJob();
  250. this.publishProgress({
  251. status: "started",
  252. title: "Getting alternative artist sources for Spotify artists",
  253. message: "Starting up",
  254. id: this.toString()
  255. });
  256. SpotifyModule.runJob(
  257. "GET_ALTERNATIVE_ARTIST_SOURCES_FOR_ARTISTS",
  258. {
  259. artistIds,
  260. collectAlternativeArtistSourcesOrigins
  261. },
  262. this
  263. )
  264. .then(() => next())
  265. .catch(next);
  266. }
  267. ],
  268. async err => {
  269. if (err) {
  270. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  271. this.log(
  272. "ERROR",
  273. "APIS_GET_ALTERNATIVE_ARTIST_SOURCES",
  274. `Getting alternative artist sources failed for "${artistIds.join(", ")}". "${err}"`
  275. );
  276. return cb({ status: "error", message: err });
  277. }
  278. this.log(
  279. "SUCCESS",
  280. "APIS_GET_ALTERNATIVE_ARTIST_SOURCES",
  281. `User "${session.userId}" started getting alternative artist spirces for "${artistIds.join(
  282. ", "
  283. )}".`
  284. );
  285. return cb({
  286. status: "success"
  287. });
  288. }
  289. );
  290. }
  291. ),
  292. /**
  293. * Joins a room
  294. * @param {object} session - user session
  295. * @param {string} room - the room to join
  296. * @param {Function} cb - callback
  297. */
  298. joinRoom: isLoginSometimesRequired(function joinRoom(session, room, cb) {
  299. const roomName = room.split(".")[0];
  300. // const roomId = room.split(".")[1];
  301. const rooms = {
  302. home: null,
  303. news: null,
  304. profile: null,
  305. "view-media": null,
  306. "manage-station": null,
  307. // "manage-station": "stations.view",
  308. "edit-song": "songs.update",
  309. "edit-songs": "songs.update",
  310. "import-album": "songs.update",
  311. // "edit-playlist": "playlists.update",
  312. "view-report": "reports.get",
  313. "edit-user": "users.update",
  314. "view-api-request": "youtube.getApiRequest",
  315. "view-punishment": "punishments.get"
  316. };
  317. const join = (status, error) => {
  318. if (status === "success")
  319. WSModule.runJob("SOCKET_JOIN_ROOM", {
  320. socketId: session.socketId,
  321. room
  322. })
  323. .then(() => cb({ status: "success", message: "Successfully joined room." }))
  324. .catch(err => join("error", err.message));
  325. else {
  326. this.log("ERROR", `Joining room failed: ${error}`);
  327. cb({ status: "error", message: error });
  328. }
  329. };
  330. if (rooms[roomName] === null) join("success");
  331. else if (rooms[roomName])
  332. hasPermission(rooms[roomName], session)
  333. .then(() => join("success"))
  334. .catch(err => join("error", err));
  335. else join("error", "Room not found");
  336. }),
  337. /**
  338. * Leaves a room
  339. * @param {object} session - user session
  340. * @param {string} room - the room to leave
  341. * @param {Function} cb - callback
  342. */
  343. leaveRoom(session, room, cb) {
  344. if (
  345. room === "home" ||
  346. room.startsWith("profile.") ||
  347. room.startsWith("manage-station.") ||
  348. room.startsWith("edit-song.") ||
  349. room.startsWith("view-report.") ||
  350. room === "import-album" ||
  351. room === "edit-songs"
  352. ) {
  353. WSModule.runJob("SOCKET_LEAVE_ROOM", {
  354. socketId: session.socketId,
  355. room
  356. })
  357. .then(() => {})
  358. .catch(err => {
  359. this.log("ERROR", `Leaving room failed: ${err.message}`);
  360. });
  361. }
  362. cb({ status: "success", message: "Successfully left room." });
  363. },
  364. /**
  365. * Joins an admin room
  366. * @param {object} session - user session
  367. * @param {string} page - the admin room to join
  368. * @param {Function} cb - callback
  369. */
  370. joinAdminRoom(session, page, cb) {
  371. if (
  372. page === "songs" ||
  373. page === "artists" ||
  374. page === "stations" ||
  375. page === "reports" ||
  376. page === "news" ||
  377. page === "playlists" ||
  378. page === "users" ||
  379. page === "statistics" ||
  380. page === "punishments" ||
  381. page === "youtube" ||
  382. page === "youtubeVideos" ||
  383. page === "youtubeChannels" ||
  384. (config.get("experimental.soundcloud") && (page === "soundcloud" || page === "soundcloudTracks")) ||
  385. page === "import" ||
  386. page === "dataRequests"
  387. ) {
  388. hasPermission(`admin.view.${page}`, session.userId)
  389. .then(() =>
  390. WSModule.runJob("SOCKET_LEAVE_ROOMS", { socketId: session.socketId }).then(() => {
  391. WSModule.runJob(
  392. "SOCKET_JOIN_ROOM",
  393. {
  394. socketId: session.socketId,
  395. room: `admin.${page}`
  396. },
  397. this
  398. ).then(() => cb({ status: "success", message: "Successfully joined admin room." }));
  399. })
  400. )
  401. .catch(() => cb({ status: "error", message: "Failed to join admin room." }));
  402. }
  403. },
  404. /**
  405. * Leaves all rooms
  406. * @param {object} session - user session
  407. * @param {Function} cb - callback
  408. */
  409. leaveRooms(session, cb) {
  410. WSModule.runJob("SOCKET_LEAVE_ROOMS", { socketId: session.socketId });
  411. cb({ status: "success", message: "Successfully left all rooms." });
  412. },
  413. /**
  414. * Returns current date
  415. * @param {object} session - user session
  416. * @param {Function} cb - callback
  417. */
  418. ping(session, cb) {
  419. cb({ status: "success", message: "Successfully pinged.", data: { date: Date.now() } });
  420. }
  421. };