-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathrotation.go
212 lines (194 loc) · 4.57 KB
/
rotation.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
// RotationWatcher.apk Service
package stf
import (
"bufio"
"fmt"
"io"
"log"
"net/http"
"strconv"
"strings"
"sync"
"time"
adb "github.com/openatx/go-adb"
"github.com/openatx/go-adb/wire"
"github.com/pkg/errors"
)
const (
defaultRotationPkgName = "jp.co.cyberagent.stf.rotationwatcher"
defaultRotationMaxRetry = 3
)
type STFRotation struct {
d *adb.Device
mu sync.Mutex
lastValue int
subscribers map[chan int]bool
cmdConn *wire.Conn
wg sync.WaitGroup
stopped bool
leftRetry int
}
func NewSTFRotation(d *adb.Device) *STFRotation {
return &STFRotation{
d: d,
subscribers: make(map[chan int]bool),
leftRetry: defaultRotationMaxRetry,
lastValue: -1,
}
}
// 0, 90, 180, 270
func (s *STFRotation) Rotation() (int, error) {
if s.lastValue == -1 || s.stopped {
return 0, errors.New("Rotation not ready")
}
return s.lastValue, nil
}
func (s *STFRotation) Start() error {
pmPath, err := s.preparePackage()
if err != nil {
return err
}
go func() {
var ok = true
for ok {
s.wg.Add(1)
err := s.consoleStartProcess(pmPath)
if err == nil {
s.leftRetry = defaultRotationMaxRetry
} else {
log.Printf("rotation run failed: %v, left retry %d", err, s.leftRetry)
}
s.mu.Lock()
s.leftRetry -= 1
if s.stopped || s.leftRetry <= 0 {
for subC := range s.subscribers {
s.Unsubscribe(subC)
}
ok = false
}
s.wg.Done()
s.mu.Unlock()
}
}()
return nil
}
func (s *STFRotation) Stop() error {
// cancel retry and wait until stop
s.mu.Lock()
s.stopped = true
s.mu.Unlock()
if s.cmdConn != nil {
s.cmdConn.Close()
s.cmdConn = nil
}
s.wg.Wait()
return nil
}
func (s *STFRotation) Subscribe() chan int {
s.mu.Lock()
defer s.mu.Unlock()
C := make(chan int, 1)
s.subscribers[C] = true
return C
}
// unsubscribe will also close channel
func (s *STFRotation) Unsubscribe(C chan int) {
s.mu.Lock()
defer s.mu.Unlock()
delete(s.subscribers, C)
close(C)
}
func (s *STFRotation) pub(v int) {
s.lastValue = v
for subC := range s.subscribers {
select {
case subC <- v:
case <-time.After(1 * time.Second):
s.Unsubscribe(subC)
}
}
}
func (s *STFRotation) preparePackage() (pmPath string, err error) {
if err := s.pushApk(); err != nil {
return "", err
}
return s.getPackagePath(defaultRotationPkgName)
}
func (s *STFRotation) consoleStartProcess(pmPath string) error {
fio, err := s.d.OpenCommand("CLASSPATH="+pmPath, "exec", "app_process", "/system/bin", defaultRotationPkgName+".RotationWatcher")
if err != nil {
return errors.Wrap(err, "start rotation.apk")
}
s.cmdConn = fio
defer fio.Close()
readCount := 0
scanner := bufio.NewScanner(fio)
for scanner.Scan() {
val, err := strconv.Atoi(scanner.Text())
if err != nil {
return err
}
readCount += 1
s.pub(val)
}
if readCount > 0 {
return nil
}
return errors.New("Rotation got nothing")
}
func (s *STFRotation) pushApk() error {
_, err := s.getPackagePath(defaultRotationPkgName) // If already installed, then skip
if err == nil {
return nil
}
phoneApkPath := "/data/local/tmp/RotationWatcher.apk"
wc, err := s.d.OpenWrite(phoneApkPath, 0644, time.Now())
if err != nil {
return err
}
resp, err := http.Get("https://github.com/openatx/RotationWatcher.apk/releases/download/1.0/RotationWatcher.apk")
if err != nil {
return err
}
if resp.StatusCode != http.StatusOK {
return errors.New("http download rotation watcher status " + resp.Status)
}
defer resp.Body.Close()
log.Println("downloading RotationWatcher.apk ...")
if _, err = io.Copy(wc, resp.Body); err != nil {
return err
}
log.Println("Done")
if err := wc.Close(); err != nil {
return err
}
_, err = s.checkCmdOutput("pm", "install", "-rt", phoneApkPath)
return err
}
func (s *STFRotation) getPackagePath(name string) (path string, err error) {
path, err = s.checkCmdOutput("pm", "path", name)
if err != nil {
return
}
if strings.HasPrefix(path, "package:") {
path = strings.TrimSpace(path[len("package:"):])
return
}
return "", errors.New("not rotationwatcher package found")
}
func (s *STFRotation) checkCmdOutput(name string, args ...string) (outStr string, err error) {
args = append(args, ";", "echo", ":$?")
outStr, err = s.d.RunCommand(name, args...)
if err != nil {
return
}
idx := strings.LastIndexByte(outStr, ':')
if idx == -1 {
return outStr, errors.New("adb shell error, parse exit code failed")
}
exitCode, _ := strconv.Atoi(strings.TrimSpace(outStr[idx+1:]))
if exitCode != 0 {
err = fmt.Errorf("[adb shell %s %s] exit code %d", name, strings.Join(args, " "), exitCode)
}
return outStr[0:idx], err
}