forked from jsgoecke/tesla
-
Notifications
You must be signed in to change notification settings - Fork 0
/
client.go
163 lines (146 loc) · 3.84 KB
/
client.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
package tesla
import (
"bytes"
"encoding/json"
"errors"
"io/ioutil"
"net/http"
"time"
)
// Required authorization credentials for the Tesla API
type Auth struct {
GrantType string `json:"grant_type"`
ClientID string `json:"client_id"`
ClientSecret string `json:"client_secret"`
Email string `json:"email"`
Password string `json:"password"`
URL string
StreamingURL string
}
// The token and related elements returned after a successful auth
// by the Tesla API
type Token struct {
AccessToken string `json:"access_token"`
TokenType string `json:"token_type"`
ExpiresIn int `json:"expires_in"`
Expires int64
}
// Provides the client and associated elements for interacting with the
// Tesla API
type Client struct {
Auth *Auth
Token *Token
HTTP *http.Client
}
var (
AuthURL = "https://owner-api.teslamotors.com/oauth/token"
BaseURL = "https://owner-api.teslamotors.com/api/1"
ActiveClient *Client
)
// Generates a new client for the Tesla API
func NewClient(auth *Auth) (*Client, error) {
if auth.URL == "" {
auth.URL = BaseURL
}
if auth.StreamingURL == "" {
auth.StreamingURL = StreamingURL
}
client := &Client{
Auth: auth,
HTTP: &http.Client{},
}
token, err := client.authorize(auth)
if err != nil {
return nil, err
}
client.Token = token
ActiveClient = client
return client, nil
}
// NewClientWithToken Generates a new client for the Tesla API using an existing token
func NewClientWithToken(auth *Auth, token *Token) (*Client, error) {
if auth.URL == "" {
auth.URL = BaseURL
}
if auth.StreamingURL == "" {
auth.StreamingURL = StreamingURL
}
client := &Client{
Auth: auth,
HTTP: &http.Client{},
Token: token,
}
if client.TokenExpired() {
return nil, errors.New("supplied token is expired")
}
ActiveClient = client
return client, nil
}
// TokenExpired indicates whether an existing token is within an hour of expiration
func (c Client) TokenExpired() bool {
exp := time.Unix(c.Token.Expires, 0)
return time.Until(exp) < time.Duration(1*time.Hour)
}
// Authorizes against the Tesla API with the appropriate credentials
func (c Client) authorize(auth *Auth) (*Token, error) {
now := time.Now()
auth.GrantType = "password"
data, _ := json.Marshal(auth)
body, err := c.post(AuthURL, data)
if err != nil {
return nil, err
}
token := &Token{}
err = json.Unmarshal(body, token)
if err != nil {
return nil, err
}
token.Expires = now.Add(time.Second * time.Duration(token.ExpiresIn)).Unix()
return token, nil
}
// // Calls an HTTP DELETE
func (c Client) delete(url string) error {
req, _ := http.NewRequest("DELETE", url, nil)
_, err := c.processRequest(req)
return err
}
// Calls an HTTP GET
func (c Client) get(url string) ([]byte, error) {
req, _ := http.NewRequest("GET", url, nil)
return c.processRequest(req)
}
// Calls an HTTP POST with a JSON body
func (c Client) post(url string, body []byte) ([]byte, error) {
req, _ := http.NewRequest("POST", url, bytes.NewBuffer(body))
return c.processRequest(req)
}
// Calls an HTTP PUT
func (c Client) put(resource string, body []byte) ([]byte, error) {
req, _ := http.NewRequest("PUT", BaseURL+resource, bytes.NewBuffer(body))
return c.processRequest(req)
}
// Processes a HTTP POST/PUT request
func (c Client) processRequest(req *http.Request) ([]byte, error) {
c.setHeaders(req)
res, err := c.HTTP.Do(req)
if err != nil {
return nil, err
}
if res.StatusCode != 200 {
return nil, errors.New(res.Status)
}
defer res.Body.Close()
body, err := ioutil.ReadAll(res.Body)
if err != nil {
return nil, err
}
return body, nil
}
// Sets the required headers for calls to the Tesla API
func (c Client) setHeaders(req *http.Request) {
if c.Token != nil {
req.Header.Set("Authorization", "Bearer "+c.Token.AccessToken)
}
req.Header.Set("Accept", "application/json")
req.Header.Set("Content-Type", "application/json")
}