Files
csgowtfd/csgo/demo_loader.go
2021-10-05 20:27:31 +02:00

271 lines
7.1 KiB
Go

package csgo
import (
"encoding/json"
"fmt"
"github.com/an0nfunc/go-steam/v3"
"github.com/an0nfunc/go-steam/v3/csgo/protocol/protobuf"
"github.com/an0nfunc/go-steam/v3/netutil"
"github.com/an0nfunc/go-steam/v3/protocol/gamecoordinator"
"github.com/an0nfunc/go-steam/v3/protocol/steamlang"
log "github.com/sirupsen/logrus"
"google.golang.org/protobuf/proto"
"io/ioutil"
"math/rand"
"os"
"time"
)
//goland:noinspection SpellCheckingInspection
const (
APPID = 730
)
type DemoMatchLoader struct {
client *steam.Client
GCReady bool
steamLogin *steam.LogOnDetails
matchRecv chan *protobuf.CMsgGCCStrike15V2_MatchList
cmList []*netutil.PortAddr
sentryFile string
loginKey string
serverList string
}
func AccountId2SteamId(accId uint32) uint64 {
return uint64(accId) + 76561197960265728
}
func SteamId2AccountId(steamId uint64) uint32 {
return uint32(steamId - 76561197960265728)
}
func (d *DemoMatchLoader) HandleGCPacket(pkg *gamecoordinator.GCPacket) {
switch pkg.MsgType {
case uint32(protobuf.EGCBaseClientMsg_k_EMsgGCClientWelcome):
msg := &protobuf.CMsgClientWelcome{}
err := proto.Unmarshal(pkg.Body, msg)
if err != nil {
log.Errorf("[DL] Unable to unmarshal event %v: %v", pkg.MsgType, err)
}
log.Debugf("[GC] Welcome: %+v", msg)
d.GCReady = true
case uint32(protobuf.EGCBaseClientMsg_k_EMsgGCClientConnectionStatus):
msg := &protobuf.CMsgConnectionStatus{}
err := proto.Unmarshal(pkg.Body, msg)
if err != nil {
log.Errorf("[DL] Unable to unmarshal event %v: %v", pkg.MsgType, err)
}
log.Debugf("[GC] Status: %+v", msg)
if msg.GetStatus() != protobuf.GCConnectionStatus_GCConnectionStatus_HAVE_SESSION {
d.GCReady = false
go d.greetGC()
}
case uint32(protobuf.ECsgoGCMsg_k_EMsgGCCStrike15_v2_GC2ClientGlobalStats):
msg := &protobuf.GlobalStatistics{}
err := proto.Unmarshal(pkg.Body, msg)
if err != nil {
log.Errorf("[DL] Unable to unmarshal event %v: %v", pkg.MsgType, err)
}
log.Debugf("[GC] Stats: %+v", msg)
d.GCReady = true
case uint32(protobuf.ECsgoGCMsg_k_EMsgGCCStrike15_v2_MatchList):
msg := &protobuf.CMsgGCCStrike15V2_MatchList{}
err := proto.Unmarshal(pkg.Body, msg)
if err != nil {
log.Errorf("[DL] Unable to unmarshal event %v: %v", pkg.MsgType, err)
}
d.matchRecv <- msg
default:
log.Debugf("[GC] Unhandled GC message: %+v", pkg)
}
}
func (d *DemoMatchLoader) GetMatchDetails(sharecode string) (*protobuf.CMsgGCCStrike15V2_MatchList, error) {
if !d.GCReady {
return nil, fmt.Errorf("gc not ready")
}
matchId, outcomeId, tokenId, err := DecodeSharecode(sharecode)
if err != nil {
return nil, err
}
err = d.RequestDemoInfo(matchId, outcomeId, tokenId)
if err != nil {
return nil, err
}
for {
select {
case match := <-d.matchRecv:
if *match.Matches[0].Matchid == matchId {
return match, nil
} else {
d.matchRecv <- match
}
}
}
}
func (d *DemoMatchLoader) getRandomCM() *netutil.PortAddr {
return d.cmList[rand.Intn(len(d.cmList))]
}
func (d *DemoMatchLoader) connectToSteam() error {
if d.cmList != nil {
err := d.client.ConnectTo(d.getRandomCM())
if err != nil {
return err
}
} else {
_, err := d.client.Connect()
if err != nil {
return err
}
}
return nil
}
func (d *DemoMatchLoader) Setup(username string, password string, authCode string, sentry string, loginKey string, serverList string) error {
d.loginKey = loginKey
d.sentryFile = sentry
d.serverList = serverList
d.steamLogin = new(steam.LogOnDetails)
d.steamLogin.Username = username
d.steamLogin.Password = password
d.steamLogin.AuthCode = authCode
d.steamLogin.ShouldRememberPassword = true
if _, err := os.Stat(d.sentryFile); err == nil {
hash, err := ioutil.ReadFile(d.sentryFile)
if err != nil {
return err
}
d.steamLogin.SentryFileHash = hash
}
if _, err := os.Stat(d.loginKey); err == nil {
hash, err := ioutil.ReadFile(d.loginKey)
if err != nil {
return err
}
d.steamLogin.LoginKey = string(hash)
}
if _, err := os.Stat(d.serverList); err == nil {
rawJson, err := ioutil.ReadFile(d.serverList)
if err != nil {
return err
}
err = json.Unmarshal(rawJson, &d.cmList)
if err != nil {
return err
}
}
d.client = steam.NewClient()
d.matchRecv = make(chan *protobuf.CMsgGCCStrike15V2_MatchList, 500)
go d.connectLoop()
go d.steamEventHandler()
return nil
}
func (d DemoMatchLoader) connectLoop() {
for d.connectToSteam() != nil {
log.Infof("Retrying connecting to steam")
time.Sleep(time.Second)
}
}
func (d *DemoMatchLoader) steamEventHandler() {
for event := range d.client.Events() {
switch e := event.(type) {
case *steam.ConnectedEvent:
log.Debug("[DL] Connected!")
d.client.Auth.LogOn(d.steamLogin)
case *steam.ClientCMListEvent:
log.Debug("[DL] CM list")
serverJson, err := json.Marshal(e.Addresses)
if err != nil {
log.Errorf("[DL] Unable to marshal JSON: %v", err)
}
err = ioutil.WriteFile(d.serverList, serverJson, os.ModePerm)
if err != nil {
log.Errorf("[DL] Unable to write server list: %v", err)
}
case *steam.MachineAuthUpdateEvent:
log.Debug("[DL] Got sentry!")
err := ioutil.WriteFile(d.sentryFile, e.Hash, os.ModePerm)
if err != nil {
log.Errorf("[DL] Unable write sentry file: %v", err)
}
case *steam.LoggedOnEvent:
log.Debug("[DL] Login successfully!")
d.client.Social.SetPersonaState(steamlang.EPersonaState_Online)
go d.SetPlaying()
case *steam.LogOnFailedEvent:
log.Warningf("[DL] Steam login denied: %+v", e)
switch e.Result {
case steamlang.EResult_AccountLogonDenied:
log.Fatalf("[DL] Please provide AuthCode with --authcode")
case steamlang.EResult_InvalidPassword:
os.Remove(d.sentryFile)
os.Remove(d.loginKey)
log.Fatalf("[DL] Steam login wrong")
}
case *steam.DisconnectedEvent:
log.Warningf("Steam disconnected, trying to reconnect...")
_, err := d.client.Connect()
if err != nil {
log.Errorf("[DL] Unable to reconnect to steam: %v", err)
}
case *steam.LoginKeyEvent:
log.Debug("Got login_key!")
err := ioutil.WriteFile(d.loginKey, []byte(e.LoginKey), os.ModePerm)
if err != nil {
log.Errorf("[DL] Unable write login_key: %v", err)
}
case steam.FatalErrorEvent:
log.Debugf("[DL] Got FatalError %+v", e)
case error:
log.Fatalf("[DL] Got error %+v", e)
default:
log.Debugf("[DL] %T: %v", e, e)
}
}
}
func (d *DemoMatchLoader) SetPlaying() {
d.client.GC.SetGamesPlayed(APPID)
d.client.GC.RegisterPacketHandler(d)
go d.greetGC()
}
func (d *DemoMatchLoader) greetGC() {
for !d.GCReady {
log.Debugf("[DL] Sending GC greeting")
msg := protobuf.CMsgClientHello{}
d.client.GC.Write(gamecoordinator.NewGCMsgProtobuf(APPID, uint32(protobuf.EGCBaseClientMsg_k_EMsgGCClientHello), &msg))
time.Sleep(500 * time.Millisecond)
}
}
func (d *DemoMatchLoader) RequestDemoInfo(matchId uint64, conclusionId uint64, tokenId uint32) error {
if !d.GCReady {
return fmt.Errorf("gc not ready")
}
msg := protobuf.CMsgGCCStrike15V2_MatchListRequestFullGameInfo{Matchid: &matchId,
Outcomeid: &conclusionId,
Token: &tokenId}
d.client.GC.Write(gamecoordinator.NewGCMsgProtobuf(APPID, uint32(protobuf.ECsgoGCMsg_k_EMsgGCCStrike15_v2_MatchListRequestFullGameInfo), &msg))
return nil
}