link.ts 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507
  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. const deletedLink = await knex<Link>("links")
  215. .where("id", link.id)
  216. .delete();
  217. redis.del(getRedisKey.link(link.address, link.domain_id, link.user_id));
  218. return !!deletedLink;
  219. };
  220. /*
  221. ** Collecting stats
  222. */
  223. interface StatsResult {
  224. stats: {
  225. browser: { name: string; value: number }[];
  226. os: { name: string; value: number }[];
  227. country: { name: string; value: number }[];
  228. referrer: { name: string; value: number }[];
  229. };
  230. views: number[];
  231. }
  232. const getInitStats = (): Stats =>
  233. Object.create({
  234. browser: {
  235. chrome: 0,
  236. edge: 0,
  237. firefox: 0,
  238. ie: 0,
  239. opera: 0,
  240. other: 0,
  241. safari: 0
  242. },
  243. os: {
  244. android: 0,
  245. ios: 0,
  246. linux: 0,
  247. macos: 0,
  248. other: 0,
  249. windows: 0
  250. },
  251. country: {},
  252. referrer: {}
  253. });
  254. const STATS_PERIODS: [number, "lastDay" | "lastWeek" | "lastMonth"][] = [
  255. [1, "lastDay"],
  256. [7, "lastWeek"],
  257. [30, "lastMonth"]
  258. ];
  259. interface IGetStatsResponse {
  260. allTime: StatsResult;
  261. id: string;
  262. lastDay: StatsResult;
  263. lastMonth: StatsResult;
  264. lastWeek: StatsResult;
  265. shortLink: string;
  266. shortUrl: string;
  267. target: string;
  268. total: number;
  269. updatedAt: string;
  270. }
  271. export const getStats = async (link: Link, domain: Domain) => {
  272. const stats = {
  273. lastDay: {
  274. stats: getInitStats(),
  275. views: new Array(24).fill(0)
  276. },
  277. lastWeek: {
  278. stats: getInitStats(),
  279. views: new Array(7).fill(0)
  280. },
  281. lastMonth: {
  282. stats: getInitStats(),
  283. views: new Array(30).fill(0)
  284. },
  285. allTime: {
  286. stats: getInitStats(),
  287. views: new Array(18).fill(0)
  288. }
  289. };
  290. const visitsStream: any = knex<Visit>("visits")
  291. .where("link_id", link.id)
  292. .stream();
  293. const nowUTC = getUTCDate();
  294. const now = new Date();
  295. for await (const visit of visitsStream as Visit[]) {
  296. STATS_PERIODS.forEach(([days, type]) => {
  297. const isIncluded = isAfter(visit.created_at, subDays(nowUTC, days));
  298. if (isIncluded) {
  299. const diffFunction = getDifferenceFunction(type);
  300. const diff = diffFunction(now, visit.created_at);
  301. const index = stats[type].views.length - diff - 1;
  302. const view = stats[type].views[index];
  303. const period = stats[type].stats;
  304. stats[type].stats = {
  305. browser: {
  306. chrome: period.browser.chrome + visit.br_chrome,
  307. edge: period.browser.edge + visit.br_edge,
  308. firefox: period.browser.firefox + visit.br_firefox,
  309. ie: period.browser.ie + visit.br_ie,
  310. opera: period.browser.opera + visit.br_opera,
  311. other: period.browser.other + visit.br_other,
  312. safari: period.browser.safari + visit.br_safari
  313. },
  314. os: {
  315. android: period.os.android + visit.os_android,
  316. ios: period.os.ios + visit.os_ios,
  317. linux: period.os.linux + visit.os_linux,
  318. macos: period.os.macos + visit.os_macos,
  319. other: period.os.other + visit.os_other,
  320. windows: period.os.windows + visit.os_windows
  321. },
  322. country: {
  323. ...period.country,
  324. ...Object.entries(visit.countries).reduce(
  325. (obj, [country, count]) => ({
  326. ...obj,
  327. [country]: (period.country[country] || 0) + count
  328. }),
  329. {}
  330. )
  331. },
  332. referrer: {
  333. ...period.referrer,
  334. ...Object.entries(visit.referrers).reduce(
  335. (obj, [referrer, count]) => ({
  336. ...obj,
  337. [referrer]: (period.referrer[referrer] || 0) + count
  338. }),
  339. {}
  340. )
  341. }
  342. };
  343. stats[type].views[index] = view + visit.total;
  344. }
  345. });
  346. const allTime = stats.allTime.stats;
  347. const diffFunction = getDifferenceFunction("allTime");
  348. const diff = diffFunction(now, visit.created_at);
  349. const index = stats.allTime.views.length - diff - 1;
  350. const view = stats.allTime.views[index];
  351. stats.allTime.stats = {
  352. browser: {
  353. chrome: allTime.browser.chrome + visit.br_chrome,
  354. edge: allTime.browser.edge + visit.br_edge,
  355. firefox: allTime.browser.firefox + visit.br_firefox,
  356. ie: allTime.browser.ie + visit.br_ie,
  357. opera: allTime.browser.opera + visit.br_opera,
  358. other: allTime.browser.other + visit.br_other,
  359. safari: allTime.browser.safari + visit.br_safari
  360. },
  361. os: {
  362. android: allTime.os.android + visit.os_android,
  363. ios: allTime.os.ios + visit.os_ios,
  364. linux: allTime.os.linux + visit.os_linux,
  365. macos: allTime.os.macos + visit.os_macos,
  366. other: allTime.os.other + visit.os_other,
  367. windows: allTime.os.windows + visit.os_windows
  368. },
  369. country: {
  370. ...allTime.country,
  371. ...Object.entries(visit.countries).reduce(
  372. (obj, [country, count]) => ({
  373. ...obj,
  374. [country]: (allTime.country[country] || 0) + count
  375. }),
  376. {}
  377. )
  378. },
  379. referrer: {
  380. ...allTime.referrer,
  381. ...Object.entries(visit.referrers).reduce(
  382. (obj, [referrer, count]) => ({
  383. ...obj,
  384. [referrer]: (allTime.referrer[referrer] || 0) + count
  385. }),
  386. {}
  387. )
  388. }
  389. };
  390. stats.allTime.views[index] = view + visit.total;
  391. }
  392. const response: IGetStatsResponse = {
  393. allTime: {
  394. stats: statsObjectToArray(stats.allTime.stats),
  395. views: stats.allTime.views
  396. },
  397. id: link.address,
  398. lastDay: {
  399. stats: statsObjectToArray(stats.lastDay.stats),
  400. views: stats.lastDay.views
  401. },
  402. lastMonth: {
  403. stats: statsObjectToArray(stats.lastDay.stats),
  404. views: stats.lastDay.views
  405. },
  406. lastWeek: {
  407. stats: statsObjectToArray(stats.lastWeek.stats),
  408. views: stats.lastWeek.views
  409. },
  410. shortLink: generateShortLink(link.address, domain.address),
  411. shortUrl: generateShortLink(link.address, domain.address),
  412. target: link.target,
  413. total: link.visit_count,
  414. updatedAt: new Date().toISOString()
  415. };
  416. return response;
  417. };
  418. interface IBanLink {
  419. adminId?: number;
  420. banUser?: boolean;
  421. domain?: string;
  422. host?: string;
  423. address: string;
  424. }
  425. export const banLink = async (data: IBanLink) => {
  426. const tasks = [];
  427. const banned_by_id = data.adminId;
  428. // Ban link
  429. const [link]: Link[] = await knex<Link>("links")
  430. .where({ address: data.address, domain_id: null })
  431. .update(
  432. { banned: true, banned_by_id, updated_at: new Date().toISOString() },
  433. "*"
  434. );
  435. if (!link) throw new Error("No link has been found.");
  436. // If user, ban user and all of their links.
  437. if (data.banUser && link.user_id) {
  438. tasks.push(banUser(link.user_id, banned_by_id));
  439. tasks.push(
  440. knex<Link>("links")
  441. .where({ user_id: link.user_id })
  442. .update(
  443. { banned: true, banned_by_id, updated_at: new Date().toISOString() },
  444. "*"
  445. )
  446. );
  447. }
  448. // Ban host
  449. if (data.host) tasks.push(banHost(data.host, banned_by_id));
  450. // Ban domain
  451. if (data.domain) tasks.push(banDomain(data.domain, banned_by_id));
  452. redis.del(getRedisKey.link(link.address, link.domain_id, link.user_id));
  453. return Promise.all(tasks);
  454. };