forked from schoentoon/go-adb
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathdevice_extra.go
286 lines (264 loc) · 6.55 KB
/
device_extra.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
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
package adb
import (
"bufio"
"fmt"
"io"
"math/rand"
"net/http"
"os"
"regexp"
"strconv"
"strings"
"syscall"
"time"
"github.com/franela/goreq"
)
type Process struct {
User string
Pid int
Name string
}
// ListProcesses return list of Process
func (c *Device) ListProcesses() (ps []Process, err error) {
reader, err := c.OpenCommand("ps")
if err != nil {
return
}
defer reader.Close()
var fieldNames []string
bufrd := bufio.NewReader(reader)
for {
line, _, err := bufrd.ReadLine()
fields := strings.Fields(strings.TrimSpace(string(line)))
if len(fields) == 0 {
break
}
if err == io.EOF {
break
}
if fieldNames == nil {
fieldNames = fields
continue
}
var process Process
/* example output of command "ps"
USER PID PPID VSIZE RSS WCHAN PC NAME
root 1 0 684 540 ffffffff 00000000 S /init
root 2 0 0 0 ffffffff 00000000 S kthreadd
*/
if len(fields) != len(fieldNames)+1 {
continue
}
for index, name := range fieldNames {
value := fields[index]
switch strings.ToUpper(name) {
case "PID":
process.Pid, _ = strconv.Atoi(value)
case "NAME":
process.Name = fields[len(fields)-1]
case "USER":
process.User = value
}
}
if process.Pid == 0 {
continue
}
ps = append(ps, process)
}
return
}
// KillProcessByName return if killed success
func (c *Device) KillProcessByName(name string, sig syscall.Signal) error {
ps, err := c.ListProcesses()
if err != nil {
return err
}
for _, p := range ps {
if p.Name != name {
continue
}
// log.Printf("kill %s with pid: %d", p.Name, p.Pid)
_, _, er := c.RunCommandWithExitCode("kill", "-"+strconv.Itoa(int(sig)), strconv.Itoa(p.Pid))
if er != nil {
return er
}
}
return nil
}
type PackageInfo struct {
Name string
Path string
Version struct {
Code int
Name string
}
}
var (
rePkgPath = regexp.MustCompile(`codePath=([^\s]+)`)
reVerCode = regexp.MustCompile(`versionCode=(\d+)`)
reVerName = regexp.MustCompile(`versionName=([^\s]+)`)
)
// StatPackage returns PackageInfo
// If package not found, err will be ErrPackageNotExist
func (c *Device) StatPackage(packageName string) (pi PackageInfo, err error) {
pi.Name = packageName
out, err := c.RunCommand("dumpsys", "package", packageName)
if err != nil {
return
}
matches := rePkgPath.FindStringSubmatch(out)
if len(matches) == 0 {
err = ErrPackageNotExist
return
}
pi.Path = matches[1]
matches = reVerCode.FindStringSubmatch(out)
if len(matches) == 0 {
err = ErrPackageNotExist
return
}
pi.Version.Code, _ = strconv.Atoi(matches[1])
matches = reVerName.FindStringSubmatch(out)
if len(matches) == 0 {
err = ErrPackageNotExist
return
}
pi.Version.Name = matches[1]
return
}
// Properties extract info from $ adb shell getprop
func (c *Device) Properties() (props map[string]string, err error) {
propOutput, err := c.RunCommand("getprop")
if err != nil {
return nil, err
}
re := regexp.MustCompile(`\[(.*?)\]:\s*\[(.*?)\]`)
matches := re.FindAllStringSubmatch(propOutput, -1)
props = make(map[string]string)
for _, m := range matches {
var key = m[1]
var val = m[2]
props[key] = val
}
return
}
/*
RunCommandWithExitCode use a little tricky to get exit code
The tricky is append "; echo :$?" to the command,
and parse out the exit code from output
*/
func (c *Device) RunCommandWithExitCode(cmd string, args ...string) (string, int, error) {
exArgs := append(args, ";", "echo", ":$?")
outStr, err := c.RunCommand(cmd, exArgs...)
if err != nil {
return outStr, 0, err
}
idx := strings.LastIndexByte(outStr, ':')
if idx == -1 {
return outStr, 0, fmt.Errorf("adb shell aborted, can not parse exit code")
}
exitCode, _ := strconv.Atoi(strings.TrimSpace(outStr[idx+1:]))
if exitCode != 0 {
commandLine, _ := prepareCommandLine(cmd, args...)
err = ShellExitError{commandLine, exitCode}
}
outStr = strings.Replace(outStr[0:idx], "\r\n", "\n", -1) // put somewhere else
return outStr, exitCode, err
}
type ShellExitError struct {
Command string
ExitCode int
}
func (s ShellExitError) Error() string {
return fmt.Sprintf("shell %s exit code %d", strconv.Quote(s.Command), s.ExitCode)
}
// DoWriteFile return an object, use this object can Cancel write and get Process
func (c *Device) DoSyncFile(path string, rd io.ReadCloser, size int64, perms os.FileMode) (aw *AsyncWriter, err error) {
dst, err := c.OpenWrite(path, perms, time.Now())
if err != nil {
return nil, err
}
awr := newAsyncWriter(c, dst, path, size)
go func() {
awr.doCopy(rd)
rd.Close()
}()
return awr, nil
}
func (c *Device) DoSyncLocalFile(dst string, src string, perms os.FileMode) (aw *AsyncWriter, err error) {
f, err := os.Open(src)
if err != nil {
return
}
finfo, err := f.Stat()
if err != nil {
return
}
return c.DoSyncFile(dst, f, finfo.Size(), perms)
}
func (c *Device) DoSyncHTTPFile(dst string, srcUrl string, perms os.FileMode) (aw *AsyncWriter, err error) {
res, err := goreq.Request{
Uri: srcUrl,
RedirectHeaders: true,
MaxRedirects: 10,
}.Do()
if err != nil {
return
}
var length int64
fmt.Sscanf(res.Header.Get("Content-Length"), "%d", &length)
return c.DoSyncFile(dst, res.Body, length, perms)
}
// WriteToFile write a reader stream to device
func (c *Device) WriteToFile(path string, rd io.Reader, perms os.FileMode) (written int64, err error) {
dst, err := c.OpenWrite(path, perms, time.Now())
if err != nil {
return
}
defer func() {
dst.Close()
if err != nil || written == 0 {
return
}
// wait until write finished.
fromTime := time.Now()
for {
if time.Since(fromTime) > time.Second*600 {
err = fmt.Errorf("write file to device timeout (10min)")
return
}
finfo, er := c.Stat(path)
if er != nil && !HasErrCode(er, FileNoExistError) {
err = er
return
}
if finfo == nil {
err = fmt.Errorf("target file %s not created", strconv.Quote(path))
return
}
if finfo != nil && finfo.Size == int32(written) {
break
}
time.Sleep(time.Duration(200+rand.Intn(100)) * time.Millisecond)
}
}()
written, err = io.Copy(dst, rd)
return
}
// WriteHttpToFile download http resource to device
func (c *Device) WriteHttpToFile(path string, urlStr string, perms os.FileMode) (written int64, err error) {
resp, err := goreq.Request{
Uri: urlStr,
RedirectHeaders: true,
MaxRedirects: 10,
}.Do()
if err != nil {
return
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
err = fmt.Errorf("http download <%s> status %v", urlStr, resp.Status)
return
}
return c.WriteToFile(path, resp.Body, perms)
}