| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275 |
- const ms = require("ms");
- const path = require("path");
- const nanoid = require("nanoid/generate");
- const JWT = require("jsonwebtoken");
- const { differenceInDays, differenceInHours, differenceInMonths, differenceInMilliseconds, addDays } = require("date-fns");
- const hbs = require("hbs");
- const env = require("../env");
- class CustomError extends Error {
- constructor(message, statusCode, data) {
- super(message);
- this.name = this.constructor.name;
- this.statusCode = statusCode ?? 500;
- this.data = data;
- }
- }
- const query = require("../queries");
- function isAdmin(email) {
- return env.ADMIN_EMAILS.split(",")
- .map((e) => e.trim())
- .includes(email)
- }
- function signToken(user) {
- return JWT.sign(
- {
- iss: "ApiAuth",
- sub: user.email,
- domain: user.domain || "",
- iat: parseInt((new Date().getTime() / 1000).toFixed(0)),
- exp: parseInt((addDays(new Date(), 7).getTime() / 1000).toFixed(0))
- },
- env.JWT_SECRET
- )
- }
- async function generateId(domain_id) {
- const address = nanoid(
- "abcdefghkmnpqrstuvwxyzABCDEFGHKLMNPQRSTUVWXYZ23456789",
- env.LINK_LENGTH
- );
- const link = await query.link.find({ address, domain_id });
- if (!link) return address;
- return generateId(domain_id);
- }
- function addProtocol(url) {
- const hasProtocol = /^\w+:\/\//.test(url);
- return hasProtocol ? url : `http://${url}`;
- }
- function getShortURL(address, domain) {
- const protocol = env.CUSTOM_DOMAIN_USE_HTTPS || !domain ? "https://" : "http://";
- const link = `${domain || env.DEFAULT_DOMAIN}/${address}`;
- const url = `${protocol}${link}`;
- return { link, url };
- }
- const getRedisKey = {
- // TODO: remove user id and make domain id required
- link: (address, domain_id, user_id) => `${address}-${domain_id || ""}-${user_id || ""}`,
- domain: (address) => `d-${address}`,
- host: (address) => `h-${address}`,
- user: (emailOrKey) => `u-${emailOrKey}`
- };
- function getStatsLimit() {
- return env.DEFAULT_MAX_STATS_PER_LINK || 100000000;
- };
- function getStatsCacheTime(total) {
- return (total > 50000 ? ms("5 minutes") : ms("1 minutes")) / 1000
- };
- function statsObjectToArray(obj) {
- const objToArr = (key) =>
- Array.from(Object.keys(obj[key]))
- .map((name) => ({
- name,
- value: obj[key][name]
- }))
- .sort((a, b) => b.value - a.value);
-
- return {
- browser: objToArr("browser"),
- os: objToArr("os"),
- country: objToArr("country"),
- referrer: objToArr("referrer")
- };
- }
- function getDifferenceFunction(type) {
- if (type === "lastDay") return differenceInHours;
- if (type === "lastWeek") return differenceInDays;
- if (type === "lastMonth") return differenceInDays;
- if (type === "allTime") return differenceInMonths;
- throw new Error("Unknown type.");
- }
- function getUTCDate(dateString) {
- const date = new Date(dateString || Date.now());
- return new Date(
- date.getUTCFullYear(),
- date.getUTCMonth(),
- date.getUTCDate(),
- date.getUTCHours()
- );
- }
- const STATS_PERIODS = [
- [1, "lastDay"],
- [7, "lastWeek"],
- [30, "lastMonth"]
- ];
- const preservedURLs = [
- "login",
- "logout",
- "signup",
- "reset-password",
- "resetpassword",
- "url-password",
- "url-info",
- "settings",
- "stats",
- "verify",
- "api",
- "404",
- "static",
- "images",
- "banned",
- "terms",
- "privacy",
- "protected",
- "report",
- "pricing"
- ];
- function getInitStats() {
- return Object.create({
- browser: {
- chrome: 0,
- edge: 0,
- firefox: 0,
- ie: 0,
- opera: 0,
- other: 0,
- safari: 0
- },
- os: {
- android: 0,
- ios: 0,
- linux: 0,
- macos: 0,
- other: 0,
- windows: 0
- },
- country: {},
- referrer: {}
- });
- }
- // format date to relative date
- const MINUTE = 60,
- HOUR = MINUTE * 60,
- DAY = HOUR * 24,
- WEEK = DAY * 7,
- MONTH = DAY * 30,
- YEAR = DAY * 365;
- function getTimeAgo(date) {
- const secondsAgo = Math.round((Date.now() - Number(date)) / 1000);
- if (secondsAgo < MINUTE) {
- return `${secondsAgo} second${secondsAgo !== 1 ? "s" : ""} ago`;
- }
- let divisor;
- let unit = "";
- if (secondsAgo < HOUR) {
- [divisor, unit] = [MINUTE, "minute"];
- } else if (secondsAgo < DAY) {
- [divisor, unit] = [HOUR, "hour"];
- } else if (secondsAgo < WEEK) {
- [divisor, unit] = [DAY, "day"];
- } else if (secondsAgo < MONTH) {
- [divisor, unit] = [WEEK, "week"];
- } else if (secondsAgo < YEAR) {
- [divisor, unit] = [MONTH, "month"];
- } else {
- [divisor, unit] = [YEAR, "year"];
- }
- const count = Math.floor(secondsAgo / divisor);
- return `${count} ${unit}${count > 1 ? "s" : ""} ago`;
- }
- const sanitize = {
- domain: domain => ({
- ...domain,
- id: domain.uuid,
- uuid: undefined,
- user_id: undefined,
- banned_by_id: undefined
- }),
- link: link => ({
- ...link,
- banned_by_id: undefined,
- domain_id: undefined,
- user_id: undefined,
- uuid: undefined,
- id: link.uuid,
- relative_created_at: getTimeAgo(link.created_at),
- relative_expire_in: link.expire_in && ms(differenceInMilliseconds(new Date(link.expire_in), new Date()), { long: true }),
- password: !!link.password,
- link: getShortURL(link.address, link.domain)
- })
- };
- function sleep(ms) {
- return new Promise(resolve => setTimeout(resolve, ms));
- }
- function removeWww(host) {
- return host.replace("www.", "");
- };
- function registerHandlebarsHelpers() {
- hbs.registerHelper("ifEquals", function(arg1, arg2, options) {
- return (arg1 === arg2) ? options.fn(this) : options.inverse(this);
- });
-
- const blocks = {};
- hbs.registerHelper("extend", function(name, context) {
- let block = blocks[name];
- if (!block) {
- block = blocks[name] = [];
- }
- block.push(context.fn(this));
- });
- hbs.registerHelper("block", function(name) {
- const val = (blocks[name] || []).join('\n');
- blocks[name] = [];
- return val;
- });
- hbs.registerPartials(path.join(__dirname, "../views/partials"), function (err) {});
- }
- module.exports = {
- addProtocol,
- CustomError,
- generateId,
- getDifferenceFunction,
- getInitStats,
- getRedisKey,
- getShortURL,
- getStatsCacheTime,
- getStatsLimit,
- getUTCDate,
- isAdmin,
- preservedURLs,
- registerHandlebarsHelpers,
- removeWww,
- sanitize,
- signToken,
- sleep,
- STATS_PERIODS,
- statsObjectToArray,
- }
|