utils.js 6.4 KB

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