api.js 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253
  1. import config from "config";
  2. import async from "async";
  3. import CoreClass from "../core";
  4. // let APIModule;
  5. let AppModule;
  6. // let DBModule;
  7. let PlaylistsModule;
  8. let UtilsModule;
  9. let PunishmentsModule;
  10. let CacheModule;
  11. // let NotificationsModule;
  12. class _APIModule extends CoreClass {
  13. // eslint-disable-next-line require-jsdoc
  14. constructor() {
  15. super("api");
  16. // APIModule = this;
  17. }
  18. /**
  19. * Initialises the api module
  20. *
  21. * @returns {Promise} - returns promise (reject, resolve)
  22. */
  23. initialize() {
  24. return new Promise((resolve, reject) => {
  25. AppModule = this.moduleManager.modules.app;
  26. // DBModule = this.moduleManager.modules.db;
  27. PlaylistsModule = this.moduleManager.modules.playlists;
  28. UtilsModule = this.moduleManager.modules.utils;
  29. PunishmentsModule = this.moduleManager.modules.punishments;
  30. CacheModule = this.moduleManager.modules.cache;
  31. // NotificationsModule = this.moduleManager.modules.notifications;
  32. const SIDname = config.get("cookie.SIDname");
  33. const isLoggedIn = (req, res, next) => {
  34. let SID;
  35. async.waterfall(
  36. [
  37. next => {
  38. UtilsModule.runJob("PARSE_COOKIES", {
  39. cookieString: req.headers.cookie
  40. })
  41. .then(res => {
  42. SID = res[SIDname];
  43. next(null);
  44. })
  45. .catch(next);
  46. },
  47. next => {
  48. if (!SID) return next("No SID.");
  49. return next();
  50. },
  51. next => {
  52. CacheModule.runJob("HGET", { table: "sessions", key: SID }).then(session =>
  53. next(null, session)
  54. );
  55. },
  56. (session, next) => {
  57. if (!session) return next("No session found.");
  58. session.refreshDate = Date.now();
  59. req.session = session;
  60. return CacheModule.runJob("HSET", {
  61. table: "sessions",
  62. key: SID,
  63. value: session
  64. }).then(session => {
  65. next(null, session);
  66. });
  67. },
  68. (res, next) => {
  69. // check if a session's user / IP is banned
  70. PunishmentsModule.runJob("GET_PUNISHMENTS", {})
  71. .then(punishments => {
  72. const isLoggedIn = !!(req.session && req.session.refreshDate);
  73. const userId = isLoggedIn ? req.session.userId : null;
  74. const banishment = { banned: false, ban: 0 };
  75. punishments.forEach(punishment => {
  76. if (punishment.expiresAt > banishment.ban) banishment.ban = punishment;
  77. if (
  78. punishment.type === "banUserId" &&
  79. isLoggedIn &&
  80. punishment.value === userId
  81. )
  82. banishment.banned = true;
  83. if (punishment.type === "banUserIp" && punishment.value === req.ip)
  84. banishment.banned = true;
  85. });
  86. req.banishment = banishment;
  87. next();
  88. })
  89. .catch(() => {
  90. next();
  91. });
  92. }
  93. ],
  94. err => {
  95. if (err) return res.json({ status: "error", message: "You are not logged in" });
  96. return next();
  97. }
  98. );
  99. };
  100. AppModule.runJob("GET_APP", {})
  101. .then(response => {
  102. response.app.get("/", (req, res) => {
  103. res.json({
  104. status: "success",
  105. message: "Coming Soon"
  106. });
  107. });
  108. response.app.get("/export/privatePlaylist/:playlistId", isLoggedIn, (req, res) => {
  109. const { playlistId } = req.params;
  110. PlaylistsModule.runJob("GET_PLAYLIST", { playlistId })
  111. .then(playlist => {
  112. if (playlist.createdBy === req.session.userId)
  113. res.json({ status: "success", playlist });
  114. else res.json({ status: "error", message: "You're not the owner." });
  115. })
  116. .catch(err => {
  117. res.json({ status: "error", message: err.message });
  118. });
  119. });
  120. // response.app.get("/debug_station", async (req, res) => {
  121. // const responseObject = {};
  122. // const stationModel = await DBModule.runJob(
  123. // "GET_MODEL",
  124. // {
  125. // modelName: "station",
  126. // }
  127. // );
  128. // async.waterfall([
  129. // next => {
  130. // stationModel.find({}, next);
  131. // },
  132. // (stations, next) => {
  133. // responseObject.mongo = {
  134. // stations
  135. // };
  136. // next();
  137. // },
  138. // next => {
  139. // CacheModule
  140. // .runJob("HGETALL", { table: "stations" })
  141. // .then(stations => {
  142. // next(null, stations);
  143. // })
  144. // .catch(next);
  145. // },
  146. // (stations, next) => {
  147. // responseObject.redis = {
  148. // stations
  149. // };
  150. // next();
  151. // },
  152. // next => {
  153. // responseObject.cryptoExamples = {};
  154. // responseObject.mongo.stations.forEach(station => {
  155. // const payloadName = `stations.nextSong?id=${station._id}`;
  156. // responseObject.cryptoExamples[station._id] = crypto
  157. // .createHash("md5")
  158. // .update(`_notification:${payloadName}_`)
  159. // .digest("hex")
  160. // });
  161. // next();
  162. // },
  163. // next => {
  164. // NotificationModule.pub.keys("*", next);
  165. // },
  166. // (redisKeys, next) => {
  167. // responseObject.redis = {
  168. // ...redisKeys,
  169. // ttl: {}
  170. // };
  171. // async.eachLimit(redisKeys, 1, (redisKey, next) => {
  172. // NotificationModule.pub.ttl(redisKey, (err, ttl) => {
  173. // responseObject.redis.ttl[redisKey] = ttl;
  174. // next(err);
  175. // })
  176. // }, next);
  177. // },
  178. // next => {
  179. // responseObject.debugLogs = this.moduleManager.debugLogs.stationIssue;
  180. // next();
  181. // },
  182. // next => {
  183. // responseObject.debugJobs = this.moduleManager.debugJobs;
  184. // next();
  185. // }
  186. // ], (err, response) => {
  187. // if (err) {
  188. // console.log(err);
  189. // return res.json({
  190. // error: err,
  191. // objectSoFar: responseObject
  192. // });
  193. // }
  194. // res.json(responseObject);
  195. // });
  196. // });
  197. // Object.keys(actions).forEach(namespace => {
  198. // Object.keys(actions[namespace]).forEach(action => {
  199. // let name = `/${namespace}/${action}`;
  200. // response.app.get(name, (req, res) => {
  201. // actions[namespace][action](null, result => {
  202. // if (typeof cb === "function")
  203. // return res.json(result);
  204. // });
  205. // });
  206. // });
  207. // });
  208. resolve();
  209. })
  210. .catch(err => {
  211. reject(err);
  212. });
  213. });
  214. }
  215. }
  216. export default new _APIModule();