-
Notifications
You must be signed in to change notification settings - Fork 0
/
stats.go
67 lines (57 loc) · 1.48 KB
/
stats.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
package ipfs
import (
"encoding/json"
"log"
"github.com/arken/arkstat/database"
"github.com/arken/arkstat/mail"
"github.com/libp2p/go-libp2p-core/network"
)
type report struct {
Email string `json:"email"`
TotalSpace float64 `json:"total_space"`
UsedSpace float64 `json:"used_space"`
}
func BuildStatsHandler(db *database.DB, mailbox *mail.Mailbox) network.StreamHandler {
return func(stream network.Stream) {
defer stream.Close()
// Create report and json input into struct
r := report{}
buf := make([]byte, 128)
n, err := stream.Read(buf)
if err != nil {
log.Println(err)
return
}
// Parse input json.
err = json.Unmarshal(buf[:n], &r)
if err != nil {
return
}
// Check for mailformed stats
if r.UsedSpace > r.TotalSpace || r.UsedSpace == 0 || r.TotalSpace == 0 {
return
}
// Construct peer db entry
peer := database.Node{
ID: stream.Conn().RemotePeer().Pretty(),
Email: r.Email,
TotalSpace: r.TotalSpace / 1000,
UsedSpace: r.UsedSpace / 1000,
}
// Check for existing record
prev, _ := db.Get(peer.ID)
// Add info to database
err = db.Add(peer)
if err != nil {
log.Printf("IPFS Handler <--> DB - %s", err)
}
log.Printf("Received Stats from Node: %s", stream.Conn().RemotePeer().Pretty())
// Send confirmation email
if prev.Email == "" && peer.Email != "" && mailbox != nil {
err = mailbox.Send("mail/templates/welcome.yml", peer.Email)
if err != nil {
log.Println(err)
}
}
}
}