Stop using stdlib log

This commit is contained in:
Tulir Asokan 2023-06-30 14:48:50 +03:00
parent bbca40d74b
commit 2f5c5e2c6d
14 changed files with 36 additions and 53 deletions

View file

@ -3,7 +3,6 @@ package libgm
import ( import (
"encoding/base64" "encoding/base64"
"io" "io"
"log"
"net/http" "net/http"
"net/url" "net/url"
"time" "time"
@ -91,7 +90,7 @@ func (c *Client) SetProxy(proxy string) error {
func (c *Client) Connect(rpcKey string) error { func (c *Client) Connect(rpcKey string) error {
rpcPayload, receiveMesageSessionId, err := payload.ReceiveMessages(rpcKey) rpcPayload, receiveMesageSessionId, err := payload.ReceiveMessages(rpcKey)
if err != nil { if err != nil {
log.Fatal(err) panic(err)
return err return err
} }
c.rpc.rpcSessionId = receiveMesageSessionId c.rpc.rpcSessionId = receiveMesageSessionId
@ -114,7 +113,7 @@ func (c *Client) Reconnect(rpcKey string) error {
c.Logger.Debug().Any("rpcKey", rpcKey).Msg("Successfully reconnected to server") c.Logger.Debug().Any("rpcKey", rpcKey).Msg("Successfully reconnected to server")
sendInitialDataErr := c.rpc.sendInitialData() sendInitialDataErr := c.rpc.sendInitialData()
if sendInitialDataErr != nil { if sendInitialDataErr != nil {
log.Fatal(sendInitialDataErr) panic(sendInitialDataErr)
} }
return nil return nil
} }
@ -155,7 +154,7 @@ func (c *Client) decryptImages(messages *binary.FetchMessagesResponse) error {
case *binary.MessageInfo_ImageContent: case *binary.MessageInfo_ImageContent:
decryptedImageData, err := c.decryptImageData(data.ImageContent.ImageId, data.ImageContent.DecryptionKey) decryptedImageData, err := c.decryptImageData(data.ImageContent.ImageId, data.ImageContent.DecryptionKey)
if err != nil { if err != nil {
log.Fatal(err) panic(err)
return err return err
} }
data.ImageContent.ImageData = decryptedImageData data.ImageContent.ImageData = decryptedImageData
@ -213,7 +212,7 @@ func (c *Client) decryptImageData(imageId string, key []byte) ([]byte, error) {
c.imageCryptor.UpdateDecryptionKey(key) c.imageCryptor.UpdateDecryptionKey(key)
decryptedImageBytes, decryptionErr := c.imageCryptor.DecryptData(encryptedBuffImg) decryptedImageBytes, decryptionErr := c.imageCryptor.DecryptData(encryptedBuffImg)
if decryptionErr != nil { if decryptionErr != nil {
log.Println("Error:", decryptionErr) c.Logger.Err(err).Msg("Image decryption failed")
return nil, decryptionErr return nil, decryptionErr
} }
return decryptedImageBytes, nil return decryptedImageBytes, nil

View file

@ -2,7 +2,6 @@ package libgm
import ( import (
"fmt" "fmt"
"log"
"go.mau.fi/mautrix-gmessages/libgm/binary" "go.mau.fi/mautrix-gmessages/libgm/binary"
) )
@ -45,7 +44,7 @@ func (c *Conversations) SendMessage(messageBuilder *MessageBuilder, selfParticip
encryptedProtoPayload, failedToBuild := messageBuilder.Build() encryptedProtoPayload, failedToBuild := messageBuilder.Build()
if failedToBuild != nil { if failedToBuild != nil {
log.Fatal(failedToBuild) panic(failedToBuild)
} }
instruction, _ := c.client.instructions.GetInstruction(SEND_TEXT_MESSAGE) instruction, _ := c.client.instructions.GetInstruction(SEND_TEXT_MESSAGE)
@ -54,7 +53,7 @@ func (c *Conversations) SendMessage(messageBuilder *MessageBuilder, selfParticip
responses, err := c.client.sessionHandler.WaitForResponse(sentRequestId, instruction.Opcode) responses, err := c.client.sessionHandler.WaitForResponse(sentRequestId, instruction.Opcode)
if err != nil { if err != nil {
log.Fatal(err) panic(err)
return nil, err return nil, err
} }

View file

@ -2,7 +2,6 @@ package crypto
import ( import (
"crypto/rand" "crypto/rand"
"log"
) )
func GenerateKey(length int) ([]byte, error) { func GenerateKey(length int) ([]byte, error) {
@ -17,11 +16,11 @@ func GenerateKey(length int) ([]byte, error) {
func GenerateKeys() ([]byte, []byte) { func GenerateKeys() ([]byte, []byte) {
key, err := GenerateKey(32) key, err := GenerateKey(32)
if err != nil { if err != nil {
log.Fatal(err) panic(err)
} }
key2, err2 := GenerateKey(32) key2, err2 := GenerateKey(32)
if err2 != nil { if err2 != nil {
log.Fatal(err2) panic(err2)
} }
return key, key2 return key, key2
} }

View file

@ -1,17 +1,15 @@
package libgm package libgm
import ( import (
"log"
"go.mau.fi/mautrix-gmessages/libgm/binary" "go.mau.fi/mautrix-gmessages/libgm/binary"
) )
func (c *Client) handleEventOpCode(response *Response) { func (c *Client) handleEventOpCode(response *Response) {
//c.Logger.Debug().Any("res", response).Msg("got event response") c.Logger.Debug().Any("res", response).Msg("got event response?")
eventData := &binary.Event{} eventData := &binary.Event{}
decryptedErr := c.cryptor.DecryptAndDecodeData(response.Data.EncryptedData, eventData) decryptedErr := c.cryptor.DecryptAndDecodeData(response.Data.EncryptedData, eventData)
if decryptedErr != nil { if decryptedErr != nil {
log.Fatal(decryptedErr) panic(decryptedErr)
} }
switch evt := eventData.Event.(type) { switch evt := eventData.Event.(type) {
case *binary.Event_MessageEvent: case *binary.Event_MessageEvent:

View file

@ -5,7 +5,6 @@ import (
"encoding/base64" "encoding/base64"
"errors" "errors"
"io" "io"
"log"
"net/http" "net/http"
"strconv" "strconv"
@ -40,7 +39,6 @@ func (c *Client) FinalizeUploadMedia(upload *StartGoogleUpload) (*MediaUpload, e
imageType := upload.Image.GetImageType() imageType := upload.Image.GetImageType()
encryptedImageSize := strconv.Itoa(len(upload.EncryptedMediaBytes)) encryptedImageSize := strconv.Itoa(len(upload.EncryptedMediaBytes))
log.Println("EncryptedImageSize:", encryptedImageSize)
finalizeUploadHeaders := util.NewMediaUploadHeaders(encryptedImageSize, "upload, finalize", "0", imageType.Format, "") finalizeUploadHeaders := util.NewMediaUploadHeaders(encryptedImageSize, "upload, finalize", "0", imageType.Format, "")
req, reqErr := http.NewRequest("POST", upload.UploadUrl, bytes.NewBuffer(upload.EncryptedMediaBytes)) req, reqErr := http.NewRequest("POST", upload.UploadUrl, bytes.NewBuffer(upload.EncryptedMediaBytes))
if reqErr != nil { if reqErr != nil {
@ -51,7 +49,7 @@ func (c *Client) FinalizeUploadMedia(upload *StartGoogleUpload) (*MediaUpload, e
res, resErr := c.http.Do(req) res, resErr := c.http.Do(req)
if resErr != nil { if resErr != nil {
log.Fatal(resErr) panic(resErr)
} }
statusCode := res.StatusCode statusCode := res.StatusCode
@ -68,7 +66,7 @@ func (c *Client) FinalizeUploadMedia(upload *StartGoogleUpload) (*MediaUpload, e
} }
uploadStatus := rHeaders.Get("x-goog-upload-status") uploadStatus := rHeaders.Get("x-goog-upload-status")
log.Println("Upload Status: ", uploadStatus) c.Logger.Debug().Str("upload_status", uploadStatus).Msg("Upload status")
mediaIds := &binary.UploadMediaResponse{} mediaIds := &binary.UploadMediaResponse{}
err3 = crypto.DecodeAndEncodeB64(string(googleResponse), mediaIds) err3 = crypto.DecodeAndEncodeB64(string(googleResponse), mediaIds)
@ -106,7 +104,7 @@ func (c *Client) StartUploadMedia(image *Image) (*StartGoogleUpload, error) {
res, resErr := c.http.Do(req) res, resErr := c.http.Do(req)
if resErr != nil { if resErr != nil {
log.Fatal(resErr) panic(resErr)
} }
statusCode := res.StatusCode statusCode := res.StatusCode

View file

@ -2,7 +2,6 @@ package libgm
import ( import (
"errors" "errors"
"log"
"go.mau.fi/mautrix-gmessages/libgm/binary" "go.mau.fi/mautrix-gmessages/libgm/binary"
"go.mau.fi/mautrix-gmessages/libgm/util" "go.mau.fi/mautrix-gmessages/libgm/util"
@ -147,7 +146,6 @@ func (mb *MessageBuilder) newSendConversationMessage() *binary.SendMessagePayloa
func (mb *MessageBuilder) appendImagesPayload(messageInfo *[]*binary.MessageInfo) { func (mb *MessageBuilder) appendImagesPayload(messageInfo *[]*binary.MessageInfo) {
if len(mb.images) <= 0 { if len(mb.images) <= 0 {
log.Println("0 images to append, ignoring")
return return
} }

View file

@ -1,7 +1,6 @@
package libgm package libgm
import ( import (
"log"
"os" "os"
"go.mau.fi/mautrix-gmessages/libgm/builders" "go.mau.fi/mautrix-gmessages/libgm/builders"
@ -19,7 +18,7 @@ func (m *Misc) TenorSearch(searchOpts *builders.TenorSearch) (interface{}, error
} }
uri := util.TENOR_SEARCH_GIF + searchQuery uri := util.TENOR_SEARCH_GIF + searchQuery
log.Println(uri) m.client.Logger.Debug().Msg(uri)
os.Exit(1) os.Exit(1)
return nil, nil return nil, nil
} }

View file

@ -3,7 +3,6 @@ package libgm
import ( import (
"encoding/json" "encoding/json"
"fmt" "fmt"
"log"
"go.mau.fi/mautrix-gmessages/libgm/binary" "go.mau.fi/mautrix-gmessages/libgm/binary"
"go.mau.fi/mautrix-gmessages/libgm/pblite" "go.mau.fi/mautrix-gmessages/libgm/pblite"
@ -26,6 +25,7 @@ func (r *RPC) HandleRPCMsg(msgArr []interface{}) {
response := &binary.RPCResponse{} response := &binary.RPCResponse{}
deserializeErr := pblite.Deserialize(msgArr, response.ProtoReflect()) deserializeErr := pblite.Deserialize(msgArr, response.ProtoReflect())
if deserializeErr != nil { if deserializeErr != nil {
r.client.Logger.Error().Err(deserializeErr).Msg("meow")
r.client.Logger.Error().Err(fmt.Errorf("failed to deserialize response %s", msgArr)).Msg("rpc deserialize msg err") r.client.Logger.Error().Err(fmt.Errorf("failed to deserialize response %s", msgArr)).Msg("rpc deserialize msg err")
return return
} }
@ -37,7 +37,7 @@ func (r *RPC) HandleRPCMsg(msgArr []interface{}) {
if response.Data.RoutingOpCode == 19 { if response.Data.RoutingOpCode == 19 {
parsedResponse, failedParse := r.client.sessionHandler.NewResponse(response) parsedResponse, failedParse := r.client.sessionHandler.NewResponse(response)
if failedParse != nil { if failedParse != nil {
log.Fatal(failedParse) panic(failedParse)
} }
//hasBody := parsedResponse.Data.EncryptedData == nil //hasBody := parsedResponse.Data.EncryptedData == nil
//r.client.Logger.Info().Any("msgData", parsedResponse).Msg("Got event!") //r.client.Logger.Info().Any("msgData", parsedResponse).Msg("Got event!")

View file

@ -2,7 +2,6 @@ package libgm
import ( import (
"encoding/base64" "encoding/base64"
"log"
"go.mau.fi/mautrix-gmessages/libgm/binary" "go.mau.fi/mautrix-gmessages/libgm/binary"
) )
@ -10,14 +9,14 @@ import (
func (c *Client) handleSeperateOpCode(msgData *binary.MessageData) { func (c *Client) handleSeperateOpCode(msgData *binary.MessageData) {
decodedBytes, err := base64.StdEncoding.DecodeString(msgData.EncodedData) decodedBytes, err := base64.StdEncoding.DecodeString(msgData.EncodedData)
if err != nil { if err != nil {
log.Fatal(err) panic(err)
} }
switch msgData.RoutingOpCode { switch msgData.RoutingOpCode {
case 14: // paired successful case 14: // paired successful
decodedData := &binary.Container{} decodedData := &binary.Container{}
err = binary.DecodeProtoMessage(decodedBytes, decodedData) err = binary.DecodeProtoMessage(decodedBytes, decodedData)
if err != nil { if err != nil {
log.Fatal(err) panic(err)
} }
c.Logger.Debug().Any("data", decodedData).Msg("Paired device decoded data") c.Logger.Debug().Any("data", decodedData).Msg("Paired device decoded data")
c.pairer.pairCallback(decodedData) c.pairer.pairCallback(decodedData)
@ -25,13 +24,13 @@ func (c *Client) handleSeperateOpCode(msgData *binary.MessageData) {
decodedData := &binary.EncodedResponse{} decodedData := &binary.EncodedResponse{}
err = binary.DecodeProtoMessage(decodedBytes, decodedData) err = binary.DecodeProtoMessage(decodedBytes, decodedData)
if err != nil { if err != nil {
log.Fatal(err) panic(err)
} }
if (decodedData.Sub && decodedData.Third != 0) && decodedData.EncryptedData != nil { if (decodedData.Sub && decodedData.Third != 0) && decodedData.EncryptedData != nil {
bugleData := &binary.BugleBackendService{} bugleData := &binary.BugleBackendService{}
err = c.cryptor.DecryptAndDecodeData(decodedData.EncryptedData, bugleData) err = c.cryptor.DecryptAndDecodeData(decodedData.EncryptedData, bugleData)
if err != nil { if err != nil {
log.Fatal(err) panic(err)
} }
c.handleBugleOpCode(bugleData) c.handleBugleOpCode(bugleData)
} }

View file

@ -3,7 +3,6 @@ package libgm
import ( import (
"encoding/base64" "encoding/base64"
"io" "io"
"log"
"time" "time"
"go.mau.fi/mautrix-gmessages/libgm/binary" "go.mau.fi/mautrix-gmessages/libgm/binary"
@ -113,7 +112,7 @@ func (p *Pairer) RefreshPhoneRelay() {
p.client.Logger.Debug().Any("res", res).Msg("RefreshPhoneRelayResponse") p.client.Logger.Debug().Any("res", res).Msg("RefreshPhoneRelayResponse")
url, qrErr := p.GenerateQRCodeData() url, qrErr := p.GenerateQRCodeData()
if qrErr != nil { if qrErr != nil {
log.Fatal(qrErr) panic(qrErr)
} }
p.client.triggerEvent(&events.QRCODE_UPDATED{URL: url}) p.client.triggerEvent(&events.QRCODE_UPDATED{URL: url})
} }
@ -145,7 +144,7 @@ func (p *Pairer) GetWebEncryptionKey() {
p.ticker.Stop() p.ticker.Stop()
reconnectErr := p.client.Reconnect(key) reconnectErr := p.client.Reconnect(key)
if reconnectErr != nil { if reconnectErr != nil {
log.Fatal(reconnectErr) panic(reconnectErr)
} }
} }

View file

@ -1,14 +1,11 @@
package payload package payload
import ( import (
"log"
"go.mau.fi/mautrix-gmessages/libgm/binary" "go.mau.fi/mautrix-gmessages/libgm/binary"
"go.mau.fi/mautrix-gmessages/libgm/util" "go.mau.fi/mautrix-gmessages/libgm/util"
) )
func GetWebEncryptionKey(WebPairKey []byte) ([]byte, *binary.Container, error) { func GetWebEncryptionKey(WebPairKey []byte) ([]byte, *binary.Container, error) {
log.Println(WebPairKey)
id := util.RandomUUIDv4() id := util.RandomUUIDv4()
payload := &binary.Container{ payload := &binary.Container{
PhoneRelay: &binary.PhoneRelayBody{ PhoneRelay: &binary.PhoneRelayBody{

View file

@ -2,7 +2,6 @@ package libgm
import ( import (
"fmt" "fmt"
"log"
"sync" "sync"
) )
@ -16,7 +15,7 @@ type ResponseChan struct {
func (s *SessionHandler) addRequestToChannel(requestId string, opCode int64) { func (s *SessionHandler) addRequestToChannel(requestId string, opCode int64) {
instruction, notOk := s.client.instructions.GetInstruction(opCode) instruction, notOk := s.client.instructions.GetInstruction(opCode)
if !notOk { if !notOk {
log.Fatal(notOk) panic(notOk)
} }
if msgMap, ok := s.requests[requestId]; ok { if msgMap, ok := s.requests[requestId]; ok {
responseChan := &ResponseChan{ responseChan := &ResponseChan{
@ -67,7 +66,7 @@ func (s *SessionHandler) respondToRequestChannel(res *Response) {
opCodeResponseChan.receivedResponses++ opCodeResponseChan.receivedResponses++
opCodeResponseChan.wg.Done() opCodeResponseChan.wg.Done()
if !ok3 { if !ok3 {
log.Fatal(ok3) panic(ok3)
opCodeResponseChan.mu.Unlock() opCodeResponseChan.mu.Unlock()
return return
} }

View file

@ -4,8 +4,8 @@ import (
"bufio" "bufio"
"bytes" "bytes"
"errors" "errors"
"fmt"
"io" "io"
"log"
"net/http" "net/http"
"os" "os"
@ -24,13 +24,13 @@ type RPC struct {
func (r *RPC) ListenReceiveMessages(payload []byte) { func (r *RPC) ListenReceiveMessages(payload []byte) {
req, err := http.NewRequest("POST", util.RECEIVE_MESSAGES, bytes.NewReader(payload)) req, err := http.NewRequest("POST", util.RECEIVE_MESSAGES, bytes.NewReader(payload))
if err != nil { if err != nil {
log.Fatalf("Error creating request: %v", err) panic(fmt.Errorf("Error creating request: %v", err))
} }
util.BuildRelayHeaders(req, "application/json+protobuf", "*/*") util.BuildRelayHeaders(req, "application/json+protobuf", "*/*")
resp, reqErr := r.http.Do(req) resp, reqErr := r.http.Do(req)
//r.client.Logger.Info().Any("bodyLength", len(payload)).Any("url", util.RECEIVE_MESSAGES).Any("headers", resp.Request.Header).Msg("RPC Request Headers") //r.client.Logger.Info().Any("bodyLength", len(payload)).Any("url", util.RECEIVE_MESSAGES).Any("headers", resp.Request.Header).Msg("RPC Request Headers")
if reqErr != nil { if reqErr != nil {
log.Fatalf("Error making request: %v", err) panic(fmt.Errorf("Error making request: %v", err))
} }
r.conn = resp.Body r.conn = resp.Body
go r.startReadingData(resp.Body) go r.startReadingData(resp.Body)
@ -139,13 +139,13 @@ func (r *RPC) CloseConnection() {
func (r *RPC) sendMessageRequest(url string, payload []byte) (*http.Response, error) { func (r *RPC) sendMessageRequest(url string, payload []byte) (*http.Response, error) {
req, err := http.NewRequest("POST", url, bytes.NewReader(payload)) req, err := http.NewRequest("POST", url, bytes.NewReader(payload))
if err != nil { if err != nil {
log.Fatalf("Error creating request: %v", err) panic(fmt.Errorf("Error creating request: %v", err))
} }
util.BuildRelayHeaders(req, "application/json+protobuf", "*/*") util.BuildRelayHeaders(req, "application/json+protobuf", "*/*")
resp, reqErr := r.client.http.Do(req) resp, reqErr := r.client.http.Do(req)
//r.client.Logger.Info().Any("bodyLength", len(payload)).Any("url", url).Any("headers", resp.Request.Header).Msg("RPC Request Headers") //r.client.Logger.Info().Any("bodyLength", len(payload)).Any("url", url).Any("headers", resp.Request.Header).Msg("RPC Request Headers")
if reqErr != nil { if reqErr != nil {
log.Fatalf("Error making request: %v", err) panic(fmt.Errorf("Error making request: %v", err))
} }
return resp, reqErr return resp, reqErr
} }

View file

@ -3,7 +3,6 @@ package libgm
import ( import (
"encoding/json" "encoding/json"
"fmt" "fmt"
"log"
"time" "time"
"golang.org/x/exp/slices" "golang.org/x/exp/slices"
@ -72,7 +71,7 @@ func (c *Client) createAndSendRequest(instructionId int64, ttl int64, newSession
encodedData := payload.NewEncodedPayload(requestId, instruction.Opcode, encryptedData, c.sessionHandler.sessionId) encodedData := payload.NewEncodedPayload(requestId, instruction.Opcode, encryptedData, c.sessionHandler.sessionId)
encodedStr, encodeErr := crypto.EncodeProtoB64(encodedData) encodedStr, encodeErr := crypto.EncodeProtoB64(encodedData)
if encodeErr != nil { if encodeErr != nil {
log.Fatalf("Failed to encode data: %v", encodeErr) panic(fmt.Errorf("Failed to encode data: %w", encodeErr))
} }
messageData := payload.NewMessageData(requestId, encodedStr, instruction.RoutingOpCode, instruction.MsgType) messageData := payload.NewMessageData(requestId, encodedStr, instruction.RoutingOpCode, instruction.MsgType)
authMessage := payload.NewAuthData(requestId, c.rpcKey, &binary.Date{Year: 2023, Seq1: 6, Seq2: 8, Seq3: 4, Seq4: 6}) authMessage := payload.NewAuthData(requestId, c.rpcKey, &binary.Date{Year: 2023, Seq1: 6, Seq2: 8, Seq3: 4, Seq4: 6})
@ -147,14 +146,14 @@ func (s *SessionHandler) sendAckRequest() {
} }
dataArray, err := pblite.Serialize(ackMessagePayload.ProtoReflect()) dataArray, err := pblite.Serialize(ackMessagePayload.ProtoReflect())
if err != nil { if err != nil {
log.Fatal(err) panic(err)
} }
ackMessages := make([][]interface{}, 0) ackMessages := make([][]interface{}, 0)
for _, reqId := range s.ackMap { for _, reqId := range s.ackMap {
ackMessageData := &binary.AckMessageData{RequestId: reqId, Device: s.client.devicePair.Browser} ackMessageData := &binary.AckMessageData{RequestId: reqId, Device: s.client.devicePair.Browser}
ackMessageDataArr, err := pblite.Serialize(ackMessageData.ProtoReflect()) ackMessageDataArr, err := pblite.Serialize(ackMessageData.ProtoReflect())
if err != nil { if err != nil {
log.Fatal(err) panic(err)
} }
ackMessages = append(ackMessages, ackMessageDataArr) ackMessages = append(ackMessages, ackMessageDataArr)
s.ackMap = util.RemoveFromSlice(s.ackMap, reqId) s.ackMap = util.RemoveFromSlice(s.ackMap, reqId)
@ -162,20 +161,20 @@ func (s *SessionHandler) sendAckRequest() {
dataArray = append(dataArray, ackMessages) dataArray = append(dataArray, ackMessages)
jsonData, jsonErr := json.Marshal(dataArray) jsonData, jsonErr := json.Marshal(dataArray)
if jsonErr != nil { if jsonErr != nil {
log.Fatal(err) panic(err)
} }
_, err = s.client.rpc.sendMessageRequest(util.ACK_MESSAGES, jsonData) _, err = s.client.rpc.sendMessageRequest(util.ACK_MESSAGES, jsonData)
if err != nil { if err != nil {
log.Fatal(err) panic(err)
} }
log.Println("[ACK] Sent Request") s.client.Logger.Debug().Msg("[ACK] Sent Request")
} }
func (s *SessionHandler) NewResponse(response *binary.RPCResponse) (*Response, error) { func (s *SessionHandler) NewResponse(response *binary.RPCResponse) (*Response, error) {
//s.client.Logger.Debug().Any("rpcResponse", response).Msg("Raw rpc response") //s.client.Logger.Debug().Any("rpcResponse", response).Msg("Raw rpc response")
decodedData, err := crypto.DecodeEncodedResponse(response.Data.EncodedData) decodedData, err := crypto.DecodeEncodedResponse(response.Data.EncodedData)
if err != nil { if err != nil {
log.Fatal(err) panic(err)
return nil, err return nil, err
} }
return &Response{ return &Response{