googlewifi 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
googlewifi/__init__.py ADDED
@@ -0,0 +1,734 @@
1
+ import asyncio
2
+ import time
3
+ import aiohttp
4
+ import json
5
+ import datetime
6
+ import dateutil.parser
7
+ import grpc
8
+ import gpsoauth
9
+
10
+ from ghome_foyer_api.api_pb2 import GetHomeGraphRequest
11
+ from ghome_foyer_api.api_pb2_grpc import StructuresServiceStub
12
+
13
+ GH_HEADERS = {"Content-Type": "application/json"}
14
+
15
+ OAUTH_SERVICE = (
16
+ "oauth2:https://www.googleapis.com/auth/accesspoints "
17
+ "https://www.googleapis.com/auth/clouddevices"
18
+ )
19
+ GOOGLE_HOME_APP = "com.google.android.apps.chromecast.app"
20
+ GOOGLE_HOME_CLIENT_SIG = "24bb24c05e47e0aefa68a58a766179d9b613a600"
21
+ TOKEN_REFRESH_MARGIN = 300
22
+ GPSOAUTH_TIMEOUT = 30
23
+
24
+
25
+ class GoogleWifi:
26
+
27
+ def __init__(self, email:str, master_token:str, android_id:str, session:aiohttp.ClientSession = None):
28
+ """Initialize the Google Wifi API with a Google account credential set.
29
+
30
+ email: Google account email address.
31
+ master_token: aas_et/... or oauth2rt_1/... master token obtained via exchange_oauth_token().
32
+ android_id: android id used when the master token was minted.
33
+ """
34
+
35
+ if session:
36
+ self._session = session
37
+ else:
38
+ self._session = aiohttp.ClientSession()
39
+
40
+ self._email = email
41
+ self._master_token = master_token
42
+ self._android_id = android_id
43
+ self._api_token = None
44
+ self._api_token_expiry = 0
45
+ self._systems = None
46
+ self._access_points = {}
47
+
48
+ @staticmethod
49
+ async def exchange_oauth_token(email:str, oauth_token:str, android_id:str):
50
+ """Exchange an EmbeddedSetup oauth_token (oauth2_4/...) for a master token."""
51
+ def _exchange():
52
+ return gpsoauth.exchange_token(email, oauth_token, android_id)
53
+
54
+ try:
55
+ response = await asyncio.wait_for(asyncio.to_thread(_exchange), GPSOAUTH_TIMEOUT)
56
+ except asyncio.TimeoutError as error:
57
+ raise ConnectionError(f"Timed out contacting Google authentication: {error}") from error
58
+ except Exception as error:
59
+ raise GoogleWifiAuthError(f"Could not exchange oauth_token: {error}") from error
60
+
61
+ if not isinstance(response, dict):
62
+ raise GoogleWifiAuthError("Malformed response from Google authentication")
63
+
64
+ master_token = response.get("Token")
65
+ if not master_token:
66
+ error = response.get("Error") or response.get("error") or "unknown error"
67
+ raise GoogleWifiAuthError(f"Google did not return a master token: {error}")
68
+
69
+ return master_token
70
+
71
+ async def post_api(
72
+ self,
73
+ url:str,
74
+ headers:str=None,
75
+ payload:str=None,
76
+ params:str=None,
77
+ json_payload=None,
78
+ _retry:bool=True,
79
+ ):
80
+ """Post to the Google APIs."""
81
+ async with self._session.post(
82
+ url,
83
+ headers=headers,
84
+ data=payload,
85
+ params=params,
86
+ json=json_payload,
87
+ timeout=30,
88
+ ) as resp:
89
+ if resp.status == 401 and _retry:
90
+ await self._refresh_token_once(headers)
91
+ return await self.post_api(url, headers, payload, params, json_payload, False)
92
+ self._check_status(resp.status)
93
+ try:
94
+ response = await resp.text()
95
+ except aiohttp.ClientConnectorError as error:
96
+ raise ConnectionError(error)
97
+
98
+ if response:
99
+ try:
100
+ response = json.loads(response)
101
+ except json.JSONDecodeError as error:
102
+ raise ValueError(error)
103
+
104
+ return response
105
+
106
+ async def get_api(self, url:str, headers:str=None, payload:str=None, params:str=None, _retry:bool=True):
107
+ """Get call to Google APIs."""
108
+ try:
109
+ async with self._session.get(
110
+ url,
111
+ headers=headers,
112
+ data=payload,
113
+ params=params,
114
+ timeout=30,
115
+ ) as resp:
116
+ if resp.status == 401 and _retry:
117
+ await self._refresh_token_once(headers)
118
+ return await self.get_api(url, headers, payload, params, False)
119
+ self._check_status(resp.status)
120
+ try:
121
+ response = await resp.text()
122
+ except aiohttp.ClientError as error:
123
+ raise ConnectionError(error)
124
+ except asyncio.TimeoutError as error:
125
+ raise GoogleHomeIgnoreDevice(error)
126
+
127
+ if response:
128
+ try:
129
+ response = json.loads(response)
130
+ except json.JSONDecodeError as error:
131
+ raise ValueError(error)
132
+
133
+ return response
134
+
135
+ async def put_api(self, url:str, headers:str=None, payload:str=None, params:str=None, _retry:bool=True):
136
+ """Put call to Google APIs."""
137
+ async with self._session.put(
138
+ url,
139
+ headers=headers,
140
+ data=payload,
141
+ params=params,
142
+ timeout=30,
143
+ ) as resp:
144
+ if resp.status == 401 and _retry:
145
+ await self._refresh_token_once(headers)
146
+ return await self.put_api(url, headers, payload, params, False)
147
+ self._check_status(resp.status)
148
+ try:
149
+ response = await resp.text()
150
+ except aiohttp.ClientError as error:
151
+ raise ConnectionError(error)
152
+
153
+ if response:
154
+ try:
155
+ response = json.loads(response)
156
+ except json.JSONDecodeError as error:
157
+ raise ValueError(error)
158
+
159
+ return response
160
+
161
+ async def delete_api(self, url:str, headers:str=None, payload:str=None, params:str=None, _retry:bool=True):
162
+ """Delete call to Google APIs."""
163
+ async with self._session.delete(
164
+ url,
165
+ headers=headers,
166
+ data=payload,
167
+ params=params,
168
+ timeout=30,
169
+ ) as resp:
170
+ if resp.status == 401 and _retry:
171
+ await self._refresh_token_once(headers)
172
+ return await self.delete_api(url, headers, payload, params, False)
173
+ self._check_status(resp.status)
174
+ try:
175
+ response = await resp.text()
176
+ except aiohttp.ClientError as error:
177
+ raise ConnectionError(error)
178
+
179
+ if response:
180
+ try:
181
+ response = json.loads(response)
182
+ except json.JSONDecodeError as error:
183
+ raise ValueError(error)
184
+
185
+ return response
186
+
187
+ @staticmethod
188
+ def _check_status(status:int):
189
+ """Raise on error responses, re-mintable auth errors included."""
190
+ if status == 401 or status == 403:
191
+ raise GoogleWifiAuthError(f"Foyer authorization failed (HTTP {status})")
192
+ if status >= 400:
193
+ raise GoogleWifiException(f"Foyer API returned HTTP {status}")
194
+
195
+ async def get_api_token(self, force_refresh:bool=False):
196
+ """Mint or refresh the scoped API token via Google Play Services OAuth."""
197
+
198
+ if (
199
+ not force_refresh
200
+ and self._api_token
201
+ and self._api_token_expiry - TOKEN_REFRESH_MARGIN > time.time()
202
+ ):
203
+ return True
204
+
205
+ def _oauth():
206
+ return gpsoauth.perform_oauth(
207
+ self._email,
208
+ self._master_token,
209
+ self._android_id,
210
+ service=OAUTH_SERVICE,
211
+ app=GOOGLE_HOME_APP,
212
+ client_sig=GOOGLE_HOME_CLIENT_SIG,
213
+ )
214
+
215
+ try:
216
+ response = await asyncio.wait_for(asyncio.to_thread(_oauth), GPSOAUTH_TIMEOUT)
217
+ except asyncio.TimeoutError as error:
218
+ raise ConnectionError(f"Timed out contacting Google authentication: {error}") from error
219
+ except Exception as error:
220
+ raise ConnectionError(f"Google authentication token request failed: {error}") from error
221
+
222
+ if not isinstance(response, dict):
223
+ raise ConnectionError("Malformed response from Google authentication")
224
+
225
+ error = response.get("Error") or response.get("error")
226
+ if isinstance(error, str) and error.casefold() == "badauthentication":
227
+ raise GoogleWifiAuthError("Google rejected the stored master token")
228
+
229
+ token = response.get("Auth")
230
+ if not token:
231
+ raise GoogleWifiAuthError(
232
+ f"Google did not return an access token: {error or 'unknown error'}"
233
+ )
234
+
235
+ try:
236
+ lifetime = int(response.get("ExpiresInDurationSec", 3600))
237
+ except (TypeError, ValueError):
238
+ lifetime = 3600
239
+
240
+ self._api_token = token
241
+ self._api_token_expiry = time.time() + max(lifetime, 0)
242
+
243
+ return True
244
+
245
+ async def _refresh_token_once(self, headers):
246
+ """Force a token re-mint and update the Authorization header in place."""
247
+ await self.get_api_token(force_refresh=True)
248
+ if isinstance(headers, dict):
249
+ headers["Authorization"] = f"Bearer {self._api_token}"
250
+
251
+ async def connect(self):
252
+ """Authenticate to the Google Wifi services."""
253
+ await self.get_api_token()
254
+ return bool(self._api_token)
255
+
256
+ async def get_systems(self):
257
+ """Get the systems on this account."""
258
+ if await self.connect():
259
+ url = "https://googlehomefoyer-pa.googleapis.com/v2/groups?prettyPrint=false"
260
+ headers = {
261
+ "Authorization": f"Bearer {self._api_token}",
262
+ "Content-Type": "application/json; charset=utf-8"
263
+ }
264
+ payload = {}
265
+
266
+ response = await self.get_api(url, headers, payload)
267
+
268
+ if response.get("groups"):
269
+ return await self.structure_systems(response)
270
+ else:
271
+ raise GoogleWifiException("Failed to retreive Google Wifi Data.")
272
+
273
+ async def get_devices(self, system_id):
274
+ """Retrieve the devices list for a given system."""
275
+
276
+ if await self.connect():
277
+ url = f"https://googlehomefoyer-pa.googleapis.com/v2/groups/{system_id}/stations?prettyPrint=false"
278
+ headers = {
279
+ "Content-Type": "application/json; charset=utf-8",
280
+ "Authorization": f"Bearer {self._api_token}"
281
+ }
282
+ payload = {}
283
+
284
+ response = await self.get_api(url, headers, payload)
285
+
286
+ return(response)
287
+
288
+ async def get_status(self, system_id):
289
+ """Retrieve the status payload for a system."""
290
+
291
+ if await self.connect():
292
+ url=f"https://googlehomefoyer-pa.googleapis.com/v2/groups/{system_id}/status?prettyPrint=false"
293
+ headers = {
294
+ "Content-Type": "application/json; charset=utf-8",
295
+ "Authorization": f"Bearer {self._api_token}"
296
+ }
297
+ payload = {}
298
+
299
+ response = await self.get_api(url, headers, payload)
300
+
301
+ return(response)
302
+
303
+ async def structure_systems(self, system_data):
304
+ """Structure the data with ids in dict."""
305
+ systems = {}
306
+
307
+ for this_system in system_data["groups"]:
308
+ systems[this_system["id"]] = this_system
309
+
310
+ system_status = await self.get_status(this_system["id"])
311
+ system_metrics = await self.get_realtime_metrics(this_system["id"])
312
+
313
+ try:
314
+ systems[this_system["id"]]["status"] = system_status["wanConnectionStatus"]
315
+ systems[this_system["id"]]["groupTraffic"] = system_metrics.get("groupTraffic",None)
316
+ except KeyError as error:
317
+ raise GoogleWifiException(error)
318
+
319
+ blocking_policies = {}
320
+ family_hub_settings = this_system["groupSettings"].get("familyHubSettings") or {}
321
+ if family_hub_settings.get("stationPolicies"):
322
+ for blocking_policy in family_hub_settings["stationPolicies"]:
323
+ blocking_policies[blocking_policy["stationId"]] = blocking_policy
324
+
325
+ this_status = {}
326
+ for this_ap in system_status["apStatuses"]:
327
+ this_status[this_ap["apId"]] = this_ap
328
+
329
+ system_status["status"] = this_status
330
+
331
+ access_points = {}
332
+
333
+ try:
334
+ for this_ap in this_system["accessPoints"]:
335
+ access_points[this_ap["id"]] = this_ap
336
+ access_points[this_ap["id"]]["status"] = system_status["status"][this_ap["id"]]["apState"]
337
+ except KeyError as error:
338
+ raise GoogleWifiException(error)
339
+
340
+ systems[this_system["id"]]["access_points"] = access_points
341
+
342
+ devices_list = await self.get_devices(this_system["id"])
343
+
344
+ devices = {}
345
+ station_ids = []
346
+
347
+ try:
348
+ for this_device in devices_list["stations"]:
349
+ devices[this_device["id"]] = this_device
350
+ station_ids.append(this_device["id"])
351
+ device_paused = False
352
+
353
+ if blocking_policies.get(this_device["id"]):
354
+ expire_date = dateutil.parser.parse(blocking_policies[this_device["id"]]["blockingPolicy"]["expiryTimestamp"])
355
+
356
+ if expire_date > datetime.datetime.now(datetime.timezone.utc) or expire_date.timestamp() == 0:
357
+ device_paused = True
358
+
359
+ devices[this_device["id"]]["paused"] = device_paused
360
+ except KeyError as error:
361
+ raise GoogleWifiException(error)
362
+
363
+ sensitive_info = await self.get_sensitive_info(system_id=this_system["id"], station_ids=station_ids)
364
+ for this_station in sensitive_info:
365
+ if this_station["stationId"] in devices:
366
+ devices[this_station["stationId"]]["macAddress"] = this_station.get("macAddress",{})
367
+
368
+ if system_metrics.get("stationMetrics"):
369
+ for this_station in system_metrics.get("stationMetrics"):
370
+ if this_station["station"]["id"] in devices:
371
+ devices[this_station["station"]["id"]]["traffic"] = this_station.get("traffic",{})
372
+
373
+ systems[this_system["id"]]["devices"] = devices
374
+
375
+ return systems
376
+
377
+ async def pause_device(self, system_id:str, device_id:str, pause_state:bool):
378
+ """Pause or unpause a specific device"""
379
+
380
+ if await self.connect():
381
+ url = f"https://googlehomefoyer-pa.googleapis.com/v2/groups/{system_id}/stationBlocking?prettyPrint=false"
382
+ headers = {
383
+ "Content-Type": "application/json; charset=utf-8",
384
+ "Authorization": f"Bearer {self._api_token}"
385
+ }
386
+
387
+ payload = {
388
+ "blocked": str(pause_state).lower(),
389
+ "stationId": device_id
390
+ }
391
+ payload = json.dumps(payload)
392
+
393
+ response = await self.put_api(url, headers, payload)
394
+
395
+ return response.get("operation").get("operationState") == "CREATED"
396
+
397
+ else:
398
+ return False
399
+
400
+ async def prioritize_device(self, system_id:str, device_id:str, duration_hours:int=1):
401
+ """Set priority device for specified time (default 1 hour)."""
402
+
403
+ if await self.connect():
404
+ duration_hours = 1 if duration_hours < 1 else duration_hours
405
+ duration_hours = 6 if duration_hours > 6 else duration_hours
406
+
407
+ url = f"https://googlehomefoyer-pa.googleapis.com/v2/groups/{system_id}/prioritizedStation?prettyPrint=false"
408
+ headers = {
409
+ "Content-Type": "application/json; charset=utf-8",
410
+ "Authorization": f"Bearer {self._api_token}"
411
+ }
412
+
413
+ end_time = datetime.datetime.now() + datetime.timedelta(hours=duration_hours)
414
+
415
+ end_time = end_time.astimezone().replace(microsecond=0).isoformat()
416
+
417
+ payload = {
418
+ "stationId": device_id,
419
+ "prioritizationEndTime": end_time
420
+ }
421
+
422
+ payload = json.dumps(payload)
423
+
424
+ response = await self.put_api(url, headers=headers, payload=payload)
425
+
426
+ return response.get("operation").get("operationState") == "CREATED"
427
+
428
+ else:
429
+ return False
430
+
431
+ async def clear_prioritization(self, system_id:str):
432
+ """Clear any device prioritization."""
433
+
434
+ if await self.connect():
435
+ url=f"https://googlehomefoyer-pa.googleapis.com/v2/groups/{system_id}/prioritizedStation?prettyPrint=false"
436
+
437
+ headers = {
438
+ "Content-Type": "application/json; charset=utf-8",
439
+ "Authorization": f"Bearer {self._api_token}"
440
+ }
441
+
442
+ payload = {}
443
+
444
+ response = await self.delete_api(url, headers=headers, payload=payload)
445
+
446
+ return response.get("operation").get("operationState") == "CREATED"
447
+
448
+ else:
449
+ return False
450
+
451
+ async def set_brightness(self, ap_id:str, brightness:int):
452
+ """Set Access Point Light Brightness."""
453
+
454
+ if await self.connect():
455
+ brightness = 0 if brightness < 0 else brightness
456
+ brightness = 100 if brightness > 100 else brightness
457
+
458
+ url = f"https://googlehomefoyer-pa.googleapis.com/v2/accesspoints/{ap_id}/lighting?prettyPrint=false"
459
+
460
+ headers = {
461
+ "Content-Type": "application/json; charset=utf-8",
462
+ "Authorization": f"Bearer {self._api_token}"
463
+ }
464
+
465
+ payload = {
466
+ "automatic": False,
467
+ "intensity": brightness
468
+ }
469
+
470
+ payload = json.dumps(payload)
471
+
472
+ response = await self.put_api(url, headers=headers, payload=payload)
473
+
474
+ return response.get("operation").get("operationState") == "CREATED"
475
+
476
+ else:
477
+ return False
478
+
479
+ async def restart_ap(self, ap_id:str):
480
+ """Restart a specific Access Point."""
481
+
482
+ if await self.connect():
483
+ url=f"https://googlehomefoyer-pa.googleapis.com/v2/accesspoints/{ap_id}/reboot?prettyPrint=false"
484
+
485
+ headers = {
486
+ "Content-Type": "application/json; charset=utf-8",
487
+ "Authorization": f"Bearer {self._api_token}"
488
+ }
489
+
490
+ payload = {}
491
+
492
+ response = await self.post_api(url, headers=headers, payload=payload)
493
+
494
+ return response.get("operation").get("operationState") == "CREATED"
495
+
496
+ else:
497
+ return False
498
+
499
+ async def restart_system(self, system_id:str):
500
+ """Restart the whole Google Wifi System."""
501
+
502
+ if await self.connect():
503
+ url = f"https://googlehomefoyer-pa.googleapis.com/v2/groups/{system_id}/reboot?prettyPrint=false"
504
+
505
+ headers = {
506
+ "Content-Type": "application/json; charset=utf-8",
507
+ "Authorization": f"Bearer {self._api_token}"
508
+ }
509
+
510
+ payload = {}
511
+
512
+ response = await self.post_api(url, headers=headers, payload=payload)
513
+
514
+ return response.get("operation").get("operationState") == "CREATED"
515
+
516
+ else:
517
+ return False
518
+
519
+ async def refresh_tokens(self):
520
+ """Refresh the Google Access tokens for local Google devices."""
521
+ if await self.connect():
522
+ creds = grpc.access_token_call_credentials(self._api_token)
523
+ ssl = grpc.ssl_channel_credentials()
524
+ composite = grpc.composite_channel_credentials(ssl, creds)
525
+ channel = grpc.secure_channel("googlehomefoyer-pa.googleapis.com:443", composite)
526
+ service = StructuresServiceStub(channel)
527
+ resp = service.GetHomeGraph(GetHomeGraphRequest())
528
+ data = resp.home.devices
529
+
530
+ tokens = {}
531
+
532
+ for device in data:
533
+ # this is the 'cloud device id'
534
+ if device.local_auth_token != "":
535
+ tokens[
536
+ device.device_info.project_info.string2
537
+ ] = device.local_auth_token
538
+
539
+ return tokens
540
+
541
+ async def update_info(self, host):
542
+ """Update data from Google Home."""
543
+
544
+ if await self.connect():
545
+ url = f"https://{host}:8443/setup/eureka_info"
546
+ params = {
547
+ "params":"version,audio,name,build_info,detail,device_info,net,wifi,setup,settings,opt_in,opencast,multizone,proxy,night_mode_params,user_eq,room_equalizer",
548
+ "options":"detail"
549
+ }
550
+
551
+ response = await self.get_api(url=url,params=params)
552
+
553
+ if response:
554
+ return response
555
+ else:
556
+ raise GoogleHomeUpdateFailed()
557
+
558
+ async def get_bluetooth_status(self, host, token):
559
+ """Retrieve the current bluetooth status."""
560
+ if await self.connect():
561
+ url = f"https://{host}:8443/setup/bluetooth/status"
562
+ headers = {"cast-local-authorization-token": token}
563
+
564
+ response = await self.get_api(url=url,headers=headers)
565
+
566
+ return response
567
+
568
+ async def get_bluetooth_devices(self, host, token):
569
+ """Retrieve the current bluetooth clients from a Google Home."""
570
+
571
+ if await self.connect():
572
+ url = f"https://{host}:8443/setup/bluetooth/scan"
573
+ data = {"enable": True, "clear_results": True, "timeout": 5}
574
+ headers = GH_HEADERS
575
+ headers["Host"] = host
576
+ headers["cast-local-authorization-token"] = token
577
+
578
+ await self.post_api(url=url,headers=headers,json_payload=data)
579
+ await asyncio.sleep(5)
580
+
581
+ url = f"https://{host}:8443/setup/bluetooth/scan_results"
582
+
583
+ response = await self.get_api(url=url,headers=headers)
584
+
585
+ return response
586
+
587
+ async def create_wan_speedtest(self, system_id:str):
588
+ """Start a speed test operation on a system."""
589
+ if await self.connect():
590
+ url = f"https://googlehomefoyer-pa.googleapis.com/v2/groups/{system_id}/wanSpeedTest"
591
+ headers = {
592
+ "Content-Type": "application/json; charset=utf-8",
593
+ "Authorization": f"Bearer {self._api_token}"
594
+ }
595
+ payload = {}
596
+ params = (
597
+ ('prettyPrint', 'false'),
598
+ )
599
+
600
+ response = await self.post_api(url=url,headers=headers,payload=payload,params=params)
601
+ operation_id = response["operation"]["operationId"]
602
+
603
+ return operation_id
604
+
605
+ async def check_operation(self, operation_id: str):
606
+ """Check the status of a speed test operation."""
607
+ if await self.connect():
608
+ url = f"https://googlehomefoyer-pa.googleapis.com/v2/operations/{operation_id}"
609
+ headers = {
610
+ "Content-Type": "application/json; charset=utf-8",
611
+ "Authorization": f"Bearer {self._api_token}"
612
+ }
613
+ payload = {}
614
+ params = (
615
+ ('prettyPrint', 'false'),
616
+ )
617
+
618
+ return await self.get_api(url=url,headers=headers,payload=payload,params=params)
619
+
620
+ async def speed_test_results(self, system_id:str):
621
+ """Retrieve the speed test results."""
622
+ if await self.connect():
623
+ url = f"https://googlehomefoyer-pa.googleapis.com/v2/groups/{system_id}/speedTestResults"
624
+ headers = {
625
+ "Content-Type": "application/json; charset=utf-8",
626
+ "Authorization": f"Bearer {self._api_token}"
627
+ }
628
+ payload = {}
629
+ params = (
630
+ ('prettyPrint', 'false'),
631
+ ('maxResultCount', 1)
632
+ )
633
+
634
+ response = await self.get_api(url=url,headers=headers,payload=payload,params=params)
635
+
636
+ return response["speedTestResults"]
637
+
638
+ async def run_speed_test(self, system_id:str):
639
+ """Run a speed test and return the results."""
640
+ if await self.connect():
641
+ operation_id = await self.create_wan_speedtest(system_id=system_id)
642
+
643
+ status = await self.check_operation(operation_id)
644
+ status = status["operationState"]
645
+
646
+ while status != "DONE":
647
+ status = await self.check_operation(operation_id)
648
+ status = status["operationState"]
649
+ await asyncio.sleep(5)
650
+
651
+ results = await self.speed_test_results(system_id=system_id)
652
+ return results[0]
653
+
654
+ async def start_retrieve_sensitive_info(self, system_id:str, station_ids:list):
655
+ """Start the request to return the device sensitive information."""
656
+ if await self.connect():
657
+ url = f"https://googlehomefoyer-pa.googleapis.com/v2/groups/{system_id}/stations/operations/sensitiveInfo"
658
+
659
+ headers = {
660
+ "Content-Type": "application/json; charset=utf-8",
661
+ "Authorization": f"Bearer {self._api_token}"
662
+ }
663
+ json_payload = {"stationIds":station_ids}
664
+ params = (
665
+ ('prettyPrint', 'false'),
666
+ )
667
+
668
+ response = await self.post_api(url=url,headers=headers,json_payload=json_payload,params=params)
669
+ operation_id = response.get("operation",[]).get("operationId")
670
+
671
+ return operation_id
672
+
673
+ async def sensitive_info_results(self, operation_id:str):
674
+ """Return the results of the sensitive info request."""
675
+ if await self.connect():
676
+ url = f"https://googlehomefoyer-pa.googleapis.com/v2/operations/{operation_id}/sensitiveInfo"
677
+ params = (
678
+ ('prettyPrint', 'false'),
679
+ )
680
+ headers = {
681
+ "Content-Type": "application/json; charset=utf-8",
682
+ "Authorization": f"Bearer {self._api_token}"
683
+ }
684
+ payload = {}
685
+
686
+ return await self.get_api(url=url, headers=headers, payload=payload, params=params)
687
+
688
+ async def get_sensitive_info(self, system_id:str, station_ids:list):
689
+ """Return a full set of sensitive info on the system."""
690
+ if await self.connect():
691
+ operation_id = await self.start_retrieve_sensitive_info(
692
+ system_id=system_id,station_ids=station_ids
693
+ )
694
+
695
+ status = await self.check_operation(operation_id)
696
+ status = status["operationState"]
697
+
698
+ while status != "DONE":
699
+ status = await self.check_operation(operation_id)
700
+ status = status["operationState"]
701
+ await asyncio.sleep(5)
702
+
703
+ results = await self.sensitive_info_results(operation_id=operation_id)
704
+ return results.get("stationSensitiveInfos",[])
705
+
706
+ async def get_realtime_metrics(self, system_id:str):
707
+ """Return real-time metrics from the system."""
708
+ if await self.connect():
709
+ url = f"https://googlehomefoyer-pa.googleapis.com/v2/groups/{system_id}/realtimeMetrics"
710
+ params = (
711
+ ('prettyPrint', 'false'),
712
+ )
713
+ headers = {
714
+ "Content-Type": "application/json; charset=utf-8",
715
+ "Authorization": f"Bearer {self._api_token}"
716
+ }
717
+ payload = {}
718
+
719
+ return await self.get_api(url=url, headers=headers, payload=payload, params=params)
720
+
721
+
722
+ class GoogleWifiException(Exception):
723
+ """Platform not ready exception."""
724
+ pass
725
+
726
+ class GoogleWifiAuthError(Exception):
727
+ """Stored Google credentials were rejected; re-authentication required."""
728
+ pass
729
+
730
+ class GoogleHomeUpdateFailed(Exception):
731
+ """Google Home Update failed, token refresh required."""
732
+
733
+ class GoogleHomeIgnoreDevice(Exception):
734
+ """Google Home can't get data, ignore it."""
@@ -0,0 +1,133 @@
1
+ Metadata-Version: 2.4
2
+ Name: googlewifi
3
+ Version: 0.1.0
4
+ Summary: Google WiFi API wrapper for integration to Google Wifi systems.
5
+ Home-page: https://github.com/djtimca/googlewifi-api
6
+ Download-URL: https://github.com/djtimca/googlewifi-api/archive/v_0.1.0.tar.gz
7
+ Author: Tim Empringham
8
+ Author-email: tim.empringham@live.ca
9
+ License: apache-2.0
10
+ Keywords: Google,Wifi
11
+ Classifier: Development Status :: 3 - Alpha
12
+ Classifier: Intended Audience :: Developers
13
+ Classifier: Topic :: Software Development :: Build Tools
14
+ Classifier: License :: OSI Approved :: Apache Software License
15
+ Classifier: Programming Language :: Python :: 3
16
+ Classifier: Programming Language :: Python :: 3.4
17
+ Classifier: Programming Language :: Python :: 3.5
18
+ Classifier: Programming Language :: Python :: 3.6
19
+ Requires-Python: >=3.9
20
+ Description-Content-Type: text/markdown
21
+ License-File: LICENCE
22
+ License-File: LICENSE.txt
23
+ Requires-Dist: ghome-foyer-api<2.0.0,>=1.0.0
24
+ Requires-Dist: gpsoauth==2.0.0
25
+ Dynamic: author
26
+ Dynamic: author-email
27
+ Dynamic: classifier
28
+ Dynamic: description
29
+ Dynamic: description-content-type
30
+ Dynamic: download-url
31
+ Dynamic: home-page
32
+ Dynamic: keywords
33
+ Dynamic: license
34
+ Dynamic: license-file
35
+ Dynamic: requires-dist
36
+ Dynamic: requires-python
37
+ Dynamic: summary
38
+
39
+ # googlewifi-api
40
+ PyPi Integration for Google WiFi Services for Home Assistant integration. Also provides bluetooth scanning from Google/Nest Home, Mini etc smart speakers to return information about bluetooth devices in the area.
41
+
42
+ ## Required - Google account credentials
43
+
44
+ This API authenticates through Google Play Services OAuth (`gpsoauth`). You need your Google account email, a master token (`aas_et/...` or `oauth2rt_1/...`), and an `android_id`.
45
+
46
+ To obtain a master token:
47
+
48
+ 1. Open `https://accounts.google.com/EmbeddedSetup` in a browser.
49
+ 2. Sign in with the Google account that owns/manages the Wifi network.
50
+ 3. Open browser developer tools and copy the **entire** value of the `oauth_token` cookie (it starts with `oauth2_4/`).
51
+ 4. Exchange it for a master token:
52
+
53
+ ```python
54
+ import secrets, asyncio
55
+ from googlewifi import GoogleWifi
56
+
57
+ android_id = secrets.token_hex(8)
58
+ master_token = asyncio.run(
59
+ GoogleWifi.exchange_oauth_token("you@gmail.com", "oauth2_4/...", android_id)
60
+ )
61
+ ```
62
+
63
+ The short-lived `oauth_token` is only used once. The resulting master token is reusable and sensitive — treat it like a password.
64
+
65
+ If you already have a master token, skip the exchange and pass it directly.
66
+
67
+ ## Usage
68
+
69
+ ```python
70
+ api = GoogleWifi(
71
+ email="you@gmail.com",
72
+ master_token="aas_et/...",
73
+ android_id="0123456789abcdef",
74
+ )
75
+ await api.connect()
76
+ systems = await api.get_systems()
77
+ ```
78
+
79
+ Session can be sent as an optional aiohttp session if you are managing your session within an application.
80
+
81
+ `GoogleWifiAuthError` is raised when the stored master token is rejected by Google and a new `oauth_token` exchange is required.
82
+
83
+ ## Available Methods
84
+
85
+ ### get_systems()
86
+
87
+ Returns a structured data set that includes the entire system data including system status, access point information and status, and devices from the network.
88
+
89
+ ### pause_device(system_id:str, device_id:str, pause_state:bool)
90
+
91
+ Pause or unpause a specific device on the network. Must specify the system_id, device_id and pause_state (True to pause, False to unpause). Returns True/False on success of the call.
92
+
93
+ ### prioritize_device(system_id:str, device_id:str, duration_hours:int (default 1))
94
+
95
+ Prioritize a device for a period of hours (to be specified by duration_hours) from 1 hour to 6 hours maximum. Must specify the system_id and device_id. If duration_hours is not passed it will default to 1 hour prioritization. Returns True/False on success of the call.
96
+
97
+ ### clear_prioritization(system_id:str)
98
+
99
+ Clear any existing device prioritization from the system. Must specify the system_id to clear. Returns True/False on success of the call.
100
+
101
+ ### set_brightness(ap_id:str, brightness:int)
102
+
103
+ Set the light brightness on the Access Point. Must specify the access point id (ap_id) and the desired brightness. Brightness range is 0-100. Returns True/False on the success of the call.
104
+
105
+ ### restart_ap(ap_id:str)
106
+
107
+ Restart a specific Access Point. Must specify the access point (ap_id). Returns True/False on the success of the call.
108
+
109
+ ### restart_system(system_id:str)
110
+
111
+ Restart the entire system. Must specify the system to restart (system_id). Returns True/False on the success of the call.
112
+
113
+ ### refresh_tokens()
114
+
115
+ Will return a dict of local access tokens for Google Home/Mini etc devices in format {cloud_device_id:local_access_token}. These tokens are required to access a Google Home device for bluetooth updates and scanning.
116
+
117
+ ### update_info(host:str)
118
+
119
+ Will return the detailed capabilities and information for a Google Home/Mini etc device. You have to provide the host IP (ie. 192.168.0.20) and it will return a detailed JSON payload which includes the capabilities of the device as well as the cloud device ID which can be used to extract the correct local access token from the refresh_tokens() dict.
120
+
121
+ ### get_bluetooth_status(host:str, token:str)
122
+
123
+ Will return the current bluetooth status for the Google Home/Mini etc device.
124
+
125
+ ### get_bluetooth_devices(host:str, token:str)
126
+
127
+ Will return a list of all bluetooth devices which are within range of that Google Home/Mini etc including the MAC address, device type, name, and RSSI (signal strength).
128
+
129
+ ### run_speed_test(system_id:str)
130
+
131
+ Will run a WAN speed test on the system and return the results (upload/download speed).
132
+
133
+ Note: This library was built specifically for integration to Home Assistant.
@@ -0,0 +1,7 @@
1
+ googlewifi/__init__.py,sha256=wGuzq45lLD9fbEDRljUEj3p30eCAXawYDL9PY6mkby0,24387
2
+ googlewifi-0.1.0.dist-info/licenses/LICENCE,sha256=xx0jnfkXJvxRnG63LTGOxlggYnIysveWIZ6H3PNdCrQ,11357
3
+ googlewifi-0.1.0.dist-info/licenses/LICENSE.txt,sha256=pzLIIAQjBdx3-aXX85_dyrsgU38S5z6gkA73FRLWw3Y,583
4
+ googlewifi-0.1.0.dist-info/METADATA,sha256=6RVVwMShU3w0V9GhcWJl4idethR0WXNJ8xpKr8cwIBA,5557
5
+ googlewifi-0.1.0.dist-info/WHEEL,sha256=YVMoNqKzERt-wjUZwJ33xBGAwnFl-4cqbYkTtWa4itE,91
6
+ googlewifi-0.1.0.dist-info/top_level.txt,sha256=SazTAc4CAT5AdCQs-VQdU0U1M0FRHeb1kzE50x7C8jQ,11
7
+ googlewifi-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.0.0)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
@@ -0,0 +1,14 @@
1
+ Copyright 2020 Tim Empringham
2
+
3
+ Licensed under the Apache License, Version 2.0 (the "License");
4
+ you may not use this file except in compliance with the License.
5
+ You may obtain a copy of the License at
6
+
7
+ http://www.apache.org/licenses/LICENSE-2.0
8
+
9
+ Unless required by applicable law or agreed to in writing, software
10
+ distributed under the License is distributed on an "AS IS" BASIS,
11
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ See the License for the specific language governing permissions and
13
+ limitations under the License.
14
+
@@ -0,0 +1 @@
1
+ googlewifi