-
-
Notifications
You must be signed in to change notification settings - Fork 197
/
Copy pathandroid-application-manager.ts
329 lines (302 loc) · 9.98 KB
/
android-application-manager.ts
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
import { EOL } from "os";
import { ApplicationManagerBase } from "../application-manager-base";
import { TARGET_FRAMEWORK_IDENTIFIERS, LiveSyncPaths } from "../../constants";
import { hook, sleep, regExpEscape } from "../../helpers";
import { cache } from "../../decorators";
import { parse, join } from "path";
import * as _ from "lodash";
import { AAB_EXTENSION_NAME, APKS_EXTENSION_NAME } from "../../../constants";
import { IOptions } from "../../../declarations";
import {
IAndroidBuildData,
IAndroidSigningData,
} from "../../../definitions/build";
import { IAndroidBundleToolService } from "../../../definitions/android-bundle-tool-service";
import {
IFileSystem,
Server,
IErrors,
IHooksService,
IDictionary,
} from "../../declarations";
export class AndroidApplicationManager extends ApplicationManagerBase {
public PID_CHECK_INTERVAL = 100;
public PID_CHECK_TIMEOUT = 10000; // 10 secs
constructor(
private adb: Mobile.IDeviceAndroidDebugBridge,
private identifier: string,
private $androidBundleToolService: IAndroidBundleToolService,
private $fs: IFileSystem,
private $options: IOptions,
private $logcatHelper: Mobile.ILogcatHelper,
private $androidProcessService: Mobile.IAndroidProcessService,
private $httpClient: Server.IHttpClient,
protected $deviceLogProvider: Mobile.IDeviceLogProvider,
private $errors: IErrors,
$logger: ILogger,
$hooksService: IHooksService
) {
super($logger, $hooksService, $deviceLogProvider);
}
public async getInstalledApplications(): Promise<string[]> {
let result = "";
try {
result = await this.adb.executeShellCommand(["pm", "list", "packages"]);
} catch (err) {
/**
* on some devices (Samsung) listing packages is prevented by a permission error
* notably, some system apps (bloatware) is installed under user 150
* and listing these packages results in a permission error.
* if this happens, we have to first list all the users, and then loop through
* all the users and trying to list packages for that specific user, ignoring
* any errors. These are all then concatenated together and parsed normally.
* This is a slower operation, so we only do it in case listing failed in the first place.
*/
const userIDs: string[] = [];
const users = await this.adb.executeShellCommand(["pm", "list", "users"]);
/**
* Users:
* UserInfo{0:Owner:c13} running
*/
const userIDRegex = /UserInfo{(\d+)[:}]/;
users.split(EOL).forEach((line: string) => {
const [, userID] = line.match(userIDRegex) ?? [];
if (userID) {
userIDs.push(userID);
}
});
for (let id of userIDs) {
try {
result +=
EOL +
(await this.adb.executeShellCommand([
"pm",
"list",
"packages",
"--user",
id,
]));
} catch (err) {
// ignore - likely permission denied.
}
}
}
const regex = /package:(.+)/;
return result
.split(EOL)
.map((packageString: string) => {
const match = packageString.match(regex);
return match ? match[1] : null;
})
.filter((parsedPackage: string) => parsedPackage !== null);
}
@hook("install")
public async installApplication(
packageFilePath: string,
appIdentifier?: string,
buildData?: IAndroidBuildData
): Promise<void> {
if (appIdentifier) {
const deviceRootPath = `${LiveSyncPaths.ANDROID_TMP_DIR_NAME}/${appIdentifier}`;
await this.adb.executeShellCommand(["rm", "-rf", deviceRootPath]);
}
const { dir, name, ext } = parse(packageFilePath);
if (ext === AAB_EXTENSION_NAME) {
const apksOutputPath = join(dir, name) + APKS_EXTENSION_NAME;
if (!this.hasValidApksFile(packageFilePath, apksOutputPath)) {
await this.$androidBundleToolService.buildApks({
aabFilePath: packageFilePath,
apksOutputPath,
signingData: <IAndroidSigningData>buildData,
});
}
await this.$androidBundleToolService.installApks({
apksFilePath: apksOutputPath,
deviceId: this.identifier,
});
} else {
return this.adb.executeCommand(["install", "-r", `${packageFilePath}`]);
}
}
public uninstallApplication(appIdentifier: string): Promise<void> {
// Need to set the treatErrorsAsWarnings to true because when using tns run command if the application is not installed on the device it will throw error
return this.adb.executeShellCommand(
["pm", "uninstall", `${appIdentifier}`],
{ treatErrorsAsWarnings: true }
);
}
public async startApplication(
appData: Mobile.IStartApplicationData
): Promise<void> {
if (appData.waitForDebugger) {
await this.adb.executeShellCommand([
`cat /dev/null > ${LiveSyncPaths.ANDROID_TMP_DIR_NAME}/${appData.appId}-debugbreak`,
]);
}
// If the app is debuggable, the Runtime will update the file when its ready for debugging
// and we will be able to take decisions and synchronize the debug experience based on the content
await this.adb.executeShellCommand([
`cat /dev/null > ${LiveSyncPaths.ANDROID_TMP_DIR_NAME}/${appData.appId}-debugger-started`,
]);
/*
Example "pm dump <app_identifier> | grep -A 1 MAIN" output"
android.intent.action.MAIN:
3b2df03 org.nativescript.cliapp/com.tns.NativeScriptActivity filter 50dd82e
Action: "android.intent.action.MAIN"
Category: "android.intent.category.LAUNCHER"
--
intent={act=android.intent.action.MAIN cat=[android.intent.category.LAUNCHER] flg=0x10200000 cmp=org.nativescript.cliapp/com.tns.NativeScriptActivity}
realActivity=org.nativescript.cliapp/com.tns.NativeScriptActivity
--
Intent { act=android.intent.action.MAIN cat=[android.intent.category.LAUNCHER] flg=0x10200000 cmp=org.nativescript.cliapp/com.tns.NativeScriptActivity }
frontOfTask=true task=TaskRecord{fe592ac #449 A=org.nativescript.cliapp U=0 StackId=1 sz=1}
*/
const appIdentifier = appData.appId;
const pmDumpOutput = await this.adb.executeShellCommand([
"pm",
"dump",
appIdentifier,
"|",
"grep",
"-A",
"1",
"MAIN",
]);
const activityMatch = this.getFullyQualifiedActivityRegex(appIdentifier);
const match = activityMatch.exec(pmDumpOutput);
const possibleIdentifier = match && match[0];
if (possibleIdentifier) {
await this.adb.executeShellCommand([
"am",
"start",
"-n",
possibleIdentifier,
]);
} else {
this.$logger.trace(
`Tried starting activity for: ${appIdentifier}, using activity manager but failed.`
);
await this.adb.executeShellCommand([
"monkey",
"-p",
appIdentifier,
"-c",
"android.intent.category.LAUNCHER",
"1",
]);
}
if (!this.$options.justlaunch && !appData.justLaunch) {
const deviceIdentifier = this.identifier;
const processIdentifier = await this.getAppProcessId(
deviceIdentifier,
appIdentifier
);
if (processIdentifier) {
this.$deviceLogProvider.setApplicationPidForDevice(
deviceIdentifier,
processIdentifier
);
this.$deviceLogProvider.setProjectDirForDevice(
deviceIdentifier,
appData.projectDir
);
await this.$logcatHelper.start({
deviceIdentifier: this.identifier,
pid: processIdentifier,
});
} else {
await this.$logcatHelper.dump(this.identifier);
this.$errors.fail(
`Unable to find running "${appIdentifier}" application on device "${deviceIdentifier}".`
);
}
}
}
private async getAppProcessId(
deviceIdentifier: string,
appIdentifier: string
) {
const appIdCheckStartTime = new Date().getTime();
let processIdentifier = "";
let hasTimedOut = false;
while (!processIdentifier && !hasTimedOut) {
processIdentifier = await this.$androidProcessService.getAppProcessId(
deviceIdentifier,
appIdentifier
);
if (!processIdentifier) {
this.$logger.trace(
`Wasn't able to get pid of the app. Sleeping for "${this.PID_CHECK_INTERVAL}ms".`
);
await sleep(this.PID_CHECK_INTERVAL);
hasTimedOut =
new Date().getTime() - appIdCheckStartTime > this.PID_CHECK_TIMEOUT;
}
}
return processIdentifier;
}
public stopApplication(appData: Mobile.IApplicationData): Promise<void> {
this.$logcatHelper.stop(this.identifier);
this.$deviceLogProvider.setApplicationPidForDevice(this.identifier, null);
this.$deviceLogProvider.setProjectDirForDevice(this.identifier, null);
return this.adb.executeShellCommand([
"am",
"force-stop",
`${appData.appId}`,
]);
}
public getDebuggableApps(): Promise<Mobile.IDeviceApplicationInformation[]> {
return this.$androidProcessService.getDebuggableApps(this.identifier);
}
public async getDebuggableAppViews(
appIdentifiers: string[]
): Promise<IDictionary<Mobile.IDebugWebViewInfo[]>> {
const mappedAppIdentifierPorts = await this.$androidProcessService.getMappedAbstractToTcpPorts(
this.identifier,
appIdentifiers,
TARGET_FRAMEWORK_IDENTIFIERS.Cordova
),
applicationViews: IDictionary<Mobile.IDebugWebViewInfo[]> = {};
await Promise.all(
_.map(
mappedAppIdentifierPorts,
async (port: number, appIdentifier: string) => {
applicationViews[appIdentifier] = [];
const localAddress = `http://127.0.0.1:${port}/json`;
try {
if (port) {
const apps = (await this.$httpClient.httpRequest(localAddress))
.body;
applicationViews[appIdentifier] = JSON.parse(apps);
}
} catch (err) {
this.$logger.trace(
`Error while checking ${localAddress}. Error is: ${err.message}`
);
}
}
)
);
return applicationViews;
}
@cache()
private getFullyQualifiedActivityRegex(appIdentifier: string): RegExp {
const packageActivitySeparator = "\\/";
const fullJavaClassName = "([a-zA-Z_0-9]*\\.)*[A-Z_$]($[A-Z_$]|[$_\\w_])*";
return new RegExp(
`${regExpEscape(
appIdentifier
)}${packageActivitySeparator}${fullJavaClassName}`,
`m`
);
}
private hasValidApksFile(aabFilaPath: string, apksFilePath: string): boolean {
let isValid = false;
if (this.$fs.exists(apksFilePath)) {
const lastUpdatedApks = this.$fs.getFsStats(apksFilePath).ctime.getTime();
const lastUpdatedAab = this.$fs.getFsStats(aabFilaPath).ctime.getTime();
isValid = lastUpdatedApks >= lastUpdatedAab;
}
return isValid;
}
}