This repository has been archived by the owner on Jul 26, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathvrc_auto_rejoin_tool.go
509 lines (423 loc) · 10.7 KB
/
vrc_auto_rejoin_tool.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
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
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
package vrcarjt
import (
"errors"
"fmt"
"regexp"
"os/exec"
"runtime"
"github.com/faiface/beep"
"github.com/faiface/beep/speaker"
"github.com/faiface/beep/wav"
"github.com/hpcloud/tail"
"github.com/jinzhu/now"
gops "github.com/mitchellh/go-ps"
"github.com/shirou/gopsutil/process"
"io/ioutil"
"log"
"os"
"sort"
"strings"
"sync"
"time"
)
const WorldLogIdentifier = "] Destination set: wrld_"
const Location = "Local"
const TimeFormat = "2006.01.02 15:04:05"
const vrcRelativeLogPath = `\AppData\LocalLow\VRChat\VRChat\`
const Timeout = "Timeout: Your connection to VRChat timed out."
var BuildVersion = "v0.0.0"
func NewVRCAutoRejoinTool() *VRCAutoRejoinTool {
conf := LoadConf("setting.yml")
return &VRCAutoRejoinTool{
Config: conf,
Args: "",
LatestInstance: Instance{},
EnableRejoin: !conf.EnableSleepDetector, // EnableSleepDetectorがOnのとき即座にインスタンス移動の検出をしないため
InSleep: false,
rejoinLock: &sync.Mutex{},
playAudioLock: &sync.Mutex{},
running: false,
shutdown: false,
}
}
// VRCAutoRejoinTool ...
type VRCAutoRejoinTool struct {
Config *Setting
Args string
LatestInstance Instance
EnableRejoin bool
InSleep bool
rejoinLock *sync.Mutex
playAudioLock *sync.Mutex
running bool
shutdown bool
}
type AutoRejoin interface {
Run() error
IsRun() bool
ParseLatestInstance(path string) (Instance, error)
SleepStart()
Stop() error
GetUserHome() string
}
func (v *VRCAutoRejoinTool) IsRun() bool {
v.rejoinLock.Lock()
defer v.rejoinLock.Unlock()
return v.running
}
func (v *VRCAutoRejoinTool) IsShutdown() bool {
v.rejoinLock.Lock()
defer v.rejoinLock.Unlock()
return v.shutdown
}
func (v *VRCAutoRejoinTool) SleepStart() {
v.rejoinLock.Lock()
defer v.rejoinLock.Unlock()
v.InSleep = true
}
func (v *VRCAutoRejoinTool) Stop() error {
if !v.running {
return nil
}
v.rejoinLock.Lock()
defer v.rejoinLock.Unlock()
go v.playAudioFile("stop.wav")
v.running = false
return nil
}
func (v *VRCAutoRejoinTool) sleepInstanceDetector() Instance {
return Instance{}
}
func (v *VRCAutoRejoinTool) GetUserHome() string {
if runtime.GOOS == "windows" {
home := os.Getenv("HOMEDRIVE") + os.Getenv("HOMEPATH")
if home == "" {
home = os.Getenv("USERPROFILE")
}
return home
}
return os.Getenv("HOME")
}
func init() {
var err error
time.Local, err = time.LoadLocation(Location)
if err != nil {
time.Local = time.FixedZone(Location, 9*60*60)
}
}
func (v *VRCAutoRejoinTool) Run() error {
home := v.GetUserHome()
if home == "" {
return errors.New("home folder not found")
}
var err error
v.Args, err = v.findProcessArgsByName("VRChat.exe")
if err == ErrProcessNotFound {
go v.playAudioFile("start_vrc.wav")
v.rejoinLock.Lock()
v.running = false
v.rejoinLock.Unlock()
return nil
}
if err != nil {
v.rejoinLock.Lock()
v.running = false
v.rejoinLock.Unlock()
return err
}
v.rejoinLock.Lock()
v.running = true
v.shutdown = false
v.rejoinLock.Unlock()
go v.playAudioFile("start.wav")
path := home + vrcRelativeLogPath
latestLog, err := v.fetchLatestLogName(path)
if err != nil {
return fmt.Errorf("log file not found. %s", err)
}
start := time.Now().In(time.Local)
fmt.Println("RUNNING START AT", start.Format(TimeFormat))
v.LatestInstance, err = v.ParseLatestInstance(path + latestLog)
if err != nil {
return err
}
t, err := tail.TailFile(path+latestLog, tail.Config{
Follow: true,
MustExist: true,
ReOpen: true,
Poll: true,
})
if err != nil {
v.rejoinLock.Lock()
v.running = false
v.rejoinLock.Unlock()
return err
}
if v.Config.EnableProcessCheck {
go v.processWatcher()
}
go v.logInspector(t, start)
return nil
}
func (v *VRCAutoRejoinTool) rejoin(i Instance, killProcess bool) error {
v.rejoinLock.Lock()
v.shutdown = true
defer func() {
v.running = false
v.rejoinLock.Unlock()
}()
if killProcess {
err := v.killProcessByName("VRChat.exe")
if err != nil {
log.Println(err)
}
}
args := prepareExecArgs(v.Args, i)
cmd := exec.Command(args.ExePath, args.Args...)
return cmd.Start()
}
func (v *VRCAutoRejoinTool) ParseLatestInstance(path string) (Instance, error) {
content, err := ioutil.ReadFile(path)
if err != nil {
log.Println(err)
return Instance{}, err
}
return v.parseLatestInstance(string(content))
}
// ErrProcessNotFound is an error that is returned when the target process could not be found
var ErrProcessNotFound = errors.New("process not found")
func (v *VRCAutoRejoinTool) findProcessPIDByName(name string) (int32, error) {
processes, err := gops.Processes()
if err != nil {
return -1, err
}
for _, p := range processes {
if strings.Contains(p.Executable(), name) {
return int32(p.Pid()), nil
}
}
return -1, ErrProcessNotFound
}
func (v *VRCAutoRejoinTool) findProcessArgsByName(name string) (string, error) {
pid, err := v.findProcessPIDByName(name)
if err != nil {
return "", ErrProcessNotFound
}
p, err := process.NewProcess(pid)
if err != nil {
log.Println(err)
return "", err
}
return p.Cmdline()
}
func (v *VRCAutoRejoinTool) killProcessByName(name string) error {
pid, err := v.findProcessPIDByName(name)
if err != nil {
return err
}
p, err := os.FindProcess(int(pid))
if err != nil {
return err
}
return p.Kill()
}
func (v *VRCAutoRejoinTool) inTimeRange(start time.Time, end time.Time, target time.Time) bool {
// https://stackoverflow.com/questions/55093676/checking-if-current-time-is-in-a-given-interval-golang
if start.Before(end) {
return !target.Before(start) && !target.After(end)
}
if start.Equal(end) {
return target.Equal(start)
}
return !start.After(target) || !end.Before(target)
}
func (v *VRCAutoRejoinTool) playAudioFile(path string) {
f, err := os.Open(path)
if err != nil {
log.Fatal(err)
}
streamer, format, err := wav.Decode(f)
if err != nil {
log.Fatal(err)
}
defer func() {
_ = streamer.Close()
}()
v.playAudioLock.Lock()
defer v.playAudioLock.Unlock()
wait := &sync.WaitGroup{}
wait.Add(1)
err = speaker.Init(format.SampleRate, format.SampleRate.N(time.Second/10))
if err != nil {
log.Fatal(err)
}
speaker.Play(beep.Seq(streamer, beep.Callback(func() {
wait.Done()
})))
wait.Wait()
}
func (v *VRCAutoRejoinTool) parseLatestInstance(s string) (Instance, error) {
latestInstance := Instance{}
for _, line := range strings.Split(s, "\n") {
if line == "" {
continue
}
if len(line) > 0 && line[len(line)-1] == '\r' {
line = line[:len(line)-1]
}
if !strings.Contains(line, WorldLogIdentifier) {
continue
}
instance, err := NewInstanceByLog(line)
if err != nil {
return instance, err
}
latestInstance = instance
}
return latestInstance, nil
}
func (v *VRCAutoRejoinTool) fetchLatestLogName(path string) (string, error) {
files, err := ioutil.ReadDir(path)
if err != nil {
log.Println(err)
return "", err
}
sort.Slice(files, func(i, j int) bool {
return files[i].ModTime().After(files[j].ModTime())
})
var filtered []os.FileInfo
for _, v := range files {
if strings.Contains(v.Name(), "output_log") {
filtered = append(filtered, v)
}
}
latestLog := ""
if len(filtered) > 0 {
latestLog = filtered[0].Name()
}
return latestLog, nil
}
func (v *VRCAutoRejoinTool) processWatcher() {
for v.IsRun() && !v.IsShutdown() {
log.Println("process watcher available")
_, err := v.findProcessPIDByName("VRChat.exe")
if err == ErrProcessNotFound {
if v.Config.EnableRejoinNotice {
go v.playAudioFile("rejoin_notice.wav")
time.Sleep(1 * time.Minute)
}
// 警告オーディオ再生中に止まった場合なにもしない
if !v.running {
log.Println("cancel rejoin")
v.shutdown = true
return
}
err := v.rejoin(v.LatestInstance, false)
if err != nil {
log.Println(err)
}
return
}
time.Sleep(10 * time.Second)
}
log.Println("process watcher clean up by other.")
}
func (v *VRCAutoRejoinTool) logInspector(tail *tail.Tail, at time.Time) {
for msg := range tail.Lines {
if !v.IsRun() || v.IsShutdown() {
log.Println("log watcher clean up by other.")
tail.Cleanup()
break
}
logLine := msg.Text
if !v.isMove(at, logLine) && !v.isTimeout(logLine) {
continue
}
log.Println("instance move detected")
if v.Config.EnableRadioExercises {
start, err := now.ParseInLocation(time.Local, "05:45")
if err != nil {
log.Println(err)
continue
}
end, err := now.ParseInLocation(time.Local, "08:00")
if err != nil {
log.Println(err)
continue
}
if v.inTimeRange(start, end, time.Now().In(time.Local)) {
continue
}
}
if v.Config.EnableRejoinNotice {
go v.playAudioFile("rejoin_notice.wav")
time.Sleep(1 * time.Minute)
}
// 警告オーディオ再生中に止まった場合なにもしない
if !v.running {
tail.Cleanup()
log.Println("cancel rejoin")
return
}
err := v.rejoin(v.LatestInstance, true)
if err != nil {
log.Println(err)
}
tail.Cleanup()
return
}
}
func (v *VRCAutoRejoinTool) isMove(at time.Time, l string) bool {
if l == "" {
return false
}
if !strings.Contains(l, WorldLogIdentifier) {
return false
}
i, err := NewInstanceByLog(l)
if err != nil {
return false
}
if i.Time.Before(at) {
return false
}
if v.LatestInstance.ID == i.ID {
return false
}
return true
}
func (v *VRCAutoRejoinTool) isTimeout(log string) bool {
return strings.Contains(log, Timeout)
}
type Exec struct {
ExePath string
Args []string
}
var instancePattern = regexp.MustCompile(`vrchat://.+`)
func prepareExecArgs(processArgs string, i Instance) Exec {
// 起動時に vrchat:// のインスタンス指定があった場合は競合するため消す
if strings.Contains(processArgs, "vrchat://") {
processArgs = instancePattern.ReplaceAllString(processArgs, "")
}
// 既存の起動引数を用いて rejoin するインスタンスを指定する
args := processArgs + ` vrchat://launch?id=` + i.ID
// 今動いている VRChat.exe までのパスを取得する
// go の windows の exec は exe までのパスと引数を完全に別物として扱うため
arg := strings.Split(args, `VRChat.exe`)
exe := arg[:1][0] + `VRChat.exe`
// C:\Program Files (x86) などのスペースを含む階層以下にある場合のVRChat.exe のパスは "" で囲まれているため除去する
// 末尾の " は exe の組立時に VRChat.exe で追加しているため除去不要
if strings.HasPrefix(exe, `"`) {
exe = exe[1:]
}
tmpArgs := arg[1:][0]
// C:\Program Files (x86) 以下の階層にある場合はexeのパスの " がのこるので除去する
if strings.HasPrefix(tmpArgs, `"`) {
tmpArgs = tmpArgs[1:]
}
exeArgs := strings.Fields(strings.TrimSpace(tmpArgs))
return Exec{
ExePath: exe,
Args: exeArgs,
}
}