105 lines
2.3 KiB
Go
105 lines
2.3 KiB
Go
package main
|
|
|
|
import (
|
|
"context"
|
|
"encoding/json"
|
|
"fmt"
|
|
"io/ioutil"
|
|
"net/http"
|
|
"strings"
|
|
"time"
|
|
|
|
"github.com/wailsapp/wails/v2/pkg/runtime"
|
|
)
|
|
|
|
// App struct
|
|
type App struct {
|
|
ctx context.Context
|
|
}
|
|
|
|
// NewApp creates a new App application struct
|
|
func NewApp() *App {
|
|
return &App{}
|
|
}
|
|
|
|
// startup is called when the app starts. The context is saved
|
|
// so we can call the runtime methods
|
|
func (a *App) startup(ctx context.Context) {
|
|
a.ctx = ctx
|
|
go a.fetchLogs()
|
|
}
|
|
|
|
// LogEntry represents a single log entry
|
|
type LogEntry struct {
|
|
PeerID string `json:"my_peer_id"`
|
|
MsgHash string `json:"msg_hash"`
|
|
Timestamp string `json:"_time"`
|
|
}
|
|
|
|
// NodeEvent represents an event to be sent to the frontend
|
|
type NodeEvent struct {
|
|
PeerID string `json:"peerId"`
|
|
Color string `json:"color"`
|
|
}
|
|
|
|
// fetchLogs periodically fetches logs and processes them
|
|
func (a *App) fetchLogs() {
|
|
ticker := time.NewTicker(3 * time.Second)
|
|
processedLogs := make(map[string]bool)
|
|
|
|
for range ticker.C {
|
|
logs, err := a.queryLogs()
|
|
if err != nil {
|
|
fmt.Println("Error fetching logs:", err)
|
|
continue
|
|
}
|
|
|
|
for _, log := range logs {
|
|
key := log.MsgHash + log.Timestamp
|
|
if !processedLogs[key] {
|
|
color := generateColor(log.MsgHash)
|
|
event := NodeEvent{
|
|
PeerID: log.PeerID,
|
|
Color: color,
|
|
}
|
|
a.sendEventToFrontend(event)
|
|
processedLogs[key] = true
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
// queryLogs fetches the latest logs from the API
|
|
func (a *App) queryLogs() ([]LogEntry, error) {
|
|
url := "https://vmselect.riff.cc/select/logsql/query"
|
|
payload := strings.NewReader("query=_time:5s relay received")
|
|
req, _ := http.NewRequest("POST", url, payload)
|
|
req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
|
|
|
|
res, err := http.DefaultClient.Do(req)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
defer res.Body.Close()
|
|
|
|
body, _ := ioutil.ReadAll(res.Body)
|
|
var logs []LogEntry
|
|
err = json.Unmarshal(body, &logs)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
return logs, nil
|
|
}
|
|
|
|
// generateColor creates a color based on the message hash
|
|
func generateColor(hash string) string {
|
|
// Simple color generation, can be improved
|
|
return "#" + hash[2:8]
|
|
}
|
|
|
|
// sendEventToFrontend sends an event to the frontend using Wails runtime
|
|
func (a *App) sendEventToFrontend(event NodeEvent) {
|
|
runtime.EventsEmit(a.ctx, "nodeUpdate", event)
|
|
}
|