-
Notifications
You must be signed in to change notification settings - Fork 13
/
smartcar.py
365 lines (284 loc) · 12.2 KB
/
smartcar.py
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
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
import base64
import hmac
import hashlib
import os
import re
from typing import NamedTuple, List, Dict, Optional, Union
from warnings import warn
import smartcar.config as config
import smartcar.helpers as helpers
import smartcar.types as types
API_VERSION = "2.0"
def set_api_version(version: str) -> None:
"""
Update the version of Smartcar API you are using
Args:
version (str): the version of the api you want to use
"""
if re.match(r"\d+\.\d+", version):
global API_VERSION
API_VERSION = version
else:
raise ValueError(
rf"Version '{version}' must match regex '\d+\.\d+' . e.g. '2.0', '1.0'"
)
def get_api_version() -> str:
"""
Returns:
Version of API requests are currently being sent to.
NOTE: May not reflect the version of Smartcar API that instantiated smartcar.Vehicle's
are sending requests to.
"""
global API_VERSION
return API_VERSION
def get_user(access_token: str) -> types.User:
"""
Retrieve the userId associated with the access_token
Args:
access_token (str): Smartcar access token
Returns:
User: NamedTuple("User", [("id", str), ("meta", namedtuple)])
Raises:
SmartcarException
"""
url = f"{config.API_URL}/v{API_VERSION}/user"
headers = {"Authorization": f"Bearer {access_token}"}
response = helpers.requester("GET", url, headers=headers)
return types.select_named_tuple("user", response)
def get_vehicles(access_token: str, paging: dict = None) -> types.Vehicles:
"""
Get a list of the user's vehicle ids
Args:
access_token (str): A valid access token from a previously retrieved
access object
paging (dictionary, optional): Can include "limit" and "offset" keys:
limit (int, optional): The number of vehicle ids to return
offset (int, optional): The index to start the vehicle list at
Returns:
Vehicles: NamedTuple("Vehicles", [("vehicles", List[str]), ("paging", Paging), ("meta", namedtuple)])
Raises:
SmartcarException
"""
url = f"{config.API_URL}/v{API_VERSION}/vehicles"
headers = {"Authorization": f"Bearer {access_token}"}
params = paging if paging is not None else None
response = helpers.requester("GET", url, headers=headers, params=params)
return types.select_named_tuple("vehicles", response)
def get_compatibility(
vin: str, scope: List[str], country: str = "US", options: dict = None
) -> Union[types.CompatibilityV1, types.CompatibilityV2]:
"""
Verify if a vehicle (vin) is eligible to use Smartcar. Use to confirm whether
specific vehicle is compatible with the permissions provided.
A compatible vehicle is one that:
1. Has hardware required for internet connectivity
2. Belongs to the makes and models Smartcar is compatible with
3. Is compatible with the required permissions (scope) that your app is requesting
access to
Note: The `mode` and `test_mode_compatibility_level` options arguments are only valid for Smartcar API v1.0
and `test_mode` has been deprecated
Args:
vin (str)
scope (List[str]): List of scopes (permissions) -> to check if vehicle is compatible
country (str, optional)
options (dict): Can contain client_id, client_secret, and flags.
client_id (str, optional)
client_secret (str, optional)
version (str): Version of API you want to use
flags (dict - {str: bool}, optional): An optional list of feature flags
test_mode (bool, optional): Deprecated, please use `mode` instead.
Launch Smartcar Connect in [test mode](https://smartcar.com/docs/guides/testing/).
mode (str, optional): Determine what mode Smartcar Connect should be launched in.
Should be one of test, live or simulated.
test_mode_compatibility_level (str, optional): This parameter is required when the API is invoked in test mode.
Possible values with details are documented in our Integration Guide.
Returns:
CompatibilityV1: NamedTuple("Compatibility", [("compatible", bool), ("meta", namedtuple)])
OR
CompatibilityV2: NamedTuple("Compatibility",
[
("compatible", bool),
("reason", Union[str, None]),
("capabilities", List[dict]),
("meta", namedtuple),
],
)
"""
client_id = os.environ.get("SMARTCAR_CLIENT_ID")
client_secret = os.environ.get("SMARTCAR_CLIENT_SECRET")
api_version = API_VERSION
params = {"vin": vin, "scope": " ".join(scope), "country": country}
# Configuring options.
if options is None:
helpers.validate_env()
else:
# client_id and client_secret passed in options dict() will take precedence
# over environment variables.
client_id = options.get("client_id", client_id)
client_secret = options.get("client_secret", client_secret)
api_version = options.get("version", api_version)
if options.get("flags"):
flags_str = helpers.format_flag_query(options["flags"])
params["flags"] = flags_str
if options.get("version"):
api_version = options["version"]
if api_version == "1.0":
if options.get("test_mode") is not None:
warn(
'The "testMode" parameter is deprecated, please use the "mode" parameter instead.',
DeprecationWarning,
)
params["mode"] = "test" if options.get("test_mode") else "live"
elif options.get("mode"):
params["mode"] = options.get["mode"]
if options.get("test_mode_compatibility_level"):
params["test_mode_compatibility_level"] = options[
"test_mode_compatibility_level"
]
params["mode"] = "test"
if params.mode not in ["test", "live", "simulated"]:
raise Exception(
"The \"mode\" parameter MUST be one of the following: 'test', 'live', 'simulated'",
)
# Ensuring client_id and client_secret are present
if client_id is None or client_secret is None:
raise Exception(
"'get_compatibility' requires a client_id AND client_secret. "
"Either set these as environment variables, OR pass them in as part of the 'options'"
"dictionary. The recommended course of action is to set up environment variables"
"with your client credentials. i.e.: "
"'SMARTCAR_CLIENT_ID' and 'SMARTCAR_CLIENT_SECRET'"
)
url = f"{config.API_URL}/v{api_version}/compatibility"
# Configuring for compatibility endpoint
id_secret = f"{client_id}:{client_secret}"
encoded_id_secret = id_secret.encode("ascii")
base64_bytes = base64.b64encode(encoded_id_secret)
base64_id_secret = base64_bytes.decode("ascii")
headers = {"Authorization": f"Basic {base64_id_secret}"}
response = helpers.requester("GET", url, headers=headers, params=params)
if api_version == "1.0":
return types.select_named_tuple("compatibility_v1", response)
elif api_version == "2.0":
return types.select_named_tuple("compatibility_v2", response)
else:
raise Exception("Please use a valid API version (e.g. '1.0' or '2.0')")
# ===========================================
# Webhook functions
# ===========================================
def hash_challenge(amt: str, challenge: str) -> str:
"""
Take in a randomly generated challenge string, and use an
Application Management Token as a key to be hashed.
Args:
amt (str): Application Management Token from Smartcar Dashboard
challenge: Randomly generated string from smartcar after requesting
a challenge.
Returns:
hex-encoding of resulting hash
"""
h = hmac.new(amt.encode(), challenge.encode(), hashlib.sha256)
return h.hexdigest()
def verify_payload(amt: str, signature: str, body: str) -> bool:
"""
Verify webhook payload against AMT and signature
Args:
amt (str): Application Management Token from Smartcar Dashboard
signature: sc-signature header value
body: Stringified JSON of the webhook response body
Returns:
Boolean
"""
return hash_challenge(amt, body) == signature
# ===========================================
# Management
# ===========================================
def get_management_token(amt: str, username: str = "default") -> str:
secret = f"{username}:{amt}"
encoded_secret = secret.encode("ascii")
base64_bytes = base64.b64encode(encoded_secret)
return base64_bytes.decode("ascii")
def get_connections(
amt: str,
filter: Optional[Dict[str, str]] = None,
paging: Optional[Dict[str, Optional[int]]] = None,
) -> types.GetConnections:
"""
Returns a paged list of all the vehicles that are connected to the application
associated with the management API token used, sorted in descending order by connection date.
Args:
amt (str): Application Management Token from Smartcar Dashboard
filter (dict, optional):
vehicle_id (str, optional): If provided, filters connections to a specific vehicle.
user_id (str, optional): If provided, filters connections to a specific user.
paging (dict, optional):
limit (int, optional): The maximum number of connections to return.
cursor (str, optional): The cursor ID for pagination to retrieve the next set of results.
Returns:
GetConnections: A named tuple containing connections, paging information, and meta data.
"""
if filter is None:
filter = {}
if paging is None:
paging = {}
params = {}
if "user_id" in filter:
params["user_id"] = filter["user_id"]
if "vehicle_id" in filter:
params["vehicle_id"] = filter["vehicle_id"]
if "cursor" in paging:
params["cursor"] = paging["cursor"]
if "limit" in paging:
params["limit"] = paging["limit"]
url = f"{config.MANAGEMENT_API_URL}/v{get_api_version()}/management/connections/"
headers = {"Authorization": f"Basic {get_management_token(amt)}"}
response = helpers.requester("GET", url, headers=headers, params=params)
data = response.json()
connections = [
types.Connection(c.get("vehicleId"), c.get("userId"), c.get("connectedAt"))
for c in data["connections"]
]
response_paging = data.get("paging", {})
response_paging = types.PagingCursor(response_paging.get("cursor"))
return types.GetConnections(
connections,
response_paging,
types.build_meta(response.headers),
)
def delete_connections(amt: str, filter: dict = {}) -> types.DeleteConnections:
"""
Deletes all the connections by vehicle or user ID and returns a list
of all connections that were deleted.
Args:
amt (str): Application Management Token from Smartcar Dashboard
filter (dict, optional): Can contain EITHER vehicle_id OR user_id
vehicle_id (str, optional)
user_id (str, optional)
Returns:
DeleteConnections = NamedTuple("DeleteConnections", [
("connections", List[Connection]),
("meta", namedtuple)
],
)
"""
user_id = filter.get("user_id")
vehicle_id = filter.get("vehicle_id")
if user_id and vehicle_id:
raise Exception("Filter can contain EITHER user_id OR vehicle_id, not both")
params = {}
if user_id:
params["user_id"] = user_id
elif vehicle_id:
params["vehicle_id"] = vehicle_id
url = f"{config.MANAGEMENT_API_URL}/v{get_api_version()}/management/connections/"
headers = {"Authorization": f"Basic {get_management_token(amt)}"}
response = helpers.requester("DELETE", url, headers=headers, params=params)
data = response.json()
connections = [
types.Connection(c.get("vehicleId"), c.get("userId"), c.get("connectedAt"))
for c in data["connections"]
]
return types.DeleteConnections(
connections,
types.build_meta(response.headers),
)