github.com/LagrangeDev/LagrangeGo@v0.0.0-20240512064304-ad4a85e10cb4/client/packets/oidb/builder.go (about) 1 package oidb 2 3 import ( 4 "errors" 5 "fmt" 6 7 "github.com/LagrangeDev/LagrangeGo/client/packets/pb/service/oidb" 8 "github.com/LagrangeDev/LagrangeGo/internal/proto" 9 "github.com/LagrangeDev/LagrangeGo/utils" 10 ) 11 12 // var oidbLogger = utils.GetLogger("oidb") 13 14 type OidbPacket struct { 15 Cmd string 16 Data []byte 17 ExtraData []byte 18 } 19 20 func BuildOidbPacket(cmd, subCmd uint32, body any, isLafter, isUid bool) (*OidbPacket, error) { 21 bodyData, err := proto.Marshal(body) 22 if err != nil { 23 return nil, err 24 } 25 oidbPkt := &oidb.OidbSvcTrpcTcpBase{ 26 Command: cmd, 27 SubCommand: subCmd, 28 Body: bodyData, 29 Reserved: int32(utils.Bool2Int(isUid)), 30 } 31 if isLafter { 32 oidbPkt.Lafter = &oidb.OidbLafter{} 33 } 34 35 data, err := proto.Marshal(oidbPkt) 36 if err != nil { 37 return nil, err 38 } 39 40 return &OidbPacket{ 41 Cmd: fmt.Sprintf("OidbSvcTrpcTcp.0x%02x_%d", cmd, subCmd), 42 Data: data, 43 }, nil 44 } 45 46 func ParseOidbPacket(b []byte, pkt any) (oidbBaseResp oidb.OidbSvcTrpcTcpBase, err error) { 47 err = proto.Unmarshal(b, &oidbBaseResp) 48 if err != nil { 49 return 50 } 51 if pkt == nil { 52 return 53 } 54 err = proto.Unmarshal(oidbBaseResp.Body, pkt) 55 return 56 } 57 58 func CheckError(data []byte) error { 59 baseResp, err := ParseOidbPacket(data, nil) 60 if err != nil { 61 return err 62 } 63 if baseResp.ErrorCode != 0 { 64 return errors.New(baseResp.ErrorMsg) 65 } 66 return nil 67 } 68 69 func CheckTypedError[T any](data []byte) error { 70 var resp T 71 baseResp, err := ParseOidbPacket(data, &resp) 72 if err != nil { 73 return err 74 } 75 if baseResp.ErrorCode != 0 { 76 return errors.New(baseResp.ErrorMsg) 77 } 78 return nil 79 }