visit.js 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. const useragent = require("useragent");
  2. const geoip = require("geoip-lite");
  3. const URL = require("url");
  4. const { getStatsLimit, removeWww } = require("../utils");
  5. const query = require("../queries");
  6. const browsersList = ["IE", "Firefox", "Chrome", "Opera", "Safari", "Edge"];
  7. const osList = ["Windows", "Mac OS", "Linux", "Android", "iOS"];
  8. function filterInBrowser(agent) {
  9. return function(item) {
  10. return agent.family.toLowerCase().includes(item.toLocaleLowerCase());
  11. }
  12. }
  13. function filterInOs(agent) {
  14. return function(item) {
  15. return agent.os.family.toLowerCase().includes(item.toLocaleLowerCase());
  16. }
  17. }
  18. module.exports = function({ data }) {
  19. const tasks = [];
  20. tasks.push(query.link.incrementVisit({ id: data.link.id }));
  21. if (data.link.visit_count < getStatsLimit()) {
  22. // the following line is for backward compatibility
  23. // used to send the whole header to get the user agent
  24. const userAgent = data.userAgent || data.headers?.["user-agent"];
  25. const agent = useragent.parse(userAgent);
  26. const [browser = "Other"] = browsersList.filter(filterInBrowser(agent));
  27. const [os = "Other"] = osList.filter(filterInOs(agent));
  28. const referrer =
  29. data.referrer && removeWww(URL.parse(data.referrer).hostname);
  30. const location = geoip.lookup(data.ip);
  31. const country = location && location.country;
  32. tasks.push(
  33. query.visit.add({
  34. browser: browser.toLowerCase(),
  35. country: country || "Unknown",
  36. id: data.link.id,
  37. os: os.toLowerCase().replace(/\s/gi, ""),
  38. referrer: (referrer && referrer.replace(/\./gi, "[dot]")) || "Direct"
  39. })
  40. );
  41. }
  42. return Promise.all(tasks);
  43. }