link.ts 13 KB

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