apis.js 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257
  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. export default {
  12. /**
  13. * Fetches a list of songs from Youtube's API
  14. *
  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. *
  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. *
  64. * @param session
  65. * @param query - the query
  66. * @param {Function} cb
  67. */
  68. searchDiscogs: useHasPermission("apis.searchDiscogs", function searchDiscogs(session, query, page, cb) {
  69. async.waterfall(
  70. [
  71. next => {
  72. const options = {
  73. params: { q: query, per_page: 20, page },
  74. headers: {
  75. "User-Agent": "Request",
  76. Authorization: `Discogs key=${config.get("apis.discogs.client")}, secret=${config.get(
  77. "apis.discogs.secret"
  78. )}`
  79. }
  80. };
  81. axios
  82. .get("https://api.discogs.com/database/search", options)
  83. .then(res => next(null, res.data))
  84. .catch(err => next(err));
  85. }
  86. ],
  87. async (err, body) => {
  88. if (err) {
  89. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  90. this.log(
  91. "ERROR",
  92. "APIS_SEARCH_DISCOGS",
  93. `Searching discogs failed with query "${query}". "${err}"`
  94. );
  95. return cb({ status: "error", message: err });
  96. }
  97. this.log(
  98. "SUCCESS",
  99. "APIS_SEARCH_DISCOGS",
  100. `User "${session.userId}" searched Discogs succesfully for query "${query}".`
  101. );
  102. return cb({
  103. status: "success",
  104. data: {
  105. results: body.results,
  106. pages: body.pagination.pages
  107. }
  108. });
  109. }
  110. );
  111. }),
  112. /**
  113. * Joins a room
  114. *
  115. * @param {object} session - user session
  116. * @param {string} room - the room to join
  117. * @param {Function} cb - callback
  118. */
  119. joinRoom(session, room, cb) {
  120. const roomName = room.split(".")[0];
  121. // const roomId = room.split(".")[1];
  122. const rooms = {
  123. home: null,
  124. news: null,
  125. profile: null,
  126. "view-youtube-video": null,
  127. "manage-station": null,
  128. // "manage-station": "stations.view",
  129. "edit-song": "songs.update",
  130. "edit-songs": "songs.update",
  131. "import-album": "songs.update",
  132. // "edit-playlist": "playlists.update",
  133. "view-report": "reports.get",
  134. "edit-user": "users.update",
  135. "view-api-request": "youtube.getApiRequest",
  136. "view-punishment": "punishments.get"
  137. };
  138. const join = (status, error) => {
  139. if (status === "success")
  140. WSModule.runJob("SOCKET_JOIN_ROOM", {
  141. socketId: session.socketId,
  142. room
  143. })
  144. .then(() => cb({ status: "success", message: "Successfully joined room." }))
  145. .catch(err => join("error", err.message));
  146. else {
  147. this.log("ERROR", `Joining room failed: ${error}`);
  148. cb({ status: "error", message: error });
  149. }
  150. };
  151. if (rooms[roomName] === null) join("success");
  152. else if (rooms[roomName])
  153. hasPermission(rooms[roomName], session)
  154. .then(() => join("success"))
  155. .catch(err => join("error", err));
  156. else join("error", "Room not found");
  157. },
  158. /**
  159. * Leaves a room
  160. *
  161. * @param {object} session - user session
  162. * @param {string} room - the room to leave
  163. * @param {Function} cb - callback
  164. */
  165. leaveRoom(session, room, cb) {
  166. if (
  167. room === "home" ||
  168. room.startsWith("profile.") ||
  169. room.startsWith("manage-station.") ||
  170. room.startsWith("edit-song.") ||
  171. room.startsWith("view-report.") ||
  172. room === "import-album" ||
  173. room === "edit-songs"
  174. ) {
  175. WSModule.runJob("SOCKET_LEAVE_ROOM", {
  176. socketId: session.socketId,
  177. room
  178. })
  179. .then(() => {})
  180. .catch(err => {
  181. this.log("ERROR", `Leaving room failed: ${err.message}`);
  182. });
  183. }
  184. cb({ status: "success", message: "Successfully left room." });
  185. },
  186. /**
  187. * Joins an admin room
  188. *
  189. * @param {object} session - user session
  190. * @param {string} page - the admin room to join
  191. * @param {Function} cb - callback
  192. */
  193. joinAdminRoom(session, page, cb) {
  194. if (
  195. page === "songs" ||
  196. page === "stations" ||
  197. page === "reports" ||
  198. page === "news" ||
  199. page === "playlists" ||
  200. page === "users" ||
  201. page === "statistics" ||
  202. page === "punishments" ||
  203. page === "youtube" ||
  204. page === "youtubeVideos" ||
  205. page === "import" ||
  206. page === "dataRequests"
  207. ) {
  208. hasPermission(`admin.view.${page}`, session.userId)
  209. .then(() =>
  210. WSModule.runJob("SOCKET_LEAVE_ROOMS", { socketId: session.socketId }).then(() => {
  211. WSModule.runJob(
  212. "SOCKET_JOIN_ROOM",
  213. {
  214. socketId: session.socketId,
  215. room: `admin.${page}`
  216. },
  217. this
  218. ).then(() => cb({ status: "success", message: "Successfully joined admin room." }));
  219. })
  220. )
  221. .catch(() => cb({ status: "error", message: "Failed to join admin room." }));
  222. }
  223. },
  224. /**
  225. * Leaves all rooms
  226. *
  227. * @param {object} session - user session
  228. * @param {Function} cb - callback
  229. */
  230. leaveRooms(session, cb) {
  231. WSModule.runJob("SOCKET_LEAVE_ROOMS", { socketId: session.socketId });
  232. cb({ status: "success", message: "Successfully left all rooms." });
  233. },
  234. /**
  235. * Returns current date
  236. *
  237. * @param {object} session - user session
  238. * @param {Function} cb - callback
  239. */
  240. ping(session, cb) {
  241. cb({ status: "success", message: "Successfully pinged.", data: { date: Date.now() } });
  242. }
  243. };