forked from worldveil/peerchat
/
chat.go
202 lines (167 loc) · 4.5 KB
/
chat.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
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
package main
import "fmt"
import "bufio"
import "os"
import "dht"
import "io/ioutil"
import "time"
import "github.com/pmylund/sortutil"
import "path/filepath"
func main() {
startChat()
//testsort()
}
type Thing struct {
Field1 int
Field2 int64
}
func testsort() {
slice := make([]Thing, 0)
for i := 0; i < 19; i++ {
thing := Thing{Field1: i, Field2: time.Now().Unix()}
slice = append(slice, thing)
//time.Sleep(1001 * time.Millisecond)
}
//print in order
sortutil.AscByField(slice, "Field1")
for i := 0; i < len(slice); i++ {
fmt.Printf("thing: %+v\n", slice[i])
}
}
func input(reader *bufio.Reader) string {
input, _ := reader.ReadString('\n')
input = input[:len(input)-1]
return input
}
func startChat() {
reader := bufio.NewReader(os.Stdin)
// load the Peerchat banner
content, err := ioutil.ReadFile("peerchat.txt")
if err != nil {
//Do something
}
fmt.Println(string(content))
// get username
fmt.Printf("Enter username: ")
username := input(reader)
fmt.Printf("Enter IP Address (xxx.xxx.xxx.xxx:yyyy): ")
address := input(reader)
// search for this user's history
files, _ := filepath.Glob("/tmp/*.gob")
userfile := ""
user := new(dht.User)
for _, file := range files {
if file == dht.UsernameToPath(username) {
userfile = file
}
}
// did we find the file?
if userfile != "" {
// we found this user, load from file
user = dht.Login(username, address)
} else {
// we did not find a matching user
fmt.Printf("\n[*] Looks like you haven't logged in on this computer before! Would you like to create a new network, or join an existing one?\n")
fmt.Printf("Join existing? Type (Y/N):")
join := input(reader)
if join == "Y" || join == "y" {
// join existing network, ask for boostrap IP
fmt.Printf("\n[*] To join an existing network, please enter an IP address/port of a friend (xxx.xxx.xxx.xxx:yyyy): ")
boostrapAddress := input(reader)
user = dht.RegisterAndLogin(username, address, boostrapAddress)
} else {
// creating a new network, simply create new user
// use bogus address and start with empty routing table
user = dht.RegisterAndLogin(username, address, "")
}
}
// we're now logged in with a user
fmt.Printf("Connecting to Peerchat")
time.Sleep(300 * time.Millisecond)
fmt.Printf(".")
time.Sleep(300 * time.Millisecond)
fmt.Printf(".")
time.Sleep(300 * time.Millisecond)
fmt.Printf(".\n")
// prompt them to chat
// fmt.Printf("Connected as user: %+v\n", user)
// update loop
go func() {
notifications := user.GetNotificationsChannel()
for {
<- notifications
paint(user)
}
}()
// input loop
peer := ""
for {
// State 1) get a user to chat with
if peer == "" {
fmt.Printf("User to chat with: ")
peer = input(reader)
fmt.Printf("Starting to talk to: %s\n", peer)
user.UpdateCurrentPeer(peer)
fmt.Printf("me> ")
// State 2) continue chatting
} else {
text := input(reader)
if text == "" {
// do nothing
fmt.Printf("%s> \n", peer)
paint(user)
} else if text[0] == 92 {
// switching users to chat with
peer = text[1:]
fmt.Printf("Swtiching to talk to: %v\n", peer)
user.UpdateCurrentPeer(peer)
fmt.Printf("me> ")
paint(user)
} else if text == "exit" {
// exit peerchat
fmt.Printf("Exiting Peerchat!\n")
user.Logoff()
break
} else {
// send the message!
user.SendMessage(user.Current, text)
paint(user)
}
}
}
}
func paint(user *dht.User) {
// clear space
for j := 1; j < 100; j++ {
fmt.Println("")
}
// new messages?
usersWithPendingMessages := make([]string, 0)
for peer, _ := range user.MessageHistory {
areNew, _ := user.AreNewMessagesFrom(peer)
if areNew {
usersWithPendingMessages = append(usersWithPendingMessages, peer)
}
}
// print users with pending messages
for _, peer := range usersWithPendingMessages {
fmt.Printf("New message(s) from `%s`!\n", peer)
}
fmt.Printf("\n\n========================================\n")
// are we current chatting?
if user.Current != "" {
fmt.Printf("Conversation with `%s`:\n\n", user.Current)
newMessages := user.AllMessagesFromUser(user.Current)
messages := make([]dht.SendMessageArgs, 0)
for _, msg := range newMessages {
messages = append(messages, *msg)
}
sortutil.AscByField(messages, "Timestamp")
for i := 0; i < len(messages); i++ {
msg := messages[i]
fmt.Printf("%s> %s\n", msg.FromUsername, msg.Content)
}
}
fmt.Printf("=========================================\n")
fmt.Printf("me> ")
}