api.js 7.1 KB

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