Rename binary package to gmproto

This commit is contained in:
Tulir Asokan 2023-07-17 16:51:31 +03:00
parent 7008a9ca60
commit 4d6233d94b
58 changed files with 444 additions and 444 deletions

View file

@ -27,7 +27,7 @@ import (
"maunium.net/go/mautrix/id" "maunium.net/go/mautrix/id"
"maunium.net/go/mautrix/util/dbutil" "maunium.net/go/mautrix/util/dbutil"
"go.mau.fi/mautrix-gmessages/libgm/binary" "go.mau.fi/mautrix-gmessages/libgm/gmproto"
) )
type MessageQuery struct { type MessageQuery struct {
@ -73,7 +73,7 @@ func (mq *MessageQuery) GetLastInChat(ctx context.Context, chat Key) (*Message,
} }
type MessageStatus struct { type MessageStatus struct {
Type binary.MessageStatusType Type gmproto.MessageStatusType
} }
type Message struct { type Message struct {

View file

@ -14,8 +14,8 @@ import (
"github.com/rs/zerolog" "github.com/rs/zerolog"
"go.mau.fi/mautrix-gmessages/libgm" "go.mau.fi/mautrix-gmessages/libgm"
"go.mau.fi/mautrix-gmessages/libgm/binary"
"go.mau.fi/mautrix-gmessages/libgm/events" "go.mau.fi/mautrix-gmessages/libgm/events"
"go.mau.fi/mautrix-gmessages/libgm/gmproto"
) )
func must(err error) { func must(err error) {
@ -128,9 +128,9 @@ func evtHandler(rawEvt any) {
log.Debug().Any("data", evt).Msg("Pair successful") log.Debug().Any("data", evt).Msg("Pair successful")
saveSession() saveSession()
log.Debug().Msg("Wrote session") log.Debug().Msg("Wrote session")
case *binary.Message: case *gmproto.Message:
log.Debug().Any("data", evt).Msg("Message event") log.Debug().Any("data", evt).Msg("Message event")
case *binary.Conversation: case *gmproto.Conversation:
log.Debug().Any("data", evt).Msg("Conversation event") log.Debug().Any("data", evt).Msg("Conversation event")
case *events.BrowserActive: case *events.BrowserActive:
log.Debug().Any("data", evt).Msg("Browser active") log.Debug().Any("data", evt).Msg("Browser active")

View file

@ -16,9 +16,9 @@ import (
"github.com/rs/zerolog" "github.com/rs/zerolog"
"google.golang.org/protobuf/proto" "google.golang.org/protobuf/proto"
"go.mau.fi/mautrix-gmessages/libgm/binary"
"go.mau.fi/mautrix-gmessages/libgm/crypto" "go.mau.fi/mautrix-gmessages/libgm/crypto"
"go.mau.fi/mautrix-gmessages/libgm/events" "go.mau.fi/mautrix-gmessages/libgm/events"
"go.mau.fi/mautrix-gmessages/libgm/gmproto"
"go.mau.fi/mautrix-gmessages/libgm/pblite" "go.mau.fi/mautrix-gmessages/libgm/pblite"
"go.mau.fi/mautrix-gmessages/libgm/util" "go.mau.fi/mautrix-gmessages/libgm/util"
) )
@ -29,8 +29,8 @@ type AuthData struct {
// Key used to sign requests to refresh the tachyon auth token from the server // Key used to sign requests to refresh the tachyon auth token from the server
RefreshKey *crypto.JWK `json:"refresh_key,omitempty"` RefreshKey *crypto.JWK `json:"refresh_key,omitempty"`
// Identity of the paired phone and browser // Identity of the paired phone and browser
Browser *binary.Device `json:"browser,omitempty"` Browser *gmproto.Device `json:"browser,omitempty"`
Mobile *binary.Device `json:"mobile,omitempty"` Mobile *gmproto.Device `json:"mobile,omitempty"`
// Key used to authenticate with the server // Key used to authenticate with the server
TachyonAuthToken []byte `json:"tachyon_token,omitempty"` TachyonAuthToken []byte `json:"tachyon_token,omitempty"`
TachyonExpiry time.Time `json:"tachyon_expiry,omitempty"` TachyonExpiry time.Time `json:"tachyon_expiry,omitempty"`
@ -146,7 +146,7 @@ func (c *Client) StartLogin() (string, error) {
} }
func (c *Client) GenerateQRCodeData(pairingKey []byte) (string, error) { func (c *Client) GenerateQRCodeData(pairingKey []byte) (string, error) {
urlData := &binary.URLData{ urlData := &gmproto.URLData{
PairingKey: pairingKey, PairingKey: pairingKey,
AESKey: c.AuthData.RequestCrypto.AESKey, AESKey: c.AuthData.RequestCrypto.AESKey,
HMACKey: c.AuthData.RequestCrypto.HMACKey, HMACKey: c.AuthData.RequestCrypto.HMACKey,
@ -193,12 +193,12 @@ func (c *Client) triggerEvent(evt interface{}) {
} }
func (c *Client) DownloadMedia(mediaID string, key []byte) ([]byte, error) { func (c *Client) DownloadMedia(mediaID string, key []byte) ([]byte, error) {
downloadMetadata := &binary.UploadImagePayload{ downloadMetadata := &gmproto.UploadImagePayload{
MetaData: &binary.ImageMetaData{ MetaData: &gmproto.ImageMetaData{
ImageID: mediaID, ImageID: mediaID,
Encrypted: true, Encrypted: true,
}, },
AuthData: &binary.AuthMessage{ AuthData: &gmproto.AuthMessage{
RequestID: uuid.NewString(), RequestID: uuid.NewString(),
TachyonAuthToken: c.AuthData.TachyonAuthToken, TachyonAuthToken: c.AuthData.TachyonAuthToken,
ConfigVersion: util.ConfigMessage, ConfigVersion: util.ConfigMessage,
@ -264,7 +264,7 @@ func (c *Client) FetchConfigVersion() {
} }
} }
func (c *Client) diffVersionFormat(curr *binary.ConfigVersion, latest *binary.ConfigVersion) string { func (c *Client) diffVersionFormat(curr *gmproto.ConfigVersion, latest *gmproto.ConfigVersion) string {
return fmt.Sprintf("%d.%d.%d -> %d.%d.%d", curr.Year, curr.Month, curr.Day, latest.Year, latest.Month, latest.Day) return fmt.Sprintf("%d.%d.%d -> %d.%d.%d", curr.Year, curr.Month, curr.Day, latest.Year, latest.Month, latest.Day)
} }
@ -304,8 +304,8 @@ func (c *Client) refreshAuthToken() error {
return err return err
} }
payload, err := pblite.Marshal(&binary.RegisterRefreshPayload{ payload, err := pblite.Marshal(&gmproto.RegisterRefreshPayload{
MessageAuth: &binary.AuthMessage{ MessageAuth: &gmproto.AuthMessage{
RequestID: requestID, RequestID: requestID,
TachyonAuthToken: c.AuthData.TachyonAuthToken, TachyonAuthToken: c.AuthData.TachyonAuthToken,
ConfigVersion: util.ConfigMessage, ConfigVersion: util.ConfigMessage,
@ -313,7 +313,7 @@ func (c *Client) refreshAuthToken() error {
CurrBrowserDevice: c.AuthData.Browser, CurrBrowserDevice: c.AuthData.Browser,
UnixTimestamp: timestamp, UnixTimestamp: timestamp,
Signature: sig, Signature: sig,
EmptyRefreshArr: &binary.EmptyRefreshArr{EmptyArr: &binary.EmptyArr{}}, EmptyRefreshArr: &gmproto.EmptyRefreshArr{EmptyArr: &gmproto.EmptyArr{}},
MessageType: 2, // hmm MessageType: 2, // hmm
}) })
if err != nil { if err != nil {
@ -337,7 +337,7 @@ func (c *Client) refreshAuthToken() error {
return readErr return readErr
} }
resp := &binary.RegisterRefreshResponse{} resp := &gmproto.RegisterRefreshResponse{}
deserializeErr := pblite.Unmarshal(responseBody, resp) deserializeErr := pblite.Unmarshal(responseBody, resp)
if deserializeErr != nil { if deserializeErr != nil {
return deserializeErr return deserializeErr

View file

@ -5,7 +5,7 @@ import (
"google.golang.org/protobuf/proto" "google.golang.org/protobuf/proto"
"go.mau.fi/mautrix-gmessages/libgm/binary" "go.mau.fi/mautrix-gmessages/libgm/gmproto"
) )
type ConversationBuilderError struct { type ConversationBuilderError struct {
@ -19,9 +19,9 @@ func (cbe *ConversationBuilderError) Error() string {
type ConversationBuilder struct { type ConversationBuilder struct {
conversationId string conversationId string
actionStatus binary.ConversationActionStatus actionStatus gmproto.ConversationActionStatus
status binary.ConversationStatus status gmproto.ConversationStatus
muteStatus *binary.ConversationMuteStatus muteStatus *gmproto.ConversationMuteStatus
} }
func (cb *ConversationBuilder) SetConversationId(conversationId string) *ConversationBuilder { func (cb *ConversationBuilder) SetConversationId(conversationId string) *ConversationBuilder {
@ -30,18 +30,18 @@ func (cb *ConversationBuilder) SetConversationId(conversationId string) *Convers
} }
// For block, unblock, block & report // For block, unblock, block & report
func (cb *ConversationBuilder) SetConversationActionStatus(actionStatus binary.ConversationActionStatus) *ConversationBuilder { func (cb *ConversationBuilder) SetConversationActionStatus(actionStatus gmproto.ConversationActionStatus) *ConversationBuilder {
cb.actionStatus = actionStatus cb.actionStatus = actionStatus
return cb return cb
} }
// For archive, unarchive, delete // For archive, unarchive, delete
func (cb *ConversationBuilder) SetConversationStatus(status binary.ConversationStatus) *ConversationBuilder { func (cb *ConversationBuilder) SetConversationStatus(status gmproto.ConversationStatus) *ConversationBuilder {
cb.status = status cb.status = status
return cb return cb
} }
func (cb *ConversationBuilder) SetMuteStatus(muteStatus *binary.ConversationMuteStatus) *ConversationBuilder { func (cb *ConversationBuilder) SetMuteStatus(muteStatus *gmproto.ConversationMuteStatus) *ConversationBuilder {
cb.muteStatus = muteStatus cb.muteStatus = muteStatus
return cb return cb
} }
@ -52,7 +52,7 @@ func (cb *ConversationBuilder) Build(protoMessage proto.Message) (proto.Message,
} }
switch protoMessage.(type) { switch protoMessage.(type) {
case *binary.UpdateConversationPayload: case *gmproto.UpdateConversationPayload:
payload, failedBuild := cb.buildUpdateConversationPayload() payload, failedBuild := cb.buildUpdateConversationPayload()
if failedBuild != nil { if failedBuild != nil {
return nil, failedBuild return nil, failedBuild
@ -64,25 +64,25 @@ func (cb *ConversationBuilder) Build(protoMessage proto.Message) (proto.Message,
return nil, &ConversationBuilderError{errMsg: "failed to build for unknown reasons"} return nil, &ConversationBuilderError{errMsg: "failed to build for unknown reasons"}
} }
func (cb *ConversationBuilder) buildUpdateConversationPayload() (*binary.UpdateConversationPayload, error) { func (cb *ConversationBuilder) buildUpdateConversationPayload() (*gmproto.UpdateConversationPayload, error) {
if cb.actionStatus == 0 && cb.status == 0 && cb.muteStatus == nil { if cb.actionStatus == 0 && cb.status == 0 && cb.muteStatus == nil {
return nil, &ConversationBuilderError{errMsg: "actionStatus, status & muteStatus can not be empty when updating conversation, set atleast 1"} return nil, &ConversationBuilderError{errMsg: "actionStatus, status & muteStatus can not be empty when updating conversation, set atleast 1"}
} }
payload := &binary.UpdateConversationPayload{} payload := &gmproto.UpdateConversationPayload{}
if cb.actionStatus != 0 { if cb.actionStatus != 0 {
payload.Action = cb.actionStatus payload.Action = cb.actionStatus
payload.Action5 = &binary.ConversationAction5{ payload.Action5 = &gmproto.ConversationAction5{
Field2: true, Field2: true,
} }
payload.ConversationID = cb.conversationId payload.ConversationID = cb.conversationId
} else if cb.status != 0 || cb.muteStatus != nil { } else if cb.status != 0 || cb.muteStatus != nil {
payload.Data = &binary.UpdateConversationData{ConversationID: cb.conversationId} payload.Data = &gmproto.UpdateConversationData{ConversationID: cb.conversationId}
if cb.muteStatus != nil { if cb.muteStatus != nil {
payload.Data.Data = &binary.UpdateConversationData_Mute{Mute: *cb.muteStatus} payload.Data.Data = &gmproto.UpdateConversationData_Mute{Mute: *cb.muteStatus}
} else if cb.status != 0 { } else if cb.status != 0 {
payload.Data.Data = &binary.UpdateConversationData_Status{Status: cb.status} payload.Data.Data = &gmproto.UpdateConversationData_Status{Status: cb.status}
} }
} }

View file

@ -3,184 +3,184 @@ package libgm
import ( import (
"fmt" "fmt"
"go.mau.fi/mautrix-gmessages/libgm/binary" "go.mau.fi/mautrix-gmessages/libgm/gmproto"
) )
func (c *Client) ListConversations(count int64, folder binary.ListConversationsPayload_Folder) (*binary.Conversations, error) { func (c *Client) ListConversations(count int64, folder gmproto.ListConversationsPayload_Folder) (*gmproto.Conversations, error) {
payload := &binary.ListConversationsPayload{Count: count, Folder: folder} payload := &gmproto.ListConversationsPayload{Count: count, Folder: folder}
//var actionType binary.ActionType //var actionType gmproto.ActionType
//if !c.synced { //if !c.synced {
// actionType = binary.ActionType_LIST_CONVERSATIONS_SYNC // actionType = gmproto.ActionType_LIST_CONVERSATIONS_SYNC
// c.synced = true // c.synced = true
//} else { //} else {
actionType := binary.ActionType_LIST_CONVERSATIONS actionType := gmproto.ActionType_LIST_CONVERSATIONS
response, err := c.sessionHandler.sendMessage(actionType, payload) response, err := c.sessionHandler.sendMessage(actionType, payload)
if err != nil { if err != nil {
return nil, err return nil, err
} }
res, ok := response.Data.Decrypted.(*binary.Conversations) res, ok := response.Data.Decrypted.(*gmproto.Conversations)
if !ok { if !ok {
return nil, fmt.Errorf("unexpected response type %T, expected *binary.Conversations", response.Data.Decrypted) return nil, fmt.Errorf("unexpected response type %T, expected *gmproto.Conversations", response.Data.Decrypted)
} }
return res, nil return res, nil
} }
func (c *Client) ListContacts() (*binary.ListContactsResponse, error) { func (c *Client) ListContacts() (*gmproto.ListContactsResponse, error) {
payload := &binary.ListContactsPayload{ payload := &gmproto.ListContactsPayload{
I1: 1, I1: 1,
I2: 350, I2: 350,
I3: 50, I3: 50,
} }
actionType := binary.ActionType_LIST_CONTACTS actionType := gmproto.ActionType_LIST_CONTACTS
response, err := c.sessionHandler.sendMessage(actionType, payload) response, err := c.sessionHandler.sendMessage(actionType, payload)
if err != nil { if err != nil {
return nil, err return nil, err
} }
res, ok := response.Data.Decrypted.(*binary.ListContactsResponse) res, ok := response.Data.Decrypted.(*gmproto.ListContactsResponse)
if !ok { if !ok {
return nil, fmt.Errorf("unexpected response type %T, expected *binary.ListContactsResponse", response.Data.Decrypted) return nil, fmt.Errorf("unexpected response type %T, expected *gmproto.ListContactsResponse", response.Data.Decrypted)
} }
return res, nil return res, nil
} }
func (c *Client) ListTopContacts() (*binary.ListTopContactsResponse, error) { func (c *Client) ListTopContacts() (*gmproto.ListTopContactsResponse, error) {
payload := &binary.ListTopContactsPayload{ payload := &gmproto.ListTopContactsPayload{
Count: 8, Count: 8,
} }
actionType := binary.ActionType_LIST_TOP_CONTACTS actionType := gmproto.ActionType_LIST_TOP_CONTACTS
response, err := c.sessionHandler.sendMessage(actionType, payload) response, err := c.sessionHandler.sendMessage(actionType, payload)
if err != nil { if err != nil {
return nil, err return nil, err
} }
res, ok := response.Data.Decrypted.(*binary.ListTopContactsResponse) res, ok := response.Data.Decrypted.(*gmproto.ListTopContactsResponse)
if !ok { if !ok {
return nil, fmt.Errorf("unexpected response type %T, expected *binary.ListTopContactsResponse", response.Data.Decrypted) return nil, fmt.Errorf("unexpected response type %T, expected *gmproto.ListTopContactsResponse", response.Data.Decrypted)
} }
return res, nil return res, nil
} }
func (c *Client) GetOrCreateConversation(req *binary.GetOrCreateConversationPayload) (*binary.GetOrCreateConversationResponse, error) { func (c *Client) GetOrCreateConversation(req *gmproto.GetOrCreateConversationPayload) (*gmproto.GetOrCreateConversationResponse, error) {
actionType := binary.ActionType_GET_OR_CREATE_CONVERSATION actionType := gmproto.ActionType_GET_OR_CREATE_CONVERSATION
response, err := c.sessionHandler.sendMessage(actionType, req) response, err := c.sessionHandler.sendMessage(actionType, req)
if err != nil { if err != nil {
return nil, err return nil, err
} }
res, ok := response.Data.Decrypted.(*binary.GetOrCreateConversationResponse) res, ok := response.Data.Decrypted.(*gmproto.GetOrCreateConversationResponse)
if !ok { if !ok {
return nil, fmt.Errorf("unexpected response type %T, expected *binary.GetOrCreateConversationResponse", response.Data.Decrypted) return nil, fmt.Errorf("unexpected response type %T, expected *gmproto.GetOrCreateConversationResponse", response.Data.Decrypted)
} }
return res, nil return res, nil
} }
func (c *Client) GetConversationType(conversationID string) (*binary.GetConversationTypeResponse, error) { func (c *Client) GetConversationType(conversationID string) (*gmproto.GetConversationTypeResponse, error) {
payload := &binary.ConversationTypePayload{ConversationID: conversationID} payload := &gmproto.ConversationTypePayload{ConversationID: conversationID}
actionType := binary.ActionType_GET_CONVERSATION_TYPE actionType := gmproto.ActionType_GET_CONVERSATION_TYPE
response, err := c.sessionHandler.sendMessage(actionType, payload) response, err := c.sessionHandler.sendMessage(actionType, payload)
if err != nil { if err != nil {
return nil, err return nil, err
} }
res, ok := response.Data.Decrypted.(*binary.GetConversationTypeResponse) res, ok := response.Data.Decrypted.(*gmproto.GetConversationTypeResponse)
if !ok { if !ok {
return nil, fmt.Errorf("unexpected response type %T, expected *binary.GetConversationTypeResponse", response.Data.Decrypted) return nil, fmt.Errorf("unexpected response type %T, expected *gmproto.GetConversationTypeResponse", response.Data.Decrypted)
} }
return res, nil return res, nil
} }
func (c *Client) FetchMessages(conversationID string, count int64, cursor *binary.Cursor) (*binary.FetchMessagesResponse, error) { func (c *Client) FetchMessages(conversationID string, count int64, cursor *gmproto.Cursor) (*gmproto.FetchMessagesResponse, error) {
payload := &binary.FetchConversationMessagesPayload{ConversationID: conversationID, Count: count} payload := &gmproto.FetchConversationMessagesPayload{ConversationID: conversationID, Count: count}
if cursor != nil { if cursor != nil {
payload.Cursor = cursor payload.Cursor = cursor
} }
actionType := binary.ActionType_LIST_MESSAGES actionType := gmproto.ActionType_LIST_MESSAGES
response, err := c.sessionHandler.sendMessage(actionType, payload) response, err := c.sessionHandler.sendMessage(actionType, payload)
if err != nil { if err != nil {
return nil, err return nil, err
} }
res, ok := response.Data.Decrypted.(*binary.FetchMessagesResponse) res, ok := response.Data.Decrypted.(*gmproto.FetchMessagesResponse)
if !ok { if !ok {
return nil, fmt.Errorf("unexpected response type %T, expected *binary.FetchMessagesResponse", response.Data.Decrypted) return nil, fmt.Errorf("unexpected response type %T, expected *gmproto.FetchMessagesResponse", response.Data.Decrypted)
} }
return res, nil return res, nil
} }
func (c *Client) SendMessage(payload *binary.SendMessagePayload) (*binary.SendMessageResponse, error) { func (c *Client) SendMessage(payload *gmproto.SendMessagePayload) (*gmproto.SendMessageResponse, error) {
actionType := binary.ActionType_SEND_MESSAGE actionType := gmproto.ActionType_SEND_MESSAGE
response, err := c.sessionHandler.sendMessage(actionType, payload) response, err := c.sessionHandler.sendMessage(actionType, payload)
if err != nil { if err != nil {
return nil, err return nil, err
} }
res, ok := response.Data.Decrypted.(*binary.SendMessageResponse) res, ok := response.Data.Decrypted.(*gmproto.SendMessageResponse)
if !ok { if !ok {
return nil, fmt.Errorf("unexpected response type %T, expected *binary.SendMessageResponse", response.Data.Decrypted) return nil, fmt.Errorf("unexpected response type %T, expected *gmproto.SendMessageResponse", response.Data.Decrypted)
} }
return res, nil return res, nil
} }
func (c *Client) GetParticipantThumbnail(convID string) (*binary.ParticipantThumbnail, error) { func (c *Client) GetParticipantThumbnail(convID string) (*gmproto.ParticipantThumbnail, error) {
payload := &binary.GetParticipantThumbnailPayload{ConversationID: convID} payload := &gmproto.GetParticipantThumbnailPayload{ConversationID: convID}
actionType := binary.ActionType_GET_PARTICIPANTS_THUMBNAIL actionType := gmproto.ActionType_GET_PARTICIPANTS_THUMBNAIL
response, err := c.sessionHandler.sendMessage(actionType, payload) response, err := c.sessionHandler.sendMessage(actionType, payload)
if err != nil { if err != nil {
return nil, err return nil, err
} }
res, ok := response.Data.Decrypted.(*binary.ParticipantThumbnail) res, ok := response.Data.Decrypted.(*gmproto.ParticipantThumbnail)
if !ok { if !ok {
return nil, fmt.Errorf("unexpected response type %T, expected *binary.ParticipantThumbnail", response.Data.Decrypted) return nil, fmt.Errorf("unexpected response type %T, expected *gmproto.ParticipantThumbnail", response.Data.Decrypted)
} }
return res, nil return res, nil
} }
func (c *Client) UpdateConversation(convBuilder *ConversationBuilder) (*binary.UpdateConversationResponse, error) { func (c *Client) UpdateConversation(convBuilder *ConversationBuilder) (*gmproto.UpdateConversationResponse, error) {
data := &binary.UpdateConversationPayload{} data := &gmproto.UpdateConversationPayload{}
payload, buildErr := convBuilder.Build(data) payload, buildErr := convBuilder.Build(data)
if buildErr != nil { if buildErr != nil {
panic(buildErr) panic(buildErr)
} }
actionType := binary.ActionType_UPDATE_CONVERSATION actionType := gmproto.ActionType_UPDATE_CONVERSATION
response, err := c.sessionHandler.sendMessage(actionType, payload) response, err := c.sessionHandler.sendMessage(actionType, payload)
if err != nil { if err != nil {
return nil, err return nil, err
} }
res, ok := response.Data.Decrypted.(*binary.UpdateConversationResponse) res, ok := response.Data.Decrypted.(*gmproto.UpdateConversationResponse)
if !ok { if !ok {
return nil, fmt.Errorf("unexpected response type %T, expected *binary.UpdateConversationResponse", response.Data.Decrypted) return nil, fmt.Errorf("unexpected response type %T, expected *gmproto.UpdateConversationResponse", response.Data.Decrypted)
} }
return res, nil return res, nil
} }
func (c *Client) SetTyping(convID string) error { func (c *Client) SetTyping(convID string) error {
payload := &binary.TypingUpdatePayload{Data: &binary.SetTypingIn{ConversationID: convID, Typing: true}} payload := &gmproto.TypingUpdatePayload{Data: &gmproto.SetTypingIn{ConversationID: convID, Typing: true}}
actionType := binary.ActionType_TYPING_UPDATES actionType := gmproto.ActionType_TYPING_UPDATES
_, err := c.sessionHandler.sendMessage(actionType, payload) _, err := c.sessionHandler.sendMessage(actionType, payload)
return err return err

View file

@ -6,7 +6,7 @@ import (
"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/gmproto"
) )
func (r *RPC) deduplicateHash(hash [32]byte) bool { func (r *RPC) deduplicateHash(hash [32]byte) bool {
@ -42,7 +42,7 @@ func (r *RPC) deduplicateUpdate(response *pblite.Response) bool {
return false return false
} }
func (r *RPC) HandleRPCMsg(msg *binary.InternalMessage) { func (r *RPC) HandleRPCMsg(msg *gmproto.InternalMessage) {
response, decodeErr := pblite.DecryptInternalMessage(msg, r.client.AuthData.RequestCrypto) response, decodeErr := pblite.DecryptInternalMessage(msg, r.client.AuthData.RequestCrypto)
if decodeErr != nil { if decodeErr != nil {
r.client.Logger.Error().Err(decodeErr).Msg("rpc decrypt msg err") r.client.Logger.Error().Err(decodeErr).Msg("rpc decrypt msg err")
@ -58,9 +58,9 @@ func (r *RPC) HandleRPCMsg(msg *binary.InternalMessage) {
return return
} }
switch response.BugleRoute { switch response.BugleRoute {
case binary.BugleRoute_PairEvent: case gmproto.BugleRoute_PairEvent:
go r.client.handlePairingEvent(response) go r.client.handlePairingEvent(response)
case binary.BugleRoute_DataEvent: case gmproto.BugleRoute_DataEvent:
if r.skipCount > 0 { if r.skipCount > 0 {
r.skipCount-- r.skipCount--
r.client.Logger.Debug(). r.client.Logger.Debug().

View file

@ -1,7 +1,7 @@
package events package events
import ( import (
"go.mau.fi/mautrix-gmessages/libgm/binary" "go.mau.fi/mautrix-gmessages/libgm/gmproto"
) )
type QR struct { type QR struct {
@ -9,5 +9,5 @@ type QR struct {
} }
type PairSuccessful struct { type PairSuccessful struct {
*binary.PairedData *gmproto.PairedData
} }

View file

@ -4,15 +4,15 @@ import (
"fmt" "fmt"
"net/http" "net/http"
"go.mau.fi/mautrix-gmessages/libgm/binary" "go.mau.fi/mautrix-gmessages/libgm/gmproto"
) )
type ClientReady struct { type ClientReady struct {
SessionID string SessionID string
Conversations []*binary.Conversation Conversations []*gmproto.Conversation
} }
func NewClientReady(sessionID string, conversationList *binary.Conversations) *ClientReady { func NewClientReady(sessionID string, conversationList *gmproto.Conversations) *ClientReady {
return &ClientReady{ return &ClientReady{
SessionID: sessionID, SessionID: sessionID,
Conversations: conversationList.Conversations, Conversations: conversationList.Conversations,

View file

@ -4,7 +4,7 @@
// protoc v3.21.12 // protoc v3.21.12
// source: authentication.proto // source: authentication.proto
package binary package gmproto
import ( import (
protoreflect "google.golang.org/protobuf/reflect/protoreflect" protoreflect "google.golang.org/protobuf/reflect/protoreflect"

View file

@ -1,7 +1,7 @@
syntax = "proto3"; syntax = "proto3";
package authentication; package authentication;
option go_package = "../binary"; option go_package = "../gmproto";
import "messages.proto"; import "messages.proto";
import "client.proto"; import "client.proto";

View file

@ -4,7 +4,7 @@
// protoc v3.21.12 // protoc v3.21.12
// source: client.proto // source: client.proto
package binary package gmproto
import ( import (
protoreflect "google.golang.org/protobuf/reflect/protoreflect" protoreflect "google.golang.org/protobuf/reflect/protoreflect"

View file

@ -1,7 +1,7 @@
syntax = "proto3"; syntax = "proto3";
package client; package client;
option go_package = "../binary"; option go_package = "../gmproto";
import "messages.proto"; import "messages.proto";

View file

@ -4,7 +4,7 @@
// protoc v3.21.12 // protoc v3.21.12
// source: conversations.proto // source: conversations.proto
package binary package gmproto
import ( import (
protoreflect "google.golang.org/protobuf/reflect/protoreflect" protoreflect "google.golang.org/protobuf/reflect/protoreflect"

View file

@ -1,7 +1,7 @@
syntax = "proto3"; syntax = "proto3";
package conversations; package conversations;
option go_package = "../binary"; option go_package = "../gmproto";
import "reactions.proto"; import "reactions.proto";

View file

@ -1,4 +1,4 @@
package binary package gmproto
func (et EmojiType) Unicode() string { func (et EmojiType) Unicode() string {
switch et { switch et {

View file

@ -4,7 +4,7 @@
// protoc v3.21.12 // protoc v3.21.12
// source: events.proto // source: events.proto
package binary package gmproto
import ( import (
protoreflect "google.golang.org/protobuf/reflect/protoreflect" protoreflect "google.golang.org/protobuf/reflect/protoreflect"

View file

@ -1,7 +1,7 @@
syntax = "proto3"; syntax = "proto3";
package events; package events;
option go_package = "../binary"; option go_package = "../gmproto";
import "conversations.proto"; import "conversations.proto";
import "authentication.proto"; import "authentication.proto";

View file

@ -4,7 +4,7 @@
// protoc v3.21.12 // protoc v3.21.12
// source: media.proto // source: media.proto
package binary package gmproto
import ( import (
protoreflect "google.golang.org/protobuf/reflect/protoreflect" protoreflect "google.golang.org/protobuf/reflect/protoreflect"

View file

@ -1,7 +1,7 @@
syntax = "proto3"; syntax = "proto3";
package media; package media;
option go_package = "../binary"; option go_package = "../gmproto";
import "messages.proto"; import "messages.proto";

View file

@ -4,7 +4,7 @@
// protoc v3.21.12 // protoc v3.21.12
// source: messages.proto // source: messages.proto
package binary package gmproto
import ( import (
protoreflect "google.golang.org/protobuf/reflect/protoreflect" protoreflect "google.golang.org/protobuf/reflect/protoreflect"

View file

@ -1,7 +1,7 @@
syntax = "proto3"; syntax = "proto3";
package messages; package messages;
option go_package = "../binary"; option go_package = "../gmproto";
message RegisterRefreshPayload { message RegisterRefreshPayload {
AuthMessage messageAuth = 1; AuthMessage messageAuth = 1;

View file

@ -4,7 +4,7 @@
// protoc v3.21.12 // protoc v3.21.12
// source: reactions.proto // source: reactions.proto
package binary package gmproto
import ( import (
protoreflect "google.golang.org/protobuf/reflect/protoreflect" protoreflect "google.golang.org/protobuf/reflect/protoreflect"

View file

@ -1,7 +1,7 @@
syntax = "proto3"; syntax = "proto3";
package reactions; package reactions;
option go_package = "../binary"; option go_package = "../gmproto";
enum Reaction { enum Reaction {
UNSPECIFIED = 0; UNSPECIFIED = 0;

View file

@ -4,7 +4,7 @@
// protoc v3.21.12 // protoc v3.21.12
// source: responses.proto // source: responses.proto
package binary package gmproto
import ( import (
protoreflect "google.golang.org/protobuf/reflect/protoreflect" protoreflect "google.golang.org/protobuf/reflect/protoreflect"

View file

@ -1,7 +1,7 @@
syntax = "proto3"; syntax = "proto3";
package responses; package responses;
option go_package = "../binary"; option go_package = "../gmproto";
import "events.proto"; import "events.proto";
import "messages.proto"; import "messages.proto";

View file

@ -4,7 +4,7 @@
// protoc v3.21.12 // protoc v3.21.12
// source: settings.proto // source: settings.proto
package binary package gmproto
import ( import (
protoreflect "google.golang.org/protobuf/reflect/protoreflect" protoreflect "google.golang.org/protobuf/reflect/protoreflect"

View file

@ -1,7 +1,7 @@
syntax = "proto3"; syntax = "proto3";
package settings; package settings;
option go_package = "../binary"; option go_package = "../gmproto";
message Settings { message Settings {

View file

@ -3,45 +3,45 @@ package libgm
import ( import (
"fmt" "fmt"
"go.mau.fi/mautrix-gmessages/libgm/binary" "go.mau.fi/mautrix-gmessages/libgm/gmproto"
) )
func (c *Client) SendReaction(payload *binary.SendReactionPayload) (*binary.SendReactionResponse, error) { func (c *Client) SendReaction(payload *gmproto.SendReactionPayload) (*gmproto.SendReactionResponse, error) {
actionType := binary.ActionType_SEND_REACTION actionType := gmproto.ActionType_SEND_REACTION
response, err := c.sessionHandler.sendMessage(actionType, payload) response, err := c.sessionHandler.sendMessage(actionType, payload)
if err != nil { if err != nil {
return nil, err return nil, err
} }
res, ok := response.Data.Decrypted.(*binary.SendReactionResponse) res, ok := response.Data.Decrypted.(*gmproto.SendReactionResponse)
if !ok { if !ok {
return nil, fmt.Errorf("unexpected response type %T, expected *binary.SendReactionResponse", response.Data.Decrypted) return nil, fmt.Errorf("unexpected response type %T, expected *gmproto.SendReactionResponse", response.Data.Decrypted)
} }
return res, nil return res, nil
} }
func (c *Client) DeleteMessage(messageID string) (*binary.DeleteMessageResponse, error) { func (c *Client) DeleteMessage(messageID string) (*gmproto.DeleteMessageResponse, error) {
payload := &binary.DeleteMessagePayload{MessageID: messageID} payload := &gmproto.DeleteMessagePayload{MessageID: messageID}
actionType := binary.ActionType_DELETE_MESSAGE actionType := gmproto.ActionType_DELETE_MESSAGE
response, err := c.sessionHandler.sendMessage(actionType, payload) response, err := c.sessionHandler.sendMessage(actionType, payload)
if err != nil { if err != nil {
return nil, err return nil, err
} }
res, ok := response.Data.Decrypted.(*binary.DeleteMessageResponse) res, ok := response.Data.Decrypted.(*gmproto.DeleteMessageResponse)
if !ok { if !ok {
return nil, fmt.Errorf("unexpected response type %T, expected *binary.DeleteMessagesResponse", response.Data.Decrypted) return nil, fmt.Errorf("unexpected response type %T, expected *gmproto.DeleteMessagesResponse", response.Data.Decrypted)
} }
return res, nil return res, nil
} }
func (c *Client) MarkRead(conversationID, messageID string) error { func (c *Client) MarkRead(conversationID, messageID string) error {
payload := &binary.MessageReadPayload{ConversationID: conversationID, MessageID: messageID} payload := &gmproto.MessageReadPayload{ConversationID: conversationID, MessageID: messageID}
actionType := binary.ActionType_MESSAGE_READ actionType := gmproto.ActionType_MESSAGE_READ
_, err := c.sessionHandler.sendMessage(actionType, payload) _, err := c.sessionHandler.sendMessage(actionType, payload)
return err return err

View file

@ -7,26 +7,26 @@ import (
"github.com/google/uuid" "github.com/google/uuid"
"google.golang.org/protobuf/proto" "google.golang.org/protobuf/proto"
"go.mau.fi/mautrix-gmessages/libgm/binary" "go.mau.fi/mautrix-gmessages/libgm/gmproto"
"go.mau.fi/mautrix-gmessages/libgm/util" "go.mau.fi/mautrix-gmessages/libgm/util"
) )
func (c *Client) RegisterPhoneRelay() (*binary.RegisterPhoneRelayResponse, error) { func (c *Client) RegisterPhoneRelay() (*gmproto.RegisterPhoneRelayResponse, error) {
key, err := x509.MarshalPKIXPublicKey(c.AuthData.RefreshKey.GetPublicKey()) key, err := x509.MarshalPKIXPublicKey(c.AuthData.RefreshKey.GetPublicKey())
if err != nil { if err != nil {
return nil, err return nil, err
} }
body, err := proto.Marshal(&binary.AuthenticationContainer{ body, err := proto.Marshal(&gmproto.AuthenticationContainer{
AuthMessage: &binary.AuthMessage{ AuthMessage: &gmproto.AuthMessage{
RequestID: uuid.NewString(), RequestID: uuid.NewString(),
Network: &util.Network, Network: &util.Network,
ConfigVersion: util.ConfigMessage, ConfigVersion: util.ConfigMessage,
}, },
BrowserDetails: util.BrowserDetailsMessage, BrowserDetails: util.BrowserDetailsMessage,
Data: &binary.AuthenticationContainer_KeyData{ Data: &gmproto.AuthenticationContainer_KeyData{
KeyData: &binary.KeyData{ KeyData: &gmproto.KeyData{
EcdsaKeys: &binary.ECDSAKeys{ EcdsaKeys: &gmproto.ECDSAKeys{
Field1: 2, Field1: 2,
EncryptedKeys: key, EncryptedKeys: key,
}, },
@ -45,7 +45,7 @@ func (c *Client) RegisterPhoneRelay() (*binary.RegisterPhoneRelayResponse, error
return nil, err return nil, err
} }
relayResponse.Body.Close() relayResponse.Body.Close()
res := &binary.RegisterPhoneRelayResponse{} res := &gmproto.RegisterPhoneRelayResponse{}
err = proto.Unmarshal(responseBody, res) err = proto.Unmarshal(responseBody, res)
if err != nil { if err != nil {
return nil, err return nil, err
@ -54,8 +54,8 @@ func (c *Client) RegisterPhoneRelay() (*binary.RegisterPhoneRelayResponse, error
} }
func (c *Client) RefreshPhoneRelay() (string, error) { func (c *Client) RefreshPhoneRelay() (string, error) {
body, err := proto.Marshal(&binary.AuthenticationContainer{ body, err := proto.Marshal(&gmproto.AuthenticationContainer{
AuthMessage: &binary.AuthMessage{ AuthMessage: &gmproto.AuthMessage{
RequestID: uuid.NewString(), RequestID: uuid.NewString(),
Network: &util.Network, Network: &util.Network,
TachyonAuthToken: c.AuthData.TachyonAuthToken, TachyonAuthToken: c.AuthData.TachyonAuthToken,
@ -74,7 +74,7 @@ func (c *Client) RefreshPhoneRelay() (string, error) {
if err != nil { if err != nil {
return "", err return "", err
} }
res := &binary.RefreshPhoneRelayResponse{} res := &gmproto.RefreshPhoneRelayResponse{}
err = proto.Unmarshal(responseBody, res) err = proto.Unmarshal(responseBody, res)
if err != nil { if err != nil {
return "", err return "", err
@ -86,9 +86,9 @@ func (c *Client) RefreshPhoneRelay() (string, error) {
return qr, nil return qr, nil
} }
func (c *Client) GetWebEncryptionKey() (*binary.WebEncryptionKeyResponse, error) { func (c *Client) GetWebEncryptionKey() (*gmproto.WebEncryptionKeyResponse, error) {
body, err := proto.Marshal(&binary.AuthenticationContainer{ body, err := proto.Marshal(&gmproto.AuthenticationContainer{
AuthMessage: &binary.AuthMessage{ AuthMessage: &gmproto.AuthMessage{
RequestID: uuid.NewString(), RequestID: uuid.NewString(),
TachyonAuthToken: c.AuthData.TachyonAuthToken, TachyonAuthToken: c.AuthData.TachyonAuthToken,
ConfigVersion: util.ConfigMessage, ConfigVersion: util.ConfigMessage,
@ -106,7 +106,7 @@ func (c *Client) GetWebEncryptionKey() (*binary.WebEncryptionKeyResponse, error)
if err != nil { if err != nil {
return nil, err return nil, err
} }
parsedResponse := &binary.WebEncryptionKeyResponse{} parsedResponse := &gmproto.WebEncryptionKeyResponse{}
err = proto.Unmarshal(responseBody, parsedResponse) err = proto.Unmarshal(responseBody, parsedResponse)
if err != nil { if err != nil {
return nil, err return nil, err
@ -114,12 +114,12 @@ func (c *Client) GetWebEncryptionKey() (*binary.WebEncryptionKeyResponse, error)
return parsedResponse, nil return parsedResponse, nil
} }
func (c *Client) Unpair() (*binary.RevokeRelayPairingResponse, error) { func (c *Client) Unpair() (*gmproto.RevokeRelayPairingResponse, error) {
if c.AuthData.TachyonAuthToken == nil || c.AuthData.Browser == nil { if c.AuthData.TachyonAuthToken == nil || c.AuthData.Browser == nil {
return nil, nil return nil, nil
} }
payload, err := proto.Marshal(&binary.RevokeRelayPairing{ payload, err := proto.Marshal(&gmproto.RevokeRelayPairing{
AuthMessage: &binary.AuthMessage{ AuthMessage: &gmproto.AuthMessage{
RequestID: uuid.NewString(), RequestID: uuid.NewString(),
TachyonAuthToken: c.AuthData.TachyonAuthToken, TachyonAuthToken: c.AuthData.TachyonAuthToken,
ConfigVersion: util.ConfigMessage, ConfigVersion: util.ConfigMessage,
@ -138,7 +138,7 @@ func (c *Client) Unpair() (*binary.RevokeRelayPairingResponse, error) {
if err != nil { if err != nil {
return nil, err return nil, err
} }
parsedResponse := &binary.RevokeRelayPairingResponse{} parsedResponse := &gmproto.RevokeRelayPairingResponse{}
err = proto.Unmarshal(responseBody, parsedResponse) err = proto.Unmarshal(responseBody, parsedResponse)
if err != nil { if err != nil {
return nil, err return nil, err

View file

@ -6,27 +6,27 @@ import (
"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"
"go.mau.fi/mautrix-gmessages/libgm/binary" "go.mau.fi/mautrix-gmessages/libgm/gmproto"
) )
func (c *Client) handlePairingEvent(response *pblite.Response) { func (c *Client) handlePairingEvent(response *pblite.Response) {
pairEventData, ok := response.Data.Decrypted.(*binary.PairEvents) pairEventData, ok := response.Data.Decrypted.(*gmproto.PairEvents)
if !ok { if !ok {
c.Logger.Error().Type("decrypted_type", response.Data.Decrypted).Msg("Unexpected data type in pair event") c.Logger.Error().Type("decrypted_type", response.Data.Decrypted).Msg("Unexpected data type in pair event")
return return
} }
switch evt := pairEventData.Event.(type) { switch evt := pairEventData.Event.(type) {
case *binary.PairEvents_Paired: case *gmproto.PairEvents_Paired:
c.completePairing(evt.Paired) c.completePairing(evt.Paired)
case *binary.PairEvents_Revoked: case *gmproto.PairEvents_Revoked:
c.triggerEvent(evt.Revoked) c.triggerEvent(evt.Revoked)
default: default:
c.Logger.Debug().Any("evt", evt).Msg("Unknown pair event type") c.Logger.Debug().Any("evt", evt).Msg("Unknown pair event type")
} }
} }
func (c *Client) completePairing(data *binary.PairedData) { func (c *Client) completePairing(data *gmproto.PairedData) {
c.updateTachyonAuthToken(data.GetTokenData().GetTachyonAuthToken(), data.GetTokenData().GetTTL()) c.updateTachyonAuthToken(data.GetTokenData().GetTachyonAuthToken(), data.GetTokenData().GetTTL())
c.AuthData.Mobile = data.Mobile c.AuthData.Mobile = data.Mobile
c.AuthData.Browser = data.Browser c.AuthData.Browser = data.Browser

View file

@ -5,16 +5,16 @@ import (
"google.golang.org/protobuf/proto" "google.golang.org/protobuf/proto"
"go.mau.fi/mautrix-gmessages/libgm/binary"
"go.mau.fi/mautrix-gmessages/libgm/crypto" "go.mau.fi/mautrix-gmessages/libgm/crypto"
"go.mau.fi/mautrix-gmessages/libgm/gmproto"
"go.mau.fi/mautrix-gmessages/libgm/pblite" "go.mau.fi/mautrix-gmessages/libgm/pblite"
"go.mau.fi/mautrix-gmessages/libgm/routes" "go.mau.fi/mautrix-gmessages/libgm/routes"
"go.mau.fi/mautrix-gmessages/libgm/util" "go.mau.fi/mautrix-gmessages/libgm/util"
) )
type SendMessageBuilder struct { type SendMessageBuilder struct {
message *binary.SendMessage message *gmproto.SendMessage
b64Message *binary.SendMessageInternal b64Message *gmproto.SendMessageInternal
err error err error
} }
@ -23,33 +23,33 @@ func (sm *SendMessageBuilder) Err() error {
return sm.err return sm.err
} }
func NewSendMessageBuilder(tachyonAuthToken []byte, pairedDevice *binary.Device, requestId string, sessionId string) *SendMessageBuilder { func NewSendMessageBuilder(tachyonAuthToken []byte, pairedDevice *gmproto.Device, requestId string, sessionId string) *SendMessageBuilder {
return &SendMessageBuilder{ return &SendMessageBuilder{
message: &binary.SendMessage{ message: &gmproto.SendMessage{
Mobile: pairedDevice, Mobile: pairedDevice,
MessageData: &binary.SendMessageData{ MessageData: &gmproto.SendMessageData{
RequestID: requestId, RequestID: requestId,
}, },
MessageAuth: &binary.SendMessageAuth{ MessageAuth: &gmproto.SendMessageAuth{
RequestID: requestId, RequestID: requestId,
TachyonAuthToken: tachyonAuthToken, TachyonAuthToken: tachyonAuthToken,
ConfigVersion: util.ConfigMessage, ConfigVersion: util.ConfigMessage,
}, },
EmptyArr: &binary.EmptyArr{}, EmptyArr: &gmproto.EmptyArr{},
}, },
b64Message: &binary.SendMessageInternal{ b64Message: &gmproto.SendMessageInternal{
RequestID: requestId, RequestID: requestId,
SessionID: sessionId, SessionID: sessionId,
}, },
} }
} }
func (sm *SendMessageBuilder) SetPairedDevice(device *binary.Device) *SendMessageBuilder { func (sm *SendMessageBuilder) SetPairedDevice(device *gmproto.Device) *SendMessageBuilder {
sm.message.Mobile = device sm.message.Mobile = device
return sm return sm
} }
func (sm *SendMessageBuilder) setBugleRoute(bugleRoute binary.BugleRoute) *SendMessageBuilder { func (sm *SendMessageBuilder) setBugleRoute(bugleRoute gmproto.BugleRoute) *SendMessageBuilder {
sm.message.MessageData.BugleRoute = bugleRoute sm.message.MessageData.BugleRoute = bugleRoute
return sm return sm
} }
@ -66,7 +66,7 @@ func (sm *SendMessageBuilder) SetSessionId(sessionId string) *SendMessageBuilder
return sm return sm
} }
func (sm *SendMessageBuilder) SetRoute(actionType binary.ActionType) *SendMessageBuilder { func (sm *SendMessageBuilder) SetRoute(actionType gmproto.ActionType) *SendMessageBuilder {
action, ok := routes.Routes[actionType] action, ok := routes.Routes[actionType]
if !ok { if !ok {
sm.err = fmt.Errorf("invalid action type") sm.err = fmt.Errorf("invalid action type")
@ -79,9 +79,9 @@ func (sm *SendMessageBuilder) SetRoute(actionType binary.ActionType) *SendMessag
return sm return sm
} }
func (sm *SendMessageBuilder) setMessageType(eventType binary.MessageType) *SendMessageBuilder { func (sm *SendMessageBuilder) setMessageType(eventType gmproto.MessageType) *SendMessageBuilder {
sm.message.MessageData.MessageTypeData = &binary.MessageTypeData{ sm.message.MessageData.MessageTypeData = &gmproto.MessageTypeData{
EmptyArr: &binary.EmptyArr{}, EmptyArr: &gmproto.EmptyArr{},
MessageType: eventType, MessageType: eventType,
} }
return sm return sm

View file

@ -4,53 +4,53 @@ import (
"google.golang.org/protobuf/proto" "google.golang.org/protobuf/proto"
"google.golang.org/protobuf/reflect/protoreflect" "google.golang.org/protobuf/reflect/protoreflect"
"go.mau.fi/mautrix-gmessages/libgm/binary"
"go.mau.fi/mautrix-gmessages/libgm/crypto" "go.mau.fi/mautrix-gmessages/libgm/crypto"
"go.mau.fi/mautrix-gmessages/libgm/gmproto"
"go.mau.fi/mautrix-gmessages/libgm/routes" "go.mau.fi/mautrix-gmessages/libgm/routes"
) )
type DevicePair struct { type DevicePair struct {
Mobile *binary.Device `json:"mobile,omitempty"` Mobile *gmproto.Device `json:"mobile,omitempty"`
Browser *binary.Device `json:"browser,omitempty"` Browser *gmproto.Device `json:"browser,omitempty"`
} }
type RequestData struct { type RequestData struct {
RequestID string `json:"requestId,omitempty"` RequestID string `json:"requestId,omitempty"`
Timestamp int64 `json:"timestamp,omitempty"` Timestamp int64 `json:"timestamp,omitempty"`
Action binary.ActionType `json:"action,omitempty"` Action gmproto.ActionType `json:"action,omitempty"`
Bool1 bool `json:"bool1,omitempty"` Bool1 bool `json:"bool1,omitempty"`
Bool2 bool `json:"bool2,omitempty"` Bool2 bool `json:"bool2,omitempty"`
EncryptedData []byte `json:"requestData,omitempty"` EncryptedData []byte `json:"requestData,omitempty"`
RawDecrypted []byte `json:"-,omitempty"` RawDecrypted []byte `json:"-,omitempty"`
Decrypted proto.Message `json:"decrypted,omitempty"` Decrypted proto.Message `json:"decrypted,omitempty"`
Bool3 bool `json:"bool3,omitempty"` Bool3 bool `json:"bool3,omitempty"`
} }
type Response struct { type Response struct {
ResponseID string `json:"responseId,omitempty"` ResponseID string `json:"responseId,omitempty"`
BugleRoute binary.BugleRoute `json:"bugleRoute,omitempty"` BugleRoute gmproto.BugleRoute `json:"bugleRoute,omitempty"`
StartExecute string `json:"startExecute,omitempty"` StartExecute string `json:"startExecute,omitempty"`
MessageType binary.MessageType `json:"eventType,omitempty"` MessageType gmproto.MessageType `json:"eventType,omitempty"`
FinishExecute string `json:"finishExecute,omitempty"` FinishExecute string `json:"finishExecute,omitempty"`
MillisecondsTaken string `json:"millisecondsTaken,omitempty"` MillisecondsTaken string `json:"millisecondsTaken,omitempty"`
Devices *DevicePair `json:"devices,omitempty"` Devices *DevicePair `json:"devices,omitempty"`
Data RequestData `json:"data,omitempty"` Data RequestData `json:"data,omitempty"`
SignatureId string `json:"signatureId,omitempty"` SignatureId string `json:"signatureId,omitempty"`
Timestamp string `json:"timestamp"` Timestamp string `json:"timestamp"`
} }
func DecryptInternalMessage(internalMessage *binary.InternalMessage, cryptor *crypto.AESCTRHelper) (*Response, error) { func DecryptInternalMessage(internalMessage *gmproto.InternalMessage, cryptor *crypto.AESCTRHelper) (*Response, error) {
var resp *Response var resp *Response
switch internalMessage.Data.BugleRoute { switch internalMessage.Data.BugleRoute {
case binary.BugleRoute_PairEvent: case gmproto.BugleRoute_PairEvent:
decodedData := &binary.PairEvents{} decodedData := &gmproto.PairEvents{}
decodeErr := proto.Unmarshal(internalMessage.Data.ProtobufData, decodedData) decodeErr := proto.Unmarshal(internalMessage.Data.ProtobufData, decodedData)
if decodeErr != nil { if decodeErr != nil {
return nil, decodeErr return nil, decodeErr
} }
resp = newResponseFromPairEvent(internalMessage.GetData(), decodedData) resp = newResponseFromPairEvent(internalMessage.GetData(), decodedData)
case binary.BugleRoute_DataEvent: case gmproto.BugleRoute_DataEvent:
internalRequestData := &binary.InternalRequestData{} internalRequestData := &gmproto.InternalRequestData{}
decodeErr := proto.Unmarshal(internalMessage.Data.ProtobufData, internalRequestData) decodeErr := proto.Unmarshal(internalMessage.Data.ProtobufData, internalRequestData)
if decodeErr != nil { if decodeErr != nil {
return nil, decodeErr return nil, decodeErr
@ -74,7 +74,7 @@ func DecryptInternalMessage(internalMessage *binary.InternalMessage, cryptor *cr
return resp, nil return resp, nil
} }
func newResponseFromPairEvent(internalMsg *binary.InternalMessageData, data *binary.PairEvents) *Response { func newResponseFromPairEvent(internalMsg *gmproto.InternalMessageData, data *gmproto.PairEvents) *Response {
resp := &Response{ resp := &Response{
ResponseID: internalMsg.GetResponseID(), ResponseID: internalMsg.GetResponseID(),
BugleRoute: internalMsg.GetBugleRoute(), BugleRoute: internalMsg.GetBugleRoute(),
@ -96,7 +96,7 @@ func newResponseFromPairEvent(internalMsg *binary.InternalMessageData, data *bin
return resp return resp
} }
func newResponseFromDataEvent(internalMsg *binary.InternalMessageData, internalRequestData *binary.InternalRequestData, rawData []byte, decrypted protoreflect.ProtoMessage) *Response { func newResponseFromDataEvent(internalMsg *gmproto.InternalMessageData, internalRequestData *gmproto.InternalRequestData, rawData []byte, decrypted protoreflect.ProtoMessage) *Response {
resp := &Response{ resp := &Response{
ResponseID: internalMsg.GetResponseID(), ResponseID: internalMsg.GetResponseID(),
BugleRoute: internalMsg.GetBugleRoute(), BugleRoute: internalMsg.GetBugleRoute(),

View file

@ -1,56 +1,56 @@
package routes package routes
import "go.mau.fi/mautrix-gmessages/libgm/binary" import "go.mau.fi/mautrix-gmessages/libgm/gmproto"
var LIST_CONVERSATIONS_WITH_UPDATES = Route{ var LIST_CONVERSATIONS_WITH_UPDATES = Route{
Action: binary.ActionType_LIST_CONVERSATIONS, Action: gmproto.ActionType_LIST_CONVERSATIONS,
MessageType: binary.MessageType_BUGLE_ANNOTATION, MessageType: gmproto.MessageType_BUGLE_ANNOTATION,
BugleRoute: binary.BugleRoute_DataEvent, BugleRoute: gmproto.BugleRoute_DataEvent,
ResponseStruct: &binary.Conversations{}, ResponseStruct: &gmproto.Conversations{},
UseSessionID: false, UseSessionID: false,
UseTTL: true, UseTTL: true,
} }
var LIST_CONVERSATIONS = Route{ var LIST_CONVERSATIONS = Route{
Action: binary.ActionType_LIST_CONVERSATIONS, Action: gmproto.ActionType_LIST_CONVERSATIONS,
MessageType: binary.MessageType_BUGLE_MESSAGE, MessageType: gmproto.MessageType_BUGLE_MESSAGE,
BugleRoute: binary.BugleRoute_DataEvent, BugleRoute: gmproto.BugleRoute_DataEvent,
ResponseStruct: &binary.Conversations{}, ResponseStruct: &gmproto.Conversations{},
UseSessionID: false, UseSessionID: false,
UseTTL: true, UseTTL: true,
} }
var GET_CONVERSATION_TYPE = Route{ var GET_CONVERSATION_TYPE = Route{
Action: binary.ActionType_GET_CONVERSATION_TYPE, Action: gmproto.ActionType_GET_CONVERSATION_TYPE,
MessageType: binary.MessageType_BUGLE_MESSAGE, MessageType: gmproto.MessageType_BUGLE_MESSAGE,
BugleRoute: binary.BugleRoute_DataEvent, BugleRoute: gmproto.BugleRoute_DataEvent,
ResponseStruct: &binary.GetConversationTypeResponse{}, ResponseStruct: &gmproto.GetConversationTypeResponse{},
UseSessionID: false, UseSessionID: false,
UseTTL: true, UseTTL: true,
} }
var GET_PARTICIPANT_THUMBNAIL = Route{ var GET_PARTICIPANT_THUMBNAIL = Route{
Action: binary.ActionType_GET_PARTICIPANTS_THUMBNAIL, Action: gmproto.ActionType_GET_PARTICIPANTS_THUMBNAIL,
MessageType: binary.MessageType_BUGLE_MESSAGE, MessageType: gmproto.MessageType_BUGLE_MESSAGE,
BugleRoute: binary.BugleRoute_DataEvent, BugleRoute: gmproto.BugleRoute_DataEvent,
ResponseStruct: &binary.ParticipantThumbnail{}, ResponseStruct: &gmproto.ParticipantThumbnail{},
UseSessionID: false, UseSessionID: false,
UseTTL: true, UseTTL: true,
} }
var UPDATE_CONVERSATION = Route{ var UPDATE_CONVERSATION = Route{
Action: binary.ActionType_UPDATE_CONVERSATION, Action: gmproto.ActionType_UPDATE_CONVERSATION,
MessageType: binary.MessageType_BUGLE_MESSAGE, MessageType: gmproto.MessageType_BUGLE_MESSAGE,
BugleRoute: binary.BugleRoute_DataEvent, BugleRoute: gmproto.BugleRoute_DataEvent,
ResponseStruct: &binary.UpdateConversationResponse{}, ResponseStruct: &gmproto.UpdateConversationResponse{},
UseSessionID: false, UseSessionID: false,
UseTTL: true, UseTTL: true,
} }
var TYPING_UPDATES = Route{ var TYPING_UPDATES = Route{
Action: binary.ActionType_TYPING_UPDATES, Action: gmproto.ActionType_TYPING_UPDATES,
MessageType: binary.MessageType_BUGLE_MESSAGE, MessageType: gmproto.MessageType_BUGLE_MESSAGE,
BugleRoute: binary.BugleRoute_DataEvent, BugleRoute: gmproto.BugleRoute_DataEvent,
ResponseStruct: nil, ResponseStruct: nil,
UseSessionID: false, UseSessionID: false,
UseTTL: true, UseTTL: true,

View file

@ -3,33 +3,33 @@ package routes
import ( import (
"google.golang.org/protobuf/proto" "google.golang.org/protobuf/proto"
"go.mau.fi/mautrix-gmessages/libgm/binary" "go.mau.fi/mautrix-gmessages/libgm/gmproto"
) )
type Route struct { type Route struct {
Action binary.ActionType Action gmproto.ActionType
MessageType binary.MessageType MessageType gmproto.MessageType
BugleRoute binary.BugleRoute BugleRoute gmproto.BugleRoute
ResponseStruct proto.Message ResponseStruct proto.Message
UseSessionID bool UseSessionID bool
UseTTL bool UseTTL bool
} }
var Routes = map[binary.ActionType]Route{ var Routes = map[gmproto.ActionType]Route{
binary.ActionType_IS_BUGLE_DEFAULT: IS_BUGLE_DEFAULT, gmproto.ActionType_IS_BUGLE_DEFAULT: IS_BUGLE_DEFAULT,
binary.ActionType_GET_UPDATES: GET_UPDATES, gmproto.ActionType_GET_UPDATES: GET_UPDATES,
binary.ActionType_LIST_CONVERSATIONS: LIST_CONVERSATIONS, gmproto.ActionType_LIST_CONVERSATIONS: LIST_CONVERSATIONS,
binary.ActionType_LIST_CONVERSATIONS_SYNC: LIST_CONVERSATIONS_WITH_UPDATES, gmproto.ActionType_LIST_CONVERSATIONS_SYNC: LIST_CONVERSATIONS_WITH_UPDATES,
binary.ActionType_MESSAGE_READ: MESSAGE_READ, gmproto.ActionType_MESSAGE_READ: MESSAGE_READ,
binary.ActionType_NOTIFY_DITTO_ACTIVITY: NOTIFY_DITTO_ACTIVITY, gmproto.ActionType_NOTIFY_DITTO_ACTIVITY: NOTIFY_DITTO_ACTIVITY,
binary.ActionType_GET_CONVERSATION_TYPE: GET_CONVERSATION_TYPE, gmproto.ActionType_GET_CONVERSATION_TYPE: GET_CONVERSATION_TYPE,
binary.ActionType_LIST_MESSAGES: LIST_MESSAGES, gmproto.ActionType_LIST_MESSAGES: LIST_MESSAGES,
binary.ActionType_SEND_MESSAGE: SEND_MESSAGE, gmproto.ActionType_SEND_MESSAGE: SEND_MESSAGE,
binary.ActionType_SEND_REACTION: SEND_REACTION, gmproto.ActionType_SEND_REACTION: SEND_REACTION,
binary.ActionType_DELETE_MESSAGE: DELETE_MESSAGE, gmproto.ActionType_DELETE_MESSAGE: DELETE_MESSAGE,
binary.ActionType_TYPING_UPDATES: TYPING_UPDATES, gmproto.ActionType_TYPING_UPDATES: TYPING_UPDATES,
binary.ActionType_GET_PARTICIPANTS_THUMBNAIL: GET_PARTICIPANT_THUMBNAIL, gmproto.ActionType_GET_PARTICIPANTS_THUMBNAIL: GET_PARTICIPANT_THUMBNAIL,
binary.ActionType_LIST_CONTACTS: LIST_CONTACTS, gmproto.ActionType_LIST_CONTACTS: LIST_CONTACTS,
binary.ActionType_LIST_TOP_CONTACTS: LIST_TOP_CONTACTS, gmproto.ActionType_LIST_TOP_CONTACTS: LIST_TOP_CONTACTS,
binary.ActionType_GET_OR_CREATE_CONVERSATION: GET_OR_CREATE_CONVERSATION, gmproto.ActionType_GET_OR_CREATE_CONVERSATION: GET_OR_CREATE_CONVERSATION,
} }

View file

@ -1,47 +1,47 @@
package routes package routes
import "go.mau.fi/mautrix-gmessages/libgm/binary" import "go.mau.fi/mautrix-gmessages/libgm/gmproto"
var LIST_MESSAGES = Route{ var LIST_MESSAGES = Route{
Action: binary.ActionType_LIST_MESSAGES, Action: gmproto.ActionType_LIST_MESSAGES,
MessageType: binary.MessageType_BUGLE_MESSAGE, MessageType: gmproto.MessageType_BUGLE_MESSAGE,
BugleRoute: binary.BugleRoute_DataEvent, BugleRoute: gmproto.BugleRoute_DataEvent,
ResponseStruct: &binary.FetchMessagesResponse{}, ResponseStruct: &gmproto.FetchMessagesResponse{},
UseSessionID: false, UseSessionID: false,
UseTTL: true, UseTTL: true,
} }
var SEND_MESSAGE = Route{ var SEND_MESSAGE = Route{
Action: binary.ActionType_SEND_MESSAGE, Action: gmproto.ActionType_SEND_MESSAGE,
MessageType: binary.MessageType_BUGLE_MESSAGE, MessageType: gmproto.MessageType_BUGLE_MESSAGE,
BugleRoute: binary.BugleRoute_DataEvent, BugleRoute: gmproto.BugleRoute_DataEvent,
ResponseStruct: &binary.SendMessageResponse{}, ResponseStruct: &gmproto.SendMessageResponse{},
UseSessionID: false, UseSessionID: false,
UseTTL: true, UseTTL: true,
} }
var SEND_REACTION = Route{ var SEND_REACTION = Route{
Action: binary.ActionType_SEND_REACTION, Action: gmproto.ActionType_SEND_REACTION,
MessageType: binary.MessageType_BUGLE_MESSAGE, MessageType: gmproto.MessageType_BUGLE_MESSAGE,
BugleRoute: binary.BugleRoute_DataEvent, BugleRoute: gmproto.BugleRoute_DataEvent,
ResponseStruct: &binary.SendReactionResponse{}, ResponseStruct: &gmproto.SendReactionResponse{},
UseSessionID: false, UseSessionID: false,
UseTTL: true, UseTTL: true,
} }
var DELETE_MESSAGE = Route{ var DELETE_MESSAGE = Route{
Action: binary.ActionType_DELETE_MESSAGE, Action: gmproto.ActionType_DELETE_MESSAGE,
MessageType: binary.MessageType_BUGLE_MESSAGE, MessageType: gmproto.MessageType_BUGLE_MESSAGE,
BugleRoute: binary.BugleRoute_DataEvent, BugleRoute: gmproto.BugleRoute_DataEvent,
ResponseStruct: &binary.DeleteMessageResponse{}, ResponseStruct: &gmproto.DeleteMessageResponse{},
UseSessionID: false, UseSessionID: false,
UseTTL: true, UseTTL: true,
} }
var MESSAGE_READ = Route{ var MESSAGE_READ = Route{
Action: binary.ActionType_MESSAGE_READ, Action: gmproto.ActionType_MESSAGE_READ,
MessageType: binary.MessageType_BUGLE_MESSAGE, MessageType: gmproto.MessageType_BUGLE_MESSAGE,
BugleRoute: binary.BugleRoute_DataEvent, BugleRoute: gmproto.BugleRoute_DataEvent,
ResponseStruct: nil, ResponseStruct: nil,
UseSessionID: false, UseSessionID: false,
UseTTL: true, UseTTL: true,

View file

@ -1,57 +1,57 @@
package routes package routes
import "go.mau.fi/mautrix-gmessages/libgm/binary" import "go.mau.fi/mautrix-gmessages/libgm/gmproto"
var IS_BUGLE_DEFAULT = Route{ var IS_BUGLE_DEFAULT = Route{
Action: binary.ActionType_IS_BUGLE_DEFAULT, Action: gmproto.ActionType_IS_BUGLE_DEFAULT,
MessageType: binary.MessageType_BUGLE_MESSAGE, MessageType: gmproto.MessageType_BUGLE_MESSAGE,
BugleRoute: binary.BugleRoute_DataEvent, BugleRoute: gmproto.BugleRoute_DataEvent,
ResponseStruct: &binary.IsBugleDefaultResponse{}, ResponseStruct: &gmproto.IsBugleDefaultResponse{},
UseSessionID: false, UseSessionID: false,
UseTTL: true, UseTTL: true,
} }
var GET_UPDATES = Route{ var GET_UPDATES = Route{
Action: binary.ActionType_GET_UPDATES, Action: gmproto.ActionType_GET_UPDATES,
MessageType: binary.MessageType_BUGLE_MESSAGE, MessageType: gmproto.MessageType_BUGLE_MESSAGE,
BugleRoute: binary.BugleRoute_DataEvent, BugleRoute: gmproto.BugleRoute_DataEvent,
ResponseStruct: &binary.UpdateEvents{}, ResponseStruct: &gmproto.UpdateEvents{},
UseSessionID: true, UseSessionID: true,
UseTTL: false, UseTTL: false,
} }
var NOTIFY_DITTO_ACTIVITY = Route{ var NOTIFY_DITTO_ACTIVITY = Route{
Action: binary.ActionType_NOTIFY_DITTO_ACTIVITY, Action: gmproto.ActionType_NOTIFY_DITTO_ACTIVITY,
MessageType: binary.MessageType_BUGLE_MESSAGE, MessageType: gmproto.MessageType_BUGLE_MESSAGE,
BugleRoute: binary.BugleRoute_DataEvent, BugleRoute: gmproto.BugleRoute_DataEvent,
ResponseStruct: nil, ResponseStruct: nil,
UseSessionID: false, UseSessionID: false,
UseTTL: true, UseTTL: true,
} }
var LIST_CONTACTS = Route{ var LIST_CONTACTS = Route{
Action: binary.ActionType_LIST_CONTACTS, Action: gmproto.ActionType_LIST_CONTACTS,
MessageType: binary.MessageType_BUGLE_MESSAGE, MessageType: gmproto.MessageType_BUGLE_MESSAGE,
BugleRoute: binary.BugleRoute_DataEvent, BugleRoute: gmproto.BugleRoute_DataEvent,
ResponseStruct: &binary.ListContactsResponse{}, ResponseStruct: &gmproto.ListContactsResponse{},
UseSessionID: false, UseSessionID: false,
UseTTL: true, UseTTL: true,
} }
var LIST_TOP_CONTACTS = Route{ var LIST_TOP_CONTACTS = Route{
Action: binary.ActionType_LIST_TOP_CONTACTS, Action: gmproto.ActionType_LIST_TOP_CONTACTS,
MessageType: binary.MessageType_BUGLE_MESSAGE, MessageType: gmproto.MessageType_BUGLE_MESSAGE,
BugleRoute: binary.BugleRoute_DataEvent, BugleRoute: gmproto.BugleRoute_DataEvent,
ResponseStruct: &binary.ListTopContactsResponse{}, ResponseStruct: &gmproto.ListTopContactsResponse{},
UseSessionID: false, UseSessionID: false,
UseTTL: true, UseTTL: true,
} }
var GET_OR_CREATE_CONVERSATION = Route{ var GET_OR_CREATE_CONVERSATION = Route{
Action: binary.ActionType_GET_OR_CREATE_CONVERSATION, Action: gmproto.ActionType_GET_OR_CREATE_CONVERSATION,
MessageType: binary.MessageType_BUGLE_MESSAGE, MessageType: gmproto.MessageType_BUGLE_MESSAGE,
BugleRoute: binary.BugleRoute_DataEvent, BugleRoute: gmproto.BugleRoute_DataEvent,
ResponseStruct: &binary.GetOrCreateConversationResponse{}, ResponseStruct: &gmproto.GetOrCreateConversationResponse{},
UseSessionID: false, UseSessionID: false,
UseTTL: true, UseTTL: true,
} }

View file

@ -17,7 +17,7 @@ import (
"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"
"go.mau.fi/mautrix-gmessages/libgm/binary" "go.mau.fi/mautrix-gmessages/libgm/gmproto"
"go.mau.fi/mautrix-gmessages/libgm/util" "go.mau.fi/mautrix-gmessages/libgm/util"
) )
@ -47,14 +47,14 @@ func (r *RPC) ListenReceiveMessages() {
return return
} }
r.client.Logger.Debug().Msg("Starting new long-polling request") r.client.Logger.Debug().Msg("Starting new long-polling request")
receivePayload, err := pblite.Marshal(&binary.ReceiveMessagesRequest{ receivePayload, err := pblite.Marshal(&gmproto.ReceiveMessagesRequest{
Auth: &binary.AuthMessage{ Auth: &gmproto.AuthMessage{
RequestID: listenReqID, RequestID: listenReqID,
TachyonAuthToken: r.client.AuthData.TachyonAuthToken, TachyonAuthToken: r.client.AuthData.TachyonAuthToken,
ConfigVersion: util.ConfigMessage, ConfigVersion: util.ConfigMessage,
}, },
Unknown: &binary.ReceiveMessagesRequest_UnknownEmptyObject2{ Unknown: &gmproto.ReceiveMessagesRequest_UnknownEmptyObject2{
Unknown: &binary.ReceiveMessagesRequest_UnknownEmptyObject1{}, Unknown: &gmproto.ReceiveMessagesRequest_UnknownEmptyObject1{},
}, },
}) })
if err != nil { if err != nil {
@ -160,7 +160,7 @@ func (r *RPC) startReadingData(rc io.ReadCloser) {
} }
currentBlock := accumulatedData currentBlock := accumulatedData
accumulatedData = accumulatedData[:0] accumulatedData = accumulatedData[:0]
msg := &binary.InternalMessage{} msg := &gmproto.InternalMessage{}
err = pblite.Unmarshal(currentBlock, msg) err = pblite.Unmarshal(currentBlock, msg)
if err != nil { if err != nil {
r.client.Logger.Err(err).Msg("Error deserializing pblite message") r.client.Logger.Err(err).Msg("Error deserializing pblite message")

View file

@ -3,36 +3,36 @@ package libgm
import ( import (
"fmt" "fmt"
"go.mau.fi/mautrix-gmessages/libgm/binary" "go.mau.fi/mautrix-gmessages/libgm/gmproto"
) )
func (c *Client) SetActiveSession() error { func (c *Client) SetActiveSession() error {
c.sessionHandler.ResetSessionID() c.sessionHandler.ResetSessionID()
actionType := binary.ActionType_GET_UPDATES actionType := gmproto.ActionType_GET_UPDATES
return c.sessionHandler.sendMessageNoResponse(actionType, nil) return c.sessionHandler.sendMessageNoResponse(actionType, nil)
} }
func (c *Client) IsBugleDefault() (*binary.IsBugleDefaultResponse, error) { func (c *Client) IsBugleDefault() (*gmproto.IsBugleDefaultResponse, error) {
c.sessionHandler.ResetSessionID() c.sessionHandler.ResetSessionID()
actionType := binary.ActionType_IS_BUGLE_DEFAULT actionType := gmproto.ActionType_IS_BUGLE_DEFAULT
response, err := c.sessionHandler.sendMessage(actionType, nil) response, err := c.sessionHandler.sendMessage(actionType, nil)
if err != nil { if err != nil {
return nil, err return nil, err
} }
res, ok := response.Data.Decrypted.(*binary.IsBugleDefaultResponse) res, ok := response.Data.Decrypted.(*gmproto.IsBugleDefaultResponse)
if !ok { if !ok {
return nil, fmt.Errorf("unexpected response type %T, expected *binary.IsBugleDefaultResponse", response.Data.Decrypted) return nil, fmt.Errorf("unexpected response type %T, expected *gmproto.IsBugleDefaultResponse", response.Data.Decrypted)
} }
return res, nil return res, nil
} }
func (c *Client) NotifyDittoActivity() error { func (c *Client) NotifyDittoActivity() error {
payload := &binary.NotifyDittoActivityPayload{Success: true} payload := &gmproto.NotifyDittoActivityPayload{Success: true}
actionType := binary.ActionType_NOTIFY_DITTO_ACTIVITY actionType := gmproto.ActionType_NOTIFY_DITTO_ACTIVITY
_, err := c.sessionHandler.sendMessage(actionType, payload) _, err := c.sessionHandler.sendMessage(actionType, payload)
return err return err

View file

@ -11,7 +11,7 @@ import (
"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/gmproto"
"go.mau.fi/mautrix-gmessages/libgm/payload" "go.mau.fi/mautrix-gmessages/libgm/payload"
"go.mau.fi/mautrix-gmessages/libgm/routes" "go.mau.fi/mautrix-gmessages/libgm/routes"
"go.mau.fi/mautrix-gmessages/libgm/util" "go.mau.fi/mautrix-gmessages/libgm/util"
@ -36,7 +36,7 @@ func (s *SessionHandler) ResetSessionID() {
s.sessionID = uuid.NewString() s.sessionID = uuid.NewString()
} }
func (s *SessionHandler) sendMessageNoResponse(actionType binary.ActionType, encryptedData proto.Message) error { func (s *SessionHandler) sendMessageNoResponse(actionType gmproto.ActionType, encryptedData proto.Message) error {
_, payload, _, err := s.buildMessage(actionType, encryptedData) _, payload, _, err := s.buildMessage(actionType, encryptedData)
if err != nil { if err != nil {
return err return err
@ -46,7 +46,7 @@ func (s *SessionHandler) sendMessageNoResponse(actionType binary.ActionType, enc
return err return err
} }
func (s *SessionHandler) sendAsyncMessage(actionType binary.ActionType, encryptedData proto.Message) (<-chan *pblite.Response, error) { func (s *SessionHandler) sendAsyncMessage(actionType gmproto.ActionType, encryptedData proto.Message) (<-chan *pblite.Response, error) {
requestID, payload, _, buildErr := s.buildMessage(actionType, encryptedData) requestID, payload, _, buildErr := s.buildMessage(actionType, encryptedData)
if buildErr != nil { if buildErr != nil {
return nil, buildErr return nil, buildErr
@ -61,7 +61,7 @@ func (s *SessionHandler) sendAsyncMessage(actionType binary.ActionType, encrypte
return ch, nil return ch, nil
} }
func (s *SessionHandler) sendMessage(actionType binary.ActionType, encryptedData proto.Message) (*pblite.Response, error) { func (s *SessionHandler) sendMessage(actionType gmproto.ActionType, encryptedData proto.Message) (*pblite.Response, error) {
ch, err := s.sendAsyncMessage(actionType, encryptedData) ch, err := s.sendAsyncMessage(actionType, encryptedData)
if err != nil { if err != nil {
return nil, err return nil, err
@ -71,7 +71,7 @@ func (s *SessionHandler) sendMessage(actionType binary.ActionType, encryptedData
return <-ch, nil return <-ch, nil
} }
func (s *SessionHandler) buildMessage(actionType binary.ActionType, encryptedData proto.Message) (string, []byte, binary.ActionType, error) { func (s *SessionHandler) buildMessage(actionType gmproto.ActionType, encryptedData proto.Message) (string, []byte, gmproto.ActionType, error) {
var requestID string var requestID string
pairedDevice := s.client.AuthData.Mobile pairedDevice := s.client.AuthData.Mobile
sessionId := s.client.sessionHandler.sessionID sessionId := s.client.sessionHandler.sessionID
@ -138,20 +138,20 @@ func (s *SessionHandler) sendAckRequest() {
if len(dataToAck) == 0 { if len(dataToAck) == 0 {
return return
} }
ackMessages := make([]*binary.AckMessageData, len(dataToAck)) ackMessages := make([]*gmproto.AckMessageData, len(dataToAck))
for i, reqID := range dataToAck { for i, reqID := range dataToAck {
ackMessages[i] = &binary.AckMessageData{ ackMessages[i] = &gmproto.AckMessageData{
RequestID: reqID, RequestID: reqID,
Device: s.client.AuthData.Browser, Device: s.client.AuthData.Browser,
} }
} }
ackMessagePayload := &binary.AckMessagePayload{ ackMessagePayload := &gmproto.AckMessagePayload{
AuthData: &binary.AuthMessage{ AuthData: &gmproto.AuthMessage{
RequestID: uuid.NewString(), RequestID: uuid.NewString(),
TachyonAuthToken: s.client.AuthData.TachyonAuthToken, TachyonAuthToken: s.client.AuthData.TachyonAuthToken,
ConfigVersion: util.ConfigMessage, ConfigVersion: util.ConfigMessage,
}, },
EmptyArr: &binary.EmptyArr{}, EmptyArr: &gmproto.EmptyArr{},
Acks: ackMessages, Acks: ackMessages,
} }
jsonData, err := pblite.Marshal(ackMessagePayload) jsonData, err := pblite.Marshal(ackMessagePayload)

View file

@ -4,40 +4,40 @@ import (
"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"
"go.mau.fi/mautrix-gmessages/libgm/binary" "go.mau.fi/mautrix-gmessages/libgm/gmproto"
) )
func (c *Client) handleUpdatesEvent(res *pblite.Response) { func (c *Client) handleUpdatesEvent(res *pblite.Response) {
switch res.Data.Action { switch res.Data.Action {
case binary.ActionType_GET_UPDATES: case gmproto.ActionType_GET_UPDATES:
data, ok := res.Data.Decrypted.(*binary.UpdateEvents) data, ok := res.Data.Decrypted.(*gmproto.UpdateEvents)
if !ok { if !ok {
c.Logger.Error().Type("data_type", res.Data.Decrypted).Msg("Unexpected data type in GET_UPDATES event") c.Logger.Error().Type("data_type", res.Data.Decrypted).Msg("Unexpected data type in GET_UPDATES event")
return return
} }
switch evt := data.Event.(type) { switch evt := data.Event.(type) {
case *binary.UpdateEvents_UserAlertEvent: case *gmproto.UpdateEvents_UserAlertEvent:
c.rpc.logContent(res) c.rpc.logContent(res)
c.handleUserAlertEvent(res, evt.UserAlertEvent) c.handleUserAlertEvent(res, evt.UserAlertEvent)
case *binary.UpdateEvents_SettingsEvent: case *gmproto.UpdateEvents_SettingsEvent:
c.rpc.logContent(res) c.rpc.logContent(res)
c.triggerEvent(evt.SettingsEvent) c.triggerEvent(evt.SettingsEvent)
case *binary.UpdateEvents_ConversationEvent: case *gmproto.UpdateEvents_ConversationEvent:
if c.rpc.deduplicateUpdate(res) { if c.rpc.deduplicateUpdate(res) {
return return
} }
c.triggerEvent(evt.ConversationEvent.GetData()) c.triggerEvent(evt.ConversationEvent.GetData())
case *binary.UpdateEvents_MessageEvent: case *gmproto.UpdateEvents_MessageEvent:
if c.rpc.deduplicateUpdate(res) { if c.rpc.deduplicateUpdate(res) {
return return
} }
c.triggerEvent(evt.MessageEvent.GetData()) c.triggerEvent(evt.MessageEvent.GetData())
case *binary.UpdateEvents_TypingEvent: case *gmproto.UpdateEvents_TypingEvent:
c.rpc.logContent(res) c.rpc.logContent(res)
c.triggerEvent(evt.TypingEvent.GetData()) c.triggerEvent(evt.TypingEvent.GetData())
@ -50,7 +50,7 @@ func (c *Client) handleUpdatesEvent(res *pblite.Response) {
} }
func (c *Client) handleClientReady(newSessionId string) { func (c *Client) handleClientReady(newSessionId string) {
conversations, convErr := c.ListConversations(25, binary.ListConversationsPayload_INBOX) conversations, convErr := c.ListConversations(25, gmproto.ListConversationsPayload_INBOX)
if convErr != nil { if convErr != nil {
panic(convErr) panic(convErr)
} }
@ -62,10 +62,10 @@ func (c *Client) handleClientReady(newSessionId string) {
c.triggerEvent(readyEvt) c.triggerEvent(readyEvt)
} }
func (c *Client) handleUserAlertEvent(res *pblite.Response, data *binary.UserAlertEvent) { func (c *Client) handleUserAlertEvent(res *pblite.Response, data *gmproto.UserAlertEvent) {
alertType := data.AlertType alertType := data.AlertType
switch alertType { switch alertType {
case binary.AlertType_BROWSER_ACTIVE: case gmproto.AlertType_BROWSER_ACTIVE:
newSessionID := res.Data.RequestID newSessionID := res.Data.RequestID
c.Logger.Debug().Any("session_id", newSessionID).Msg("Got browser active notification") c.Logger.Debug().Any("session_id", newSessionID).Msg("Got browser active notification")
if newSessionID != c.sessionHandler.sessionID { if newSessionID != c.sessionHandler.sessionID {

View file

@ -12,70 +12,70 @@ import (
"github.com/google/uuid" "github.com/google/uuid"
"google.golang.org/protobuf/proto" "google.golang.org/protobuf/proto"
"go.mau.fi/mautrix-gmessages/libgm/binary"
"go.mau.fi/mautrix-gmessages/libgm/crypto" "go.mau.fi/mautrix-gmessages/libgm/crypto"
"go.mau.fi/mautrix-gmessages/libgm/gmproto"
"go.mau.fi/mautrix-gmessages/libgm/util" "go.mau.fi/mautrix-gmessages/libgm/util"
) )
type MediaType struct { type MediaType struct {
Extension string Extension string
Format string Format string
Type binary.MediaFormats Type gmproto.MediaFormats
} }
var MimeToMediaType = map[string]MediaType{ var MimeToMediaType = map[string]MediaType{
"image/jpeg": {Extension: "jpeg", Type: binary.MediaFormats_IMAGE_JPEG}, "image/jpeg": {Extension: "jpeg", Type: gmproto.MediaFormats_IMAGE_JPEG},
"image/jpg": {Extension: "jpg", Type: binary.MediaFormats_IMAGE_JPG}, "image/jpg": {Extension: "jpg", Type: gmproto.MediaFormats_IMAGE_JPG},
"image/png": {Extension: "png", Type: binary.MediaFormats_IMAGE_PNG}, "image/png": {Extension: "png", Type: gmproto.MediaFormats_IMAGE_PNG},
"image/gif": {Extension: "gif", Type: binary.MediaFormats_IMAGE_GIF}, "image/gif": {Extension: "gif", Type: gmproto.MediaFormats_IMAGE_GIF},
"image/wbmp": {Extension: "wbmp", Type: binary.MediaFormats_IMAGE_WBMP}, "image/wbmp": {Extension: "wbmp", Type: gmproto.MediaFormats_IMAGE_WBMP},
"image/bmp": {Extension: "bmp", Type: binary.MediaFormats_IMAGE_X_MS_BMP}, "image/bmp": {Extension: "bmp", Type: gmproto.MediaFormats_IMAGE_X_MS_BMP},
"image/x-ms-bmp": {Extension: "bmp", Type: binary.MediaFormats_IMAGE_X_MS_BMP}, "image/x-ms-bmp": {Extension: "bmp", Type: gmproto.MediaFormats_IMAGE_X_MS_BMP},
"video/mp4": {Extension: "mp4", Type: binary.MediaFormats_VIDEO_MP4}, "video/mp4": {Extension: "mp4", Type: gmproto.MediaFormats_VIDEO_MP4},
"video/3gpp2": {Extension: "3gpp2", Type: binary.MediaFormats_VIDEO_3G2}, "video/3gpp2": {Extension: "3gpp2", Type: gmproto.MediaFormats_VIDEO_3G2},
"video/3gpp": {Extension: "3gpp", Type: binary.MediaFormats_VIDEO_3GPP}, "video/3gpp": {Extension: "3gpp", Type: gmproto.MediaFormats_VIDEO_3GPP},
"video/webm": {Extension: "webm", Type: binary.MediaFormats_VIDEO_WEBM}, "video/webm": {Extension: "webm", Type: gmproto.MediaFormats_VIDEO_WEBM},
"video/x-matroska": {Extension: "mkv", Type: binary.MediaFormats_VIDEO_MKV}, "video/x-matroska": {Extension: "mkv", Type: gmproto.MediaFormats_VIDEO_MKV},
"audio/aac": {Extension: "aac", Type: binary.MediaFormats_AUDIO_AAC}, "audio/aac": {Extension: "aac", Type: gmproto.MediaFormats_AUDIO_AAC},
"audio/amr": {Extension: "amr", Type: binary.MediaFormats_AUDIO_AMR}, "audio/amr": {Extension: "amr", Type: gmproto.MediaFormats_AUDIO_AMR},
"audio/mp3": {Extension: "mp3", Type: binary.MediaFormats_AUDIO_MP3}, "audio/mp3": {Extension: "mp3", Type: gmproto.MediaFormats_AUDIO_MP3},
"audio/mpeg": {Extension: "mpeg", Type: binary.MediaFormats_AUDIO_MPEG}, "audio/mpeg": {Extension: "mpeg", Type: gmproto.MediaFormats_AUDIO_MPEG},
"audio/mpg": {Extension: "mpg", Type: binary.MediaFormats_AUDIO_MPG}, "audio/mpg": {Extension: "mpg", Type: gmproto.MediaFormats_AUDIO_MPG},
"audio/mp4": {Extension: "mp4", Type: binary.MediaFormats_AUDIO_MP4}, "audio/mp4": {Extension: "mp4", Type: gmproto.MediaFormats_AUDIO_MP4},
"audio/mp4-latm": {Extension: "latm", Type: binary.MediaFormats_AUDIO_MP4_LATM}, "audio/mp4-latm": {Extension: "latm", Type: gmproto.MediaFormats_AUDIO_MP4_LATM},
"audio/3gpp": {Extension: "3gpp", Type: binary.MediaFormats_AUDIO_3GPP}, "audio/3gpp": {Extension: "3gpp", Type: gmproto.MediaFormats_AUDIO_3GPP},
"audio/ogg": {Extension: "ogg", Type: binary.MediaFormats_AUDIO_OGG}, "audio/ogg": {Extension: "ogg", Type: gmproto.MediaFormats_AUDIO_OGG},
"text/vcard": {Extension: "vcard", Type: binary.MediaFormats_TEXT_VCARD}, "text/vcard": {Extension: "vcard", Type: gmproto.MediaFormats_TEXT_VCARD},
"application/pdf": {Extension: "pdf", Type: binary.MediaFormats_APP_PDF}, "application/pdf": {Extension: "pdf", Type: gmproto.MediaFormats_APP_PDF},
"text/plain": {Extension: "txt", Type: binary.MediaFormats_APP_TXT}, "text/plain": {Extension: "txt", Type: gmproto.MediaFormats_APP_TXT},
"text/html": {Extension: "html", Type: binary.MediaFormats_APP_HTML}, "text/html": {Extension: "html", Type: gmproto.MediaFormats_APP_HTML},
"application/msword": {Extension: "doc", Type: binary.MediaFormats_APP_DOC}, "application/msword": {Extension: "doc", Type: gmproto.MediaFormats_APP_DOC},
"application/vnd.openxmlformats-officedocument.wordprocessingml.document": {Extension: "docx", Type: binary.MediaFormats_APP_DOCX}, "application/vnd.openxmlformats-officedocument.wordprocessingml.document": {Extension: "docx", Type: gmproto.MediaFormats_APP_DOCX},
"application/vnd.openxmlformats-officedocument.presentationml.presentation": {Extension: "pptx", Type: binary.MediaFormats_APP_PPTX}, "application/vnd.openxmlformats-officedocument.presentationml.presentation": {Extension: "pptx", Type: gmproto.MediaFormats_APP_PPTX},
"application/vnd.ms-powerpoint": {Extension: "ppt", Type: binary.MediaFormats_APP_PPT}, "application/vnd.ms-powerpoint": {Extension: "ppt", Type: gmproto.MediaFormats_APP_PPT},
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet": {Extension: "xlsx", Type: binary.MediaFormats_APP_XLSX}, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet": {Extension: "xlsx", Type: gmproto.MediaFormats_APP_XLSX},
"application/vnd.ms-excel": {Extension: "xls", Type: binary.MediaFormats_APP_XLS}, "application/vnd.ms-excel": {Extension: "xls", Type: gmproto.MediaFormats_APP_XLS},
"application/vnd.android.package-archive": {Extension: "apk", Type: binary.MediaFormats_APP_APK}, "application/vnd.android.package-archive": {Extension: "apk", Type: gmproto.MediaFormats_APP_APK},
"application/zip": {Extension: "zip", Type: binary.MediaFormats_APP_ZIP}, "application/zip": {Extension: "zip", Type: gmproto.MediaFormats_APP_ZIP},
"application/java-archive": {Extension: "jar", Type: binary.MediaFormats_APP_JAR}, "application/java-archive": {Extension: "jar", Type: gmproto.MediaFormats_APP_JAR},
"text/x-calendar": {Extension: "vcs", Type: binary.MediaFormats_CAL_TEXT_VCALENDAR}, "text/x-calendar": {Extension: "vcs", Type: gmproto.MediaFormats_CAL_TEXT_VCALENDAR},
"text/calendar": {Extension: "ics", Type: binary.MediaFormats_CAL_TEXT_CALENDAR}, "text/calendar": {Extension: "ics", Type: gmproto.MediaFormats_CAL_TEXT_CALENDAR},
"image": {Type: binary.MediaFormats_IMAGE_UNSPECIFIED}, "image": {Type: gmproto.MediaFormats_IMAGE_UNSPECIFIED},
"video": {Type: binary.MediaFormats_VIDEO_UNSPECIFIED}, "video": {Type: gmproto.MediaFormats_VIDEO_UNSPECIFIED},
"audio": {Type: binary.MediaFormats_AUDIO_UNSPECIFIED}, "audio": {Type: gmproto.MediaFormats_AUDIO_UNSPECIFIED},
"application": {Type: binary.MediaFormats_APP_UNSPECIFIED}, "application": {Type: gmproto.MediaFormats_APP_UNSPECIFIED},
"text": {Type: binary.MediaFormats_APP_TXT}, "text": {Type: gmproto.MediaFormats_APP_TXT},
} }
var FormatToMediaType = map[binary.MediaFormats]MediaType{ var FormatToMediaType = map[gmproto.MediaFormats]MediaType{
binary.MediaFormats_CAL_TEXT_XVCALENDAR: MimeToMediaType["text/x-calendar"], gmproto.MediaFormats_CAL_TEXT_XVCALENDAR: MimeToMediaType["text/x-calendar"],
binary.MediaFormats_CAL_APPLICATION_VCS: MimeToMediaType["text/x-calendar"], gmproto.MediaFormats_CAL_APPLICATION_VCS: MimeToMediaType["text/x-calendar"],
binary.MediaFormats_CAL_APPLICATION_ICS: MimeToMediaType["text/calendar"], gmproto.MediaFormats_CAL_APPLICATION_ICS: MimeToMediaType["text/calendar"],
//binary.MediaFormats_CAL_APPLICATION_HBSVCS: ??? //gmproto.MediaFormats_CAL_APPLICATION_HBSVCS: ???
} }
func init() { func init() {
@ -87,7 +87,7 @@ func init() {
} }
} }
func (c *Client) UploadMedia(data []byte, fileName, mime string) (*binary.MediaContent, error) { func (c *Client) UploadMedia(data []byte, fileName, mime string) (*gmproto.MediaContent, error) {
mediaType := MimeToMediaType[mime] mediaType := MimeToMediaType[mime]
if mediaType.Type == 0 { if mediaType.Type == 0 {
mediaType = MimeToMediaType[strings.Split(mime, "/")[0]] mediaType = MimeToMediaType[strings.Split(mime, "/")[0]]
@ -109,7 +109,7 @@ func (c *Client) UploadMedia(data []byte, fileName, mime string) (*binary.MediaC
if err != nil { if err != nil {
return nil, err return nil, err
} }
return &binary.MediaContent{ return &gmproto.MediaContent{
Format: mediaType.Type, Format: mediaType.Type,
MediaID: upload.MediaID, MediaID: upload.MediaID,
MediaName: fileName, MediaName: fileName,
@ -171,7 +171,7 @@ func (c *Client) FinalizeUploadMedia(upload *StartGoogleUpload) (*MediaUpload, e
uploadStatus := rHeaders.Get("x-goog-upload-status") uploadStatus := rHeaders.Get("x-goog-upload-status")
c.Logger.Debug().Str("upload_status", uploadStatus).Msg("Upload complete") c.Logger.Debug().Str("upload_status", uploadStatus).Msg("Upload complete")
mediaIDs := &binary.UploadMediaResponse{} mediaIDs := &gmproto.UploadMediaResponse{}
err3 = proto.Unmarshal(googleResponse, mediaIDs) err3 = proto.Unmarshal(googleResponse, mediaIDs)
if err3 != nil { if err3 != nil {
return nil, err3 return nil, err3
@ -229,9 +229,9 @@ func (c *Client) StartUploadMedia(encryptedImageBytes []byte, mime string) (*Sta
} }
func (c *Client) buildStartUploadPayload() (string, error) { func (c *Client) buildStartUploadPayload() (string, error) {
protoData := &binary.StartMediaUploadPayload{ protoData := &gmproto.StartMediaUploadPayload{
ImageType: 1, ImageType: 1,
AuthData: &binary.AuthMessage{ AuthData: &gmproto.AuthMessage{
RequestID: uuid.NewString(), RequestID: uuid.NewString(),
TachyonAuthToken: c.AuthData.TachyonAuthToken, TachyonAuthToken: c.AuthData.TachyonAuthToken,
ConfigVersion: util.ConfigMessage, ConfigVersion: util.ConfigMessage,

View file

@ -1,10 +1,10 @@
package util package util
import ( import (
"go.mau.fi/mautrix-gmessages/libgm/binary" "go.mau.fi/mautrix-gmessages/libgm/gmproto"
) )
var ConfigMessage = &binary.ConfigVersion{ var ConfigMessage = &gmproto.ConfigVersion{
Year: 2023, Year: 2023,
Month: 7, Month: 7,
Day: 10, Day: 10,
@ -12,9 +12,9 @@ var ConfigMessage = &binary.ConfigVersion{
V2: 6, V2: 6,
} }
var Network = "Bugle" var Network = "Bugle"
var BrowserDetailsMessage = &binary.BrowserDetails{ var BrowserDetailsMessage = &gmproto.BrowserDetails{
UserAgent: UserAgent, UserAgent: UserAgent,
BrowserType: binary.BrowserTypes_OTHER, BrowserType: gmproto.BrowserTypes_OTHER,
OS: "libgm", OS: "libgm",
SomeBool: true, SomeBool: true,
} }

View file

@ -8,7 +8,7 @@ import (
"strconv" "strconv"
"time" "time"
"go.mau.fi/mautrix-gmessages/libgm/binary" "go.mau.fi/mautrix-gmessages/libgm/gmproto"
) )
func GenerateTmpID() string { func GenerateTmpID() string {
@ -91,7 +91,7 @@ func NewMediaUploadHeaders(imageSize string, command string, uploadOffset string
return headers return headers
} }
func ParseConfigVersion(res []byte) (*binary.ConfigVersion, error) { func ParseConfigVersion(res []byte) (*gmproto.ConfigVersion, error) {
var data []interface{} var data []interface{}
marshalErr := json.Unmarshal(res, &data) marshalErr := json.Unmarshal(res, &data)
@ -126,7 +126,7 @@ func ParseConfigVersion(res []byte) (*binary.ConfigVersion, error) {
return nil, e2 return nil, e2
} }
configMessage := &binary.ConfigVersion{ configMessage := &gmproto.ConfigVersion{
Year: int32(first), Year: int32(first),
Month: int32(second), Month: int32(second),
Day: int32(third), Day: int32(third),

View file

@ -28,7 +28,7 @@ import (
"go.mau.fi/mautrix-gmessages/config" "go.mau.fi/mautrix-gmessages/config"
"go.mau.fi/mautrix-gmessages/database" "go.mau.fi/mautrix-gmessages/database"
"go.mau.fi/mautrix-gmessages/libgm/binary" "go.mau.fi/mautrix-gmessages/libgm/gmproto"
"go.mau.fi/mautrix-gmessages/libgm/util" "go.mau.fi/mautrix-gmessages/libgm/util"
) )
@ -68,11 +68,11 @@ func (br *GMBridge) Init() {
br.RegisterCommands() br.RegisterCommands()
util.BrowserDetailsMessage.OS = br.Config.GoogleMessages.OS util.BrowserDetailsMessage.OS = br.Config.GoogleMessages.OS
browserVal, ok := binary.BrowserTypes_value[br.Config.GoogleMessages.Browser] browserVal, ok := gmproto.BrowserTypes_value[br.Config.GoogleMessages.Browser]
if !ok { if !ok {
br.ZLog.Error().Str("browser_value", br.Config.GoogleMessages.Browser).Msg("Invalid browser value") br.ZLog.Error().Str("browser_value", br.Config.GoogleMessages.Browser).Msg("Invalid browser value")
} else { } else {
util.BrowserDetailsMessage.BrowserType = binary.BrowserTypes(browserVal) util.BrowserDetailsMessage.BrowserType = gmproto.BrowserTypes(browserVal)
} }
Segment.log = br.ZLog.With().Str("component", "segment").Logger() Segment.log = br.ZLog.With().Str("component", "segment").Logger()

View file

@ -31,7 +31,7 @@ import (
"maunium.net/go/mautrix/event" "maunium.net/go/mautrix/event"
"maunium.net/go/mautrix/id" "maunium.net/go/mautrix/id"
"go.mau.fi/mautrix-gmessages/libgm/binary" "go.mau.fi/mautrix-gmessages/libgm/gmproto"
) )
var ( var (
@ -48,10 +48,10 @@ var (
errMessageTakingLong = errors.New("bridging the message is taking longer than usual") errMessageTakingLong = errors.New("bridging the message is taking longer than usual")
) )
type OutgoingStatusError binary.MessageStatusType type OutgoingStatusError gmproto.MessageStatusType
func (ose OutgoingStatusError) Error() string { func (ose OutgoingStatusError) Error() string {
return strings.TrimPrefix(string((binary.MessageStatusType)(ose).Descriptor().Name()), "OUTGOING_") return strings.TrimPrefix(string((gmproto.MessageStatusType)(ose).Descriptor().Name()), "OUTGOING_")
} }
func (ose OutgoingStatusError) HumanError() string { func (ose OutgoingStatusError) HumanError() string {

View file

@ -42,7 +42,7 @@ import (
"go.mau.fi/mautrix-gmessages/database" "go.mau.fi/mautrix-gmessages/database"
"go.mau.fi/mautrix-gmessages/libgm" "go.mau.fi/mautrix-gmessages/libgm"
"go.mau.fi/mautrix-gmessages/libgm/binary" "go.mau.fi/mautrix-gmessages/libgm/gmproto"
"go.mau.fi/mautrix-gmessages/libgm/util" "go.mau.fi/mautrix-gmessages/libgm/util"
) )
@ -208,7 +208,7 @@ func (br *GMBridge) NewPortal(dbPortal *database.Portal) *Portal {
const recentlyHandledLength = 100 const recentlyHandledLength = 100
type PortalMessage struct { type PortalMessage struct {
evt *binary.Message evt *gmproto.Message
source *User source *User
} }
@ -313,7 +313,7 @@ func (portal *Portal) handleMessageLoop() {
} }
} }
func (portal *Portal) isOutgoingMessage(msg *binary.Message) id.EventID { func (portal *Portal) isOutgoingMessage(msg *gmproto.Message) id.EventID {
portal.outgoingMessagesLock.Lock() portal.outgoingMessagesLock.Lock()
defer portal.outgoingMessagesLock.Unlock() defer portal.outgoingMessagesLock.Unlock()
out, ok := portal.outgoingMessages[msg.TmpID] out, ok := portal.outgoingMessages[msg.TmpID]
@ -327,18 +327,18 @@ func (portal *Portal) isOutgoingMessage(msg *binary.Message) id.EventID {
out.Saved = true out.Saved = true
} }
switch msg.GetMessageStatus().GetStatus() { switch msg.GetMessageStatus().GetStatus() {
case binary.MessageStatusType_OUTGOING_DELIVERED, binary.MessageStatusType_OUTGOING_COMPLETE, binary.MessageStatusType_OUTGOING_DISPLAYED: case gmproto.MessageStatusType_OUTGOING_DELIVERED, gmproto.MessageStatusType_OUTGOING_COMPLETE, gmproto.MessageStatusType_OUTGOING_DISPLAYED:
delete(portal.outgoingMessages, msg.TmpID) delete(portal.outgoingMessages, msg.TmpID)
go portal.sendStatusEvent(out.ID, "", nil) go portal.sendStatusEvent(out.ID, "", nil)
case binary.MessageStatusType_OUTGOING_FAILED_GENERIC, case gmproto.MessageStatusType_OUTGOING_FAILED_GENERIC,
binary.MessageStatusType_OUTGOING_FAILED_EMERGENCY_NUMBER, gmproto.MessageStatusType_OUTGOING_FAILED_EMERGENCY_NUMBER,
binary.MessageStatusType_OUTGOING_CANCELED, gmproto.MessageStatusType_OUTGOING_CANCELED,
binary.MessageStatusType_OUTGOING_FAILED_TOO_LARGE, gmproto.MessageStatusType_OUTGOING_FAILED_TOO_LARGE,
binary.MessageStatusType_OUTGOING_FAILED_RECIPIENT_LOST_RCS, gmproto.MessageStatusType_OUTGOING_FAILED_RECIPIENT_LOST_RCS,
binary.MessageStatusType_OUTGOING_FAILED_NO_RETRY_NO_FALLBACK, gmproto.MessageStatusType_OUTGOING_FAILED_NO_RETRY_NO_FALLBACK,
binary.MessageStatusType_OUTGOING_FAILED_RECIPIENT_DID_NOT_DECRYPT, gmproto.MessageStatusType_OUTGOING_FAILED_RECIPIENT_DID_NOT_DECRYPT,
binary.MessageStatusType_OUTGOING_FAILED_RECIPIENT_LOST_ENCRYPTION, gmproto.MessageStatusType_OUTGOING_FAILED_RECIPIENT_LOST_ENCRYPTION,
binary.MessageStatusType_OUTGOING_FAILED_RECIPIENT_DID_NOT_DECRYPT_NO_MORE_RETRY: gmproto.MessageStatusType_OUTGOING_FAILED_RECIPIENT_DID_NOT_DECRYPT_NO_MORE_RETRY:
err := OutgoingStatusError(msg.GetMessageStatus().GetStatus()) err := OutgoingStatusError(msg.GetMessageStatus().GetStatus())
go portal.sendStatusEvent(out.ID, "", err) go portal.sendStatusEvent(out.ID, "", err)
// TODO error notice // TODO error notice
@ -347,9 +347,9 @@ func (portal *Portal) isOutgoingMessage(msg *binary.Message) id.EventID {
} }
return "" return ""
} }
func hasInProgressMedia(msg *binary.Message) bool { func hasInProgressMedia(msg *gmproto.Message) bool {
for _, part := range msg.MessageInfo { for _, part := range msg.MessageInfo {
media, ok := part.GetData().(*binary.MessageInfo_MediaContent) media, ok := part.GetData().(*gmproto.MessageInfo_MediaContent)
if ok && media.MediaContent.GetMediaID() == "" { if ok && media.MediaContent.GetMediaID() == "" {
return true return true
} }
@ -357,7 +357,7 @@ func hasInProgressMedia(msg *binary.Message) bool {
return false return false
} }
func (portal *Portal) handleMessage(source *User, evt *binary.Message) { func (portal *Portal) handleMessage(source *User, evt *gmproto.Message) {
if len(portal.MXID) == 0 { if len(portal.MXID) == 0 {
portal.zlog.Warn().Msg("handleMessage called even though portal.MXID is empty") portal.zlog.Warn().Msg("handleMessage called even though portal.MXID is empty")
return return
@ -374,10 +374,10 @@ func (portal *Portal) handleMessage(source *User, evt *binary.Message) {
Logger() Logger()
ctx := log.WithContext(context.TODO()) ctx := log.WithContext(context.TODO())
switch evt.GetMessageStatus().GetStatus() { switch evt.GetMessageStatus().GetStatus() {
case binary.MessageStatusType_INCOMING_AUTO_DOWNLOADING, binary.MessageStatusType_INCOMING_RETRYING_AUTO_DOWNLOAD: case gmproto.MessageStatusType_INCOMING_AUTO_DOWNLOADING, gmproto.MessageStatusType_INCOMING_RETRYING_AUTO_DOWNLOAD:
log.Debug().Msg("Not handling incoming message that is auto downloading") log.Debug().Msg("Not handling incoming message that is auto downloading")
return return
case binary.MessageStatusType_MESSAGE_DELETED: case gmproto.MessageStatusType_MESSAGE_DELETED:
portal.handleGoogleDeletion(ctx, evt.MessageID) portal.handleGoogleDeletion(ctx, evt.MessageID)
return return
} }
@ -435,7 +435,7 @@ func (portal *Portal) handleGoogleDeletion(ctx context.Context, messageID string
} }
} }
func (portal *Portal) syncReactions(ctx context.Context, source *User, message *database.Message, reactions []*binary.ReactionResponse) { func (portal *Portal) syncReactions(ctx context.Context, source *User, message *database.Message, reactions []*gmproto.ReactionResponse) {
log := zerolog.Ctx(ctx) log := zerolog.Ctx(ctx)
existing, err := portal.bridge.DB.Reaction.GetAllByMessage(ctx, portal.Key, message.ID) existing, err := portal.bridge.DB.Reaction.GetAllByMessage(ctx, portal.Key, message.ID)
if err != nil { if err != nil {
@ -535,7 +535,7 @@ func (portal *Portal) getIntent(ctx context.Context, source *User, participant s
} }
} }
func (portal *Portal) convertGoogleMessage(ctx context.Context, source *User, evt *binary.Message, backfill bool) *ConvertedMessage { func (portal *Portal) convertGoogleMessage(ctx context.Context, source *User, evt *gmproto.Message, backfill bool) *ConvertedMessage {
log := zerolog.Ctx(ctx) log := zerolog.Ctx(ctx)
var cm ConvertedMessage var cm ConvertedMessage
@ -568,7 +568,7 @@ func (portal *Portal) convertGoogleMessage(ctx context.Context, source *User, ev
for _, part := range evt.MessageInfo { for _, part := range evt.MessageInfo {
var content event.MessageEventContent var content event.MessageEventContent
switch data := part.GetData().(type) { switch data := part.GetData().(type) {
case *binary.MessageInfo_MessageContent: case *gmproto.MessageInfo_MessageContent:
content = event.MessageEventContent{ content = event.MessageEventContent{
MsgType: event.MsgText, MsgType: event.MsgText,
Body: data.MessageContent.GetContent(), Body: data.MessageContent.GetContent(),
@ -579,7 +579,7 @@ func (portal *Portal) convertGoogleMessage(ctx context.Context, source *User, ev
content.Body = fmt.Sprintf("**%s**\n%s", subject, content.Body) content.Body = fmt.Sprintf("**%s**\n%s", subject, content.Body)
subject = "" subject = ""
} }
case *binary.MessageInfo_MediaContent: case *gmproto.MessageInfo_MediaContent:
contentPtr, err := portal.convertGoogleMedia(source, cm.Intent, data.MediaContent) contentPtr, err := portal.convertGoogleMedia(source, cm.Intent, data.MediaContent)
if err != nil { if err != nil {
log.Err(err).Msg("Failed to copy attachment") log.Err(err).Msg("Failed to copy attachment")
@ -642,7 +642,7 @@ func (msg *ConvertedMessage) MergeCaption() {
msg.Parts = []ConvertedMessagePart{filePart} msg.Parts = []ConvertedMessagePart{filePart}
} }
func (portal *Portal) convertGoogleMedia(source *User, intent *appservice.IntentAPI, msg *binary.MediaContent) (*event.MessageEventContent, error) { func (portal *Portal) convertGoogleMedia(source *User, intent *appservice.IntentAPI, msg *gmproto.MediaContent) (*event.MessageEventContent, error) {
var data []byte var data []byte
var err error var err error
data, err = source.Client.DownloadMedia(msg.MediaID, msg.DecryptionKey) data, err = source.Client.DownloadMedia(msg.MediaID, msg.DecryptionKey)
@ -707,8 +707,8 @@ func (portal *Portal) markHandled(cm *ConvertedMessage, eventID id.EventID, rece
return msg return msg
} }
func (portal *Portal) SyncParticipants(source *User, metadata *binary.Conversation) (userIDs []id.UserID, changed bool) { func (portal *Portal) SyncParticipants(source *User, metadata *gmproto.Conversation) (userIDs []id.UserID, changed bool) {
var firstParticipant *binary.Participant var firstParticipant *gmproto.Participant
var manyParticipants bool var manyParticipants bool
for _, participant := range metadata.Participants { for _, participant := range metadata.Participants {
if participant.IsMe { if participant.IsMe {
@ -782,7 +782,7 @@ func (portal *Portal) UpdateName(name string, updateInfo bool) bool {
return false return false
} }
func (portal *Portal) UpdateMetadata(user *User, info *binary.Conversation) []id.UserID { func (portal *Portal) UpdateMetadata(user *User, info *gmproto.Conversation) []id.UserID {
participants, update := portal.SyncParticipants(user, info) participants, update := portal.SyncParticipants(user, info)
if portal.SelfUserID != info.SelfParticipantID { if portal.SelfUserID != info.SelfParticipantID {
portal.SelfUserID = info.SelfParticipantID portal.SelfUserID = info.SelfParticipantID
@ -811,7 +811,7 @@ func (portal *Portal) ensureUserInvited(user *User) bool {
return user.ensureInvited(portal.MainIntent(), portal.MXID, portal.IsPrivateChat()) return user.ensureInvited(portal.MainIntent(), portal.MXID, portal.IsPrivateChat())
} }
func (portal *Portal) UpdateMatrixRoom(user *User, groupInfo *binary.Conversation) bool { func (portal *Portal) UpdateMatrixRoom(user *User, groupInfo *gmproto.Conversation) bool {
if len(portal.MXID) == 0 { if len(portal.MXID) == 0 {
return false return false
} }
@ -899,7 +899,7 @@ func (portal *Portal) GetEncryptionEventContent() (evt *event.EncryptionEventCon
return return
} }
func (portal *Portal) CreateMatrixRoom(user *User, conv *binary.Conversation) error { func (portal *Portal) CreateMatrixRoom(user *User, conv *gmproto.Conversation) error {
portal.roomCreateLock.Lock() portal.roomCreateLock.Lock()
defer portal.roomCreateLock.Unlock() defer portal.roomCreateLock.Unlock()
if len(portal.MXID) > 0 { if len(portal.MXID) > 0 {
@ -1172,12 +1172,12 @@ func (portal *Portal) uploadMedia(intent *appservice.IntentAPI, data []byte, con
return nil return nil
} }
func (portal *Portal) convertMatrixMessage(ctx context.Context, sender *User, content *event.MessageEventContent, txnID string) (*binary.SendMessagePayload, error) { func (portal *Portal) convertMatrixMessage(ctx context.Context, sender *User, content *event.MessageEventContent, txnID string) (*gmproto.SendMessagePayload, error) {
log := zerolog.Ctx(ctx) log := zerolog.Ctx(ctx)
req := &binary.SendMessagePayload{ req := &gmproto.SendMessagePayload{
ConversationID: portal.ID, ConversationID: portal.ID,
TmpID: txnID, TmpID: txnID,
MessagePayload: &binary.MessagePayload{ MessagePayload: &gmproto.MessagePayload{
ConversationID: portal.ID, ConversationID: portal.ID,
TmpID: txnID, TmpID: txnID,
TmpID2: txnID, TmpID2: txnID,
@ -1194,7 +1194,7 @@ func (portal *Portal) convertMatrixMessage(ctx context.Context, sender *User, co
log.Warn().Str("reply_to_mxid", replyToMXID.String()).Msg("Reply target message not found") log.Warn().Str("reply_to_mxid", replyToMXID.String()).Msg("Reply target message not found")
} else { } else {
req.IsReply = true req.IsReply = true
req.Reply = &binary.ReplyPayload{MessageID: replyToMsg.ID} req.Reply = &gmproto.ReplyPayload{MessageID: replyToMsg.ID}
} }
} }
@ -1204,8 +1204,8 @@ func (portal *Portal) convertMatrixMessage(ctx context.Context, sender *User, co
if content.MsgType == event.MsgEmote { if content.MsgType == event.MsgEmote {
text = "/me " + text text = "/me " + text
} }
req.MessagePayload.MessageInfo = []*binary.MessageInfo{{ req.MessagePayload.MessageInfo = []*gmproto.MessageInfo{{
Data: &binary.MessageInfo_MessageContent{MessageContent: &binary.MessageContent{ Data: &gmproto.MessageInfo_MessageContent{MessageContent: &gmproto.MessageContent{
Content: text, Content: text,
}}, }},
}} }}
@ -1240,8 +1240,8 @@ func (portal *Portal) convertMatrixMessage(ctx context.Context, sender *User, co
if err != nil { if err != nil {
return nil, mutil.NewDualError(errMediaReuploadFailed, err) return nil, mutil.NewDualError(errMediaReuploadFailed, err)
} }
req.MessagePayload.MessageInfo = []*binary.MessageInfo{{ req.MessagePayload.MessageInfo = []*gmproto.MessageInfo{{
Data: &binary.MessageInfo_MediaContent{MediaContent: resp}, Data: &gmproto.MessageInfo_MediaContent{MediaContent: resp},
}} }}
default: default:
return nil, fmt.Errorf("%w %s", errUnknownMsgType, content.MsgType) return nil, fmt.Errorf("%w %s", errUnknownMsgType, content.MsgType)
@ -1349,13 +1349,13 @@ func (portal *Portal) handleMatrixReaction(sender *User, evt *event.Event) error
} }
emoji := variationselector.Remove(content.RelatesTo.Key) emoji := variationselector.Remove(content.RelatesTo.Key)
action := binary.Reaction_ADD action := gmproto.Reaction_ADD
if existingReaction != nil { if existingReaction != nil {
action = binary.Reaction_SWITCH action = gmproto.Reaction_SWITCH
} }
resp, err := sender.Client.SendReaction(&binary.SendReactionPayload{ resp, err := sender.Client.SendReaction(&gmproto.SendReactionPayload{
MessageID: msg.ID, MessageID: msg.ID,
ReactionData: binary.MakeReactionData(emoji), ReactionData: gmproto.MakeReactionData(emoji),
Action: action, Action: action,
}) })
if err != nil { if err != nil {
@ -1425,10 +1425,10 @@ func (portal *Portal) handleMatrixReactionRedaction(ctx context.Context, sender
return errTargetNotFound return errTargetNotFound
} }
resp, err := sender.Client.SendReaction(&binary.SendReactionPayload{ resp, err := sender.Client.SendReaction(&gmproto.SendReactionPayload{
MessageID: existingReaction.MessageID, MessageID: existingReaction.MessageID,
ReactionData: binary.MakeReactionData(existingReaction.Reaction), ReactionData: gmproto.MakeReactionData(existingReaction.Reaction),
Action: binary.Reaction_REMOVE, Action: gmproto.Reaction_REMOVE,
}) })
if err != nil { if err != nil {
return fmt.Errorf("failed to send reaction removal: %w", err) return fmt.Errorf("failed to send reaction removal: %w", err)

View file

@ -32,7 +32,7 @@ import (
"maunium.net/go/mautrix/bridge/status" "maunium.net/go/mautrix/bridge/status"
"maunium.net/go/mautrix/id" "maunium.net/go/mautrix/id"
"go.mau.fi/mautrix-gmessages/libgm/binary" "go.mau.fi/mautrix-gmessages/libgm/gmproto"
) )
type ProvisioningAPI struct { type ProvisioningAPI struct {
@ -195,10 +195,10 @@ func (prov *ProvisioningAPI) StartChat(w http.ResponseWriter, r *http.Request) {
ErrCode: "bad json", ErrCode: "bad json",
}) })
} }
var reqData binary.GetOrCreateConversationPayload var reqData gmproto.GetOrCreateConversationPayload
reqData.Numbers = make([]*binary.ContactNumber, 0, len(req.Numbers)) reqData.Numbers = make([]*gmproto.ContactNumber, 0, len(req.Numbers))
for _, number := range req.Numbers { for _, number := range req.Numbers {
reqData.Numbers = append(reqData.Numbers, &binary.ContactNumber{ reqData.Numbers = append(reqData.Numbers, &gmproto.ContactNumber{
// This should maybe sometimes be 7 // This should maybe sometimes be 7
MysteriousInt: 2, MysteriousInt: 2,
Number: number, Number: number,
@ -213,7 +213,7 @@ func (prov *ProvisioningAPI) StartChat(w http.ResponseWriter, r *http.Request) {
ErrCode: "unknown error", ErrCode: "unknown error",
}) })
return return
} else if resp.GetStatus() == binary.GetOrCreateConversationResponse_CREATE_RCS { } else if resp.GetStatus() == gmproto.GetOrCreateConversationResponse_CREATE_RCS {
prov.zlog.Debug().Msg("Creating RCS group") prov.zlog.Debug().Msg("Creating RCS group")
// TODO this will always create a new group and won't deduplicate // TODO this will always create a new group and won't deduplicate
reqData.CreateRCSGroup = proto.Bool(true) reqData.CreateRCSGroup = proto.Bool(true)

View file

@ -29,7 +29,7 @@ import (
"maunium.net/go/mautrix/id" "maunium.net/go/mautrix/id"
"go.mau.fi/mautrix-gmessages/database" "go.mau.fi/mautrix-gmessages/database"
"go.mau.fi/mautrix-gmessages/libgm/binary" "go.mau.fi/mautrix-gmessages/libgm/gmproto"
) )
var userIDRegex *regexp.Regexp var userIDRegex *regexp.Regexp
@ -253,7 +253,7 @@ func (puppet *Puppet) updatePortalName() {
// TODO implement // TODO implement
} }
func (puppet *Puppet) Sync(source *User, contact *binary.Participant) { func (puppet *Puppet) Sync(source *User, contact *gmproto.Participant) {
err := puppet.DefaultIntent().EnsureRegistered() err := puppet.DefaultIntent().EnsureRegistered()
if err != nil { if err != nil {
puppet.log.Err(err).Msg("Failed to ensure registered") puppet.log.Err(err).Msg("Failed to ensure registered")

34
user.go
View file

@ -42,8 +42,8 @@ import (
"go.mau.fi/mautrix-gmessages/database" "go.mau.fi/mautrix-gmessages/database"
"go.mau.fi/mautrix-gmessages/libgm" "go.mau.fi/mautrix-gmessages/libgm"
"go.mau.fi/mautrix-gmessages/libgm/binary"
"go.mau.fi/mautrix-gmessages/libgm/events" "go.mau.fi/mautrix-gmessages/libgm/events"
"go.mau.fi/mautrix-gmessages/libgm/gmproto"
) )
type User struct { type User struct {
@ -602,7 +602,7 @@ func (user *User) HandleEvent(event interface{}) {
if ch := user.pairSuccessChan; ch != nil { if ch := user.pairSuccessChan; ch != nil {
close(ch) close(ch)
} }
case *binary.RevokePairData: case *gmproto.RevokePairData:
user.zlog.Info().Any("revoked_device", v.GetRevokedDevice()).Msg("Got pair revoked event") user.zlog.Info().Any("revoked_device", v.GetRevokedDevice()).Msg("Got pair revoked event")
user.Logout(status.BridgeState{ user.Logout(status.BridgeState{
StateEvent: status.StateBadCredentials, StateEvent: status.StateBadCredentials,
@ -613,9 +613,9 @@ func (user *User) HandleEvent(event interface{}) {
if err != nil { if err != nil {
user.zlog.Err(err).Msg("Failed to update session in database") user.zlog.Err(err).Msg("Failed to update session in database")
} }
case *binary.Conversation: case *gmproto.Conversation:
user.syncConversation(v) user.syncConversation(v)
case *binary.Message: case *gmproto.Message:
portal := user.GetPortalByID(v.GetConversationID()) portal := user.GetPortalByID(v.GetConversationID())
portal.messages <- PortalMessage{evt: v, source: user} portal.messages <- PortalMessage{evt: v, source: user}
case *events.ClientReady: case *events.ClientReady:
@ -629,30 +629,30 @@ func (user *User) HandleEvent(event interface{}) {
case *events.BrowserActive: case *events.BrowserActive:
user.zlog.Trace().Any("data", v).Msg("Browser active") user.zlog.Trace().Any("data", v).Msg("Browser active")
user.browserInactiveType = "" user.browserInactiveType = ""
case *binary.UserAlertEvent: case *gmproto.UserAlertEvent:
user.handleUserAlert(v) user.handleUserAlert(v)
default: default:
user.zlog.Trace().Any("data", v).Type("data_type", v).Msg("Unknown event") user.zlog.Trace().Any("data", v).Type("data_type", v).Msg("Unknown event")
} }
} }
func (user *User) handleUserAlert(v *binary.UserAlertEvent) { func (user *User) handleUserAlert(v *gmproto.UserAlertEvent) {
user.zlog.Debug().Any("data", v).Msg("Got user alert event") user.zlog.Debug().Any("data", v).Msg("Got user alert event")
switch v.GetAlertType() { switch v.GetAlertType() {
case binary.AlertType_BROWSER_INACTIVE: case gmproto.AlertType_BROWSER_INACTIVE:
// TODO aggressively reactivate if configured to do so // TODO aggressively reactivate if configured to do so
user.browserInactiveType = GMBrowserInactive user.browserInactiveType = GMBrowserInactive
case binary.AlertType_BROWSER_INACTIVE_FROM_TIMEOUT: case gmproto.AlertType_BROWSER_INACTIVE_FROM_TIMEOUT:
user.browserInactiveType = GMBrowserInactiveTimeout user.browserInactiveType = GMBrowserInactiveTimeout
case binary.AlertType_BROWSER_INACTIVE_FROM_INACTIVITY: case gmproto.AlertType_BROWSER_INACTIVE_FROM_INACTIVITY:
user.browserInactiveType = GMBrowserInactiveInactivity user.browserInactiveType = GMBrowserInactiveInactivity
case binary.AlertType_MOBILE_DATA_CONNECTION: case gmproto.AlertType_MOBILE_DATA_CONNECTION:
user.mobileData = true user.mobileData = true
case binary.AlertType_MOBILE_WIFI_CONNECTION: case gmproto.AlertType_MOBILE_WIFI_CONNECTION:
user.mobileData = false user.mobileData = false
case binary.AlertType_MOBILE_BATTERY_LOW: case gmproto.AlertType_MOBILE_BATTERY_LOW:
user.batteryLow = true user.batteryLow = true
case binary.AlertType_MOBILE_BATTERY_RESTORED: case gmproto.AlertType_MOBILE_BATTERY_RESTORED:
user.batteryLow = false user.batteryLow = false
default: default:
return return
@ -696,13 +696,13 @@ func (user *User) Logout(state status.BridgeState, unpair bool) (logoutOK bool)
return return
} }
func (user *User) syncConversation(v *binary.Conversation) { func (user *User) syncConversation(v *gmproto.Conversation) {
updateType := v.GetStatus() updateType := v.GetStatus()
portal := user.GetPortalByID(v.GetConversationID()) portal := user.GetPortalByID(v.GetConversationID())
if portal.MXID != "" { if portal.MXID != "" {
switch updateType { switch updateType {
// TODO also delete if blocked? // TODO also delete if blocked?
case binary.ConvUpdateTypes_DELETED: case gmproto.ConvUpdateTypes_DELETED:
user.zlog.Info().Str("conversation_id", portal.ID).Msg("Got delete event, cleaning up portal") user.zlog.Info().Str("conversation_id", portal.ID).Msg("Got delete event, cleaning up portal")
portal.Delete() portal.Delete()
portal.Cleanup(false) portal.Cleanup(false)
@ -711,7 +711,7 @@ func (user *User) syncConversation(v *binary.Conversation) {
portal.missedForwardBackfill(user, time.UnixMicro(v.LastMessageTimestamp), v.LatestMessageID, !v.GetUnread()) portal.missedForwardBackfill(user, time.UnixMicro(v.LastMessageTimestamp), v.LatestMessageID, !v.GetUnread())
// TODO sync read status if there was nothing backfilled // TODO sync read status if there was nothing backfilled
} }
} else if updateType == binary.ConvUpdateTypes_UNARCHIVED || updateType == binary.ConvUpdateTypes_ARCHIVED { } else if updateType == gmproto.ConvUpdateTypes_UNARCHIVED || updateType == gmproto.ConvUpdateTypes_ARCHIVED {
err := portal.CreateMatrixRoom(user, v) err := portal.CreateMatrixRoom(user, v)
if err != nil { if err != nil {
user.zlog.Err(err).Msg("Error creating Matrix room from conversation event") user.zlog.Err(err).Msg("Error creating Matrix room from conversation event")
@ -787,7 +787,7 @@ type CustomReadMarkers struct {
FullyReadExtra CustomReadReceipt `json:"com.beeper.fully_read.extra"` FullyReadExtra CustomReadReceipt `json:"com.beeper.fully_read.extra"`
} }
func (user *User) syncChatDoublePuppetDetails(portal *Portal, conv *binary.Conversation, justCreated bool) { func (user *User) syncChatDoublePuppetDetails(portal *Portal, conv *gmproto.Conversation, justCreated bool) {
if user.DoublePuppetIntent == nil || len(portal.MXID) == 0 { if user.DoublePuppetIntent == nil || len(portal.MXID) == 0 {
return return
} }