link.ts 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511
  1. import bcrypt from "bcryptjs";
  2. import { isAfter, subDays } from "date-fns";
  3. import knex from "../knex";
  4. import * as redis from "../redis";
  5. import {
  6. generateShortLink,
  7. getRedisKey,
  8. getUTCDate,
  9. getDifferenceFunction,
  10. statsObjectToArray
  11. } from "../utils";
  12. import { banDomain } from "./domain";
  13. import { banHost } from "./host";
  14. import { banUser } from "./user";
  15. interface CreateLink extends Link {
  16. reuse?: boolean;
  17. domainName?: string;
  18. }
  19. export const createShortLink = async (data: CreateLink, user: UserJoined) => {
  20. const { id: user_id = null, domain, domain_id = null } =
  21. user || ({} as UserJoined);
  22. let password;
  23. if (data.password) {
  24. const salt = await bcrypt.genSalt(12);
  25. password = await bcrypt.hash(data.password, salt);
  26. }
  27. const [link]: Link[] = await knex<Link>("links").insert(
  28. {
  29. domain_id,
  30. address: data.address,
  31. password,
  32. target: data.target,
  33. user_id
  34. },
  35. "*"
  36. );
  37. return {
  38. ...link,
  39. password: !!data.password,
  40. reuse: !!data.reuse,
  41. shortLink: generateShortLink(data.address, domain),
  42. shortUrl: generateShortLink(data.address, domain)
  43. };
  44. };
  45. export const addLinkCount = async (id: number) => {
  46. return knex<Link>("links")
  47. .where({ id })
  48. .increment("visit_count", 1);
  49. };
  50. interface ICreateVisit {
  51. browser: string;
  52. country: string;
  53. domain?: string;
  54. id: number;
  55. limit: number;
  56. os: string;
  57. referrer: string;
  58. }
  59. export const createVisit = async (params: ICreateVisit) => {
  60. const data = {
  61. ...params,
  62. country: params.country.toLowerCase(),
  63. referrer: params.referrer.toLowerCase()
  64. };
  65. const visit = await knex<Visit>("visits")
  66. .where({ link_id: params.id })
  67. .andWhere(
  68. knex.raw("date_trunc('hour', created_at) = date_trunc('hour', ?)", [
  69. knex.fn.now()
  70. ])
  71. )
  72. .first();
  73. if (visit) {
  74. await knex("visits")
  75. .where({ id: visit.id })
  76. .increment(`br_${data.browser}`, 1)
  77. .increment(`os_${data.os}`, 1)
  78. .increment("total", 1)
  79. .update({
  80. updated_at: new Date().toISOString(),
  81. countries: knex.raw(
  82. "jsonb_set(countries, '{??}', (COALESCE(countries->>?,'0')::int + 1)::text::jsonb)",
  83. [data.country, data.country]
  84. ),
  85. referrers: knex.raw(
  86. "jsonb_set(referrers, '{??}', (COALESCE(referrers->>?,'0')::int + 1)::text::jsonb)",
  87. [data.referrer, data.referrer]
  88. )
  89. });
  90. } else {
  91. await knex<Visit>("visits").insert({
  92. [`br_${data.browser}`]: 1,
  93. countries: { [data.country]: 1 },
  94. referrers: { [data.referrer]: 1 },
  95. [`os_${data.os}`]: 1,
  96. total: 1,
  97. link_id: data.id
  98. });
  99. }
  100. return visit;
  101. };
  102. interface IFindLink {
  103. address?: string;
  104. domain_id?: number | null;
  105. user_id?: number | null;
  106. target?: string;
  107. }
  108. export const findLink = async ({
  109. address,
  110. domain_id,
  111. user_id,
  112. target
  113. }: IFindLink): Promise<Link> => {
  114. const redisKey = getRedisKey.link(address, domain_id, user_id);
  115. const cachedLink = await redis.get(redisKey);
  116. if (cachedLink) return JSON.parse(cachedLink);
  117. const link = await knex<Link>("links")
  118. .where({
  119. ...(address && { address }),
  120. ...(domain_id && { domain_id }),
  121. ...(user_id && { user_id }),
  122. ...(target && { target })
  123. })
  124. .first();
  125. if (link) {
  126. redis.set(redisKey, JSON.stringify(link), "EX", 60 * 60 * 2);
  127. }
  128. return link;
  129. };
  130. export const getUserLinksCount = async (params: {
  131. user_id: number;
  132. date?: Date;
  133. }) => {
  134. const model = knex<Link>("links").where({ user_id: params.user_id });
  135. // TODO: Test counts;
  136. let res;
  137. if (params.date) {
  138. res = await model
  139. .andWhere("created_at", ">", params.date.toISOString())
  140. .count("id");
  141. } else {
  142. res = await model.count("id");
  143. }
  144. return res[0] && res[0].count;
  145. };
  146. interface IGetLinksOptions {
  147. count?: string;
  148. page?: string;
  149. search?: string;
  150. }
  151. export const getLinks = async (
  152. user_id: number,
  153. options: IGetLinksOptions = {}
  154. ) => {
  155. const { count = "5", page = "1", search = "" } = options;
  156. const limit = parseInt(count) < 50 ? parseInt(count) : 50;
  157. const offset = (parseInt(page) - 1) * limit;
  158. const model = knex<LinkJoinedDomain>("links")
  159. .select(
  160. "links.id",
  161. "links.address",
  162. "links.banned",
  163. "links.created_at",
  164. "links.domain_id",
  165. "links.updated_at",
  166. "links.password",
  167. "links.target",
  168. "links.visit_count",
  169. "links.user_id",
  170. "domains.address as domain"
  171. )
  172. .offset(offset)
  173. .limit(limit)
  174. .orderBy("created_at", "desc")
  175. .where("links.user_id", user_id);
  176. if (search) {
  177. model.andWhereRaw("links.address || ' ' || target ILIKE '%' || ? || '%'", [
  178. search
  179. ]);
  180. }
  181. const matchedLinks = await model.leftJoin(
  182. "domains",
  183. "links.domain_id",
  184. "domains.id"
  185. );
  186. const links = matchedLinks.map(link => ({
  187. ...link,
  188. id: link.address,
  189. password: !!link.password,
  190. shortLink: generateShortLink(link.address, link.domain),
  191. shortUrl: generateShortLink(link.address, link.domain)
  192. }));
  193. return links;
  194. };
  195. interface IDeleteLink {
  196. address: string;
  197. user_id: number;
  198. domain?: string;
  199. }
  200. export const deleteLink = async (data: IDeleteLink) => {
  201. const link: LinkJoinedDomain = await knex<LinkJoinedDomain>("links")
  202. .select("links.id", "domains.address as domain")
  203. .where({
  204. "links.address": data.address,
  205. "links.user_id": data.user_id,
  206. ...(!data.domain && { domain_id: null })
  207. })
  208. .leftJoin("domains", "links.domain_id", "domains.id")
  209. .first();
  210. if (!link) return;
  211. if (link.domain !== data.domain) {
  212. return;
  213. }
  214. await knex<Visit>("visits")
  215. .where("link_id", link.id)
  216. .delete();
  217. const deletedLink = await knex<Link>("links")
  218. .where("id", link.id)
  219. .delete();
  220. redis.del(getRedisKey.link(link.address, link.domain_id, link.user_id));
  221. return !!deletedLink;
  222. };
  223. /*
  224. ** Collecting stats
  225. */
  226. interface StatsResult {
  227. stats: {
  228. browser: { name: string; value: number }[];
  229. os: { name: string; value: number }[];
  230. country: { name: string; value: number }[];
  231. referrer: { name: string; value: number }[];
  232. };
  233. views: number[];
  234. }
  235. const getInitStats = (): Stats =>
  236. Object.create({
  237. browser: {
  238. chrome: 0,
  239. edge: 0,
  240. firefox: 0,
  241. ie: 0,
  242. opera: 0,
  243. other: 0,
  244. safari: 0
  245. },
  246. os: {
  247. android: 0,
  248. ios: 0,
  249. linux: 0,
  250. macos: 0,
  251. other: 0,
  252. windows: 0
  253. },
  254. country: {},
  255. referrer: {}
  256. });
  257. const STATS_PERIODS: [number, "lastDay" | "lastWeek" | "lastMonth"][] = [
  258. [1, "lastDay"],
  259. [7, "lastWeek"],
  260. [30, "lastMonth"]
  261. ];
  262. interface IGetStatsResponse {
  263. allTime: StatsResult;
  264. id: string;
  265. lastDay: StatsResult;
  266. lastMonth: StatsResult;
  267. lastWeek: StatsResult;
  268. shortLink: string;
  269. shortUrl: string;
  270. target: string;
  271. total: number;
  272. updatedAt: string;
  273. }
  274. export const getStats = async (link: Link, domain: Domain) => {
  275. const stats = {
  276. lastDay: {
  277. stats: getInitStats(),
  278. views: new Array(24).fill(0)
  279. },
  280. lastWeek: {
  281. stats: getInitStats(),
  282. views: new Array(7).fill(0)
  283. },
  284. lastMonth: {
  285. stats: getInitStats(),
  286. views: new Array(30).fill(0)
  287. },
  288. allTime: {
  289. stats: getInitStats(),
  290. views: new Array(18).fill(0)
  291. }
  292. };
  293. const visitsStream: any = knex<Visit>("visits")
  294. .where("link_id", link.id)
  295. .stream();
  296. const nowUTC = getUTCDate();
  297. const now = new Date();
  298. for await (const visit of visitsStream as Visit[]) {
  299. STATS_PERIODS.forEach(([days, type]) => {
  300. const isIncluded = isAfter(visit.created_at, subDays(nowUTC, days));
  301. if (isIncluded) {
  302. const diffFunction = getDifferenceFunction(type);
  303. const diff = diffFunction(now, visit.created_at);
  304. const index = stats[type].views.length - diff - 1;
  305. const view = stats[type].views[index];
  306. const period = stats[type].stats;
  307. stats[type].stats = {
  308. browser: {
  309. chrome: period.browser.chrome + visit.br_chrome,
  310. edge: period.browser.edge + visit.br_edge,
  311. firefox: period.browser.firefox + visit.br_firefox,
  312. ie: period.browser.ie + visit.br_ie,
  313. opera: period.browser.opera + visit.br_opera,
  314. other: period.browser.other + visit.br_other,
  315. safari: period.browser.safari + visit.br_safari
  316. },
  317. os: {
  318. android: period.os.android + visit.os_android,
  319. ios: period.os.ios + visit.os_ios,
  320. linux: period.os.linux + visit.os_linux,
  321. macos: period.os.macos + visit.os_macos,
  322. other: period.os.other + visit.os_other,
  323. windows: period.os.windows + visit.os_windows
  324. },
  325. country: {
  326. ...period.country,
  327. ...Object.entries(visit.countries).reduce(
  328. (obj, [country, count]) => ({
  329. ...obj,
  330. [country]: (period.country[country] || 0) + count
  331. }),
  332. {}
  333. )
  334. },
  335. referrer: {
  336. ...period.referrer,
  337. ...Object.entries(visit.referrers).reduce(
  338. (obj, [referrer, count]) => ({
  339. ...obj,
  340. [referrer]: (period.referrer[referrer] || 0) + count
  341. }),
  342. {}
  343. )
  344. }
  345. };
  346. stats[type].views[index] = view + visit.total;
  347. }
  348. });
  349. const allTime = stats.allTime.stats;
  350. const diffFunction = getDifferenceFunction("allTime");
  351. const diff = diffFunction(now, visit.created_at);
  352. const index = stats.allTime.views.length - diff - 1;
  353. const view = stats.allTime.views[index];
  354. stats.allTime.stats = {
  355. browser: {
  356. chrome: allTime.browser.chrome + visit.br_chrome,
  357. edge: allTime.browser.edge + visit.br_edge,
  358. firefox: allTime.browser.firefox + visit.br_firefox,
  359. ie: allTime.browser.ie + visit.br_ie,
  360. opera: allTime.browser.opera + visit.br_opera,
  361. other: allTime.browser.other + visit.br_other,
  362. safari: allTime.browser.safari + visit.br_safari
  363. },
  364. os: {
  365. android: allTime.os.android + visit.os_android,
  366. ios: allTime.os.ios + visit.os_ios,
  367. linux: allTime.os.linux + visit.os_linux,
  368. macos: allTime.os.macos + visit.os_macos,
  369. other: allTime.os.other + visit.os_other,
  370. windows: allTime.os.windows + visit.os_windows
  371. },
  372. country: {
  373. ...allTime.country,
  374. ...Object.entries(visit.countries).reduce(
  375. (obj, [country, count]) => ({
  376. ...obj,
  377. [country]: (allTime.country[country] || 0) + count
  378. }),
  379. {}
  380. )
  381. },
  382. referrer: {
  383. ...allTime.referrer,
  384. ...Object.entries(visit.referrers).reduce(
  385. (obj, [referrer, count]) => ({
  386. ...obj,
  387. [referrer]: (allTime.referrer[referrer] || 0) + count
  388. }),
  389. {}
  390. )
  391. }
  392. };
  393. stats.allTime.views[index] = view + visit.total;
  394. }
  395. const response: IGetStatsResponse = {
  396. allTime: {
  397. stats: statsObjectToArray(stats.allTime.stats),
  398. views: stats.allTime.views
  399. },
  400. id: link.address,
  401. lastDay: {
  402. stats: statsObjectToArray(stats.lastDay.stats),
  403. views: stats.lastDay.views
  404. },
  405. lastMonth: {
  406. stats: statsObjectToArray(stats.lastDay.stats),
  407. views: stats.lastDay.views
  408. },
  409. lastWeek: {
  410. stats: statsObjectToArray(stats.lastWeek.stats),
  411. views: stats.lastWeek.views
  412. },
  413. shortLink: generateShortLink(link.address, domain.address),
  414. shortUrl: generateShortLink(link.address, domain.address),
  415. target: link.target,
  416. total: link.visit_count,
  417. updatedAt: new Date().toISOString()
  418. };
  419. return response;
  420. };
  421. interface IBanLink {
  422. adminId?: number;
  423. banUser?: boolean;
  424. domain?: string;
  425. host?: string;
  426. address: string;
  427. }
  428. export const banLink = async (data: IBanLink) => {
  429. const tasks = [];
  430. const banned_by_id = data.adminId;
  431. // Ban link
  432. const [link]: Link[] = await knex<Link>("links")
  433. .where({ address: data.address, domain_id: null })
  434. .update(
  435. { banned: true, banned_by_id, updated_at: new Date().toISOString() },
  436. "*"
  437. );
  438. if (!link) throw new Error("No link has been found.");
  439. // If user, ban user and all of their links.
  440. if (data.banUser && link.user_id) {
  441. tasks.push(banUser(link.user_id, banned_by_id));
  442. tasks.push(
  443. knex<Link>("links")
  444. .where({ user_id: link.user_id })
  445. .update(
  446. { banned: true, banned_by_id, updated_at: new Date().toISOString() },
  447. "*"
  448. )
  449. );
  450. }
  451. // Ban host
  452. if (data.host) tasks.push(banHost(data.host, banned_by_id));
  453. // Ban domain
  454. if (data.domain) tasks.push(banDomain(data.domain, banned_by_id));
  455. redis.del(getRedisKey.link(link.address, link.domain_id, link.user_id));
  456. return Promise.all(tasks);
  457. };