Repository navigation
Expand file tree
/
Copy pathAndroidAPI.py
More file actions
211 lines (168 loc) · 7.02 KB
/
Copy pathAndroidAPI.py
File metadata and controls
211 lines (168 loc) · 7.02 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
import sys
from pathlib import Path
from AdbConnect import AdbConnection
"""Copyright (c) 2026 Alan. All Rights Reserved."""
# Custom exceptions. If you write code on top of this and want to catch them,
# don't touch the excepthook below, just catch them normally.
#
# RebootToOnState -> tried to reboot into the state the device is already in
# UnknownState -> that state doesn't exist
# UnknownShutdownMode -> mode wasn't "graceful" or "force"
# ErrorWhileHandleApp -> couldn't open/close the app
# FailedToGetDeviceInfo -> couldn't read info from the device
# WrongFilePassedError -> file isn't an .apk
# FailedToSideloadApp -> pm install failed
class RebootToOnState(Exception):
pass
class UnknownState(Exception):
pass
class UnknownShutdownMode(Exception):
pass
class ErrorWhileHandleApp(Exception):
pass
class FailedToGetDeviceInfo(Exception):
pass
class WrongFilePassedError(Exception):
pass
class FailedToSideloadApp(Exception):
pass
CUSTOM_ERRORS = (
RebootToOnState,
UnknownState,
UnknownShutdownMode,
ErrorWhileHandleApp,
FailedToGetDeviceInfo,
WrongFilePassedError,
FailedToSideloadApp,
)
# Our own errors print as a single clean line, everything else gets the normal traceback
def Customclass_Handler(exctype, value, traceback):
if issubclass(exctype, CUSTOM_ERRORS):
print(f"{exctype.__name__}: {value}")
else:
sys.__excepthook__(exctype, value, traceback)
sys.excepthook = Customclass_Handler
# Helper classes, not meant to be used much on their own
class DeviceInfo:
def __init__(self, conn: AdbConnection):
self.conn = conn
# Returns the current boot state: Normal, Recovery, fastbootd, bootloader or Unknown
def GetDeviceInfo(self) -> str:
result: str = self.conn.shell("getprop sys.boot_completed").strip()
if result == "1":
return "Normal"
bootmode: str = self.conn.shell("getprop ro.bootmode").strip()
if bootmode == "recovery":
return "Recovery"
if bootmode == "fastbootd":
return "fastbootd"
if bootmode == "bootloader":
return "bootloader"
return "Unknown"
# Checks if the state we want is the one we're already in.
# Gives back an error message if so, None if we're good to go.
def _match_states(self, State: str) -> str | None:
current: str = self.GetDeviceInfo()
wanted: str = State.lower()
if current == "Normal" and wanted == "system":
return f"Trying to get to {State} but on {current}!"
if current == "fastbootd" and wanted == "fastbootd":
return f"Trying to get to {State} but on {current}!"
if current == "Recovery" and wanted == "recovery":
return f"Trying to get to {State} but on {current}!"
if current == "bootloader" and wanted == "bootloader":
return f"Trying to get to {State} but on {current}!"
return None
# Main classes ---------------------------------------------------------
class DevicePower:
def __init__(self, conn: AdbConnection):
self.conn = conn
self.info = DeviceInfo(conn)
# usage: DevicePower(conn).RebootTo("recovery")
def RebootTo(self, State: str) -> None:
err: str | None = self.info._match_states(State)
if err is not None:
raise RebootToOnState(f"\x1b[31m{err}\x1b[0m")
if State.lower() == "system":
self.conn.shell("reboot")
elif State.lower() == "recovery":
self.conn.shell("reboot recovery")
elif State.lower() == "fastbootd":
self.conn.shell("reboot fastboot")
elif State.lower() == "bootloader":
self.conn.shell("reboot bootloader")
else:
raise UnknownState(f"\x1b[31mUnknown state: {State}\x1b[0m")
# usage: DevicePower(conn).Shutdown("graceful") or "force"
def Shutdown(self, SafelyOrNo: str) -> None:
if SafelyOrNo.lower() == "graceful":
self.conn.shell("svc power shutdown")
elif SafelyOrNo.lower() == "force":
self.conn.shell("reboot -p")
else:
raise UnknownShutdownMode(
f"\x1b[31mUnknown shutdown mode: {SafelyOrNo}\x1b[0m"
)
# ----------------------------------------------------------------------
class OpenApp:
def __init__(self, conn: AdbConnection):
self.conn = conn
# usage: OpenApp(conn).Open("com.dev.package")
def Open(self, PkgName: str) -> None:
result: str = self.conn.shell(
f"am start -a android.intent.action.MAIN -c android.intent.category.LAUNCHER -p {PkgName}"
)
if "Error" in result or "Exception" in result:
raise ErrorWhileHandleApp(f"\x1b[31mFailed to open: {PkgName}\x1b[0m")
# usage: OpenApp(conn).Close("com.dev.package")
def Close(self, PkgName: str) -> None:
result: str = self.conn.shell(f"am force-stop {PkgName}")
if "Error" in result or "Exception" in result:
raise ErrorWhileHandleApp(f"\x1b[31mFailed to close: {PkgName}\x1b[0m")
# ----------------------------------------------------------------------
# Each getter returns the value, or prints it if say=True
class AndroidInfo:
def __init__(self, conn: AdbConnection):
self.conn = conn
def _getprop(self, prop: str, label: str) -> str:
value: str = self.conn.shell(f"getprop {prop}").strip()
if not value:
raise FailedToGetDeviceInfo(f"\x1b[31mFailed to get {label}!\x1b[0m")
return value
def AndroidVersion(self, say: bool = False) -> str | None:
version: str = self._getprop("ro.build.version.release", "version")
if say:
print(version)
else:
return version
def AndroidSDKVersion(self, say: bool = False) -> str | None:
version: str = self._getprop("ro.build.version.sdk", "SDK version")
if say:
print(version)
else:
return version
# usage: AndroidInfo(conn).AndroidBuildID(say=True)
def AndroidBuildID(self, say: bool = False) -> str | None:
version: str = self._getprop("ro.build.id", "build ID")
if say:
print(version)
else:
return version
# ----------------------------------------------------------------------
class SideloadAPK:
def __init__(self, conn: AdbConnection):
self.conn = conn
# usage: SideloadAPK(conn).SideloadAPK("path/to/app.apk")
def SideloadAPK(self, APKPath: str) -> None:
APKP: Path = Path(APKPath)
if not APKP.exists():
raise FileNotFoundError(
f"\x1b[31mPath: {APKPath} is not a correct path for the APK!\x1b[0m"
)
if APKP.suffix.lower() != ".apk":
raise WrongFilePassedError(
f"\x1b[31mAPK: {APKPath} is not a .apk file!\x1b[0m"
)
result: str = self.conn.shell(f"pm install -r {APKPath}")
if "Failure" in result or "Error" in result:
raise FailedToSideloadApp("\x1b[31mFailed to sideload app!\x1b[0m")