-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
316 lines (284 loc) · 7.95 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
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
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
package main
/*
#include <stdlib.h>
*/
import "C"
import (
b64 "encoding/base64"
"encoding/json"
"flag"
"fmt"
"html/template"
"io/ioutil"
"log"
"net/http"
"net/url"
"os"
"os/exec"
"strconv"
"strings"
com "./commands"
)
//var serverDirectory string
var serverPort int
var serverHost string
var tmpl = template.Must(template.New("tmpl").ParseFiles("./static/index.html"))
var history string
var HistoryCounter int = 1
var SpotifyClientID = "f137e890f3734bd38fdcf1d980158139"
var SpotifyClientSecrt = "119bb13ee90043919bb53c48baf17fa9"
var AccessToken = ""
var UsersConnected []user_struct
func main() {
flag.StringVar(&serverHost, "host", "0.0.0.0", "Server Host")
flag.IntVar(&serverPort, "port", 3000, "Server Port")
//flag.StringVar(&serverDirectory, "dir", "index.html", "Server start file")
flag.Parse()
//define endpoints
//http.HandleFunc("/", handler)
fs := http.FileServer(http.Dir("static"))
http.Handle("/", fs)
http.HandleFunc("/command", commandhandler)
http.HandleFunc("/response", responseHandler)
http.HandleFunc("/oauth", oauthTokenHandler)
http.HandleFunc("/users", usersHandler)
//Listen and serve connections
fmt.Println("Server Running...")
http.ListenAndServe(fmt.Sprintf("%s:%d", serverHost, serverPort), nil)
}
func runSphinx() string {
out, err := exec.Command("./psphinx").Output()
if err != nil {
log.Printf("%s\n", err)
}
check := string(out)
log.Printf("Command: %s", check)
return check
}
func commandhandler(res http.ResponseWriter, req *http.Request) {
testString := runSphinx()
var commands = []string{
"get me the weather\n",
"events near me\n",
"send email\n",
"set alarm\n",
"play music\n",
//"who is connected\n",
//"where is\n",
"turn on light\n",
"turn off light\n",
"list commands\n",
}
//add string from user to a history buffer
history = history + fmt.Sprintf("%d. %s\n", HistoryCounter, testString)
HistoryCounter += 1
flag := 0
//if string is equal to command
for i := 0; i < len(commands); i++ {
if strings.Compare(testString, commands[i]) == 0 {
log.Println(commands[i])
flag = 1
if i == 0 {
log.Println("What city?")
fmt.Fprintln(res, "weather; Please input the city")
} else if i == 1 {
flag = 1
log.Println("What city?")
fmt.Fprintln(res, "event; Please input the city")
} else if i == 2 {
flag = 1
log.Println("Type Email Address")
fmt.Fprintln(res, "email; Please type Email Address")
/*} else if i == 3 {
flag = 1
log.Println("What word would you like to search?")
fmt.Fprintln(res, "define; What word would you like to search?")*/
} else if i == 3 {
flag = 1
log.Println("Alarm; Enter Alarm Time in minutes (MAX 59)")
fmt.Fprintln(res, ("alarm; Enter Alarm Time in minutes (MAX 59)"))
} else if i == 4 {
flag = 1
log.Println(com.PlayMusic(AccessToken))
fmt.Fprintln(res, com.PlayMusic(AccessToken))
/*} else if i == 5 {
flag = 1
log.Println(PrintConnected(UsersConnected))
fmt.Fprintln(res, PrintConnected(UsersConnected))*/
} else if i == 5 {
flag = 1
log.Println("Turn on lights")
fmt.Fprintln(res, "lights; Turning on lights")
} else if i == 6 {
flag = 1
log.Println("Turn off lights")
fmt.Fprintln(res, "lights; Turning off lights")
} else if i == 7 {
flag = 1
log.Println((commands))
i := 0
fmt.Fprintln(res, "commands; List Commands;")
for i < len(commands) {
fmt.Fprintln(res, (commands[i]))
i++
}
}
}
}
if flag == 0 {
log.Println("Command not found.")
fmt.Fprintln(res, "Command not found. Please Try Again.")
}
}
func responseHandler(res http.ResponseWriter, req *http.Request) {
sp := req.FormValue("value")
speech, err := strconv.Atoi(sp)
if err == nil {
speech = speech
}
duty := req.FormValue("duty")
var whom = "test@gmail.com"
var answer = "a"
if duty != "email" {
answer = req.FormValue("value")
answer = strings.TrimSuffix(answer, "\n")
} else {
whom = req.FormValue("email")
}
who := string([]byte(whom))
if duty == "weather" {
log.Println(com.GetWeather(answer))
fmt.Fprintln(res, com.GetWeather(answer))
} else if duty == "event" {
log.Println(com.GetEvents(answer))
fmt.Fprintln(res, com.GetEvents(answer))
} else if duty == "email" {
message := "HELLO This is from kift"
value := com.SendEmail(message, who)
log.Println(value)
fmt.Fprintln(res, value)
} else if duty == "define" {
log.Println(com.SearchTerm(answer))
fmt.Fprintln(res, com.SearchTerm(answer))
}
}
func handler(res http.ResponseWriter, req *http.Request) {
path := req.URL.Path[1:]
log.Println(path)
data, err := ioutil.ReadFile(string(path))
userIP := req.RemoteAddr
log.Println(userIP)
if err == nil {
var contentType string
if strings.HasSuffix(path, ".css") {
contentType = "text/css"
} else if strings.HasSuffix(path, ".html") {
contentType = "text/html"
} else if strings.HasSuffix(path, ".js") {
contentType = "application/javascript"
} else if strings.HasSuffix(path, ".png") {
contentType = "image/png"
} else if strings.HasSuffix(path, ".svg") {
contentType = "image/svg+xml"
} else {
contentType = "text/plain"
}
res.Header().Add("Content Type", contentType)
res.Write(data)
}
http.ServeFile(res, req, fmt.Sprintf("%s", "index.html"))
}
func oauthTokenHandler(w http.ResponseWriter, r *http.Request) {
//grab the code which is used to grab auth token
code := r.URL.Query().Get("code")
//Create form
form := url.Values{}
form.Add("code", code)
form.Add("grant_type", "authorization_code")
form.Add("redirect_uri", "http://localhost:3000/oauth")
// Construct post request
req, err := http.NewRequest("POST", "https://accounts.spotify.com/api/token", strings.NewReader(form.Encode()))
if err != nil {
log.Print(err)
os.Exit(1)
}
req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
encoded := fmt.Sprintf("Basic %s", b64.StdEncoding.EncodeToString([]byte(fmt.Sprintf("%s:%s", SpotifyClientID, SpotifyClientSecrt))))
req.Header.Set("Authorization", encoded)
//Using Token grab auth token
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
log.Print(err)
os.Exit(1)
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
log.Fatal(err)
os.Exit(1)
}
type AccessResp struct {
AccessToken string `json:"access_token"`
TokenType string `json:"token_type"`
ExpiresIn int `json:"expires_in"`
RefreshToken string `json:"refresh_token"`
Scope string `json:"scope"`
}
var m AccessResp
err = json.Unmarshal(body, &m)
// Save accessToken for later use
AccessToken = m.AccessToken
fmt.Println(AccessToken)
http.Redirect(w, r, "/", http.StatusSeeOther)
}
type OAuthAccessResponse struct {
AccessToken string `json:"access_token"`
}
type user_struct struct {
Username string
Location string
}
func usersHandler(w http.ResponseWriter, r *http.Request) {
switch r.Method {
case "POST":
body, err := ioutil.ReadAll(r.Body)
if err != nil {
panic(err)
}
log.Println(string(body))
var t user_struct
err = json.Unmarshal(body, &t)
if err != nil {
panic(err)
}
log.Println("HERE ", t.Location)
//ADD THE struct to UsersConnected ARRAY
UsersConnected = append(UsersConnected, t)
PrintSlice(UsersConnected)
default:
fmt.Fprintf(w, "Only Post request method is supported")
}
fmt.Fprintf(w, "Welcome to the users!")
fmt.Println("Endpoint Hit: users")
}
func PrintSlice(s []user_struct) {
fmt.Printf("len=%d cap=%d %+v\n", len(s), cap(s), s)
}
func findLocation(username string) string {
var location = "Location; No user found"
for i := 0; i < len(UsersConnected); i++ {
if UsersConnected[i].Username == username {
location = fmt.Sprintf("Location; Location is %s\n", UsersConnected[i].Location)
}
}
return location
}
func PrintConnected(s []user_struct) string {
if len(s) == 0 {
return (fmt.Sprintf("%s\n", "Who: No Users Connected!"))
}
var who = fmt.Sprintf("%+v\n", s)
who = strings.Replace(who, ":", "=>", -1)
return fmt.Sprintf("Who; %s\n", who)
}