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+
from datetime import datetime
|
| 6 |
+
import os
|
| 7 |
+
|
| 8 |
+
app = Flask(__name__)
|
| 9 |
+
app.config['DATABASE'] = 'visitors.db'
|
| 10 |
+
app.config['IP_API_KEY'] = '' # Optional API key for ip-api.com
|
| 11 |
+
|
| 12 |
+
# Database setup
|
| 13 |
+
def get_db():
|
| 14 |
+
db = getattr(g, '_database', None)
|
| 15 |
+
if db is None:
|
| 16 |
+
db = g._database = sqlite3.connect(app.config['DATABASE'])
|
| 17 |
+
return db
|
| 18 |
+
|
| 19 |
+
def init_db():
|
| 20 |
+
with app.app_context():
|
| 21 |
+
db = get_db()
|
| 22 |
+
cursor = db.cursor()
|
| 23 |
+
cursor.execute('''
|
| 24 |
+
CREATE TABLE IF NOT EXISTS visitors (
|
| 25 |
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
| 26 |
+
timestamp TEXT NOT NULL,
|
| 27 |
+
ip TEXT NOT NULL,
|
| 28 |
+
country TEXT,
|
| 29 |
+
country_code TEXT,
|
| 30 |
+
region TEXT,
|
| 31 |
+
region_name TEXT,
|
| 32 |
+
city TEXT,
|
| 33 |
+
zip TEXT,
|
| 34 |
+
lat REAL,
|
| 35 |
+
lon REAL,
|
| 36 |
+
timezone TEXT,
|
| 37 |
+
isp TEXT,
|
| 38 |
+
org TEXT,
|
| 39 |
+
as_number TEXT,
|
| 40 |
+
mobile BOOLEAN,
|
| 41 |
+
proxy BOOLEAN,
|
| 42 |
+
hosting BOOLEAN,
|
| 43 |
+
user_agent TEXT,
|
| 44 |
+
path TEXT
|
| 45 |
+
)
|
| 46 |
+
''')
|
| 47 |
+
db.commit()
|
| 48 |
+
|
| 49 |
+
@app.teardown_appcontext
|
| 50 |
+
def close_connection(exception):
|
| 51 |
+
db = getattr(g, '_database', None)
|
| 52 |
+
if db is not None:
|
| 53 |
+
db.close()
|
| 54 |
+
|
| 55 |
+
# Helper functions
|
| 56 |
+
def get_client_ip():
|
| 57 |
+
"""Get the client IP address, handling proxy headers"""
|
| 58 |
+
if request.headers.getlist("X-Forwarded-For"):
|
| 59 |
+
ip = request.headers.getlist("X-Forwarded-For")[0].split(',')[0]
|
| 60 |
+
else:
|
| 61 |
+
ip = request.remote_addr
|
| 62 |
+
return ip
|
| 63 |
+
|
| 64 |
+
def get_location_info(ip_address):
|
| 65 |
+
"""Get geolocation information for an IP address"""
|
| 66 |
+
try:
|
| 67 |
+
# Using ip-api.com (free tier)
|
| 68 |
+
fields = 'status,message,country,countryCode,region,regionName,city,zip,lat,lon,timezone,isp,org,as,mobile,proxy,hosting,query'
|
| 69 |
+
url = f'http://ip-api.com/json/{ip_address}?fields={fields}'
|
| 70 |
+
if app.config['IP_API_KEY']:
|
| 71 |
+
url += f'&key={app.config["IP_API_KEY"]}'
|
| 72 |
+
|
| 73 |
+
response = requests.get(url, timeout=5)
|
| 74 |
+
data = response.json()
|
| 75 |
+
|
| 76 |
+
if data.get('status') == 'success':
|
| 77 |
+
return data
|
| 78 |
+
return {'error': data.get('message', 'Unknown error')}
|
| 79 |
+
except Exception as e:
|
| 80 |
+
return {'error': str(e)}
|
| 81 |
+
|
| 82 |
+
def log_visitor(ip, location_info):
|
| 83 |
+
"""Store visitor information in the database"""
|
| 84 |
+
db = get_db()
|
| 85 |
+
cursor = db.cursor()
|
| 86 |
+
|
| 87 |
+
cursor.execute('''
|
| 88 |
+
INSERT INTO visitors (
|
| 89 |
+
timestamp, ip, country, country_code, region, region_name, city, zip,
|
| 90 |
+
lat, lon, timezone, isp, org, as_number, mobile, proxy, hosting,
|
| 91 |
+
user_agent, path
|
| 92 |
+
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
| 93 |
+
''', (
|
| 94 |
+
datetime.now().isoformat(),
|
| 95 |
+
ip,
|
| 96 |
+
location_info.get('country'),
|
| 97 |
+
location_info.get('countryCode'),
|
| 98 |
+
location_info.get('region'),
|
| 99 |
+
location_info.get('regionName'),
|
| 100 |
+
location_info.get('city'),
|
| 101 |
+
location_info.get('zip'),
|
| 102 |
+
location_info.get('lat'),
|
| 103 |
+
location_info.get('lon'),
|
| 104 |
+
location_info.get('timezone'),
|
| 105 |
+
location_info.get('isp'),
|
| 106 |
+
location_info.get('org'),
|
| 107 |
+
location_info.get('as'),
|
| 108 |
+
bool(location_info.get('mobile')),
|
| 109 |
+
bool(location_info.get('proxy')),
|
| 110 |
+
bool(location_info.get('hosting')),
|
| 111 |
+
request.headers.get('User-Agent'),
|
| 112 |
+
request.path
|
| 113 |
+
))
|
| 114 |
+
db.commit()
|
| 115 |
+
|
| 116 |
+
# Routes
|
| 117 |
+
@app.route('/')
|
| 118 |
+
def index():
|
| 119 |
+
client_ip = get_client_ip()
|
| 120 |
+
location_info = get_location_info(client_ip)
|
| 121 |
+
|
| 122 |
+
if 'error' not in location_info:
|
| 123 |
+
log_visitor(client_ip, location_info)
|
| 124 |
+
|
| 125 |
+
return render_template('index.html',
|
| 126 |
+
ip=client_ip,
|
| 127 |
+
location=location_info,
|
| 128 |
+
error=location_info.get('error'))
|
| 129 |
+
|
| 130 |
+
@app.route('/visitors')
|
| 131 |
+
def show_visitors():
|
| 132 |
+
"""Admin view to see all recorded visitors"""
|
| 133 |
+
db = get_db()
|
| 134 |
+
cursor = db.cursor()
|
| 135 |
+
cursor.execute('SELECT * FROM visitors ORDER BY timestamp DESC LIMIT 100')
|
| 136 |
+
visitors = cursor.fetchall()
|
| 137 |
+
|
| 138 |
+
# Get column names
|
| 139 |
+
cursor.execute('PRAGMA table_info(visitors)')
|
| 140 |
+
columns = [column[1] for column in cursor.fetchall()]
|
| 141 |
+
|
| 142 |
+
return render_template('visitors.html', visitors=visitors, columns=columns)
|
| 143 |
+
|
| 144 |
+
if __name__ == '__main__':
|
| 145 |
+
if not os.path.exists(app.config['DATABASE']):
|
| 146 |
+
init_db()
|
| 147 |
+
app.run(host="0.0.0.0", debug=True)
|