-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
133 lines (121 loc) · 2.73 KB
/
main.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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
package main
import (
"bytes"
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"os"
"strconv"
"time"
"github.com/google/uuid"
log "github.com/sirupsen/logrus"
)
func main() {
// Discover all services on the network (e.g. _workstation._tcp)
log.SetLevel(log.DebugLevel)
port := os.Getenv("PORT")
if port == "" {
port = "8080"
}
dbname := os.Getenv("DBNAME")
if dbname == "" {
dbname = "disaster.db"
}
id := uuid.New()
s, err := NewStore(dbname)
if err != nil {
fmt.Println(err)
fmt.Println("couldn't create store")
}
tmp := MyInfo{
UserID: id,
Name: "me1",
Email: "[email protected]",
Phone: "(555) 555 5555",
Lat: -1,
Long: -1,
Time: time.Now(),
}
s.SetMyInfo(&tmp)
a := NewServer("0.0.0.0", port, id, s)
portInt, _ := strconv.Atoi(port)
go RegisterService(id, portInt)
peerChan := make(chan Peer)
go FindPeers(peerChan)
go a.Serve()
var peerList []Peer
cnt := 0
var netClient = &http.Client{
Timeout: time.Second * 10,
}
for {
select {
case peer := <-peerChan:
peerList = append(peerList, peer)
break
case <-time.Tick(time.Second * 3):
if cnt%3 == 0 {
log.Info("POSTING")
msgs := s.GetAllMessages(id)
enc, _ := json.Marshal(msgs)
_, err := netClient.Post("http://52.116.40.230:8000/update", "application/json", bytes.NewReader(enc))
if err != nil {
log.Info("No internet")
}
}
cnt++
log.Info("SYNCING")
var npl []Peer
for _, p := range peerList {
if p.UUID == id.String() {
continue
}
oneCon := false
for _, addr := range p.IPS {
curString := addr.String()
log.Debug(curString)
resp, err := netClient.Get("http://" + curString + ":" + strconv.Itoa(p.Port) + "/messages")
if err != nil {
log.Error("Could not connect to peer", curString)
log.Error(err)
} else {
defer resp.Body.Close()
oneCon = true
if resp.StatusCode == http.StatusOK {
bodyBytes, err := ioutil.ReadAll(resp.Body)
if err != nil {
log.Fatal(err)
}
var encMessages []EncryptedMessage
json.Unmarshal(bodyBytes, &encMessages)
myMessages := s.GetAllMessages(id)
var totMessages []EncryptedMessage
for _, msg := range encMessages {
found := false
for _, msg2 := range myMessages {
if string(msg.Body) == string(msg2.Body) {
found = true
break
}
}
if !found {
totMessages = append(totMessages, msg)
}
}
if len(totMessages) == 0 {
continue
}
fmt.Println("Got ", len(totMessages), " New Messages")
s.SaveMessages(totMessages)
}
}
}
if oneCon {
npl = append(npl, p)
}
}
peerList = npl
}
}
}