-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdriver.py
More file actions
1538 lines (1339 loc) · 63.1 KB
/
driver.py
File metadata and controls
1538 lines (1339 loc) · 63.1 KB
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
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import logging
import os
import platform
import subprocess
import tempfile
import time
from functools import wraps
from typing import Optional
import requests
from appium import webdriver
from appium.options.android import UiAutomator2Options
from flask import current_app
from requests.adapters import HTTPAdapter
from urllib3.exceptions import MaxRetryError
from urllib3.util.retry import Retry
from server.utils.appium_driver import AppiumDriver
from server.utils.request_utils import get_sindarin_email
logger = logging.getLogger(__name__)
class Driver:
# Class-level HTTP session with connection pooling
_http_session = None
@classmethod
def _get_http_session(cls):
"""Get or create a shared HTTP session with proper connection pooling."""
if cls._http_session is None:
cls._http_session = requests.Session()
# Configure connection pooling
adapter = HTTPAdapter(
pool_connections=10, # Number of connection pools to cache
pool_maxsize=10, # Maximum number of connections to save in the pool
max_retries=Retry(total=3, backoff_factor=0.3, status_forcelist=[500, 502, 503, 504]),
)
cls._http_session.mount("http://", adapter)
cls._http_session.mount("https://", adapter)
return cls._http_session
def __init__(self):
if hasattr(self, "_initialized_attributes"):
logger.error(f"Driver already initialized, instance: {self}", exc_info=True)
return
self.driver = None
self.device_id = None
self.automator = None # Reference to the automator instance
self.appium_port = None # Must be set
self._session_retries = 0
self._reconnecting = False # Flag to prevent infinite recursion
self._max_session_retries = 2
self._initialized_attributes = True
def _get_emulator_device_id(self, specific_device_id: Optional[str] = None) -> Optional[str]:
"""
Get the emulator device ID from adb devices, optionally targeting a specific device.
Args:
specific_device_id: Optional device ID to specifically connect to (e.g., 'emulator-5554')
Returns:
Optional[str]: The device ID if found, None otherwise
"""
email = get_sindarin_email()
try:
# If we have a specific device ID to use, check if it's available first
if specific_device_id:
result = subprocess.run(["adb", "devices"], capture_output=True, text=True, check=True)
if specific_device_id in result.stdout and "device" in result.stdout:
# Verify this is actually a working emulator
try:
verify_result = subprocess.run(
["adb", "-s", specific_device_id, "shell", "getprop", "ro.product.model"],
capture_output=True,
text=True,
check=True,
timeout=5,
)
return specific_device_id
except Exception as e:
logger.warning(f"Could not verify specific device {specific_device_id}: {e}")
# Failed to verify specific device - return None instead of falling back to any device
logger.error(
f"Requested specific device {specific_device_id} could not be verified for email={email}",
exc_info=True,
)
return None
else:
logger.warning(
f"Specified device ID {specific_device_id} not found or not ready for email={email}"
)
# Do not continue to regular device search if a specific device was requested
# but is not available. This prevents using the wrong device.
logger.error(
f"Requested specific device {specific_device_id} was not found or is not ready for email={email}",
exc_info=True,
)
return None
# CRITICAL: Do NOT search for ANY available emulator when no specific device is requested
# This prevents cross-user emulator access in production
logger.error(
f"No specific device requested for email={email}. "
f"Refusing to search for ANY available emulator to prevent cross-user access."
)
return None
except Exception as e:
logger.error(f"Error getting emulator device ID: {e}", exc_info=True)
return None
def _disable_hw_overlays(self) -> bool:
"""Disable hardware overlays to improve WebView visibility."""
try:
# Check if we already applied this setting to the current emulator
profile = self.automator.profile_manager.get_current_profile()
email = get_sindarin_email()
# If this is the same device and we already set hw_overlays_disabled, skip
if (
profile
and email
and self.automator.profile_manager.get_user_field(
email, "hw_overlays_disabled", False, section="emulator_settings"
)
):
return True
# Check current state
result = subprocess.run(
["adb", "-s", self.device_id, "shell", "settings", "get", "global", "debug.hw.overlay"],
check=True,
capture_output=True,
text=True,
)
current_state = result.stdout.strip()
if current_state == "1":
# Record this setting in the profile
self._update_profile_setting("hw_overlays_disabled", True)
return True
logger.info(f"Disabling HW overlays on device {self.device_id}")
subprocess.run(
["adb", "-s", self.device_id, "shell", "settings", "put", "global", "debug.hw.overlay", "1"],
check=True,
capture_output=True,
text=True,
)
# Record this setting in the profile
self._update_profile_setting("hw_overlays_disabled", True)
return True
except subprocess.CalledProcessError as e:
logger.error(f"Failed to handle HW overlays: {e.stderr}", exc_info=True)
return False
except Exception as e:
logger.error(f"Error handling HW overlays: {e}", exc_info=True)
return False
def _update_profile_setting(self, setting_name: str, value: bool) -> None:
"""Update a setting in the current profile under emulator_settings.
Args:
setting_name: The name of the setting to update
value: The value to set
"""
try:
profile = self.automator.profile_manager.get_current_profile()
if not profile:
logger.warning("Cannot update profile setting: no current profile")
return
email = get_sindarin_email()
avd_name = profile.get("avd_name")
if email and avd_name:
# Use the profile manager's set_user_field method to properly store under emulator_settings
self.automator.profile_manager.set_user_field(
email, setting_name, value, section="emulator_settings"
)
logger.debug(f"Updated profile setting emulator_settings.{setting_name}={value} for {email}")
else:
logger.error(
f"Failed to update profile setting: {setting_name}={value} for {email}", exc_info=True
)
except Exception as e:
logger.error(f"Error updating profile setting {setting_name}: {e}", exc_info=True)
# Continue execution even if we can't update the profile
def _clean_old_version_info(self, email: str) -> None:
"""Remove Kindle version information from preferences if present.
Args:
email: Email address of the profile
"""
try:
profile_index = self.automator.profile_manager.profiles_index
if email in profile_index and "preferences" in profile_index[email]:
preferences = profile_index[email]["preferences"]
cleaned = False
# Remove version info from preferences if present
if "kindle_version_name" in preferences:
preferences.pop("kindle_version_name")
cleaned = True
if "kindle_version_code" in preferences:
preferences.pop("kindle_version_code")
cleaned = True
# Save changes if we cleaned anything
if cleaned:
self.automator.profile_manager._save_profiles_index()
except Exception as e:
logger.error(f"Error cleaning old version info for {email}: {e}", exc_info=True)
def _update_kindle_version_in_profile(self, version_name: str, version_code: int) -> None:
"""Update Kindle version information in the current profile.
Args:
version_name: The version name (e.g. "8.121.0.100")
version_code: The version code (e.g. 1286055411)
"""
profile = self.automator.profile_manager.get_current_profile()
if not profile:
logger.warning("Cannot update Kindle version in profile: no current profile")
return
email = profile.get("email") or profile.get("assigned_profile")
avd_name = profile.get("avd_name")
if email and avd_name:
# Update version info at top level using generic field setter if available
self.automator.profile_manager.set_user_field(email, "kindle_version_name", version_name)
self.automator.profile_manager.set_user_field(email, "kindle_version_code", str(version_code))
logger.info(
f"Updated Kindle version in profile to {version_name} (code: {version_code}) for {email}"
)
def _disable_animations(self) -> bool:
"""Disable all system animations to improve reliability."""
try:
# Check if we already applied this setting to the current emulator
profile = self.automator.profile_manager.get_current_profile()
email = get_sindarin_email()
# If this is the same device and we already set animations_disabled, skip
if (
profile
and email
and self.automator.profile_manager.get_user_field(
email, "animations_disabled", False, section="emulator_settings"
)
):
return True
logger.info(f"Disabling system animations on device {self.device_id}")
# Disable all three types of Android animations
subprocess.run(
[
"adb",
"-s",
self.device_id,
"shell",
"settings",
"put",
"global",
"window_animation_scale",
"0.0",
],
check=True,
capture_output=True,
text=True,
)
subprocess.run(
[
"adb",
"-s",
self.device_id,
"shell",
"settings",
"put",
"global",
"transition_animation_scale",
"0.0",
],
check=True,
capture_output=True,
text=True,
)
subprocess.run(
[
"adb",
"-s",
self.device_id,
"shell",
"settings",
"put",
"global",
"animator_duration_scale",
"0.0",
],
check=True,
capture_output=True,
text=True,
)
# Record this setting in the profile
self._update_profile_setting("animations_disabled", True)
return True
except subprocess.CalledProcessError as e:
logger.error(f"Failed to disable animations: {e.stderr}", exc_info=True)
return False
except Exception as e:
logger.error(f"Error disabling animations: {e}", exc_info=True)
return False
def _disable_sleep(self) -> bool:
"""Disable sleep and app standby modes to prevent the device and app from sleeping."""
try:
# Check if we already applied this setting to the current emulator
profile = self.automator.profile_manager.get_current_profile()
email = get_sindarin_email()
# If this is the same device and we already set sleep_disabled, skip
if (
profile
and email
and self.automator.profile_manager.get_user_field(
email, "sleep_disabled", False, section="emulator_settings"
)
):
return True
logger.info(f"Disabling sleep and app standby for device {self.device_id}")
# Set the device to never sleep when plugged in
# Value 7 means stay on while power AND USB AND wireless charging
subprocess.run(
[
"adb",
"-s",
self.device_id,
"shell",
"settings",
"put",
"global",
"stay_on_while_plugged_in",
"7",
],
check=True,
capture_output=True,
text=True,
)
# Disable app standby and doze mode for the Kindle app
subprocess.run(
[
"adb",
"-s",
self.device_id,
"shell",
"dumpsys",
"deviceidle",
"whitelist",
"+com.amazon.kindle",
],
check=True,
capture_output=True,
text=True,
)
# Set screen timeout to never (max value for Android settings)
# 2147483647 is max integer value (around 24.8 days) Android allows
subprocess.run(
[
"adb",
"-s",
self.device_id,
"shell",
"settings",
"put",
"system",
"screen_off_timeout",
"2147483647",
],
check=True,
capture_output=True,
text=True,
)
# Record this setting in the profile
self._update_profile_setting("sleep_disabled", True)
return True
except subprocess.CalledProcessError as e:
logger.error(f"Failed to disable sleep: {e.stderr}", exc_info=True)
return False
except Exception as e:
logger.error(f"Error disabling sleep: {e}", exc_info=True)
return False
def _disable_status_bar(self) -> bool:
"""Hide the status bar at runtime using ADB."""
try:
# Check if we already applied this setting to the current emulator
profile = self.automator.profile_manager.get_current_profile()
email = get_sindarin_email()
# If this is the same device and we already set status_bar_disabled, skip
if (
profile
and email
and self.automator.profile_manager.get_user_field(
email, "status_bar_disabled", False, section="emulator_settings"
)
):
return True
logger.info(f"Hiding status bar for device {self.device_id}")
# Run the ADB command to hide the status bar using immersive mode
subprocess.run(
[
"adb",
"-s",
self.device_id,
"shell",
"settings",
"put",
"global",
"policy_control",
"immersive.status=*",
],
check=True,
capture_output=True,
text=True,
)
# Record this setting in the profile
self._update_profile_setting("status_bar_disabled", True)
return True
except subprocess.CalledProcessError as e:
logger.error(f"Failed to hide status bar: {e.stderr}", exc_info=True)
return False
except Exception as e:
logger.error(f"Error hiding status bar: {e}", exc_info=True)
return False
def _disable_auto_updates(self) -> bool:
"""Disable automatic app updates to prevent apps from being killed during updates."""
try:
# Check if we already applied this setting to the current emulator
profile = self.automator.profile_manager.get_current_profile()
email = get_sindarin_email()
# If this is the same device and we already set auto_updates_disabled, skip
if (
profile
and email
and self.automator.profile_manager.get_user_field(
email, "auto_updates_disabled", False, section="emulator_settings"
)
):
return True
logger.info(f"Disabling automatic app updates for device {self.device_id}")
# Disable automatic app updates globally
subprocess.run(
[
"adb",
"-s",
self.device_id,
"shell",
"settings",
"put",
"global",
"auto_update_disabled",
"1",
],
check=True,
capture_output=True,
text=True,
)
# Also disable auto-update over WiFi only
subprocess.run(
[
"adb",
"-s",
self.device_id,
"shell",
"settings",
"put",
"global",
"update_over_wifi_only",
"0",
],
check=True,
capture_output=True,
text=True,
)
# Disable background data for Play Store to prevent updates
subprocess.run(
[
"adb",
"-s",
self.device_id,
"shell",
"cmd",
"netpolicy",
"set",
"restrict-background",
"true",
"com.android.vending",
],
capture_output=True,
text=True,
)
# Record this setting in the profile
self._update_profile_setting("auto_updates_disabled", True)
return True
except subprocess.CalledProcessError as e:
logger.error(f"Failed to disable auto updates: {e.stderr}", exc_info=True)
return False
except Exception as e:
logger.error(f"Error disabling auto updates: {e}", exc_info=True)
return False
def _cleanup_old_sessions(self):
"""Clean up any existing UiAutomator2 sessions."""
email = get_sindarin_email()
try:
# CRITICAL: Verify this device belongs to the current user before cleaning
try:
avd_result = subprocess.run(
["adb", "-s", self.device_id, "emu", "avd", "name"],
capture_output=True,
text=True,
timeout=3,
)
if avd_result.returncode == 0:
device_avd = avd_result.stdout.strip()
# Handle "AVD_NAME\nOK" format
if "\n" in device_avd:
device_avd = device_avd.split("\n")[0].strip()
logger.info(f"Device {self.device_id} is running AVD: {device_avd}")
# Get expected AVD name for this email
profile = self.automator.profile_manager.get_current_profile()
expected_avd = profile.get("avd_name") if profile else None
if expected_avd and device_avd != expected_avd:
logger.error(
f"CRITICAL: Device {self.device_id} is running AVD {device_avd} "
f"but email {email} expects AVD {expected_avd}. REFUSING to clean sessions to prevent "
f"cross-user interference!"
)
return False
else:
logger.warning(f"Could not determine AVD for device {self.device_id}")
except Exception as e:
logger.warning(f"Error checking AVD name: {e}")
# Instead of clearing data, just force-stop the Appium process
# This avoids triggering logout in the Kindle app
try:
subprocess.run(
[
"adb",
"-s",
self.device_id,
"shell",
"am",
"force-stop",
"io.appium.uiautomator2.server",
],
capture_output=True,
text=True,
)
logger.info(f"Force-stopped io.appium.uiautomator2.server successfully")
except Exception:
pass # It's okay if the process wasn't running
return True
except Exception as e:
logger.error(f"Error cleaning up old sessions for email={email}: {e}", exc_info=True)
return False
def _is_kindle_installed(self) -> bool:
"""Check if the Kindle app is installed on the device."""
try:
result = subprocess.run(
["adb", "-s", self.device_id, "shell", "pm", "list", "packages", "com.amazon.kindle"],
capture_output=True,
text=True,
check=True,
)
return "com.amazon.kindle" in result.stdout
except Exception as e:
logger.error(f"Error checking Kindle installation: {e}", exc_info=True)
return False
def _get_installed_kindle_version(self) -> tuple:
"""Get the version of the installed Kindle app.
Returns:
tuple: (version_name, version_code) or (None, None) if failed
"""
try:
result = subprocess.run(
["adb", "-s", self.device_id, "shell", "dumpsys", "package", "com.amazon.kindle"],
capture_output=True,
text=True,
check=True,
)
version_name = None
version_code = None
for line in result.stdout.splitlines():
if "versionName=" in line:
version_name = line.split("versionName=")[1].strip()
if "versionCode=" in line:
# Extract only the version code number
version_code_str = line.split("versionCode=")[1].strip().split(" ")[0]
try:
version_code = int(version_code_str)
except ValueError:
logger.error(f"Could not parse version code: {version_code_str}", exc_info=True)
return (version_name, version_code)
except Exception as e:
logger.error(f"Error getting installed Kindle version: {e}", exc_info=True)
return (None, None)
def _get_apk_version(self, apk_path) -> tuple:
"""Extract version information from an APK file.
Args:
apk_path: Path to the APK file
Returns:
tuple: (version_name, version_code) or (None, None) if failed
"""
try:
# Parse the filename to extract version info
# Format is usually: com.amazon.kindle_8.121.0.100(2.0.40027.0)-1286055411_minAPI28(arm64-v8a)(nodpi)_apkmirror.com.apk
filename = os.path.basename(apk_path)
# Extract version name from filename
version_name_match = None
if "_" in filename and "(" in filename:
version_part = filename.split("_")[1]
if "(" in version_part:
version_name_match = version_part.split("(")[0]
# Extract version code from filename (usually after the hyphen)
version_code = None
if "-" in filename and "_" in filename:
try:
version_code_part = filename.split("-")[1].split("_")[0]
version_code = int(version_code_part)
except (IndexError, ValueError):
logger.warning(f"Could not parse version code from filename: {filename}")
# If we couldn't parse from filename, try using ADB
if not version_name_match or not version_code:
# First check if the APK file exists
if not os.path.exists(apk_path):
logger.warning(f"APK file not found at {apk_path}, skipping ADB version check")
return (None, None)
logger.info(f"Using ADB to get version info from {apk_path}")
# Upload APK to device temporarily
temp_path = "/sdcard/temp_kindle.apk"
try:
result = subprocess.run(
["adb", "-s", self.device_id, "push", apk_path, temp_path],
check=True,
capture_output=True,
text=True,
)
except subprocess.CalledProcessError as e:
logger.error(f"Failed to push APK to device: {e}")
logger.error(f"stdout: {e.stdout}")
logger.error(f"stderr: {e.stderr}")
# Don't fail completely if we can't get version info
logger.warning("Continuing without APK version information")
return (None, None)
# Use package manager to get info
result = subprocess.run(
["adb", "-s", self.device_id, "shell", "pm", "dump", temp_path],
check=True,
capture_output=True,
text=True,
)
# Clean up
subprocess.run(
["adb", "-s", self.device_id, "shell", "rm", temp_path],
check=True,
capture_output=True,
text=True,
)
# Parse output
for line in result.stdout.splitlines():
if "versionName=" in line:
version_name_match = line.split("versionName=")[1].strip()
if "versionCode=" in line:
code_str = line.split("versionCode=")[1].strip().split(" ")[0]
try:
version_code = int(code_str)
except ValueError:
pass
return (version_name_match, version_code)
except Exception as e:
logger.error(f"Error getting APK version: {e}", exc_info=True)
return (None, None)
def _find_newest_kindle_apk(self) -> str:
"""Find the newest Kindle APK among available options.
Returns:
str: Path to the newest APK
"""
apk_paths = []
# Check standard installation path - note this likely doesn't exist
standard_path = os.path.join(
os.path.dirname(__file__),
"..",
"android-sdk",
"apk",
"kindle.apk",
)
if os.path.exists(standard_path):
apk_paths.append(standard_path)
# Check ansible directory for additional APKs (android_arm)
kindle_apk_dir = os.path.join(
os.path.dirname(__file__),
"ansible",
"roles",
"android_arm",
"files",
)
if os.path.exists(kindle_apk_dir):
for file in os.listdir(kindle_apk_dir):
if "com.amazon.kindle" in file:
apk_paths.append(os.path.join(kindle_apk_dir, file))
# Also check android_x86 directory for APKs
kindle_x86_dir = os.path.join(
os.path.dirname(__file__),
"ansible",
"roles",
"android_x86",
"files",
)
if os.path.exists(kindle_x86_dir):
for file in os.listdir(kindle_x86_dir):
if "com.amazon.kindle" in file:
apk_paths.append(os.path.join(kindle_x86_dir, file))
if not apk_paths:
logger.error("No Kindle APK files found", exc_info=True)
return None
# If only one APK is found, return it
if len(apk_paths) == 1:
return apk_paths[0]
# Compare versions to find the newest
newest_apk = None
highest_version_code = -1
# First try using version codes for comparison
for apk_path in apk_paths:
version_name, version_code = self._get_apk_version(apk_path)
if version_code and version_code > highest_version_code:
highest_version_code = version_code
newest_apk = apk_path
# If we couldn't determine version codes reliably, use lexicographical sorting of filenames
if not newest_apk:
# Sort filenames lexicographically (the last one alphabetically is typically newest with version in name)
apk_paths.sort(key=lambda x: os.path.basename(x))
newest_apk = apk_paths[-1] # Get the last one lexicographically
return newest_apk
def _install_kindle(self) -> bool:
"""Install the Kindle app on the device."""
try:
logger.info(f"Installing Kindle on device {self.device_id}")
# Find the newest APK
apk_path = self._find_newest_kindle_apk()
if not apk_path:
logger.error("No Kindle APK found to install", exc_info=True)
return False
# Get version info from APK before installing
apk_version_name, apk_version_code = self._get_apk_version(apk_path)
if apk_version_name and apk_version_code:
logger.info(f"Installing Kindle version: {apk_version_name} (code: {apk_version_code})")
# Check APK supported ABIs using aapt
try:
aapt_check = subprocess.run(
["/opt/android-sdk/build-tools/35.0.0/aapt", "dump", "badging", apk_path],
capture_output=True,
text=True,
check=False,
)
if aapt_check.returncode == 0:
for line in aapt_check.stdout.splitlines():
if "native-code:" in line:
logger.info(f"APK {line}")
break
else:
logger.warning("Could not check APK ABIs with aapt")
except Exception as e:
logger.warning(f"Error checking APK ABIs: {e}")
# Check device architecture before install
try:
arch_check = subprocess.run(
["adb", "-s", self.device_id, "shell", "getprop", "ro.product.cpu.abi"],
capture_output=True,
text=True,
check=False,
)
if arch_check.returncode == 0:
device_arch = arch_check.stdout.strip()
logger.info(f"Device architecture: {device_arch}")
# Check all supported ABIs
all_abis = subprocess.run(
["adb", "-s", self.device_id, "shell", "getprop", "ro.product.cpu.abilist"],
capture_output=True,
text=True,
check=False,
)
if all_abis.returncode == 0:
logger.info(f"Device supports ABIs: {all_abis.stdout.strip()}")
# Check if libhoudini is present
houdini_check = subprocess.run(
[
"adb",
"-s",
self.device_id,
"shell",
"ls",
"/system/lib/libhoudini.so",
"2>/dev/null",
],
capture_output=True,
text=True,
check=False,
)
if houdini_check.returncode == 0:
logger.info("ARM translation (libhoudini) is available")
else:
logger.info("ARM translation (libhoudini) NOT found - ARM apps won't run!")
# Also check available storage
storage_check = subprocess.run(
["adb", "-s", self.device_id, "shell", "df", "/data"],
capture_output=True,
text=True,
check=False,
)
if storage_check.returncode == 0:
logger.debug(f"Device storage status:\n{storage_check.stdout}")
except Exception as e:
logger.warning(f"Could not check device info: {e}")
# Retry logic for APK installation
max_retries = 3
retry_delay = 2 # seconds
for attempt in range(max_retries):
try:
result = subprocess.run(
["adb", "-s", self.device_id, "install", "-r", apk_path],
check=False,
capture_output=True,
text=True,
)
if result.returncode == 0:
logger.info("Kindle app installed successfully")
break
else:
error_msg = result.stderr.strip() or result.stdout.strip()
# Log the full error for debugging
logger.warning(f"Install failed (attempt {attempt + 1}/{max_retries}): {error_msg}")
# Check if the error is related to device not ready
if any(
keyword in error_msg.lower()
for keyword in [
"offline",
"unauthorized",
"device not found",
"error: closed",
"cannot connect",
"daemon not running",
]
):
if attempt < max_retries - 1:
logger.info(
f"Device connectivity issue, waiting {retry_delay} seconds before retry..."
)
time.sleep(retry_delay)
continue
# For other errors or last attempt, log full details
if attempt == max_retries - 1:
logger.error(
f"Final install attempt failed. Full error:\nSTDOUT: {result.stdout}\nSTDERR: {result.stderr}",
exc_info=True,
)
# Fail immediately for non-connectivity errors
raise subprocess.CalledProcessError(
result.returncode, result.args, result.stdout, result.stderr
)
except subprocess.CalledProcessError as e:
if attempt == max_retries - 1:
raise
else:
logger.warning(f"Install attempt {attempt + 1} failed, retrying...")
time.sleep(retry_delay)
else:
# All retries exhausted
raise Exception(f"Failed to install APK after {max_retries} attempts")
# Store version information in profile
if apk_version_name and apk_version_code:
self._update_kindle_version_in_profile(apk_version_name, apk_version_code)
else:
# If we couldn't get version from APK, get it from the installed app
installed_version_name, installed_version_code = self._get_installed_kindle_version()
if installed_version_name and installed_version_code:
self._update_kindle_version_in_profile(installed_version_name, installed_version_code)
return True
except Exception as e:
logger.error(f"Error installing Kindle: {e}", exc_info=True)
return False
def _get_kindle_launch_activity(self) -> Optional[str]:
"""Get the main launch activity for the Kindle app."""
try:
result = subprocess.run(
[
"adb",
"-s",
self.device_id,
"shell",
"cmd package resolve-activity -c android.intent.category.LAUNCHER com.amazon.kindle",
],
capture_output=True,
text=True,
check=True,
)
# Parse output to find main activity
for line in result.stdout.splitlines():
if "name=" in line and "com.amazon.kindle" in line:
activity = line.split("name=")[1].strip()
return activity
logger.error("Could not find Kindle launch activity", exc_info=True)
return None
except Exception as e:
logger.error(f"Error getting Kindle launch activity: {e}", exc_info=True)
return None
def check_connection(self):