link.ts 13 KB

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