This commit is contained in:
skidoodle 2024-08-24 01:02:02 +02:00
parent 3148a47258
commit b690c6f789
6 changed files with 189 additions and 87 deletions

View file

@ -1,27 +1,60 @@
import random import random
from datetime import datetime, timedelta import json
from datetime import datetime
import os
import sys import sys
def generate_example_data(num_entries): IP_HISTORY_FILE = 'history.json'
data = []
for _ in range(num_entries): def generate_ipv4():
timestamp = datetime.now() - timedelta(days=random.randint(0, 365), return '.'.join(str(random.randint(0, 255)) for _ in range(4))
hours=random.randint(0, 23),
minutes=random.randint(0, 59), def generate_ipv6():
seconds=random.randint(0, 59)) return ':'.join('{:x}'.format(random.randint(0, 65535)) for _ in range(8))
ip_address = f"{random.randint(0, 255)}.{random.randint(0, 255)}.{random.randint(0, 255)}.{random.randint(0, 255)}"
entry = f"{timestamp.strftime('%Y-%m-%d %H:%M:%S')} CEST - {ip_address}" def generate_timestamp():
data.append(entry) return datetime.now().strftime("%Y-%m-%d %H:%M:%S %Z")
return data
def generate_ip_record():
return {
"timestamp": generate_timestamp(),
"ipv4": generate_ipv4(),
"ipv6": generate_ipv6()
}
def load_ip_history():
if os.path.exists(IP_HISTORY_FILE):
with open(IP_HISTORY_FILE, 'r') as file:
try:
return json.load(file)
except json.JSONDecodeError:
return []
return []
def save_ip_history(ip_history):
with open(IP_HISTORY_FILE, 'w') as file:
json.dump(ip_history, file, indent=2)
def generate_and_save_ip_records(num_records=1):
ip_history = load_ip_history()
new_records = [generate_ip_record() for _ in range(num_records)]
ip_history = new_records + ip_history # Append new records at the beginning
save_ip_history(ip_history)
if __name__ == "__main__": if __name__ == "__main__":
if len(sys.argv) != 2: if len(sys.argv) != 2:
print("Usage: python genhistory.py <num_entries>") print("Usage: python genhistory.py <number_of_records>")
sys.exit(1) sys.exit(1)
num_entries = int(sys.argv[1]) try:
example_data = generate_example_data(num_entries) num_records = int(sys.argv[1])
if num_records <= 0:
raise ValueError("Number of records must be a positive integer.")
with open('ip_history.txt', 'w') as file: generate_and_save_ip_records(num_records)
for entry in example_data: print(f"Successfully generated {num_records} IP records.")
file.write(entry + '\n')
except ValueError as e:
print(f"Error: {e}")
print("Please provide a valid positive integer for the number of records.")
sys.exit(1)

7
history.json Normal file
View file

@ -0,0 +1,7 @@
[
{
"timestamp": "2024-08-24 01:00:44",
"ipv4": "78.131.51.69",
"ipv6": "2a01:36d:3200:441c:8120:3ab4:653d:58f4"
}
]

129
main.go
View file

@ -1,7 +1,6 @@
package main package main
import ( import (
"bufio"
"encoding/json" "encoding/json"
"fmt" "fmt"
"io" "io"
@ -12,8 +11,9 @@ import (
) )
const ( const (
traceURL = "https://one.one.one.one/cdn-cgi/trace" ipv4URL = "https://4.ident.me/"
ipHistoryPath = "ip_history.txt" ipv6URL = "https://6.ident.me/"
ipHistoryPath = "history.json"
checkInterval = 30 * time.Second checkInterval = 30 * time.Second
maxRetries = 3 maxRetries = 3
retryDelay = 10 * time.Second retryDelay = 10 * time.Second
@ -21,26 +21,41 @@ const (
type IPRecord struct { type IPRecord struct {
Timestamp string `json:"timestamp"` Timestamp string `json:"timestamp"`
IPAddress string `json:"ip_address"` IPv4 string `json:"ipv4"`
IPv6 string `json:"ipv6"`
} }
func getPublicIP() (string, error) { func getPublicIPs() (string, string, error) {
var ip string var ipv4, ipv6 string
var err error var err error
for attempt := 1; attempt <= maxRetries; attempt++ { for attempt := 1; attempt <= maxRetries; attempt++ {
ip, err = fetchIP() ipv4, ipv6, err = fetchIPs()
if err == nil { if err == nil {
return ip, nil return ipv4, ipv6, nil
} }
fmt.Printf("Attempt %d: Error fetching IP: %v\n", attempt, err) fmt.Printf("Attempt %d: Error fetching IPs: %v\n", attempt, err)
time.Sleep(retryDelay) time.Sleep(retryDelay)
} }
return "", err return "", "", err
} }
func fetchIP() (string, error) { func fetchIPs() (string, string, error) {
resp, err := http.Get(traceURL) ipv4, err := fetchIP(ipv4URL)
if err != nil {
return "", "", err
}
ipv6, err := fetchIP(ipv6URL)
if err != nil {
fmt.Println("Warning: Could not fetch IPv6 address:", err)
}
return ipv4, ipv6, nil
}
func fetchIP(url string) (string, error) {
resp, err := http.Get(url)
if err != nil { if err != nil {
return "", err return "", err
} }
@ -51,12 +66,7 @@ func fetchIP() (string, error) {
return "", err return "", err
} }
for _, line := range strings.Split(string(body), "\n") { return strings.TrimSpace(string(body)), nil
if strings.HasPrefix(line, "ip=") {
return strings.TrimPrefix(line, "ip="), nil
}
}
return "", fmt.Errorf("IP address not found")
} }
func readHistory() ([]IPRecord, error) { func readHistory() ([]IPRecord, error) {
@ -68,19 +78,22 @@ func readHistory() ([]IPRecord, error) {
} }
defer file.Close() defer file.Close()
fileInfo, err := file.Stat()
if err != nil {
return nil, err
}
// Check if the file is empty
if fileInfo.Size() == 0 {
return []IPRecord{}, nil
}
var history []IPRecord var history []IPRecord
scanner := bufio.NewScanner(file) err = json.NewDecoder(file).Decode(&history)
for scanner.Scan() { if err != nil {
parts := strings.Split(scanner.Text(), " - ") return nil, err
if len(parts) == 2 {
record := IPRecord{
Timestamp: parts[0],
IPAddress: parts[1],
} }
history = append(history, record) return history, nil
}
}
return history, scanner.Err()
} }
func writeHistory(history []IPRecord) error { func writeHistory(history []IPRecord) error {
@ -90,42 +103,54 @@ func writeHistory(history []IPRecord) error {
} }
defer file.Close() defer file.Close()
writer := bufio.NewWriter(file) encoder := json.NewEncoder(file)
for _, entry := range history { encoder.SetIndent("", " ") // Pretty-print with indentation
_, err := writer.WriteString(fmt.Sprintf("%s - %s\n", entry.Timestamp, entry.IPAddress)) err = encoder.Encode(history)
if err != nil { if err != nil {
return err return err
} }
} return nil
return writer.Flush()
} }
func trackIP(ipChan <-chan string) { func trackIP(ipChan <-chan IPRecord) {
var lastLoggedIP string var lastLoggedIP IPRecord
for ip := range ipChan { hasNotifiedUpToDate := false
for ipRecord := range ipChan {
history, err := readHistory() history, err := readHistory()
if err != nil { if err != nil {
fmt.Println("Error reading IP history:", err) fmt.Println("Error reading IP history:", err)
continue continue
} }
entry := fmt.Sprintf("%s - %s", time.Now().Format("2006-01-02 15:04:05 MST"), ip) if len(history) > 0 {
if len(history) == 0 || !strings.Contains(history[0].IPAddress, ip) { lastLoggedIP = history[0]
history = append([]IPRecord{{Timestamp: time.Now().Format("2006-01-02 15:04:05 MST"), IPAddress: ip}}, history...) }
// Check if IPs are the same as the last logged one
if ipRecord.IPv4 == lastLoggedIP.IPv4 && ipRecord.IPv6 == lastLoggedIP.IPv6 {
if !hasNotifiedUpToDate {
fmt.Println("🤷 IPs are already up to date")
hasNotifiedUpToDate = true
}
continue
}
// Reset the notification flag when IP changes
hasNotifiedUpToDate = false
ipRecord.Timestamp = time.Now().Format("2006-01-02 15:04:05")
history = append([]IPRecord{ipRecord}, history...)
if err := writeHistory(history); err != nil { if err := writeHistory(history); err != nil {
fmt.Println("Error writing IP history:", err) fmt.Println("Error writing IP history:", err)
continue
} }
fmt.Printf("📄 New IP logged: %s\n", entry)
lastLoggedIP = ip fmt.Printf("📄 New IP logged: {Timestamp: %s, IPv4: %s, IPv6: %s}\n", ipRecord.Timestamp, ipRecord.IPv4, ipRecord.IPv6)
} else {
if lastLoggedIP != ip {
fmt.Println("🤷 IP is already up to date")
lastLoggedIP = ip
}
}
} }
} }
func serveWeb() { func serveWeb() {
http.Handle("/", http.StripPrefix("/", http.FileServer(http.Dir("web")))) http.Handle("/", http.StripPrefix("/", http.FileServer(http.Dir("web"))))
@ -151,15 +176,15 @@ func serveWeb() {
} }
func main() { func main() {
ipChan := make(chan string) ipChan := make(chan IPRecord)
go func() { go func() {
for { for {
ip, err := getPublicIP() ipv4, ipv6, err := getPublicIPs()
if err != nil { if err != nil {
fmt.Println("Error fetching public IP:", err) fmt.Println("Error fetching public IPs:", err)
} else { } else {
ipChan <- ip ipChan <- IPRecord{IPv4: ipv4, IPv6: ipv6}
} }
time.Sleep(checkInterval) time.Sleep(checkInterval)
} }

View file

@ -2,12 +2,11 @@
<html lang="en"> <html lang="en">
<head> <head>
<meta charset="UTF-8"> <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no"> <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
<title>IP History</title> <title>IP History</title>
<link rel="stylesheet" href="style.css"> <link rel="stylesheet" href="style.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js" integrity="sha512-v2CJ7UaYy4JwqLDIrZUI/4hqeoQieOmAZNXBeQyjo21dadnwR+8ZaIJVT8EE2iyI61OV8e6M8PP2/4hpQINQ/g==" crossorigin="anonymous" referrerpolicy="no-referrer"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js" integrity="sha512-v2CJ7UaYy4JwqLDIrZUI/4hqeoQieOmAZNXBeQyjo21dadnwR+8ZaIJVT8EE2iyI61OV8e6M8PP2/4hpQINQ/g==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<script src="script.js"></script> <script src="script.js"></script>
<link rel="stylesheet" href="style.css">
</head> </head>
<body> <body>
<h1><a href="/">IP History</a></h1> <h1><a href="/">IP History</a></h1>
@ -18,8 +17,9 @@
<table id="ipTable"> <table id="ipTable">
<thead> <thead>
<tr> <tr>
<th onclick="sortTable()">Timestamp</th> <th onclick="sortTable('timestamp')">Timestamp</th>
<th>IP Address</th> <th onclick="sortTable('ipv4')">IPv4 Address</th>
<th onclick="sortTable('ipv6')">IPv6 Address</th>
</tr> </tr>
</thead> </thead>
<tbody></tbody> <tbody></tbody>

View file

@ -15,7 +15,11 @@ $(document).ready(function() {
$('#searchBar').on('input', function() { $('#searchBar').on('input', function() {
const query = $(this).val().toLowerCase(); const query = $(this).val().toLowerCase();
filteredHistory = ipHistory.filter(entry => entry.timestamp.toLowerCase().includes(query) || entry.ip_address.toLowerCase().includes(query)); filteredHistory = ipHistory.filter(entry =>
entry.timestamp.toLowerCase().includes(query) ||
(entry.ipv4 && entry.ipv4.toLowerCase().includes(query)) ||
(entry.ipv6 && entry.ipv6.toLowerCase().includes(query))
);
currentPage = 1; currentPage = 1;
displayTable(); displayTable();
updateTotalIPs(); updateTotalIPs();
@ -31,7 +35,8 @@ function displayTable() {
currentEntries.forEach(entry => { currentEntries.forEach(entry => {
const tr = $('<tr>'); const tr = $('<tr>');
tr.append($('<td>').text(entry.timestamp)); tr.append($('<td>').text(entry.timestamp));
tr.append($('<td>').text(entry.ip_address)); tr.append($('<td>').text(entry.ipv4 || 'N/A').css('min-width', '120px')); // Set static width
tr.append($('<td>').text(entry.ipv6 || 'N/A').css('min-width', '180px')); // Set static width
tbody.append(tr); tbody.append(tr);
}); });
updatePaginationButtons(); updatePaginationButtons();
@ -62,21 +67,27 @@ function prevPage() {
} }
} }
function sortTable() { function sortTable(field) {
const isAscending = $('#ipTable th').eq(0).hasClass('sort-asc'); const isAscending = $(`#ipTable th:contains(${field.charAt(0).toUpperCase() + field.slice(1)})`).hasClass('sort-asc');
const orderModifier = isAscending ? 1 : -1; const orderModifier = isAscending ? 1 : -1;
filteredHistory.sort((a, b) => (a.timestamp.localeCompare(b.timestamp)) * orderModifier); filteredHistory.sort((a, b) => {
if (a[field] && b[field]) {
return (a[field].localeCompare(b[field])) * orderModifier;
}
return 0;
});
$('#ipTable th').removeClass('sort-asc sort-desc'); $('#ipTable th').removeClass('sort-asc sort-desc');
$('#ipTable th').eq(0).addClass(isAscending ? 'sort-desc' : 'sort-asc'); $(`#ipTable th:contains(${field.charAt(0).toUpperCase() + field.slice(1)})`).addClass(isAscending ? 'sort-desc' : 'sort-asc');
displayTable(); displayTable();
} }
function exportToCSV() { function exportToCSV() {
const rows = [ const rows = [
['Timestamp', 'IP Address'], ...filteredHistory.map(entry => [entry.timestamp, entry.ip_address]) ['Timestamp', 'IPv4 Address', 'IPv6 Address'],
...filteredHistory.map(entry => [entry.timestamp, entry.ipv4 || '', entry.ipv6 || ''])
]; ];
const csvContent = "data:text/csv;charset=utf-8," + rows.map(e => e.join(",")).join("\n"); const csvContent = "data:text/csv;charset=utf-8," + rows.map(e => e.join(",")).join("\n");
const encodedUri = encodeURI(csvContent); const encodedUri = encodeURI(csvContent);

View file

@ -1,3 +1,9 @@
* {
-webkit-tap-highlight-color: transparent;
-webkit-touch-callout: none;
touch-action: manipulation;
}
body { body {
font-family: Arial, sans-serif; font-family: Arial, sans-serif;
background-color: #222; background-color: #222;
@ -58,18 +64,21 @@ h1 a:hover {
} }
table { table {
width: 90%; width: 90%;
max-width: 800px; max-width: 1200px;
border-collapse: collapse; border-collapse: collapse;
margin: 0 auto 20px; margin: 0 auto 20px;
border-radius: 10px; border-radius: 10px;
overflow: hidden; overflow: hidden;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.3); box-shadow: 0 0 10px rgba(0, 0, 0, 0.3);
background-color: #333; background-color: #333;
table-layout: fixed;
} }
th, td { th, td {
border: 1px solid #444; border: 1px solid #444;
padding: 12px; padding: 12px;
text-align: left; text-align: left;
word-wrap: break-word;
overflow-wrap: break-word;
} }
th { th {
cursor: pointer; cursor: pointer;
@ -107,9 +116,14 @@ tbody tr:nth-child(even) {
background-color: #555; background-color: #555;
cursor: not-allowed; cursor: not-allowed;
} }
@media (max-width: 600px) { @media (max-width: 600px) {
th, td { th, td {
padding: 8px; padding: 8px;
font-size: 14px;
}
table {
font-size: 14px;
} }
.export, .pagination button { .export, .pagination button {
padding: 8px 12px; padding: 8px 12px;
@ -119,4 +133,16 @@ tbody tr:nth-child(even) {
padding: 8px; padding: 8px;
font-size: 14px; font-size: 14px;
} }
.controls {
flex-direction: column;
align-items: stretch;
}
.export {
width: 100%;
margin-bottom: 10px;
}
.search-bar {
width: 100%;
margin-left: 0;
}
} }