cosm(public-ip): update public IP card to show last updated time

This commit is contained in:
Siyuan 2025-11-10 17:22:40 +00:00
parent e9df46baec
commit 1671a245f2
2 changed files with 43 additions and 7 deletions

View File

@ -7,6 +7,7 @@ import (
"net"
"net/http"
"net/url"
"strconv"
"strings"
"sync"
"time"
@ -52,21 +53,38 @@ func (ps *PublicIPState) checkCloudflare(ctx context.Context, family int) (*Publ
return nil, err
}
values := make(map[string]string)
for line := range strings.SplitSeq(string(body), "\n") {
key, value, ok := strings.Cut(line, "=")
if !ok || key != "ip" {
if !ok {
continue
}
values[key] = value
}
ps.lastUpdated = time.Now()
if ts, ok := values["ts"]; ok {
if ts, err := strconv.ParseFloat(ts, 64); err == nil {
ps.lastUpdated = time.Unix(int64(ts), 0)
}
}
ipStr, ok := values["ip"]
if !ok {
return nil, fmt.Errorf("no IP address found")
}
ip := net.ParseIP(ipStr)
if ip == nil {
return nil, fmt.Errorf("invalid IP address: %s", ipStr)
}
return &PublicIP{
IPAddress: net.ParseIP(value),
LastUpdated: time.Now(),
IPAddress: ip,
LastUpdated: ps.lastUpdated,
}, nil
}
return nil, fmt.Errorf("no IP address found")
}
// checkAPI uses the API endpoint to get the public IP address
func (ps *PublicIPState) checkAPI(_ context.Context, _ int) (*PublicIP, error) {
return nil, fmt.Errorf("not implemented")

View File

@ -7,8 +7,25 @@ import { PublicIP } from "@hooks/stores";
import { m } from "@localizations/messages.js";
import { JsonRpcResponse, useJsonRpc } from "@hooks/useJsonRpc";
import notifications from "@/notifications";
import { formatters } from "@/utils";
const TimeAgoLabel = ({ date }: { date: Date }) => {
const [timeAgo, setTimeAgo] = useState<string | undefined>(formatters.timeAgo(date));
useEffect(() => {
const interval = setInterval(() => {
setTimeAgo(formatters.timeAgo(date));
}, 1000);
return () => clearInterval(interval);
}, [date]);
return (
<span className="text-sm text-slate-600 dark:text-slate-400 select-none">
{timeAgo}
</span>
);
};
export default function PublicIPCard() {
const { send } = useJsonRpc();
@ -76,6 +93,7 @@ export default function PublicIPCard() {
<span className="text-sm font-medium">
{ip.ip}
</span>
{ip.last_updated && <TimeAgoLabel date={new Date(ip.last_updated)} />}
</div>
))}
</div>