zardoz/file.go
2019-11-28 14:52:44 +01:00

147 lines
2.9 KiB
Go

package main
import (
"encoding/json"
"fmt"
"io"
"log"
"os"
"time"
)
type dumpStruct struct {
Update string `json:"LastUpdate"`
GOOD []GOOD `json:"GOOD"`
BAD []BAD `json:"BAD"`
MEH []MEH `json:"MEH"`
STATS []STATS `json:"STATS"`
}
type GOOD struct {
Token string `json:"Token"`
LastSeen string `json:"LastSeen"`
Delta string `json:"Age"`
}
type BAD struct {
Token string `json:"Token"`
LastSeen string `json:"LastSeen"`
Delta string `json:"Age"`
}
type MEH struct {
Token string `json:"Token"`
LastSeen string `json:"LastSeen"`
Delta string `json:"Age"`
}
type STATS struct {
Decision string `json:"Decision"`
Amount int64 `json:"Amount"`
}
// WriteToFile will print any string of text to a file safely by
// checking for errors and syncing at the end.
func writeToFile(filename string, data string) error {
file, err := os.Create(filename)
if err != nil {
return err
}
defer file.Close()
_, err = io.WriteString(file, data)
if err != nil {
return err
}
return file.Sync()
}
func handlepanic() {
if a := recover(); a != nil {
fmt.Println("OPS!: Recovering from:", a)
}
}
func saveBayesToFile() {
var tmpJSON string
var DumpJson = new(dumpStruct)
DumpJson.Update = time.Now().String()
log.Println("Trying to write json file")
Classifier.BAD.Range(func(key interface{}, value interface{}) bool {
var t BAD
v := value.(int64)
t.Token = key.(string)
t.LastSeen = time.Unix(0, v).String()
t.Delta = time.Since(time.Unix(0, v)).String()
DumpJson.BAD = append(DumpJson.BAD, t)
return true
})
Classifier.GOOD.Range(func(key interface{}, value interface{}) bool {
var t GOOD
v := value.(int64)
t.Token = key.(string)
t.LastSeen = time.Unix(0, v).String()
t.Delta = time.Since(time.Unix(0, v)).String()
DumpJson.GOOD = append(DumpJson.GOOD, t)
return true
})
Classifier.MEH.Range(func(key interface{}, value interface{}) bool {
var t MEH
v := value.(int64)
t.Token = key.(string)
t.LastSeen = time.Unix(0, v).String()
t.Delta = time.Since(time.Unix(0, v)).String()
DumpJson.MEH = append(DumpJson.MEH, t)
return true
})
Classifier.STATS.Range(func(key interface{}, value interface{}) bool {
var t STATS
t.Decision = key.(string)
t.Amount = value.(int64)
DumpJson.STATS = append(DumpJson.STATS, t)
return true
})
if tmpJ, e := json.MarshalIndent(DumpJson, "", " "); e == nil {
tmpJSON = fmt.Sprintf("%s", tmpJ)
} else {
tmpJSON = e.Error()
}
dumpfile := os.Getenv("DUMPFILE")
if dumpfile == "" {
dumpfile = "bayes.json"
}
if DebugLog {
log.Println(tmpJSON)
} else {
writeToFile(dumpfile, tmpJSON)
log.Println("File saved: ", dumpfile)
}
}
func jsonEngine() {
for {
log.Println("Zardoz Seniority: ", ProxyFlow.seniority)
saveBayesToFile()
time.Sleep(1 * time.Minute)
}
}
func init() {
log.Printf("File Engine Starting")
go jsonEngine()
log.Printf("FIle Engine Started")
}