Skip to content

Commit

Permalink
clean up and lint
Browse files Browse the repository at this point in the history
  • Loading branch information
rnons committed Dec 5, 2024
1 parent 7457b9d commit fbf6309
Show file tree
Hide file tree
Showing 6 changed files with 31 additions and 76 deletions.
12 changes: 1 addition & 11 deletions pkg/connector/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -100,21 +100,13 @@ func (c *GChatClient) onStreamEvent(ctx context.Context, raw any) {
fmt.Println("Invalid event", raw)
return
}
fmt.Println("- onEvent", evt)
switch *evt.Type {
case proto.Event_MESSAGE_POSTED:
msg := evt.Body.GetMessagePosted().Message
senderId := *msg.Creator.UserId.Id
c.UserLogin.Bridge.QueueRemoteEvent(c.UserLogin, &simplevent.Message[*proto.Message]{
EventMeta: simplevent.EventMeta{
Type: bridgev2.RemoteEventMessage,
// LogContext: func(c zerolog.Context) zerolog.Context {
// return c.
// Str("message_id", evtData.MessageID).
// Str("sender", sender.IDStr).
// Str("sender_login", sender.ScreenName).
// Bool("is_from_me", isFromMe)
// },
PortalKey: networkid.PortalKey{
ID: networkid.PortalID(evt.GroupId.String()),
Receiver: c.UserLogin.ID,
Expand All @@ -127,9 +119,7 @@ func (c *GChatClient) onStreamEvent(ctx context.Context, raw any) {
},
// Timestamp: evtData.CreatedAt,
},
ID: networkid.MessageID(*msg.LocalId),
// TargetMessage: networkid.MessageID(evtData.MessageID),
// Data: XMDFromEventMessage(&evtData),
ID: networkid.MessageID(*msg.LocalId),
Data: msg,
ConvertMessageFunc: func(ctx context.Context, portal *bridgev2.Portal, intent bridgev2.MatrixAPI, data *proto.Message) (*bridgev2.ConvertedMessage, error) {
return c.convertToMatrix(ctx, portal, intent, data), nil
Expand Down
8 changes: 5 additions & 3 deletions pkg/gchatmeow/api.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,13 @@ import (
"fmt"
"net/http"
"net/url"
"strconv"

pb "google.golang.org/protobuf/proto"
"google.golang.org/protobuf/reflect/protoreflect"

"go.mau.fi/mautrix-googlechat/pkg/gchatmeow/proto"
"go.mau.fi/util/ptr"
)

func (c *Client) gcRequest(ctx context.Context, endpoint string, requestPB protoreflect.ProtoMessage, responsePB protoreflect.ProtoMessage) error {
Expand All @@ -27,7 +29,7 @@ func (c *Client) gcRequest(ctx context.Context, endpoint string, requestPB proto
}

params := url.Values{}
params.Set("c", string(c.apiReqID))
params.Set("c", strconv.FormatInt(c.apiReqID, 10))
params.Set("rt", "b")
res, err := c.baseRequest(
ctx,
Expand All @@ -37,7 +39,7 @@ func (c *Client) gcRequest(ctx context.Context, endpoint string, requestPB proto
requestData,
headers,
params,
"POST",
http.MethodPost,
)
if err != nil {
return err
Expand Down Expand Up @@ -114,7 +116,7 @@ func (c *Client) getMembers(ctx context.Context, gcid *string) (*proto.GetMember
func (c *Client) paginatedWorld(ctx context.Context) (*proto.PaginatedWorldResponse, error) {
request := &proto.PaginatedWorldRequest{
RequestHeader: c.gcRequestHeader,
FetchFromUserSpaces: GetPointer(true),
FetchFromUserSpaces: ptr.Ptr(true),
FetchOptions: []proto.PaginatedWorldRequest_FetchOptions{
proto.PaginatedWorldRequest_EXCLUDE_GROUP_LITE,
},
Expand Down
28 changes: 13 additions & 15 deletions pkg/gchatmeow/channel.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
package gchatmeow

import (
_ "bytes"
"context"
"encoding/base64"
"encoding/binary"
Expand All @@ -18,7 +17,6 @@ import (
"strconv"
"strings"
"time"
_ "unicode/utf16"
"unicode/utf8"

"go.mau.fi/util/pblite"
Expand Down Expand Up @@ -205,12 +203,12 @@ func (c *Channel) Listen(ctx context.Context, maxAge time.Duration) error {
}

if retries > 0 && !skipBackoff {
backoffSeconds := time.Duration(pow(c.retryBackoffBase, retries)) * time.Second
log.Printf("Backing off for %v seconds", backoffSeconds)
backoffTime := time.Duration(pow(c.retryBackoffBase, retries)) * time.Second
log.Printf("Backing off for %v seconds", backoffTime)
select {
case <-ctx.Done():
return ctx.Err()
case <-time.After(backoffSeconds):
case <-time.After(backoffTime):
}
}
skipBackoff = false
Expand Down Expand Up @@ -256,7 +254,7 @@ func (c *Channel) register(ctx context.Context) (string, error) {
c.aid = 0
c.ofs = 0

resp, err := c.session.FetchRaw(ctx, "GET", channelURLBase+"register?ignore_compass_cookie=1", nil, http.Header{
resp, err := c.session.FetchRaw(ctx, http.MethodGet, channelURLBase+"register?ignore_compass_cookie=1", nil, http.Header{
"Content-Type": {"application/x-protobuf"},
}, true, nil)
if err != nil {
Expand All @@ -281,13 +279,13 @@ func (c *Channel) register(ctx context.Context) (string, error) {
return "", nil
}

func (c *Channel) sendStreamEvent(ctx context.Context, request proto.StreamEventsRequest) error {
func (c *Channel) sendStreamEvent(ctx context.Context, request *proto.StreamEventsRequest) error {
params := url.Values{
"VER": []string{"8"}, // channel protocol version
"RID": []string{fmt.Sprintf("%d", c.rid)}, // request identifier
"t": []string{"1"}, // trial
"SID": []string{c.sidParam}, // session ID
"AID": []string{string(c.aid)}, // last acknowledged id
"AID": []string{strconv.Itoa(c.aid)}, // last acknowledged id
}
c.rid++

Expand All @@ -296,7 +294,7 @@ func (c *Channel) sendStreamEvent(ctx context.Context, request proto.StreamEvent
"Content-Type": []string{"application/x-www-form-urlencoded"},
}

protoBytes, err := pblite.Marshal(&request)
protoBytes, err := pblite.Marshal(request)
if err != nil {
return fmt.Errorf("failed to marshal events request: %w", err)
}
Expand All @@ -314,7 +312,7 @@ func (c *Channel) sendStreamEvent(ctx context.Context, request proto.StreamEvent
}
c.ofs++

res, err := c.session.FetchRaw(ctx, "POST", channelURLBase+"events", params, headers, true, []byte(formData.Encode()))
res, err := c.session.FetchRaw(ctx, http.MethodPost, channelURLBase+"events", params, headers, true, []byte(formData.Encode()))
if err != nil {
return err
}
Expand All @@ -328,7 +326,7 @@ func (c *Channel) sendInitialPing(ctx context.Context) error {
interactiveState := proto.PingEvent_INTERACTIVE
notificationsEnabled := true
event := proto.PingEvent{State: &state, ApplicationFocusState: &focusState, ClientInteractiveState: &interactiveState, ClientNotificationsEnabled: &notificationsEnabled}
return c.sendStreamEvent(ctx, proto.StreamEventsRequest{PingEvent: &event})
return c.sendStreamEvent(ctx, &proto.StreamEventsRequest{PingEvent: &event})
}

// longPollRequest opens a long-polling request and receives arrays
Expand All @@ -353,7 +351,7 @@ func (c *Channel) longPollRequest(ctx context.Context) error {
params.Set("SID", c.sidParam)
}

resp, err := c.session.FetchRaw(ctx, "GET", channelURLBase+"events", params, http.Header{
resp, err := c.session.FetchRaw(ctx, http.MethodGet, channelURLBase+"events", params, http.Header{
"referer": {"https://chat.google.com/"},
}, true, nil)
if err != nil {
Expand Down Expand Up @@ -389,14 +387,14 @@ func (c *Channel) longPollRequest(ctx context.Context) error {
"VER": []string{"8"},
"RID": []string{"rpc"},
"SID": []string{c.sidParam},
"AID": []string{string(c.aid)},
"AID": []string{strconv.Itoa(c.aid)},
"CI": []string{"0"},
"TYPE": []string{"xmlhttp"},
"zx": []string{uniqueID()},
"t": []string{"1"},
}

if _, err := c.session.FetchRaw(ctx, "GET", channelURLBase+"events", params, nil, true, nil); err != nil {
if _, err := c.session.FetchRaw(ctx, http.MethodGet, channelURLBase+"events", params, nil, true, nil); err != nil {
return fmt.Errorf("failed to acknowledge sid")
}

Expand Down Expand Up @@ -478,7 +476,7 @@ func (c *Channel) onPushData(dataBytes []byte) error {

dataArray := innerArray[1]

log.Printf("Chunk contains data array with id %d:\n%v", arrayID, dataArray)
log.Printf("Chunk contains data array with id %f:\n%v", arrayID, dataArray)

// Fire receive array event
c.OnReceiveArray.Fire(dataArray)
Expand Down
49 changes: 9 additions & 40 deletions pkg/gchatmeow/client.go
Original file line number Diff line number Diff line change
@@ -1,20 +1,14 @@
package gchatmeow

import (
_ "bytes"
"context"
_ "encoding/base64"
"encoding/json"
"fmt"
_ "io"
"log"
_ "math/rand"
_ "mime"
"net/http"
"net/url"
"os"
"regexp"
_ "strings"
"sync"
"time"

Expand Down Expand Up @@ -50,14 +44,10 @@ type Client struct {
OnStreamEvent *Event

// State
gcRequestHeader *proto.RequestHeader
clientID string
email string
lastActiveSecs float64
activeClientState int
apiReqID int64
xsrfToken string
lastTokenRefresh float64
gcRequestHeader *proto.RequestHeader
apiReqID int64
xsrfToken string
lastTokenRefresh float64

// Mutex for thread safety
mu sync.RWMutex
Expand Down Expand Up @@ -91,10 +81,10 @@ func NewClient(cookies *Cookies, userAgent string, maxRetries, retryBackoffBase
session: session,

gcRequestHeader: &proto.RequestHeader{
ClientType: GetPointer(proto.RequestHeader_WEB),
ClientVersion: GetPointer(int64(2440378181258)),
ClientType: ptr.Ptr(proto.RequestHeader_WEB),
ClientVersion: ptr.Ptr(int64(2440378181258)),
ClientFeatureCapabilities: &proto.ClientFeatureCapabilities{
SpamRoomInvitesLevel: GetPointer(proto.ClientFeatureCapabilities_FULLY_SUPPORTED),
SpamRoomInvitesLevel: ptr.Ptr(proto.ClientFeatureCapabilities_FULLY_SUPPORTED),
},
},
}
Expand Down Expand Up @@ -124,24 +114,6 @@ func (c *Client) Connect(ctx context.Context, maxAge time.Duration) error {
c.OnConnect.Fire(nil)
})
c.channel.OnReceiveArray.AddObserver(c.onReceiveArray)
// go func() {
// for {
// select {
// case <-c.channel.OnConnect:
// c.OnConnect <- struct{}{}
// case <-c.channel.OnReconnect:
// c.OnReconnect <- struct{}{}
// case <-c.channel.OnDisconnect:
// c.OnDisconnect <- struct{}{}
// case arr := <-c.channel.OnReceiveArray:
// if err := c.handleReceiveArray(arr); err != nil {
// logger.Printf("Error handling receive array: %v", err)
// }
// case <-ctx.Done():
// return
// }
// }
// }()

return c.channel.Listen(ctx, maxAge)
}
Expand All @@ -161,14 +133,11 @@ func (c *Client) RefreshTokens(ctx context.Context) error {
"referer": {"https://mail.google.com/"},
}

resp, err := c.session.Fetch(ctx, "GET", fmt.Sprintf("%s/mole/world", gcBaseURL), params, headers, true, nil)
resp, err := c.session.Fetch(ctx, http.MethodGet, fmt.Sprintf("%s/mole/world", gcBaseURL), params, headers, true, nil)
if err != nil {
return err
}

os.WriteFile("body.html", resp.Body, 0644)
// fmt.Println(string(resp.Body))

matches := wizPattern.FindSubmatch(resp.Body)
if len(matches) != 2 {
return fmt.Errorf("didn't find WIZ_global_data in /mole/world response")
Expand Down Expand Up @@ -229,7 +198,7 @@ func (c *Client) onReceiveArray(arg interface{}) {
// Create and decode protobuf response
resp := &proto.StreamEventsResponse{}
if err := pblite.Unmarshal(bytes, resp); err != nil {
fmt.Printf("failed to decode proto: %w", err)
fmt.Println(fmt.Errorf("failed to decode proto: %w", err))
return
}

Expand Down
5 changes: 3 additions & 2 deletions pkg/gchatmeow/proto/googlechat.pb.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

5 changes: 0 additions & 5 deletions pkg/gchatmeow/utils.go

This file was deleted.

0 comments on commit fbf6309

Please sign in to comment.