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 1161369
Show file tree
Hide file tree
Showing 8 changed files with 35 additions and 84 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
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
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
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 1161369

Please sign in to comment.