This repository has been archived by the owner on May 27, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 274
/
apkmanager.go
106 lines (93 loc) · 2.41 KB
/
apkmanager.go
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
package main
import (
"regexp"
"strconv"
"strings"
"time"
"github.com/pkg/errors"
"github.com/shogo82148/androidbinary/apk"
)
var canFixedInstallFails = map[string]bool{
"INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE": true,
"INSTALL_FAILED_UPDATE_INCOMPATIBLE": true,
"INSTALL_FAILED_VERSION_DOWNGRADE": true,
}
type APKManager struct {
Path string
packageName string
mainActivity string
}
func (am *APKManager) PackageName() (string, error) {
if am.packageName != "" {
return am.packageName, nil
}
pkg, err := apk.OpenFile(am.Path)
if err != nil {
return "", errors.Wrap(err, "apk parse")
}
defer pkg.Close()
am.packageName = pkg.PackageName()
am.mainActivity, _ = pkg.MainActivity()
return am.packageName, nil
}
func (am *APKManager) Install() error {
sdk, _ := strconv.Atoi(getCachedProperty("ro.build.version.sdk"))
cmds := []string{"pm", "install", "-d", "-r", am.Path}
if sdk >= 23 { // android 6.0
cmds = []string{"pm", "install", "-d", "-r", "-g", am.Path}
}
out, err := runShell(cmds...)
if err != nil {
matches := regexp.MustCompile(`Failure \[([\w_ ]+)\]`).FindStringSubmatch(string(out))
if len(matches) > 0 {
return errors.Wrap(err, matches[0])
}
return errors.Wrap(err, string(out))
}
return nil
}
func (am *APKManager) ForceInstall() error {
err := am.Install()
if err == nil {
return nil
}
errType := regexp.MustCompile(`INSTALL_FAILED_[\w_]+`).FindString(err.Error())
if !canFixedInstallFails[errType] {
return err
}
log.Infof("install meet %v, try to uninstall", errType)
packageName, err := am.PackageName()
if err != nil {
return errors.Wrap(err, "apk parse")
}
log.Infof("uninstall %s", packageName)
runShell("pm", "uninstall", packageName)
return am.Install()
}
type StartOptions struct {
Stop bool
Wait bool
}
func (am *APKManager) Start(opts StartOptions) error {
packageName, err := am.PackageName()
if err != nil {
return err
}
if am.mainActivity == "" {
return errors.New("parse MainActivity failed")
}
mainActivity := am.mainActivity
if !strings.Contains(mainActivity, ".") {
mainActivity = "." + mainActivity
}
_, err = runShellTimeout(30*time.Second, "am", "start", "-n", packageName+"/"+mainActivity)
return err
}
func installAPK(path string) error {
am := &APKManager{Path: path}
return am.Install()
}
func forceInstallAPK(filepath string) error {
am := &APKManager{Path: filepath}
return am.ForceInstall()
}