index.ts 4.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170
  1. import ms from "ms";
  2. import nanoid from "nanoid";
  3. import JWT from "jsonwebtoken";
  4. import {
  5. differenceInDays,
  6. differenceInHours,
  7. differenceInMonths,
  8. addDays
  9. } from "date-fns";
  10. import query from "../queries";
  11. import env from "../env";
  12. export class CustomError extends Error {
  13. public statusCode?: number;
  14. public data?: any;
  15. public constructor(message: string, statusCode = 500, data?: any) {
  16. super(message);
  17. this.name = this.constructor.name;
  18. this.statusCode = statusCode;
  19. this.data = data;
  20. }
  21. }
  22. export const isAdmin = (email: string): boolean =>
  23. env.ADMIN_EMAILS.split(",")
  24. .map((e) => e.trim())
  25. .includes(email);
  26. export const signToken = (user: UserJoined) =>
  27. JWT.sign(
  28. {
  29. iss: "ApiAuth",
  30. sub: user.email,
  31. domain: user.domain || "",
  32. admin: isAdmin(user.email),
  33. iat: parseInt((new Date().getTime() / 1000).toFixed(0)),
  34. exp: parseInt((addDays(new Date(), 7).getTime() / 1000).toFixed(0))
  35. } as Record<string, any>,
  36. env.JWT_SECRET
  37. );
  38. export const generateId = async (domain_id: number = null) => {
  39. const address = nanoid(
  40. "abcdefghkmnpqrstuvwxyzABCDEFGHKLMNPQRSTUVWXYZ23456789",
  41. env.LINK_LENGTH
  42. );
  43. const link = await query.link.find({ address, domain_id });
  44. if (!link) return address;
  45. return generateId(domain_id);
  46. };
  47. export const addProtocol = (url: string): string => {
  48. const hasProtocol = /^\w+:\/\//.test(url);
  49. return hasProtocol ? url : `http://${url}`;
  50. };
  51. export const generateShortLink = (id: string, domain?: string): string => {
  52. const protocol =
  53. env.CUSTOM_DOMAIN_USE_HTTPS || !domain ? "https://" : "http://";
  54. return `${protocol}${domain || env.DEFAULT_DOMAIN}/${id}`;
  55. };
  56. export const getRedisKey = {
  57. // TODO: remove user id and make domain id required
  58. link: (address: string, domain_id?: number, user_id?: number) =>
  59. `${address}-${domain_id || ""}-${user_id || ""}`,
  60. domain: (address: string) => `d-${address}`,
  61. host: (address: string) => `h-${address}`,
  62. user: (emailOrKey: string) => `u-${emailOrKey}`
  63. };
  64. // TODO: Add statsLimit
  65. export const getStatsLimit = (): number =>
  66. env.DEFAULT_MAX_STATS_PER_LINK || 100000000;
  67. export const getStatsCacheTime = (total?: number): number => {
  68. return (total > 50000 ? ms("5 minutes") : ms("1 minutes")) / 1000;
  69. };
  70. export const statsObjectToArray = (obj: Stats) => {
  71. const objToArr = (key) =>
  72. Array.from(Object.keys(obj[key]))
  73. .map((name) => ({
  74. name,
  75. value: obj[key][name]
  76. }))
  77. .sort((a, b) => b.value - a.value);
  78. return {
  79. browser: objToArr("browser"),
  80. os: objToArr("os"),
  81. country: objToArr("country"),
  82. referrer: objToArr("referrer")
  83. };
  84. };
  85. export const getDifferenceFunction = (
  86. type: "lastDay" | "lastWeek" | "lastMonth" | "allTime"
  87. ) => {
  88. if (type === "lastDay") return differenceInHours;
  89. if (type === "lastWeek") return differenceInDays;
  90. if (type === "lastMonth") return differenceInDays;
  91. if (type === "allTime") return differenceInMonths;
  92. throw new Error("Unknown type.");
  93. };
  94. export const getUTCDate = (dateString?: Date) => {
  95. const date = new Date(dateString || Date.now());
  96. return new Date(
  97. date.getUTCFullYear(),
  98. date.getUTCMonth(),
  99. date.getUTCDate(),
  100. date.getUTCHours()
  101. );
  102. };
  103. export const STATS_PERIODS: [number, "lastDay" | "lastWeek" | "lastMonth"][] = [
  104. [1, "lastDay"],
  105. [7, "lastWeek"],
  106. [30, "lastMonth"]
  107. ];
  108. export const getInitStats = (): Stats => {
  109. return Object.create({
  110. browser: {
  111. chrome: 0,
  112. edge: 0,
  113. firefox: 0,
  114. ie: 0,
  115. opera: 0,
  116. other: 0,
  117. safari: 0
  118. },
  119. os: {
  120. android: 0,
  121. ios: 0,
  122. linux: 0,
  123. macos: 0,
  124. other: 0,
  125. windows: 0
  126. },
  127. country: {},
  128. referrer: {}
  129. });
  130. };
  131. export const sanitize = {
  132. domain: (domain: Domain): DomainSanitized => ({
  133. ...domain,
  134. id: domain.uuid,
  135. uuid: undefined,
  136. user_id: undefined,
  137. banned_by_id: undefined
  138. }),
  139. link: (link: LinkJoinedDomain): LinkSanitized => ({
  140. ...link,
  141. banned_by_id: undefined,
  142. domain_id: undefined,
  143. user_id: undefined,
  144. uuid: undefined,
  145. id: link.uuid,
  146. password: !!link.password,
  147. link: generateShortLink(link.address, link.domain)
  148. })
  149. };
  150. export const removeWww = (host = "") => {
  151. return host.replace("www.", "");
  152. };