utils.js 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275
  1. const ms = require("ms");
  2. const path = require("path");
  3. const nanoid = require("nanoid/generate");
  4. const JWT = require("jsonwebtoken");
  5. const { differenceInDays, differenceInHours, differenceInMonths, differenceInMilliseconds, addDays } = require("date-fns");
  6. const hbs = require("hbs");
  7. const env = require("../env");
  8. class CustomError extends Error {
  9. constructor(message, statusCode, data) {
  10. super(message);
  11. this.name = this.constructor.name;
  12. this.statusCode = statusCode ?? 500;
  13. this.data = data;
  14. }
  15. }
  16. const query = require("../queries");
  17. function isAdmin(email) {
  18. return env.ADMIN_EMAILS.split(",")
  19. .map((e) => e.trim())
  20. .includes(email)
  21. }
  22. function signToken(user) {
  23. return JWT.sign(
  24. {
  25. iss: "ApiAuth",
  26. sub: user.email,
  27. domain: user.domain || "",
  28. iat: parseInt((new Date().getTime() / 1000).toFixed(0)),
  29. exp: parseInt((addDays(new Date(), 7).getTime() / 1000).toFixed(0))
  30. },
  31. env.JWT_SECRET
  32. )
  33. }
  34. async function generateId(domain_id) {
  35. const address = nanoid(
  36. "abcdefghkmnpqrstuvwxyzABCDEFGHKLMNPQRSTUVWXYZ23456789",
  37. env.LINK_LENGTH
  38. );
  39. const link = await query.link.find({ address, domain_id });
  40. if (!link) return address;
  41. return generateId(domain_id);
  42. }
  43. function addProtocol(url) {
  44. const hasProtocol = /^\w+:\/\//.test(url);
  45. return hasProtocol ? url : `http://${url}`;
  46. }
  47. function getShortURL(address, domain) {
  48. const protocol = env.CUSTOM_DOMAIN_USE_HTTPS || !domain ? "https://" : "http://";
  49. const link = `${domain || env.DEFAULT_DOMAIN}/${address}`;
  50. const url = `${protocol}${link}`;
  51. return { link, url };
  52. }
  53. const getRedisKey = {
  54. // TODO: remove user id and make domain id required
  55. link: (address, domain_id, user_id) => `${address}-${domain_id || ""}-${user_id || ""}`,
  56. domain: (address) => `d-${address}`,
  57. host: (address) => `h-${address}`,
  58. user: (emailOrKey) => `u-${emailOrKey}`
  59. };
  60. function getStatsLimit() {
  61. return env.DEFAULT_MAX_STATS_PER_LINK || 100000000;
  62. };
  63. function getStatsCacheTime(total) {
  64. return (total > 50000 ? ms("5 minutes") : ms("1 minutes")) / 1000
  65. };
  66. function statsObjectToArray(obj) {
  67. const objToArr = (key) =>
  68. Array.from(Object.keys(obj[key]))
  69. .map((name) => ({
  70. name,
  71. value: obj[key][name]
  72. }))
  73. .sort((a, b) => b.value - a.value);
  74. return {
  75. browser: objToArr("browser"),
  76. os: objToArr("os"),
  77. country: objToArr("country"),
  78. referrer: objToArr("referrer")
  79. };
  80. }
  81. function getDifferenceFunction(type) {
  82. if (type === "lastDay") return differenceInHours;
  83. if (type === "lastWeek") return differenceInDays;
  84. if (type === "lastMonth") return differenceInDays;
  85. if (type === "allTime") return differenceInMonths;
  86. throw new Error("Unknown type.");
  87. }
  88. function getUTCDate(dateString) {
  89. const date = new Date(dateString || Date.now());
  90. return new Date(
  91. date.getUTCFullYear(),
  92. date.getUTCMonth(),
  93. date.getUTCDate(),
  94. date.getUTCHours()
  95. );
  96. }
  97. const STATS_PERIODS = [
  98. [1, "lastDay"],
  99. [7, "lastWeek"],
  100. [30, "lastMonth"]
  101. ];
  102. const preservedURLs = [
  103. "login",
  104. "logout",
  105. "signup",
  106. "reset-password",
  107. "resetpassword",
  108. "url-password",
  109. "url-info",
  110. "settings",
  111. "stats",
  112. "verify",
  113. "api",
  114. "404",
  115. "static",
  116. "images",
  117. "banned",
  118. "terms",
  119. "privacy",
  120. "protected",
  121. "report",
  122. "pricing"
  123. ];
  124. function getInitStats() {
  125. return Object.create({
  126. browser: {
  127. chrome: 0,
  128. edge: 0,
  129. firefox: 0,
  130. ie: 0,
  131. opera: 0,
  132. other: 0,
  133. safari: 0
  134. },
  135. os: {
  136. android: 0,
  137. ios: 0,
  138. linux: 0,
  139. macos: 0,
  140. other: 0,
  141. windows: 0
  142. },
  143. country: {},
  144. referrer: {}
  145. });
  146. }
  147. // format date to relative date
  148. const MINUTE = 60,
  149. HOUR = MINUTE * 60,
  150. DAY = HOUR * 24,
  151. WEEK = DAY * 7,
  152. MONTH = DAY * 30,
  153. YEAR = DAY * 365;
  154. function getTimeAgo(date) {
  155. const secondsAgo = Math.round((Date.now() - Number(date)) / 1000);
  156. if (secondsAgo < MINUTE) {
  157. return `${secondsAgo} second${secondsAgo !== 1 ? "s" : ""} ago`;
  158. }
  159. let divisor;
  160. let unit = "";
  161. if (secondsAgo < HOUR) {
  162. [divisor, unit] = [MINUTE, "minute"];
  163. } else if (secondsAgo < DAY) {
  164. [divisor, unit] = [HOUR, "hour"];
  165. } else if (secondsAgo < WEEK) {
  166. [divisor, unit] = [DAY, "day"];
  167. } else if (secondsAgo < MONTH) {
  168. [divisor, unit] = [WEEK, "week"];
  169. } else if (secondsAgo < YEAR) {
  170. [divisor, unit] = [MONTH, "month"];
  171. } else {
  172. [divisor, unit] = [YEAR, "year"];
  173. }
  174. const count = Math.floor(secondsAgo / divisor);
  175. return `${count} ${unit}${count > 1 ? "s" : ""} ago`;
  176. }
  177. const sanitize = {
  178. domain: domain => ({
  179. ...domain,
  180. id: domain.uuid,
  181. uuid: undefined,
  182. user_id: undefined,
  183. banned_by_id: undefined
  184. }),
  185. link: link => ({
  186. ...link,
  187. banned_by_id: undefined,
  188. domain_id: undefined,
  189. user_id: undefined,
  190. uuid: undefined,
  191. id: link.uuid,
  192. relative_created_at: getTimeAgo(link.created_at),
  193. relative_expire_in: link.expire_in && ms(differenceInMilliseconds(new Date(link.expire_in), new Date()), { long: true }),
  194. password: !!link.password,
  195. link: getShortURL(link.address, link.domain)
  196. })
  197. };
  198. function sleep(ms) {
  199. return new Promise(resolve => setTimeout(resolve, ms));
  200. }
  201. function removeWww(host) {
  202. return host.replace("www.", "");
  203. };
  204. function registerHandlebarsHelpers() {
  205. hbs.registerHelper("ifEquals", function(arg1, arg2, options) {
  206. return (arg1 === arg2) ? options.fn(this) : options.inverse(this);
  207. });
  208. const blocks = {};
  209. hbs.registerHelper("extend", function(name, context) {
  210. let block = blocks[name];
  211. if (!block) {
  212. block = blocks[name] = [];
  213. }
  214. block.push(context.fn(this));
  215. });
  216. hbs.registerHelper("block", function(name) {
  217. const val = (blocks[name] || []).join('\n');
  218. blocks[name] = [];
  219. return val;
  220. });
  221. hbs.registerPartials(path.join(__dirname, "../views/partials"), function (err) {});
  222. }
  223. module.exports = {
  224. addProtocol,
  225. CustomError,
  226. generateId,
  227. getDifferenceFunction,
  228. getInitStats,
  229. getRedisKey,
  230. getShortURL,
  231. getStatsCacheTime,
  232. getStatsLimit,
  233. getUTCDate,
  234. isAdmin,
  235. preservedURLs,
  236. registerHandlebarsHelpers,
  237. removeWww,
  238. sanitize,
  239. signToken,
  240. sleep,
  241. STATS_PERIODS,
  242. statsObjectToArray,
  243. }