aboutsummaryrefslogtreecommitdiff
path: root/app/util
diff options
context:
space:
mode:
authorParker <contact@pkrm.dev>2024-06-24 16:24:09 -0500
committerParker <contact@pkrm.dev>2024-06-24 16:24:09 -0500
commit5b92454760a8af14bd1031e72024946f868d1de6 (patch)
treef8384cbf0d142777d9bff341e13fd5882182908b /app/util
parent80a39d38bf829193c655a7320c86df2a3146db2a (diff)
Major overhaul + Bare bones web UI
Diffstat (limited to 'app/util')
-rw-r--r--app/util/log.py65
1 files changed, 65 insertions, 0 deletions
diff --git a/app/util/log.py b/app/util/log.py
new file mode 100644
index 0000000..e49080f
--- /dev/null
+++ b/app/util/log.py
@@ -0,0 +1,65 @@
+import ip2locationio
+import datetime
+from ua_parser import user_agent_parser
+from ip2locationio.ipgeolocation import IP2LocationIOAPIError
+
+from database import SessionLocal
+from var import LOG, API_KEY, IP_TO_LOCATION
+from models import Link, Record
+
+configuration = ip2locationio.Configuration(API_KEY)
+ipgeolocation = ip2locationio.IPGeolocation(configuration)
+
+"""
+Create a new log record whenever a link is visited
+"""
+
+
+def log(link, ip, user_agent):
+ db = SessionLocal()
+
+ # Get the redirect link and owner of the link
+ redirect_link, owner = (
+ db.query(Link.redirect_link, Link.owner).filter(Link.link == link).first()
+ )
+
+ if IP_TO_LOCATION == "TRUE":
+ # Get IP to GEO via IP2Location.io
+ try:
+ data = ipgeolocation.lookup(ip)
+ location = f'{data["country_name"]}, {data["city_name"]}'
+ isp = data["as"]
+ # Fatal error, API key is invalid or out of requests, quit
+ except IP2LocationIOAPIError:
+ LOG.error(
+ "Invalid API key or insufficient credits. Change the `config.ini` file if you no longer need the IP2Location API feature."
+ )
+ location = "-, -"
+ isp = "-"
+ else:
+ location = "-, -"
+ isp = "-"
+
+ timestamp = datetime.datetime.now()
+ ua_string = user_agent_parser.Parse(user_agent)
+ browser = ua_string["user_agent"]["family"]
+ os = f'{ua_string["os"]["family"]} {ua_string["os"]["major"]}'
+
+ # Create the log record and commit it to the database
+ link_record = Record(
+ owner=owner,
+ link=link,
+ timestamp=timestamp,
+ ip=ip,
+ location=location,
+ browser=browser,
+ os=os,
+ user_agent=user_agent,
+ isp=isp,
+ )
+ db.add(link_record)
+ db.commit()
+ db.close()
+
+ # Return the redirect link in order to properly redirect the user
+ return redirect_link