utils.js 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283
  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. const urlRegex = /^(?:(?:(?:https?|ftp):)?\/\/)(?:\S+(?::\S*)?@)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z0-9\u00a1-\uffff][a-z0-9\u00a1-\uffff_-]{0,62})?[a-z0-9\u00a1-\uffff]\.)+(?:[a-z\u00a1-\uffff]{2,}\.?))(?::\d{2,5})?(?:[/?#]\S*)?$/i;
  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(query, 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) && !env.isDev ? "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 === "lastYear") 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. function getStatsPeriods(now) {
  98. return [
  99. ["lastDay", subHours(now, 24)],
  100. ["lastWeek", subDays(now, 7)],
  101. ["lastMonth", subDays(now, 30)],
  102. ["lastYear", subMonths(now, 12)],
  103. ]
  104. }
  105. const preservedURLs = [
  106. "login",
  107. "logout",
  108. "signup",
  109. "reset-password",
  110. "resetpassword",
  111. "url-password",
  112. "url-info",
  113. "settings",
  114. "stats",
  115. "verify",
  116. "api",
  117. "404",
  118. "static",
  119. "images",
  120. "banned",
  121. "terms",
  122. "privacy",
  123. "protected",
  124. "report",
  125. "pricing"
  126. ];
  127. function getInitStats() {
  128. return Object.create({
  129. browser: {
  130. chrome: 0,
  131. edge: 0,
  132. firefox: 0,
  133. ie: 0,
  134. opera: 0,
  135. other: 0,
  136. safari: 0
  137. },
  138. os: {
  139. android: 0,
  140. ios: 0,
  141. linux: 0,
  142. macos: 0,
  143. other: 0,
  144. windows: 0
  145. },
  146. country: {},
  147. referrer: {}
  148. });
  149. }
  150. // format date to relative date
  151. const MINUTE = 60,
  152. HOUR = MINUTE * 60,
  153. DAY = HOUR * 24,
  154. WEEK = DAY * 7,
  155. MONTH = DAY * 30,
  156. YEAR = DAY * 365;
  157. function getTimeAgo(date) {
  158. const secondsAgo = Math.round((Date.now() - Number(date)) / 1000);
  159. if (secondsAgo < MINUTE) {
  160. return `${secondsAgo} second${secondsAgo !== 1 ? "s" : ""} ago`;
  161. }
  162. let divisor;
  163. let unit = "";
  164. if (secondsAgo < HOUR) {
  165. [divisor, unit] = [MINUTE, "minute"];
  166. } else if (secondsAgo < DAY) {
  167. [divisor, unit] = [HOUR, "hour"];
  168. } else if (secondsAgo < WEEK) {
  169. [divisor, unit] = [DAY, "day"];
  170. } else if (secondsAgo < MONTH) {
  171. [divisor, unit] = [WEEK, "week"];
  172. } else if (secondsAgo < YEAR) {
  173. [divisor, unit] = [MONTH, "month"];
  174. } else {
  175. [divisor, unit] = [YEAR, "year"];
  176. }
  177. const count = Math.floor(secondsAgo / divisor);
  178. return `${count} ${unit}${count > 1 ? "s" : ""} ago`;
  179. }
  180. const sanitize = {
  181. domain: domain => ({
  182. ...domain,
  183. id: domain.uuid,
  184. uuid: undefined,
  185. user_id: undefined,
  186. banned_by_id: undefined
  187. }),
  188. link: link => ({
  189. ...link,
  190. banned_by_id: undefined,
  191. domain_id: undefined,
  192. user_id: undefined,
  193. uuid: undefined,
  194. id: link.uuid,
  195. relative_created_at: getTimeAgo(link.created_at),
  196. relative_expire_in: link.expire_in && ms(differenceInMilliseconds(new Date(link.expire_in), new Date()), { long: true }),
  197. password: !!link.password,
  198. link: getShortURL(link.address, link.domain)
  199. })
  200. };
  201. function sleep(ms) {
  202. return new Promise(resolve => setTimeout(resolve, ms));
  203. }
  204. function removeWww(host) {
  205. return host.replace("www.", "");
  206. };
  207. function registerHandlebarsHelpers() {
  208. hbs.registerHelper("ifEquals", function(arg1, arg2, options) {
  209. return (arg1 === arg2) ? options.fn(this) : options.inverse(this);
  210. });
  211. hbs.registerHelper("json", function(context) {
  212. return JSON.stringify(context);
  213. });
  214. const blocks = {};
  215. hbs.registerHelper("extend", function(name, context) {
  216. let block = blocks[name];
  217. if (!block) {
  218. block = blocks[name] = [];
  219. }
  220. block.push(context.fn(this));
  221. });
  222. hbs.registerHelper("block", function(name) {
  223. const val = (blocks[name] || []).join('\n');
  224. blocks[name] = [];
  225. return val;
  226. });
  227. hbs.registerPartials(path.join(__dirname, "../views/partials"), function (err) {});
  228. }
  229. module.exports = {
  230. addProtocol,
  231. CustomError,
  232. generateId,
  233. getDifferenceFunction,
  234. getInitStats,
  235. getRedisKey,
  236. getShortURL,
  237. getStatsCacheTime,
  238. getStatsLimit,
  239. getStatsPeriods,
  240. getUTCDate,
  241. isAdmin,
  242. preservedURLs,
  243. registerHandlebarsHelpers,
  244. removeWww,
  245. sanitize,
  246. signToken,
  247. sleep,
  248. statsObjectToArray,
  249. urlRegex,
  250. }