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 0128413
Show file tree
Hide file tree
Showing 11 changed files with 39 additions and 107 deletions.
7 changes: 3 additions & 4 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,7 @@ go 1.23.0
toolchain go1.23.3

require (
github.com/google/go-querystring v1.1.0
github.com/mattn/go-colorable v0.1.13
github.com/rs/zerolog v1.33.0
go.mau.fi/util v0.8.2
golang.org/x/net v0.31.0
google.golang.org/protobuf v1.35.2
maunium.net/go/mautrix v0.22.1-0.20241126202918-4b970e0ea7e6
)
Expand All @@ -20,10 +16,12 @@ require (
github.com/gorilla/mux v1.8.0 // indirect
github.com/gorilla/websocket v1.5.0 // indirect
github.com/lib/pq v1.10.9 // indirect
github.com/mattn/go-colorable v0.1.13 // indirect
github.com/mattn/go-isatty v0.0.19 // indirect
github.com/mattn/go-sqlite3 v1.14.24 // indirect
github.com/petermattis/goid v0.0.0-20241025130422-66cb2e6d7274 // indirect
github.com/rs/xid v1.6.0 // indirect
github.com/rs/zerolog v1.33.0 // indirect
github.com/skip2/go-qrcode v0.0.0-20200617195104-da1b6568686e // indirect
github.com/tidwall/gjson v1.18.0 // indirect
github.com/tidwall/match v1.1.1 // indirect
Expand All @@ -33,6 +31,7 @@ require (
go.mau.fi/zeroconfig v0.1.3 // indirect
golang.org/x/crypto v0.29.0 // indirect
golang.org/x/exp v0.0.0-20241108190413-2d47ceb2692f // indirect
golang.org/x/net v0.31.0 // indirect
golang.org/x/sync v0.9.0 // indirect
golang.org/x/sys v0.27.0 // indirect
golang.org/x/text v0.20.0 // indirect
Expand Down
4 changes: 0 additions & 4 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -7,11 +7,8 @@ github.com/coreos/go-systemd/v22 v22.5.0/go.mod h1:Y58oyj3AT4RCenI/lSvhwexgC+NSV
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/godbus/dbus/v5 v5.0.4/go.mod h1:xhWf0FNVPg57R7Z0UbKHbJfkEywrmjJnf7w5xrFpKfA=
github.com/google/go-cmp v0.5.2/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
github.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI=
github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY=
github.com/google/go-querystring v1.1.0 h1:AnCroh3fv4ZBgVIf1Iwtovgjaw/GiKJo8M8yD/fhyJ8=
github.com/google/go-querystring v1.1.0/go.mod h1:Kcdr2DB4koayq7X8pmAG4sNG59So17icRSOU623lUBU=
github.com/gorilla/mux v1.8.0 h1:i40aqfkR1h2SlN9hojwV5ZA91wcXFOvkdNIeFDP5koI=
github.com/gorilla/mux v1.8.0/go.mod h1:DVbg23sWSpFRCP0SfiEN6jmj59UnW/n46BH5rLB71So=
github.com/gorilla/websocket v1.5.0 h1:PPwGk2jz7EePpoHN/+ClbZu8SPxiqlu12wZP/3sWmnc=
Expand Down Expand Up @@ -69,7 +66,6 @@ golang.org/x/sys v0.27.0 h1:wBqf8DvsY9Y/2P8gAfPDEYNuS30J4lPHJxXSb/nJZ+s=
golang.org/x/sys v0.27.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
golang.org/x/text v0.20.0 h1:gK/Kv2otX8gz+wn7Rmb3vT96ZwuoxnQlY+HlJVj7Qug=
golang.org/x/text v0.20.0/go.mod h1:D4IsuqiFMhST5bX19pQ9ikHC2GsaKyk/oF+pn3ducp4=
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
google.golang.org/protobuf v1.35.2 h1:8Ar7bF+apOIoThw1EdZl0p1oWvMqTHmpA2fRTyZO8io=
google.golang.org/protobuf v1.35.2/go.mod h1:9fA7Ob0pmnwhb644+1+CVWFRbNajQ6iRojtC/QF5bRE=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM=
Expand Down
13 changes: 2 additions & 11 deletions pkg/connector/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,7 @@ func (c *GChatClient) onConnect(ctx context.Context) {
return
}
for _, item := range res.WorldItems {
// TODO room name for DM, and full members list
name := item.RoomName
if name == nil {
name = ptr.Ptr("dm")
Expand Down Expand Up @@ -100,21 +101,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 +120,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
9 changes: 6 additions & 3 deletions pkg/gchatmeow/api.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,13 @@ import (
"fmt"
"net/http"
"net/url"
"strconv"

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

"go.mau.fi/util/ptr"

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

Expand All @@ -27,7 +30,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 +40,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 +117,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
40 changes: 13 additions & 27 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 All @@ -45,7 +43,6 @@ var (
lenRegex = regexp.MustCompile(lenRegexPattern)
)

// Channel represents a BrowserChannel client
type Channel struct {
session *Session
maxRetries int
Expand All @@ -65,12 +62,10 @@ type Channel struct {
OnReceiveArray *Event
}

// ChunkParser parses data from the backward channel into chunks
type ChunkParser struct {
buf []byte
}

// NewChunkParser creates a new ChunkParser instance
func NewChunkParser() *ChunkParser {
return &ChunkParser{
buf: make([]byte, 0),
Expand Down Expand Up @@ -181,12 +176,10 @@ func NewChannel(session *Session, maxRetries, retryBackoffBase int) (*Channel, e
}, nil
}

// IsConnected returns whether the channel is currently connected
func (c *Channel) IsConnected() bool {
return c.isConnected
}

// Listen listens for messages on the backwards channel
func (c *Channel) Listen(ctx context.Context, maxAge time.Duration) error {
retries := 0
skipBackoff := false
Expand All @@ -205,12 +198,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 @@ -250,13 +243,12 @@ func (c *Channel) Listen(ctx context.Context, maxAge time.Duration) error {
return fmt.Errorf("ran out of retries for long-polling request")
}

// register registers a new channel and returns the csessionid
func (c *Channel) register(ctx context.Context) (string, error) {
c.sidParam = ""
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 +273,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 +288,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 +306,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,10 +320,9 @@ 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
func (c *Channel) longPollRequest(ctx context.Context) error {
params := url.Values{
"VER": {strconv.Itoa(protocolVersion)},
Expand All @@ -353,7 +344,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 +380,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 @@ -432,14 +423,10 @@ func (c *Channel) longPollRequest(ctx context.Context) error {
}
}

// OnPushData handles incoming push data and triggers appropriate events
func (c *Channel) onPushData(dataBytes []byte) error {
// Log received chunk
log.Printf("Received chunk:\n%s", string(dataBytes))

// Update metrics
// c.receivedChunks.Add(float64(len(dataBytes)))

// Process chunks
chunks := c.chunkParser.GetChunks(dataBytes)

Expand Down Expand Up @@ -478,7 +465,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 All @@ -491,7 +478,6 @@ func (c *Channel) onPushData(dataBytes []byte) error {
return nil
}

// Helper functions (implementations not shown for brevity)
func uniqueID() string {
// Implementation of _unique_id from Python code
return base64.RawURLEncoding.EncodeToString([]byte(fmt.Sprintf("%d", rand.Int63())))
Expand Down
Loading

0 comments on commit 0128413

Please sign in to comment.