-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhound.go
More file actions
187 lines (158 loc) · 4.18 KB
/
hound.go
File metadata and controls
187 lines (158 loc) · 4.18 KB
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
package main
import (
"crypto/rand"
"encoding/json"
"flag"
"fmt"
"io/ioutil"
"log"
"net/http"
"os"
"path/filepath"
"strings"
"github.com/casimir/xdg-go"
"github.com/soundhound/houndify-sdk-go/houndify"
"github.com/spf13/viper"
)
const (
appName = "houndify-cli"
houndifyClientId = "***REMOVED***"
houndifyClientKey = "***REMOVED***"
ipstackApiAccessKey = "***REMOVED***"
ipstackApiUrl = "http://api.ipstack.com"
ipifyApiUrl = "https://api.ipify.org?format=json"
unitsMetric = "metric"
unitsImperial = "imperial"
)
// Creates a pseudo unique / random string.
func randString() string {
n := 10
b := make([]byte, n)
rand.Read(b)
return fmt.Sprintf("%X", b)
}
// Creates a valid user ID.
func userId() string {
userId := os.Getenv("USER")
if len(userId) == 0 {
userId = "hound-" + randString()
}
return userId
}
func readConfig() *viper.Viper {
// Ensure config file exists to pacify Viper
xdgApp := xdg.App{Name: appName}
configFile := xdgApp.ConfigPath(appName + ".yaml")
if _, err := os.Stat(configFile); os.IsNotExist(err) {
configFileDir := filepath.Dir(configFile)
if err := os.MkdirAll(configFileDir, 0755); err != nil {
panic(err)
}
if f, err := os.Create(configFile); err != nil {
panic(err)
} else {
defer f.Close()
}
}
// Load configuration
v := viper.New()
v.SetConfigName(appName)
v.AddConfigPath(xdgApp.ConfigPath("")) // path to look for the config file in
v.SetConfigType("yaml")
v.SetDefault("User", userId())
v.SetDefault("Units", unitsMetric)
err := v.ReadInConfig() // Find and read the config file
if err != nil {
panic(fmt.Errorf("Fatal error config file: %s \n", err))
}
return v
}
func unitsToHoundify(units string) string {
switch units {
case "imperial":
return "US"
default:
return "METRIC"
}
}
func httpGet(url string) []byte {
resp, err := http.Get(url)
if err != nil {
panic(err)
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
panic(err)
}
return body
}
type ExternalIp struct {
IP string
}
type Location struct {
Latitude float32
Longitude float32
Country_Name string
}
func location() Location {
// External IP first
var externalIP ExternalIp
json.Unmarshal(httpGet(ipifyApiUrl), &externalIP)
// Geolocaiton next
body := httpGet(ipstackApiUrl + "/" + externalIP.IP + "?access_key=" + ipstackApiAccessKey)
var location Location
json.Unmarshal(body, &location)
return location
}
func main() {
log.SetFlags(0)
unitSystems := map[string]bool{unitsMetric: true, unitsImperial: true}
// Command line arguments
flagVerbose := flag.Bool("v", false, "Verbose mode")
flagUnits := flag.String("units", "", "Unit system, '"+unitsMetric+"' or '"+unitsImperial+"'")
flag.Parse()
// Configuration
config := readConfig()
if *flagUnits != "" {
if _, ok := unitSystems[*flagUnits]; ok != true {
panic(*flagUnits + " not supported")
}
config.Set("Units", *flagUnits)
}
// Houndify
houndifyClient := houndify.Client{
ClientID: houndifyClientId,
ClientKey: houndifyClientKey,
Verbose: *flagVerbose,
}
houndifyClient.EnableConversationState()
//TODO: houndifyClient.SetConversationState()
query := strings.Join(flag.Args(), " ")
if len(query) == 0 {
query = "what can you do?"
}
location := location()
requestInfoFields := make(map[string]interface{})
requestInfoFields["UnitPreference"] = unitsToHoundify(config.GetString("Units"))
requestInfoFields["Latitude"] = location.Latitude
requestInfoFields["Longitude"] = location.Longitude
requestInfoFields["Country"] = location.Country_Name
req := houndify.TextRequest{
Query: query,
UserID: config.GetString("User"),
RequestID: randString(),
RequestInfoFields: requestInfoFields,
}
serverResponse, err := houndifyClient.TextSearch(req)
if err != nil {
log.Fatalf("Unable to talk to houndify: %v\n%s\n", err, serverResponse)
}
writtenResponse, err := houndify.ParseWrittenResponse(serverResponse)
if err != nil {
log.Fatalf("Failed to understand houndify's response:\n%s\n", serverResponse)
}
fmt.Println(writtenResponse)
//TODO: config.Set("State", houndifyClient.GetConversationState())
config.WriteConfig()
}