Fix usages of log package

This commit is contained in:
Tulir Asokan 2023-07-09 23:32:19 +03:00
parent a33e01d124
commit a350e4fc00
9 changed files with 31 additions and 41 deletions

View file

@ -5,7 +5,6 @@ import (
"encoding/json" "encoding/json"
"fmt" "fmt"
"io" "io"
"log"
"net/http" "net/http"
"net/url" "net/url"
"os" "os"
@ -102,7 +101,7 @@ func (c *Client) Connect() error {
c.Logger.Error().Any("expired", hasExpired).Any("secondsSince", authenticatedAtSeconds).Msg("TachyonToken has expired! attempting to refresh") c.Logger.Error().Any("expired", hasExpired).Any("secondsSince", authenticatedAtSeconds).Msg("TachyonToken has expired! attempting to refresh")
refreshErr := c.refreshAuthToken() refreshErr := c.refreshAuthToken()
if refreshErr != nil { if refreshErr != nil {
log.Fatal(refreshErr) panic(refreshErr)
} }
} }
c.Logger.Info().Any("secondsSince", authenticatedAtSeconds).Any("token", c.authData.TachyonAuthToken).Msg("TachyonToken has not expired, attempting to connect...") c.Logger.Info().Any("secondsSince", authenticatedAtSeconds).Any("token", c.authData.TachyonAuthToken).Msg("TachyonToken has not expired, attempting to connect...")
@ -115,7 +114,7 @@ func (c *Client) Connect() error {
c.updateWebEncryptionKey(webEncryptionKeyResponse.GetKey()) c.updateWebEncryptionKey(webEncryptionKeyResponse.GetKey())
rpcPayload, receiveMessageSessionId, err := payload.ReceiveMessages(c.authData.TachyonAuthToken) rpcPayload, receiveMessageSessionId, err := payload.ReceiveMessages(c.authData.TachyonAuthToken)
if err != nil { if err != nil {
log.Fatal(err) panic(err)
return err return err
} }
c.rpc.rpcSessionId = receiveMessageSessionId c.rpc.rpcSessionId = receiveMessageSessionId
@ -124,19 +123,19 @@ func (c *Client) Connect() error {
bugleRes, bugleErr := c.Session.IsBugleDefault() bugleRes, bugleErr := c.Session.IsBugleDefault()
if bugleErr != nil { if bugleErr != nil {
log.Fatal(bugleErr) panic(bugleErr)
} }
c.Logger.Info().Any("isBugle", bugleRes.Success).Msg("IsBugleDefault") c.Logger.Info().Any("isBugle", bugleRes.Success).Msg("IsBugleDefault")
sessionErr := c.Session.SetActiveSession() sessionErr := c.Session.SetActiveSession()
if sessionErr != nil { if sessionErr != nil {
log.Fatal(sessionErr) panic(sessionErr)
} }
//c.Logger.Debug().Any("tachyonAuthToken", c.authData.TachyonAuthToken).Msg("Successfully connected to server") //c.Logger.Debug().Any("tachyonAuthToken", c.authData.TachyonAuthToken).Msg("Successfully connected to server")
return nil return nil
} else { } else {
pairer, err := c.NewPairer(nil, 20) pairer, err := c.NewPairer(nil, 20)
if err != nil { if err != nil {
log.Fatal(err) panic(err)
} }
c.pairer = pairer c.pairer = pairer
registered, err2 := c.pairer.RegisterPhoneRelay() registered, err2 := c.pairer.RegisterPhoneRelay()
@ -146,7 +145,7 @@ func (c *Client) Connect() error {
c.authData.TachyonAuthToken = registered.AuthKeyData.TachyonAuthToken c.authData.TachyonAuthToken = registered.AuthKeyData.TachyonAuthToken
rpcPayload, receiveMessageSessionId, err := payload.ReceiveMessages(c.authData.TachyonAuthToken) rpcPayload, receiveMessageSessionId, err := payload.ReceiveMessages(c.authData.TachyonAuthToken)
if err != nil { if err != nil {
log.Fatal(err) panic(err)
return err return err
} }
c.rpc.rpcSessionId = receiveMessageSessionId c.rpc.rpcSessionId = receiveMessageSessionId
@ -214,7 +213,7 @@ func (c *Client) decryptMedias(messages *binary.FetchMessagesResponse) error {
case *binary.MessageInfo_MediaContent: case *binary.MessageInfo_MediaContent:
decryptedMediaData, err := c.DownloadMedia(data.MediaContent.MediaID, data.MediaContent.DecryptionKey) decryptedMediaData, err := c.DownloadMedia(data.MediaContent.MediaID, data.MediaContent.DecryptionKey)
if err != nil { if err != nil {
log.Fatal(err) panic(err)
return err return err
} }
data.MediaContent.MediaData = decryptedMediaData data.MediaContent.MediaData = decryptedMediaData
@ -261,7 +260,6 @@ func (c *Client) DownloadMedia(mediaID 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)
return nil, decryptionErr return nil, decryptionErr
} }
return decryptedImageBytes, nil return decryptedImageBytes, nil
@ -270,22 +268,22 @@ func (c *Client) DownloadMedia(mediaID string, key []byte) ([]byte, error) {
func (c *Client) FetchConfigVersion() { func (c *Client) FetchConfigVersion() {
req, bErr := http.NewRequest("GET", util.CONFIG_URL, nil) req, bErr := http.NewRequest("GET", util.CONFIG_URL, nil)
if bErr != nil { if bErr != nil {
log.Fatal(bErr) panic(bErr)
} }
configRes, requestErr := c.http.Do(req) configRes, requestErr := c.http.Do(req)
if requestErr != nil { if requestErr != nil {
log.Fatal(requestErr) panic(requestErr)
} }
responseBody, readErr := io.ReadAll(configRes.Body) responseBody, readErr := io.ReadAll(configRes.Body)
if readErr != nil { if readErr != nil {
log.Fatal(readErr) panic(readErr)
} }
version, parseErr := util.ParseConfigVersion(responseBody) version, parseErr := util.ParseConfigVersion(responseBody)
if parseErr != nil { if parseErr != nil {
log.Fatal(parseErr) panic(parseErr)
} }
currVersion := payload.ConfigMessage currVersion := payload.ConfigMessage
@ -352,6 +350,10 @@ func LoadAuthSession(path string) (*AuthData, error) {
return sessionData, nil return sessionData, nil
} }
func (c *Client) RefreshAuthToken() error {
return c.refreshAuthToken()
}
func (c *Client) refreshAuthToken() error { func (c *Client) refreshAuthToken() error {
jwk := c.authData.JWK jwk := c.authData.JWK

View file

@ -2,7 +2,6 @@ package libgm
import ( import (
"fmt" "fmt"
"log"
"google.golang.org/protobuf/proto" "google.golang.org/protobuf/proto"
@ -60,7 +59,7 @@ func (cb *ConversationBuilder) Build(protoMessage proto.Message) (proto.Message,
} }
return payload, nil return payload, nil
default: default:
log.Fatal("Invalid protoMessage conversation builder type") panic("Invalid protoMessage conversation builder type")
} }
return nil, &ConversationBuilderError{errMsg: "failed to build for unknown reasons"} return nil, &ConversationBuilderError{errMsg: "failed to build for unknown reasons"}
} }

View file

@ -4,7 +4,6 @@ import (
"bytes" "bytes"
"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 complete")
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

@ -1,8 +1,6 @@
package libgm package libgm
import ( import (
"log"
"go.mau.fi/mautrix-gmessages/libgm/events" "go.mau.fi/mautrix-gmessages/libgm/events"
"go.mau.fi/mautrix-gmessages/libgm/pblite" "go.mau.fi/mautrix-gmessages/libgm/pblite"
@ -21,7 +19,7 @@ func (c *Client) handlePairingEvent(response *pblite.Response) {
case *binary.PairEvents_Paired: case *binary.PairEvents_Paired:
callbackErr := c.pairCallback(evt.Paired) callbackErr := c.pairCallback(evt.Paired)
if callbackErr != nil { if callbackErr != nil {
log.Fatal(callbackErr) panic(callbackErr)
} }
case *binary.PairEvents_Revoked: case *binary.PairEvents_Revoked:
c.Logger.Debug().Any("data", evt).Msg("Revoked Device") c.Logger.Debug().Any("data", evt).Msg("Revoked Device")

View file

@ -3,7 +3,6 @@ package payload
import ( import (
"encoding/json" "encoding/json"
"fmt" "fmt"
"log"
"google.golang.org/protobuf/proto" "google.golang.org/protobuf/proto"
@ -116,7 +115,7 @@ func (sm *SendMessageBuilder) Build() ([]byte, error) {
messageProtoJSON, serializeErr := pblite.Serialize(sm.message.ProtoReflect()) messageProtoJSON, serializeErr := pblite.Serialize(sm.message.ProtoReflect())
if serializeErr != nil { if serializeErr != nil {
log.Fatal(serializeErr) panic(serializeErr)
return nil, serializeErr return nil, serializeErr
} }

View file

@ -2,7 +2,6 @@ package libgm
import ( import (
"fmt" "fmt"
"log"
"sync" "sync"
"go.mau.fi/mautrix-gmessages/libgm/pblite" "go.mau.fi/mautrix-gmessages/libgm/pblite"
@ -20,8 +19,7 @@ type ResponseChan struct {
func (s *SessionHandler) addRequestToChannel(requestId string, actionType binary.ActionType) { func (s *SessionHandler) addRequestToChannel(requestId string, actionType binary.ActionType) {
_, notOk := routes.Routes[actionType] _, notOk := routes.Routes[actionType]
if !notOk { if !notOk {
log.Println("Missing action type: ", actionType) panic(fmt.Errorf("missing action type: %v", actionType))
log.Fatal(notOk)
} }
if msgMap, ok := s.requests[requestId]; ok { if msgMap, ok := s.requests[requestId]; ok {
responseChan := &ResponseChan{ responseChan := &ResponseChan{

View file

@ -7,7 +7,6 @@ import (
"errors" "errors"
"fmt" "fmt"
"io" "io"
"log"
"net/http" "net/http"
"os" "os"
"time" "time"
@ -137,7 +136,7 @@ func (r *RPC) isAcknowledgeMessage(data []byte) bool {
if len(data) >= 3 && data[0] == 91 && data[1] == 91 && data[2] == 91 { if len(data) >= 3 && data[0] == 91 && data[1] == 91 && data[2] == 91 {
parsed, parseErr := r.parseAckMessage(data) parsed, parseErr := r.parseAckMessage(data)
if parseErr != nil { if parseErr != nil {
log.Fatal(parseErr) panic(parseErr)
} }
skipCount = parsed.Container.Data.GetAckAmount().Count skipCount = parsed.Container.Data.GetAckAmount().Count
r.client.Logger.Info().Any("count", skipCount).Msg("Messages To Skip") r.client.Logger.Info().Any("count", skipCount).Msg("Messages To Skip")
@ -184,13 +183,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) return nil, fmt.Errorf("error creating request: %w", 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) return nil, fmt.Errorf("error making request: %w", 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"
@ -138,14 +137,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.authData.DevicePair.Browser} ackMessageData := &binary.AckMessageData{RequestID: reqId, Device: s.client.authData.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)
@ -153,11 +152,11 @@ 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)
} }
s.client.Logger.Debug().Any("payload", jsonData).Msg("[ACK] Sent Request") s.client.Logger.Debug().Any("payload", jsonData).Msg("[ACK] Sent Request")
} }

View file

@ -1,8 +1,6 @@
package libgm package libgm
import ( import (
"log"
"go.mau.fi/mautrix-gmessages/libgm/pblite" "go.mau.fi/mautrix-gmessages/libgm/pblite"
"go.mau.fi/mautrix-gmessages/libgm/binary" "go.mau.fi/mautrix-gmessages/libgm/binary"
@ -22,12 +20,12 @@ func (c *Client) handleUserAlertEvent(res *pblite.Response, data *binary.UserAle
c.Logger.Info().Any("sessionId", newSessionId).Msg("Client is ready!") c.Logger.Info().Any("sessionId", newSessionId).Msg("Client is ready!")
conversations, convErr := c.Conversations.List(25) conversations, convErr := c.Conversations.List(25)
if convErr != nil { if convErr != nil {
log.Fatal(convErr) panic(convErr)
} }
c.Logger.Debug().Any("conversations", conversations).Msg("got conversations") c.Logger.Debug().Any("conversations", conversations).Msg("got conversations")
notifyErr := c.Session.NotifyDittoActivity() notifyErr := c.Session.NotifyDittoActivity()
if notifyErr != nil { if notifyErr != nil {
log.Fatal(notifyErr) panic(notifyErr)
} }
readyEvt := events.NewClientReady(newSessionId, conversations) readyEvt := events.NewClientReady(newSessionId, conversations)
c.triggerEvent(readyEvt) c.triggerEvent(readyEvt)