apis.js 12 KB

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