-
Notifications
You must be signed in to change notification settings - Fork 97
/
prophet.go
642 lines (627 loc) · 17.4 KB
/
prophet.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
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
package hh_lol_prophet
import (
"cmp"
"context"
"crypto/tls"
"encoding/base64"
"encoding/json"
"fmt"
"log"
"net"
"net/http"
"net/url"
"os"
"os/exec"
"os/signal"
"slices"
"strings"
"sync"
"time"
"github.com/atotto/clipboard"
"github.com/avast/retry-go"
"github.com/getsentry/sentry-go"
sentryGin "github.com/getsentry/sentry-go/gin"
"github.com/gin-contrib/pprof"
"github.com/gin-gonic/gin"
"github.com/gorilla/websocket"
"github.com/pkg/errors"
"go.uber.org/zap"
"golang.org/x/sync/errgroup"
"github.com/real-web-world/hh-lol-prophet/global"
ginApp "github.com/real-web-world/hh-lol-prophet/pkg/gin"
"github.com/real-web-world/hh-lol-prophet/services/lcu"
"github.com/real-web-world/hh-lol-prophet/services/lcu/models"
"github.com/real-web-world/hh-lol-prophet/services/logger"
)
type (
lcuWsEvt string
GameState string
Prophet struct {
ctx context.Context
opts *options
httpSrv *http.Server
lcuPort int
lcuToken string
lcuActive bool
currSummoner *lcu.CurrSummoner
cancel func()
api *Api
mu *sync.Mutex
GameState GameState
}
wsMsg struct {
Data interface{} `json:"data"`
EventType string `json:"event_type"`
Uri string `json:"uri"`
}
options struct {
debug bool
enablePprof bool
httpAddr string
}
)
const (
onJsonApiEventPrefixLen = len(`[8,"OnJsonApiEvent",`)
gameFlowChangedEvt lcuWsEvt = "/lol-gameflow/v1/gameflow-phase"
champSelectUpdateSessionEvt lcuWsEvt = "/lol-champ-select/v1/session"
)
// gameState
const (
GameStateNone GameState = "none"
GameStateChampSelect GameState = "champSelect"
GameStateReadyCheck GameState = "ReadyCheck"
GameStateInGame GameState = "inGame"
GameStateOther GameState = "other"
GameStateMatchmaking GameState = "Matchmaking"
)
var (
defaultOpts = &options{
debug: false,
enablePprof: true,
httpAddr: ":4396",
}
)
func NewProphet(opts ...ApplyOption) *Prophet {
ctx, cancel := context.WithCancel(context.Background())
p := &Prophet{
ctx: ctx,
cancel: cancel,
mu: &sync.Mutex{},
opts: defaultOpts,
GameState: GameStateNone,
}
if global.IsDevMode() {
opts = append(opts, WithDebug())
} else {
opts = append(opts, WithProd())
}
p.api = &Api{p: p}
for _, fn := range opts {
fn(p.opts)
}
return p
}
func (p *Prophet) Run() error {
go p.MonitorStart()
go p.captureStartMessage()
p.initGin()
go p.initWebview()
log.Printf("%s已启动 v%s -- %s", global.AppName, APPVersion, global.WebsiteTitle)
return p.notifyQuit()
}
func (p *Prophet) isLcuActive() bool {
return p.lcuActive
}
func (p *Prophet) Stop() error {
if p.cancel != nil {
p.cancel()
}
// stop all task
return nil
}
func (p *Prophet) MonitorStart() {
for {
if !p.isLcuActive() {
port, token, err := lcu.GetLolClientApiInfo()
if err != nil {
if !errors.Is(lcu.ErrLolProcessNotFound, err) {
logger.Error("获取lcu info 失败", zap.Error(err))
}
time.Sleep(time.Second)
continue
}
p.initLcuClient(port, token)
err = p.initGameFlowMonitor(port, token)
if err != nil {
logger.Debug("游戏流程监视器 err:", zap.Error(err))
}
p.lcuActive = false
p.currSummoner = nil
}
time.Sleep(time.Second)
}
}
func (p *Prophet) notifyQuit() error {
interrupt := make(chan os.Signal, 1)
signal.Notify(interrupt, os.Interrupt)
g, c := errgroup.WithContext(p.ctx)
// http
g.Go(func() error {
err := p.httpSrv.ListenAndServe()
if err != nil || !errors.Is(err, http.ErrServerClosed) {
return err
}
return nil
})
// http-shutdown
g.Go(func() error {
<-c.Done()
ctx, cancel := context.WithTimeout(context.Background(), 1*time.Second)
defer cancel()
return p.httpSrv.Shutdown(ctx)
})
// wait quit
g.Go(func() error {
for {
select {
case <-p.ctx.Done():
return p.ctx.Err()
case <-interrupt:
_ = p.Stop()
}
}
})
err := g.Wait()
if err != nil && !errors.Is(err, context.Canceled) {
return err
}
return nil
}
func (p *Prophet) initLcuClient(port int, token string) {
lcu.InitCli(port, token)
}
func (p *Prophet) initGameFlowMonitor(port int, authPwd string) error {
dialer := websocket.DefaultDialer
dialer.TLSClientConfig = &tls.Config{
InsecureSkipVerify: true,
}
dialer.NetDialContext = func(ctx context.Context, network, addr string) (conn net.Conn, err error) {
localAddr := &net.TCPAddr{IP: []byte{127, 0, 0, 100}}
serverAddr, err := net.ResolveTCPAddr(network, addr)
if err != nil {
return nil, err
}
localAddr.Port = serverAddr.Port
for i := 0; i < 10; i++ {
localAddr.IP[3] += (byte)(i)
conn, err = net.DialTCP("tcp", localAddr, serverAddr)
if err == nil {
break
}
}
return conn, err
}
rawUrl := fmt.Sprintf("wss://127.0.0.1:%d/", port)
header := http.Header{}
authSecret := base64.StdEncoding.EncodeToString([]byte(fmt.Sprintf("riot:%s", authPwd)))
header.Set("Authorization", "Basic "+authSecret)
u, _ := url.Parse(rawUrl)
c, _, err := dialer.Dial(u.String(), header)
if err != nil {
return err
}
logger.Debug(fmt.Sprintf("connect to lcu %s", u.String()))
defer func() {
_ = c.Close()
}()
err = retry.Do(func() error {
currSummoner, err := lcu.GetCurrSummoner()
if err == nil {
p.currSummoner = currSummoner
}
return err
}, retry.Attempts(5), retry.Delay(time.Second))
if err != nil {
return errors.New("获取当前召唤师信息失败:" + err.Error())
}
p.lcuActive = true
_ = c.WriteMessage(websocket.TextMessage, []byte("[5, \"OnJsonApiEvent\"]"))
for {
msgType, message, err := c.ReadMessage()
if err != nil {
// log.Println("read:", err)
logger.Debug("lol事件监控读取消息失败", zap.Error(err))
return err
}
msg := &wsMsg{}
if msgType != websocket.TextMessage || len(message) < onJsonApiEventPrefixLen+1 {
continue
}
_ = json.Unmarshal(message[onJsonApiEventPrefixLen:len(message)-1], msg)
// log.Println("ws evt: ", msg.Uri)
switch msg.Uri {
case string(gameFlowChangedEvt):
gameFlow, ok := msg.Data.(string)
if !ok {
continue
}
p.onGameFlowUpdate(gameFlow)
case string(champSelectUpdateSessionEvt):
bts, err := json.Marshal(msg.Data)
if err != nil {
continue
}
sessionInfo := &lcu.ChampSelectSessionInfo{}
err = json.Unmarshal(bts, sessionInfo)
if err != nil {
logger.Debug("champSelectUpdateSessionEvt 解析结构体失败", zap.Error(err))
continue
}
go func() {
_ = p.onChampSelectSessionUpdate(sessionInfo)
}()
default:
}
// log.Printf("recv: %s", message)
}
}
func (p *Prophet) onGameFlowUpdate(gameFlow string) {
// clientCfg := global.GetClientConf()
logger.Debug("切换状态:" + gameFlow)
switch gameFlow {
case string(models.GameFlowChampionSelect):
fmt.Println("进入英雄选择阶段,正在计算用户分数")
sentry.CaptureMessage("进入英雄选择阶段,正在计算用户分数")
p.updateGameState(GameStateChampSelect)
go p.ChampionSelectStart()
case string(models.GameFlowNone):
p.updateGameState(GameStateNone)
case string(models.GameFlowMatchmaking):
p.updateGameState(GameStateMatchmaking)
case string(models.GameFlowInProgress):
p.updateGameState(GameStateInGame)
go p.CalcEnemyTeamScore()
case string(models.GameFlowReadyCheck):
p.updateGameState(GameStateReadyCheck)
clientCfg := global.GetClientConf()
if clientCfg.AutoAcceptGame {
go p.AcceptGame()
}
default:
p.updateGameState(GameStateOther)
}
}
func (p *Prophet) updateGameState(state GameState) {
p.mu.Lock()
p.GameState = state
p.mu.Unlock()
}
func (p *Prophet) getGameState() GameState {
p.mu.Lock()
defer p.mu.Unlock()
return p.GameState
}
func (p *Prophet) captureStartMessage() {
for i := 0; i < 5; i++ {
if global.GetUserInfo().MacHash != "" {
break
}
time.Sleep(time.Second * 2)
}
sentry.CaptureMessage(global.AppName + "已启动")
}
func (p *Prophet) initGin() {
if p.opts.debug {
gin.SetMode(gin.DebugMode)
} else {
gin.SetMode(gin.ReleaseMode)
}
engine := gin.New()
engine.Use(gin.Recovery())
engine.Use(gin.LoggerWithFormatter(ginApp.LogFormatter))
if p.opts.enablePprof {
pprof.RouteRegister(engine.Group(""))
}
engine.Use(ginApp.PrepareProc)
engine.Use(sentryGin.New(sentryGin.Options{
Repanic: true,
Timeout: 3 * time.Second,
}))
engine.Use(ginApp.Cors())
engine.Use(ginApp.ErrHandler)
RegisterRoutes(engine, p.api)
srv := &http.Server{
Addr: p.opts.httpAddr,
Handler: engine,
}
p.httpSrv = srv
}
func (p *Prophet) initWebview() {
clientCfg := global.GetClientConf()
defaultUrl := "https://lol.buffge.com/dev/client?version=" + APPVersion
websiteUrl := defaultUrl
if clientCfg.ShouldAutoOpenBrowser != nil && !*clientCfg.ShouldAutoOpenBrowser {
log.Println("自动打开浏览器选项已关闭,手动打开请访问 " + websiteUrl)
return
}
// windowWeight := 1000
// windowHeight := 650
cmd := exec.Command("cmd", "/c", "start", websiteUrl)
_ = cmd.Run()
log.Println("界面已在浏览器中打开,若未打开请手动访问 " + websiteUrl)
return
}
func (p *Prophet) ChampionSelectStart() {
clientCfg := global.GetClientConf()
sendConversationMsgDelayCtx, cancel := context.WithTimeout(context.Background(),
time.Second*time.Duration(clientCfg.ChooseChampSendMsgDelaySec))
defer cancel()
var conversationID string
var summonerIDList []int64
for i := 0; i < 3; i++ {
time.Sleep(time.Second)
// 获取队伍所有用户信息
conversationID, summonerIDList, _ = getTeamUsers()
if len(summonerIDList) != 5 {
continue
}
}
// if !false && global.IsDevMode() {
//summonerIDList = []int64{2964390005, 4103784618, 4132401993, 4118593599, 4019221688}
// // summonerIDList = []int64{4006944917}
// }
if len(summonerIDList) == 0 {
return
}
logger.Debug("队伍人员列表:", zap.Any("summonerIDList", summonerIDList))
// 查询所有用户的信息并计算得分
g := errgroup.Group{}
summonerScores := make([]*lcu.UserScore, 0, 5)
mu := sync.Mutex{}
summonerIDMapInfo, err := listSummoner(summonerIDList)
if err != nil {
logger.Error("查询召唤师信息失败", zap.Error(err), zap.Any("summonerIDList", summonerIDList))
return
}
for _, summoner := range summonerIDMapInfo {
summoner := summoner
summonerID := summoner.SummonerId
g.Go(func() error {
actScore, err := GetUserScore(summoner)
if err != nil {
logger.Error("计算用户得分失败", zap.Error(err), zap.Int64("summonerID", summonerID))
return nil
}
mu.Lock()
summonerScores = append(summonerScores, actScore)
mu.Unlock()
return nil
})
}
_ = g.Wait()
slices.SortFunc(summonerScores, func(a, b *lcu.UserScore) int {
return cmp.Compare(b.Score, a.Score)
})
// 根据所有用户的分数判断小代上等马中等马下等马
//for _, score := range summonerIDMapScore {
// fmt.Printf("用户:%s,得分:%.2f\n", score.SummonerName, score.Score)
//}
scoreCfg := global.GetScoreConf()
allMsg := ""
mergedMsg := ""
// 发送到选人界面
for _, scoreInfo := range summonerScores {
var horse string
horseIdx := 0
for i, v := range scoreCfg.Horse {
if scoreInfo.Score >= v.Score {
horse = clientCfg.HorseNameConf[i]
horseIdx = i
break
}
}
currKDASb := strings.Builder{}
for i := 0; i < 5 && i < len(scoreInfo.CurrKDA); i++ {
currKDASb.WriteString(fmt.Sprintf("%d/%d/%d ", scoreInfo.CurrKDA[i][0], scoreInfo.CurrKDA[i][1],
scoreInfo.CurrKDA[i][2]))
}
currKDAMsg := currKDASb.String()
if len(currKDAMsg) > 0 {
currKDAMsg = currKDAMsg[:len(currKDAMsg)-1]
}
msg := fmt.Sprintf("%s(%d): %s %s", horse, int(scoreInfo.Score), scoreInfo.SummonerName,
currKDAMsg)
<-sendConversationMsgDelayCtx.Done()
if clientCfg.AutoSendTeamHorse {
mergedMsg += msg + "\n"
}
if !clientCfg.AutoSendTeamHorse {
if !scoreCfg.MergeMsg && !clientCfg.ShouldSendSelfHorse && p.currSummoner != nil &&
scoreInfo.SummonerID == p.currSummoner.SummonerId {
continue
}
allMsg += msg + "\n"
mergedMsg += msg + "\n"
continue
}
if !clientCfg.ShouldSendSelfHorse && p.currSummoner != nil &&
scoreInfo.SummonerID == p.currSummoner.SummonerId {
continue
}
if !clientCfg.ChooseSendHorseMsg[horseIdx] {
continue
}
if scoreCfg.MergeMsg {
continue
}
_ = SendConversationMsg(msg, conversationID)
time.Sleep(time.Millisecond * 2100)
}
if !clientCfg.AutoSendTeamHorse {
_ = clipboard.WriteAll(allMsg)
fmt.Println("已将队伍马匹信息复制到剪切板 ", time.Now().Format(time.DateTime))
fmt.Println()
fmt.Println(allMsg)
return
}
if scoreCfg.MergeMsg {
_ = SendConversationMsg(mergedMsg, conversationID)
}
}
func (p *Prophet) AcceptGame() {
_ = lcu.AcceptGame()
}
func (p *Prophet) CalcEnemyTeamScore() {
// 获取当前游戏进程
session, err := lcu.QueryGameFlowSession()
if err != nil {
return
}
if session.Phase != models.GameFlowInProgress {
return
}
if p.currSummoner == nil {
return
}
selfID := p.currSummoner.SummonerId
selfTeamUsers, enemyTeamUsers := getAllUsersFromSession(selfID, session)
_ = selfTeamUsers
summonerIDList := enemyTeamUsers
// if !false && global.IsDevMode() {
// summonerIDList = []int64{2964390005, 4103784618, 4132401993, 4118593599, 4019221688}
// // summonerIDList = []int64{4006944917}
// }
logger.Debug("敌方队伍人员列表:", zap.Any("summonerIDList", summonerIDList))
if len(summonerIDList) == 0 {
return
}
// 查询所有用户的信息并计算得分
g := errgroup.Group{}
summonerScores := make([]*lcu.UserScore, 0, 5)
mu := sync.Mutex{}
summonerIDMapInfo, err := listSummoner(summonerIDList)
if err != nil {
logger.Error("查询召唤师信息失败", zap.Error(err), zap.Any("summonerIDList", summonerIDList))
return
}
for _, summoner := range summonerIDMapInfo {
summoner := summoner
summonerID := summoner.SummonerId
g.Go(func() error {
actScore, err := GetUserScore(summoner)
if err != nil {
logger.Error("计算用户得分失败", zap.Error(err), zap.Int64("summonerID", summonerID))
return nil
}
mu.Lock()
summonerScores = append(summonerScores, actScore)
//summonerIDMapScore[summonerID] = *actScore
mu.Unlock()
return nil
})
}
scoreCfg := global.GetScoreConf()
clientCfg := global.GetClientConf()
_ = g.Wait()
if len(summonerScores) > 0 {
fmt.Println("敌方用户详情:")
}
slices.SortFunc(summonerScores, func(a, b *lcu.UserScore) int {
return cmp.Compare(b.Score, a.Score)
})
// 根据所有用户的分数判断小代上等马中等马下等马
for _, score := range summonerScores {
var horse string
for i, v := range scoreCfg.Horse {
if score.Score >= v.Score {
horse = clientCfg.HorseNameConf[i]
break
}
}
currKDASb := strings.Builder{}
for i := 0; i < 5 && i < len(score.CurrKDA); i++ {
currKDASb.WriteString(fmt.Sprintf("%d/%d/%d ", score.CurrKDA[i][0], score.CurrKDA[i][1],
score.CurrKDA[i][2]))
}
currKDAMsg := currKDASb.String()
//log.Printf("敌方用户:%s (%s) 得分:%.2f,kda:%s\n", score.SummonerName, horse, score.Score, currKDAMsg)
fmt.Printf("%s(%d): %s %s\n", horse, int(score.Score), score.SummonerName,
currKDAMsg)
}
allMsg := ""
// 发送到选人界面
for _, scoreInfo := range summonerScores {
time.Sleep(time.Second / 2)
var horse string
// horseIdx := 0
for i, v := range scoreCfg.Horse {
if scoreInfo.Score >= v.Score {
horse = clientCfg.HorseNameConf[i]
// horseIdx = i
break
}
}
currKDASb := strings.Builder{}
for i := 0; i < 5 && i < len(scoreInfo.CurrKDA); i++ {
currKDASb.WriteString(fmt.Sprintf("%d/%d/%d ", scoreInfo.CurrKDA[i][0], scoreInfo.CurrKDA[i][1],
scoreInfo.CurrKDA[i][2]))
}
currKDAMsg := currKDASb.String()
if len(currKDAMsg) > 0 {
currKDAMsg = currKDAMsg[:len(currKDAMsg)-1]
}
msg := fmt.Sprintf("%s(%d): %s %s -- %s", horse, int(scoreInfo.Score), scoreInfo.SummonerName,
currKDAMsg, global.AdaptChatWebsiteTitle)
allMsg += msg + "\n"
}
_ = clipboard.WriteAll(allMsg)
}
func (p *Prophet) onChampSelectSessionUpdate(sessionInfo *lcu.ChampSelectSessionInfo) error {
var userPickActionID, userBanActionID, pickChampionID int
var isSelfPick, isSelfBan, pickIsInProgress, banIsInProgress bool
alloyPrePickChampionIDSet := make(map[int]struct{}, 5)
if len(sessionInfo.Actions) == 0 {
return nil
}
for _, actions := range sessionInfo.Actions {
for _, action := range actions {
if action.IsAllyAction && action.Type == lcu.ChampSelectPatchTypePick && action.ChampionId > 0 {
alloyPrePickChampionIDSet[action.ChampionId] = struct{}{}
}
if action.ActorCellId != sessionInfo.LocalPlayerCellId {
continue
}
if action.Type == lcu.ChampSelectPatchTypePick {
isSelfPick = true
userPickActionID = action.Id
pickChampionID = action.ChampionId
pickIsInProgress = action.IsInProgress
} else if action.Type == lcu.ChampSelectPatchTypeBan {
isSelfBan = true
userBanActionID = action.Id
banIsInProgress = action.IsInProgress
}
break
}
}
clientCfg := global.GetClientConf()
if clientCfg.AutoPickChampID > 0 && isSelfPick {
if pickIsInProgress {
_ = lcu.PickChampion(clientCfg.AutoPickChampID, userPickActionID)
} else if pickChampionID == 0 {
_ = lcu.PrePickChampion(clientCfg.AutoPickChampID, userPickActionID)
}
}
if clientCfg.AutoBanChampID > 0 && isSelfBan && banIsInProgress {
if _, exist := alloyPrePickChampionIDSet[clientCfg.AutoBanChampID]; !exist {
_ = lcu.BanChampion(clientCfg.AutoBanChampID, userBanActionID)
}
}
return nil
}
func (p *Prophet) SetupFakerOffline() error {
data := lcu.UpdateSummonerProfileData{
Availability: lcu.AvailabilityOffline,
}
return lcu.UpdateSummonerProfile(data)
}