Spaces:
Sleeping
Sleeping
File size: 8,369 Bytes
2545af7 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 | #!/usr/bin/env python3
"""
Visitor Tracker - Track unique visitors by IP address
Stores visitor data with timestamps and provides analytics
"""
import json
import hashlib
from datetime import datetime, timedelta
from pathlib import Path
from typing import Dict, List, Optional
class VisitorTracker:
def __init__(self, data_file: str = "visitors.json"):
self.data_file = Path(data_file)
self.data = self._load_data()
def _load_data(self) -> Dict:
"""Load visitor data from JSON file"""
if self.data_file.exists():
try:
with open(self.data_file, 'r') as f:
return json.load(f)
except Exception as e:
print(f"Error loading visitor data: {e}")
return self._init_data()
return self._init_data()
def _init_data(self) -> Dict:
"""Initialize empty visitor data structure"""
return {
"visitors": {},
"total_visits": 0,
"unique_visitors": 0,
"daily_stats": {}
}
def _save_data(self):
"""Save visitor data to JSON file"""
try:
with open(self.data_file, 'w') as f:
json.dump(self.data, f, indent=2, default=str)
except Exception as e:
print(f"Error saving visitor data: {e}")
def _hash_ip(self, ip: str) -> str:
"""Hash IP address for privacy (optional)"""
# For now, store full IP. Can enable hashing later for privacy
return ip
# return hashlib.sha256(ip.encode()).hexdigest()[:16]
def track_visit(self, ip: str, user_agent: str = "", country: str = "") -> Dict:
"""
Track a visitor visit
Returns: visitor statistics
"""
ip_hash = self._hash_ip(ip)
now = datetime.now()
today = now.strftime("%Y-%m-%d")
# Initialize daily stats if needed
if today not in self.data["daily_stats"]:
self.data["daily_stats"][today] = {
"visits": 0,
"unique_visitors": set(),
"new_visitors": 0
}
# Track visitor
is_new_visitor = ip_hash not in self.data["visitors"]
if is_new_visitor:
self.data["visitors"][ip_hash] = {
"ip": ip,
"first_visit": now.isoformat(),
"last_visit": now.isoformat(),
"visit_count": 1,
"user_agent": user_agent,
"country": country
}
self.data["unique_visitors"] += 1
self.data["daily_stats"][today]["new_visitors"] += 1
else:
visitor = self.data["visitors"][ip_hash]
visitor["last_visit"] = now.isoformat()
visitor["visit_count"] += 1
if user_agent:
visitor["user_agent"] = user_agent
# Update totals
self.data["total_visits"] += 1
self.data["daily_stats"][today]["visits"] += 1
# Convert set to list for JSON serialization
if isinstance(self.data["daily_stats"][today]["unique_visitors"], set):
self.data["daily_stats"][today]["unique_visitors"] = list(
self.data["daily_stats"][today]["unique_visitors"]
)
if ip_hash not in self.data["daily_stats"][today]["unique_visitors"]:
self.data["daily_stats"][today]["unique_visitors"].append(ip_hash)
self._save_data()
return self.get_stats()
def get_stats(self) -> Dict:
"""Get current visitor statistics"""
now = datetime.now()
active_threshold = now - timedelta(minutes=30)
# Count active visitors (visited in last 30 minutes)
active_count = 0
for visitor in self.data["visitors"].values():
try:
last_visit = datetime.fromisoformat(visitor["last_visit"])
if last_visit >= active_threshold:
active_count += 1
except:
pass
today = now.strftime("%Y-%m-%d")
today_stats = self.data["daily_stats"].get(today, {
"visits": 0,
"unique_visitors": [],
"new_visitors": 0
})
return {
"total_visits": self.data["total_visits"],
"unique_visitors": self.data["unique_visitors"],
"active_visitors": active_count,
"today_visits": today_stats["visits"],
"today_unique": len(today_stats.get("unique_visitors", [])),
"today_new": today_stats.get("new_visitors", 0)
}
def get_daily_report_data(self, date: Optional[str] = None) -> Dict:
"""
Get detailed visitor data for daily report
date: YYYY-MM-DD format, defaults to today
"""
if date is None:
date = datetime.now().strftime("%Y-%m-%d")
stats = self.data["daily_stats"].get(date, {
"visits": 0,
"unique_visitors": [],
"new_visitors": 0
})
# Get visitor details for the day
visitor_details = []
unique_ips = stats.get("unique_visitors", [])
for ip_hash in unique_ips:
if ip_hash in self.data["visitors"]:
visitor = self.data["visitors"][ip_hash]
visitor_details.append({
"ip": visitor["ip"],
"visit_count": visitor["visit_count"],
"last_visit": visitor["last_visit"],
"user_agent": visitor.get("user_agent", "Unknown")
})
# Sort by visit count
visitor_details.sort(key=lambda x: x["visit_count"], reverse=True)
return {
"date": date,
"total_visits": stats["visits"],
"unique_visitors": len(unique_ips),
"new_visitors": stats.get("new_visitors", 0),
"returning_visitors": len(unique_ips) - stats.get("new_visitors", 0),
"visitor_details": visitor_details,
"all_time_total": self.data["total_visits"],
"all_time_unique": self.data["unique_visitors"]
}
def cleanup_old_data(self, days_to_keep: int = 90):
"""Remove visitor data older than specified days"""
cutoff_date = datetime.now() - timedelta(days=days_to_keep)
# Remove old daily stats
dates_to_remove = []
for date_str in self.data["daily_stats"].keys():
try:
date = datetime.strptime(date_str, "%Y-%m-%d")
if date < cutoff_date:
dates_to_remove.append(date_str)
except:
pass
for date_str in dates_to_remove:
del self.data["daily_stats"][date_str]
# Remove visitors who haven't visited in the retention period
visitors_to_remove = []
for ip_hash, visitor in self.data["visitors"].items():
try:
last_visit = datetime.fromisoformat(visitor["last_visit"])
if last_visit < cutoff_date:
visitors_to_remove.append(ip_hash)
except:
pass
for ip_hash in visitors_to_remove:
del self.data["visitors"][ip_hash]
if visitors_to_remove or dates_to_remove:
self._save_data()
print(f"Cleaned up {len(visitors_to_remove)} old visitors and {len(dates_to_remove)} old daily stats")
if __name__ == "__main__":
# Test the tracker
tracker = VisitorTracker()
# Simulate some visits
print("Simulating visits...")
tracker.track_visit("192.168.1.1", "Mozilla/5.0 (Windows NT 10.0; Win64; x64)", "US")
tracker.track_visit("192.168.1.2", "Mozilla/5.0 (iPhone; CPU iPhone OS 14_0)", "IN")
tracker.track_visit("192.168.1.1", "Mozilla/5.0 (Windows NT 10.0; Win64; x64)", "US") # Repeat visitor
# Get stats
stats = tracker.get_stats()
print("\nCurrent Stats:")
print(json.dumps(stats, indent=2))
# Get daily report
report = tracker.get_daily_report_data()
print("\nDaily Report:")
print(json.dumps(report, indent=2))
|