visit.ts 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839
  1. import useragent from "useragent";
  2. import geoip from "geoip-lite";
  3. import URL from "url";
  4. import query from "../queries";
  5. import { getStatsLimit } from "../utils";
  6. const browsersList = ["IE", "Firefox", "Chrome", "Opera", "Safari", "Edge"];
  7. const osList = ["Windows", "Mac OS", "Linux", "Android", "iOS"];
  8. const filterInBrowser = agent => item =>
  9. agent.family.toLowerCase().includes(item.toLocaleLowerCase());
  10. const filterInOs = agent => item =>
  11. agent.os.family.toLowerCase().includes(item.toLocaleLowerCase());
  12. export default function({ data }) {
  13. const tasks = [];
  14. tasks.push(query.link.increamentVisit({ id: data.link.id }));
  15. if (data.link.visit_count < getStatsLimit()) {
  16. const agent = useragent.parse(data.headers["user-agent"]);
  17. const [browser = "Other"] = browsersList.filter(filterInBrowser(agent));
  18. const [os = "Other"] = osList.filter(filterInOs(agent));
  19. const referrer = data.referrer && URL.parse(data.referrer).hostname;
  20. const location = geoip.lookup(data.realIP);
  21. const country = location && location.country;
  22. tasks.push(
  23. query.visit.add({
  24. browser: browser.toLowerCase(),
  25. country: country || "Unknown",
  26. id: data.link.id,
  27. os: os.toLowerCase().replace(/\s/gi, ""),
  28. referrer: (referrer && referrer.replace(/\./gi, "[dot]")) || "Direct"
  29. })
  30. );
  31. }
  32. return Promise.all(tasks);
  33. }