Class: TeslaApi::Client

Inherits:
Object
  • Object
show all
Defined in:
lib/tesla_api/client.rb

Constant Summary collapse

BASE_URI =
'https://owner-api.teslamotors.com'
SSO_URI =
'https://auth.tesla.com'

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(email: nil, access_token: nil, access_token_expires_at: nil, refresh_token: nil, client_id: ENV['TESLA_CLIENT_ID'], client_secret: ENV['TESLA_CLIENT_SECRET'], retry_options: nil, base_uri: nil, sso_uri: nil, client_options: {}) ⇒ Client

Returns a new instance of Client.



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
# File 'lib/tesla_api/client.rb', line 8

def initialize(
    email: nil,
    access_token: nil,
    access_token_expires_at: nil,
    refresh_token: nil,
    client_id: ENV['TESLA_CLIENT_ID'],
    client_secret: ENV['TESLA_CLIENT_SECRET'],
    retry_options: nil,
    base_uri: nil,
    sso_uri: nil,
    client_options: {}
)
  @email = email
  @base_uri = base_uri || BASE_URI
  @sso_uri = sso_uri || SSO_URI

  @client_id = client_id
  @client_secret = client_secret

  @access_token = access_token
  @access_token_expires_at = access_token_expires_at
  @refresh_token = refresh_token

  @api = Faraday.new(
    @base_uri + '/api/1',
    {
      headers: { 'User-Agent' => "github.com/timdorr/tesla-api v:#{VERSION}" }
    }.merge(client_options)
  ) do |conn|
    conn.request :json
    conn.response :json
    conn.response :raise_error
    conn.request :retry, retry_options if retry_options # Must be registered after :raise_error
    conn.adapter Faraday.default_adapter
  end
end

Instance Attribute Details

#access_tokenObject (readonly)

Returns the value of attribute access_token.



3
4
5
# File 'lib/tesla_api/client.rb', line 3

def access_token
  @access_token
end

#access_token_expires_atObject (readonly)

Returns the value of attribute access_token_expires_at.



3
4
5
# File 'lib/tesla_api/client.rb', line 3

def access_token_expires_at
  @access_token_expires_at
end

#apiObject (readonly)

Returns the value of attribute api.



3
4
5
# File 'lib/tesla_api/client.rb', line 3

def api
  @api
end

#client_idObject (readonly)

Returns the value of attribute client_id.



3
4
5
# File 'lib/tesla_api/client.rb', line 3

def client_id
  @client_id
end

#client_secretObject (readonly)

Returns the value of attribute client_secret.



3
4
5
# File 'lib/tesla_api/client.rb', line 3

def client_secret
  @client_secret
end

#emailObject (readonly)

Returns the value of attribute email.



3
4
5
# File 'lib/tesla_api/client.rb', line 3

def email
  @email
end

#refresh_tokenObject (readonly)

Returns the value of attribute refresh_token.



3
4
5
# File 'lib/tesla_api/client.rb', line 3

def refresh_token
  @refresh_token
end

Instance Method Details

#expired?Boolean

Returns:

  • (Boolean)


144
145
146
147
# File 'lib/tesla_api/client.rb', line 144

def expired?
  return true if access_token_expires_at.nil?
  access_token_expires_at <= DateTime.now
end

#get(url) ⇒ Object



149
150
151
# File 'lib/tesla_api/client.rb', line 149

def get(url)
  api.get(url.sub(/^\//, ''), nil, { 'Authorization' => "Bearer #{access_token}" }).body
end

#login!(password) ⇒ Object



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
# File 'lib/tesla_api/client.rb', line 75

def login!(password)
  code_verifier = rand(36**86).to_s(36)
  code_challenge = Base64.urlsafe_encode64(Digest::SHA256.hexdigest(code_verifier))
  state = rand(36**20).to_s(36)

  response = Faraday.get(
    @sso_uri + '/oauth2/v3/authorize',
    {
      client_id: 'ownerapi',
      code_challenge: code_challenge,
      code_challenge_method: 'S256',
      redirect_uri: 'https://auth.tesla.com/void/callback',
      response_type: 'code',
      scope: 'openid email offline_access',
      state: state,
    }
  )

  cookie = response.headers['set-cookie'].split(' ').first
  parameters = Hash[response.body.scan(/type="hidden" name="(.*?)" value="(.*?)"/)]

  response = Faraday.post(
    @sso_uri + '/oauth2/v3/authorize?' + URI.encode_www_form({
      client_id: 'ownerapi',
      code_challenge: code_challenge,
      code_challenge_method: 'S256',
      redirect_uri: 'https://auth.tesla.com/void/callback',
      response_type: 'code',
      scope: 'openid email offline_access',
      state: state,
    }),
    URI.encode_www_form(parameters.merge(
      'identity' => email,
      'credential' => password
    )),
    'Cookie' => cookie
  )

  code = CGI.parse(URI(response.headers['location']).query)['code'].first

  response = @api.post(
    @sso_uri + '/oauth2/v3/token',
    {
      grant_type: 'authorization_code',
      client_id: 'ownerapi',
      code: code,
      code_verifier: code_verifier,
      redirect_uri: 'https://auth.tesla.com/void/callback'
    }
  ).body

  @refresh_token = response['refresh_token']

  response = api.post(
    @base_uri + '/oauth/token',
    {
      grant_type: 'urn:ietf:params:oauth:grant-type:jwt-bearer',
      client_id: client_id,
      client_secret: client_secret
    },
    'Authorization' => "Bearer #{response['access_token']}"
  ).body

  @access_token = response['access_token']
  @access_token_expires_at = Time.at(response['created_at'].to_f + response['expires_in'].to_f).to_datetime

  response
end

#post(url, body: nil) ⇒ Object



153
154
155
# File 'lib/tesla_api/client.rb', line 153

def post(url, body: nil)
  api.post(url.sub(/^\//, ''), body, { 'Authorization' => "Bearer #{access_token}" }).body
end

#refresh_access_tokenObject



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
# File 'lib/tesla_api/client.rb', line 45

def refresh_access_token
  response = @api.post(
    @sso_uri + '/oauth2/v3/token',
    {
      grant_type: 'refresh_token',
      client_id: 'ownerapi',
      client_secret: client_secret,
      refresh_token: refresh_token,
      scope: 'openid email offline_access'
    }
  ).body

  @refresh_token = response['refresh_token']

  response = api.post(
    @base_uri + '/oauth/token',
    {
      grant_type: 'urn:ietf:params:oauth:grant-type:jwt-bearer',
      client_id: client_id,
      client_secret: client_secret
    },
    'Authorization' => "Bearer #{response['access_token']}"
  ).body

  @access_token = response['access_token']
  @access_token_expires_at = Time.at(response['created_at'].to_f + response['expires_in'].to_f).to_datetime

  response
end

#vehicle(id) ⇒ Object



161
162
163
# File 'lib/tesla_api/client.rb', line 161

def vehicle(id)
  Vehicle.new(self, email, id, self.get("/vehicles/#{id}")['response'])
end

#vehiclesObject



157
158
159
# File 'lib/tesla_api/client.rb', line 157

def vehicles
  get('/vehicles')['response'].map { |v| Vehicle.new(self, email, v['id'], v) }
end