You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
63 lines
1.1 KiB
63 lines
1.1 KiB
4 years ago
|
package main
|
||
|
|
||
|
import (
|
||
|
"context"
|
||
|
"encoding/json"
|
||
|
"fmt"
|
||
|
|
||
|
"github.com/bogosj/tesla"
|
||
|
"golang.org/x/oauth2"
|
||
|
"samhofi.us/x/keybase/v2"
|
||
|
)
|
||
|
|
||
|
var (
|
||
|
k = keybase.NewKeybase()
|
||
|
)
|
||
|
|
||
|
func isAuthenticated() bool {
|
||
|
chann := fmt.Sprintf("%+v,tesla_bot", k.Username)
|
||
|
test, _ := k.KVGet(&chann, "teslabot", "authtok")
|
||
|
return test.EntryValue != ""
|
||
|
}
|
||
|
|
||
|
func getTeslaClient() *tesla.Client {
|
||
|
var t *oauth2.Token
|
||
|
if !isAuthenticated() {
|
||
|
return nil
|
||
|
}
|
||
|
|
||
|
chann := fmt.Sprintf("%+v,tesla_bot", k.Username)
|
||
|
test, _ := k.KVGet(&chann, "teslabot", "authtok")
|
||
|
err := json.Unmarshal([]byte(test.EntryValue), &t)
|
||
|
if err != nil {
|
||
|
return nil
|
||
|
}
|
||
|
c, err := tesla.NewClient(context.Background(), tesla.WithToken(t))
|
||
|
if err != nil {
|
||
|
return nil
|
||
|
}
|
||
|
return c
|
||
|
}
|
||
|
|
||
|
func getVehicle(name string) *tesla.Vehicle {
|
||
|
c := getTeslaClient()
|
||
|
if c == nil {
|
||
|
return nil
|
||
|
}
|
||
|
vehicles, err := c.Vehicles()
|
||
|
if err != nil {
|
||
|
return nil
|
||
|
}
|
||
|
v := vehicles[0]
|
||
|
if name != "" {
|
||
|
for _, test := range vehicles {
|
||
|
if name == test.Vin {
|
||
|
v = test
|
||
|
}
|
||
|
if name == test.DisplayName {
|
||
|
v = test
|
||
|
}
|
||
|
}
|
||
|
}
|
||
|
return v
|
||
|
}
|