2023-06-30 11:05:33 +00:00
|
|
|
package libgm
|
2023-06-30 09:54:08 +00:00
|
|
|
|
|
|
|
import (
|
|
|
|
"bufio"
|
|
|
|
"bytes"
|
2023-07-15 13:11:36 +00:00
|
|
|
"encoding/base64"
|
2023-07-09 11:16:52 +00:00
|
|
|
"encoding/json"
|
2023-06-30 09:54:08 +00:00
|
|
|
"errors"
|
2023-06-30 11:48:50 +00:00
|
|
|
"fmt"
|
2023-06-30 09:54:08 +00:00
|
|
|
"io"
|
2023-08-09 12:27:47 +00:00
|
|
|
"net/http"
|
2023-07-03 21:03:36 +00:00
|
|
|
"time"
|
2023-06-30 09:54:08 +00:00
|
|
|
|
2023-07-16 11:36:13 +00:00
|
|
|
"github.com/google/uuid"
|
2023-07-15 13:11:36 +00:00
|
|
|
"github.com/rs/zerolog"
|
|
|
|
|
2023-06-30 09:54:08 +00:00
|
|
|
"go.mau.fi/mautrix-gmessages/libgm/events"
|
2023-07-09 11:16:52 +00:00
|
|
|
"go.mau.fi/mautrix-gmessages/libgm/pblite"
|
|
|
|
|
2023-07-17 13:51:31 +00:00
|
|
|
"go.mau.fi/mautrix-gmessages/libgm/gmproto"
|
2023-06-30 09:54:08 +00:00
|
|
|
"go.mau.fi/mautrix-gmessages/libgm/util"
|
|
|
|
)
|
|
|
|
|
2023-08-08 16:05:08 +00:00
|
|
|
const phoneNotRespondingTimeout = 30 * time.Second
|
|
|
|
|
2023-09-04 11:24:45 +00:00
|
|
|
func (c *Client) doDittoPinger(log *zerolog.Logger, dittoPing <-chan struct{}, stopPinger <-chan struct{}) {
|
2023-07-19 21:58:39 +00:00
|
|
|
notResponding := false
|
2023-11-06 14:05:21 +00:00
|
|
|
pingFails := 0
|
2023-07-19 21:58:39 +00:00
|
|
|
exit := false
|
|
|
|
onRespond := func() {
|
|
|
|
if notResponding {
|
|
|
|
log.Debug().Msg("Ditto ping succeeded, phone is back online")
|
|
|
|
c.triggerEvent(&events.PhoneRespondingAgain{})
|
|
|
|
notResponding = false
|
2023-11-06 14:05:21 +00:00
|
|
|
pingFails = 0
|
|
|
|
} else if pingFails > 0 {
|
2023-09-27 09:35:11 +00:00
|
|
|
// TODO separate event?
|
|
|
|
c.triggerEvent(&events.PhoneRespondingAgain{})
|
2023-11-06 14:05:21 +00:00
|
|
|
pingFails = 0
|
2023-07-19 21:58:39 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
doPing := func() {
|
|
|
|
pingChan, err := c.NotifyDittoActivity()
|
|
|
|
if err != nil {
|
|
|
|
log.Err(err).Msg("Error notifying ditto activity")
|
2023-11-06 14:05:21 +00:00
|
|
|
pingFails++
|
2023-09-04 11:24:45 +00:00
|
|
|
c.triggerEvent(&events.PingFailed{
|
2023-11-06 14:05:21 +00:00
|
|
|
Error: fmt.Errorf("failed to notify ditto activity: %w", err),
|
|
|
|
ErrorCount: pingFails,
|
2023-09-04 11:24:45 +00:00
|
|
|
})
|
2023-07-19 21:58:39 +00:00
|
|
|
return
|
|
|
|
}
|
|
|
|
select {
|
|
|
|
case <-pingChan:
|
|
|
|
onRespond()
|
|
|
|
return
|
2023-08-08 16:05:08 +00:00
|
|
|
case <-time.After(phoneNotRespondingTimeout):
|
2023-07-19 21:58:39 +00:00
|
|
|
log.Warn().Msg("Ditto ping is taking long, phone may be offline")
|
|
|
|
c.triggerEvent(&events.PhoneNotResponding{})
|
|
|
|
notResponding = true
|
|
|
|
case <-stopPinger:
|
|
|
|
exit = true
|
|
|
|
return
|
|
|
|
}
|
|
|
|
select {
|
|
|
|
case <-pingChan:
|
|
|
|
onRespond()
|
|
|
|
case <-stopPinger:
|
|
|
|
exit = true
|
|
|
|
return
|
|
|
|
}
|
|
|
|
}
|
|
|
|
for !exit {
|
|
|
|
select {
|
|
|
|
case <-c.pingShortCircuit:
|
|
|
|
log.Debug().Msg("Ditto ping wait short-circuited")
|
|
|
|
doPing()
|
|
|
|
case <-dittoPing:
|
|
|
|
log.Trace().Msg("Doing normal ditto ping")
|
|
|
|
doPing()
|
|
|
|
case <-stopPinger:
|
|
|
|
return
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-09-04 11:24:45 +00:00
|
|
|
func tryReadBody(resp io.ReadCloser) []byte {
|
|
|
|
data, _ := io.ReadAll(resp)
|
|
|
|
_ = resp.Close()
|
|
|
|
return data
|
|
|
|
}
|
|
|
|
|
2023-07-19 11:13:02 +00:00
|
|
|
func (c *Client) doLongPoll(loggedIn bool) {
|
2023-07-19 11:12:23 +00:00
|
|
|
c.listenID++
|
|
|
|
listenID := c.listenID
|
2023-07-16 11:36:13 +00:00
|
|
|
listenReqID := uuid.NewString()
|
2023-07-19 21:58:39 +00:00
|
|
|
|
|
|
|
log := c.Logger.With().Int("listen_id", listenID).Logger()
|
|
|
|
defer func() {
|
|
|
|
log.Debug().Msg("Long polling stopped")
|
|
|
|
}()
|
|
|
|
log.Debug().Str("listen_uuid", listenReqID).Msg("Long polling starting")
|
|
|
|
|
|
|
|
dittoPing := make(chan struct{}, 1)
|
|
|
|
stopDittoPinger := make(chan struct{})
|
|
|
|
|
|
|
|
defer close(stopDittoPinger)
|
|
|
|
go c.doDittoPinger(&log, dittoPing, stopDittoPinger)
|
|
|
|
|
2023-08-09 12:27:47 +00:00
|
|
|
errorCount := 1
|
2023-07-19 11:12:23 +00:00
|
|
|
for c.listenID == listenID {
|
|
|
|
err := c.refreshAuthToken()
|
2023-07-16 11:36:13 +00:00
|
|
|
if err != nil {
|
2023-07-19 21:58:39 +00:00
|
|
|
log.Err(err).Msg("Error refreshing auth token")
|
2023-07-18 11:51:18 +00:00
|
|
|
if loggedIn {
|
2023-07-19 11:12:23 +00:00
|
|
|
c.triggerEvent(&events.ListenFatalError{Error: fmt.Errorf("failed to refresh auth token: %w", err)})
|
2023-07-18 11:51:18 +00:00
|
|
|
}
|
2023-07-16 11:36:13 +00:00
|
|
|
return
|
2023-07-10 12:12:46 +00:00
|
|
|
}
|
2023-07-19 21:58:39 +00:00
|
|
|
log.Debug().Msg("Starting new long-polling request")
|
2023-07-19 10:58:53 +00:00
|
|
|
payload := &gmproto.ReceiveMessagesRequest{
|
2023-07-17 13:51:31 +00:00
|
|
|
Auth: &gmproto.AuthMessage{
|
2023-07-16 11:36:13 +00:00
|
|
|
RequestID: listenReqID,
|
2023-07-19 11:12:23 +00:00
|
|
|
TachyonAuthToken: c.AuthData.TachyonAuthToken,
|
2024-02-23 12:53:19 +00:00
|
|
|
Network: c.AuthData.AuthNetwork(),
|
2023-07-16 12:55:30 +00:00
|
|
|
ConfigVersion: util.ConfigMessage,
|
2023-07-16 11:36:13 +00:00
|
|
|
},
|
2023-07-17 13:51:31 +00:00
|
|
|
Unknown: &gmproto.ReceiveMessagesRequest_UnknownEmptyObject2{
|
|
|
|
Unknown: &gmproto.ReceiveMessagesRequest_UnknownEmptyObject1{},
|
2023-07-16 11:36:13 +00:00
|
|
|
},
|
|
|
|
}
|
2024-02-22 20:37:49 +00:00
|
|
|
url := util.ReceiveMessagesURL
|
|
|
|
if c.AuthData.Cookies != nil {
|
|
|
|
url = util.ReceiveMessagesURLGoogle
|
|
|
|
payload.Auth.Network = util.GoogleNetwork
|
|
|
|
}
|
|
|
|
resp, err := c.makeProtobufHTTPRequest(url, payload, ContentTypePBLite)
|
2023-07-01 09:51:13 +00:00
|
|
|
if err != nil {
|
2023-07-18 11:51:18 +00:00
|
|
|
if loggedIn {
|
2023-07-19 11:12:23 +00:00
|
|
|
c.triggerEvent(&events.ListenTemporaryError{Error: err})
|
2023-07-18 11:51:18 +00:00
|
|
|
}
|
2023-08-09 12:27:47 +00:00
|
|
|
errorCount++
|
|
|
|
sleepSeconds := (errorCount + 1) * 5
|
|
|
|
log.Err(err).Int("sleep_seconds", sleepSeconds).Msg("Error making listen request, retrying in a while")
|
|
|
|
time.Sleep(time.Duration(sleepSeconds) * time.Second)
|
2023-07-03 21:03:36 +00:00
|
|
|
continue
|
|
|
|
}
|
2023-08-09 12:27:47 +00:00
|
|
|
if resp.StatusCode == http.StatusUnauthorized || resp.StatusCode == http.StatusForbidden {
|
2023-09-04 11:24:45 +00:00
|
|
|
body := tryReadBody(resp.Body)
|
|
|
|
log.Error().
|
|
|
|
Int("status_code", resp.StatusCode).
|
|
|
|
Bytes("resp_body", body).
|
|
|
|
Msg("Error making listen request")
|
2023-07-18 11:51:18 +00:00
|
|
|
if loggedIn {
|
2023-09-04 11:24:45 +00:00
|
|
|
c.triggerEvent(&events.ListenFatalError{Error: events.HTTPError{Action: "polling", Resp: resp, Body: body}})
|
2023-07-18 11:51:18 +00:00
|
|
|
}
|
2023-07-03 21:03:36 +00:00
|
|
|
return
|
2023-08-09 12:27:47 +00:00
|
|
|
} else if resp.StatusCode >= 400 {
|
2023-07-18 11:51:18 +00:00
|
|
|
if loggedIn {
|
2023-09-04 11:24:45 +00:00
|
|
|
c.triggerEvent(&events.ListenTemporaryError{Error: events.HTTPError{Action: "polling", Resp: resp, Body: tryReadBody(resp.Body)}})
|
|
|
|
} else {
|
|
|
|
_ = resp.Body.Close()
|
2023-07-18 11:51:18 +00:00
|
|
|
}
|
2023-08-09 12:27:47 +00:00
|
|
|
errorCount++
|
|
|
|
sleepSeconds := (errorCount + 1) * 5
|
|
|
|
log.Debug().
|
|
|
|
Int("statusCode", resp.StatusCode).
|
|
|
|
Int("sleep_seconds", sleepSeconds).
|
|
|
|
Msg("Error in long polling, retrying in a while")
|
|
|
|
time.Sleep(time.Duration(sleepSeconds) * time.Second)
|
2023-07-03 21:03:36 +00:00
|
|
|
continue
|
|
|
|
}
|
2023-08-09 12:27:47 +00:00
|
|
|
if errorCount > 0 {
|
|
|
|
errorCount = 0
|
2023-07-18 11:51:18 +00:00
|
|
|
if loggedIn {
|
2023-07-19 11:12:23 +00:00
|
|
|
c.triggerEvent(&events.ListenRecovered{})
|
2023-07-18 11:51:18 +00:00
|
|
|
}
|
2023-07-01 09:51:13 +00:00
|
|
|
}
|
2023-07-19 21:58:39 +00:00
|
|
|
log.Debug().Int("statusCode", resp.StatusCode).Msg("Long polling opened")
|
2023-07-19 11:12:23 +00:00
|
|
|
c.longPollingConn = resp.Body
|
2023-07-19 21:58:39 +00:00
|
|
|
if loggedIn {
|
|
|
|
select {
|
|
|
|
case dittoPing <- struct{}{}:
|
|
|
|
default:
|
|
|
|
log.Debug().Msg("Ditto pinger is still waiting for previous ping, skipping new ping")
|
|
|
|
}
|
|
|
|
}
|
|
|
|
c.readLongPoll(&log, resp.Body)
|
2023-07-19 11:12:23 +00:00
|
|
|
c.longPollingConn = nil
|
2023-06-30 09:54:08 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-07-19 21:58:39 +00:00
|
|
|
func (c *Client) readLongPoll(log *zerolog.Logger, rc io.ReadCloser) {
|
2023-06-30 09:54:08 +00:00
|
|
|
defer rc.Close()
|
2023-07-19 11:12:23 +00:00
|
|
|
c.disconnecting = false
|
2023-06-30 09:54:08 +00:00
|
|
|
reader := bufio.NewReader(rc)
|
|
|
|
buf := make([]byte, 2621440)
|
|
|
|
var accumulatedData []byte
|
2023-07-15 12:49:51 +00:00
|
|
|
n, err := reader.Read(buf[:2])
|
|
|
|
if err != nil {
|
2023-07-19 21:58:39 +00:00
|
|
|
log.Err(err).Msg("Error reading opening bytes")
|
2023-07-15 12:49:51 +00:00
|
|
|
return
|
|
|
|
} else if n != 2 || string(buf[:2]) != "[[" {
|
2023-07-19 21:58:39 +00:00
|
|
|
log.Err(err).Msg("Opening is not [[")
|
2023-07-15 12:49:51 +00:00
|
|
|
return
|
|
|
|
}
|
2023-07-15 13:11:36 +00:00
|
|
|
var expectEOF bool
|
2023-06-30 09:54:08 +00:00
|
|
|
for {
|
2023-07-15 12:49:51 +00:00
|
|
|
n, err = reader.Read(buf)
|
2023-06-30 09:54:08 +00:00
|
|
|
if err != nil {
|
2023-07-15 13:11:36 +00:00
|
|
|
var logEvt *zerolog.Event
|
2023-07-19 11:12:23 +00:00
|
|
|
if (errors.Is(err, io.EOF) && expectEOF) || c.disconnecting {
|
2023-07-19 21:58:39 +00:00
|
|
|
logEvt = log.Debug()
|
2023-07-15 13:11:36 +00:00
|
|
|
} else {
|
2023-07-19 21:58:39 +00:00
|
|
|
logEvt = log.Warn()
|
2023-06-30 09:54:08 +00:00
|
|
|
}
|
2023-07-15 13:11:36 +00:00
|
|
|
logEvt.Err(err).Msg("Stopped reading data from server")
|
2023-06-30 09:54:08 +00:00
|
|
|
return
|
2023-07-15 13:11:36 +00:00
|
|
|
} else if expectEOF {
|
2023-07-19 21:58:39 +00:00
|
|
|
log.Warn().Msg("Didn't get EOF after stream end marker")
|
2023-06-30 09:54:08 +00:00
|
|
|
}
|
|
|
|
chunk := buf[:n]
|
2023-07-15 12:49:51 +00:00
|
|
|
if len(accumulatedData) == 0 {
|
|
|
|
if len(chunk) == 2 && string(chunk) == "]]" {
|
2023-07-19 21:58:39 +00:00
|
|
|
log.Debug().Msg("Got stream end marker")
|
2023-07-15 13:11:36 +00:00
|
|
|
expectEOF = true
|
|
|
|
continue
|
2023-06-30 09:54:08 +00:00
|
|
|
}
|
2023-07-15 12:49:51 +00:00
|
|
|
chunk = bytes.TrimPrefix(chunk, []byte{','})
|
|
|
|
}
|
|
|
|
accumulatedData = append(accumulatedData, chunk...)
|
|
|
|
if !json.Valid(accumulatedData) {
|
2023-09-04 21:31:50 +00:00
|
|
|
log.Trace().Msg("Invalid JSON, reading next chunk")
|
2023-06-30 09:54:08 +00:00
|
|
|
continue
|
|
|
|
}
|
2023-07-15 13:11:36 +00:00
|
|
|
currentBlock := accumulatedData
|
2023-07-15 12:49:51 +00:00
|
|
|
accumulatedData = accumulatedData[:0]
|
2023-07-17 23:01:06 +00:00
|
|
|
msg := &gmproto.LongPollingPayload{}
|
2023-07-15 13:11:36 +00:00
|
|
|
err = pblite.Unmarshal(currentBlock, msg)
|
2023-06-30 09:54:08 +00:00
|
|
|
if err != nil {
|
2023-07-19 21:58:39 +00:00
|
|
|
log.Err(err).Msg("Error deserializing pblite message")
|
2023-06-30 09:54:08 +00:00
|
|
|
continue
|
|
|
|
}
|
2023-07-15 12:49:51 +00:00
|
|
|
switch {
|
|
|
|
case msg.GetData() != nil:
|
2023-07-19 11:12:23 +00:00
|
|
|
c.HandleRPCMsg(msg.GetData())
|
2023-07-15 12:49:51 +00:00
|
|
|
case msg.GetAck() != nil:
|
2023-07-19 21:58:39 +00:00
|
|
|
log.Debug().Int32("count", msg.GetAck().GetCount()).Msg("Got startup ack count message")
|
2023-07-19 11:12:23 +00:00
|
|
|
c.skipCount = int(msg.GetAck().GetCount())
|
2023-07-15 12:49:51 +00:00
|
|
|
case msg.GetStartRead() != nil:
|
2023-07-19 21:58:39 +00:00
|
|
|
log.Trace().Msg("Got startRead message")
|
2023-07-15 12:49:51 +00:00
|
|
|
case msg.GetHeartbeat() != nil:
|
2023-07-19 21:58:39 +00:00
|
|
|
log.Trace().Msg("Got heartbeat message")
|
2023-07-15 12:49:51 +00:00
|
|
|
default:
|
2023-07-19 21:58:39 +00:00
|
|
|
log.Warn().
|
2023-07-15 13:11:36 +00:00
|
|
|
Str("data", base64.StdEncoding.EncodeToString(currentBlock)).
|
|
|
|
Msg("Got unknown message")
|
2023-07-09 11:16:52 +00:00
|
|
|
}
|
|
|
|
}
|
2023-06-30 09:54:08 +00:00
|
|
|
}
|
|
|
|
|
2023-07-19 11:12:23 +00:00
|
|
|
func (c *Client) closeLongPolling() {
|
|
|
|
if conn := c.longPollingConn; conn != nil {
|
2023-07-19 21:58:39 +00:00
|
|
|
c.Logger.Debug().Int("current_listen_id", c.listenID).Msg("Closing long polling connection manually")
|
2023-07-19 11:12:23 +00:00
|
|
|
c.listenID++
|
|
|
|
c.disconnecting = true
|
|
|
|
_ = conn.Close()
|
|
|
|
c.longPollingConn = nil
|
2023-06-30 09:54:08 +00:00
|
|
|
}
|
|
|
|
}
|