mirror of
https://dev.narayana.im/narayana/telegabber.git
synced 2026-08-05 20:17:08 +00:00
Compare commits
No commits in common. "master" and "v1.8.1" have entirely different histories.
27 changed files with 959 additions and 3424 deletions
1
.gitignore
vendored
1
.gitignore
vendored
|
|
@ -4,4 +4,3 @@ sessions/
|
||||||
session.dat
|
session.dat
|
||||||
session.dat.new
|
session.dat.new
|
||||||
release/
|
release/
|
||||||
tdlib/
|
|
||||||
|
|
|
||||||
|
|
@ -29,7 +29,7 @@ WORKDIR /src
|
||||||
RUN make ${MAKEOPTS}
|
RUN make ${MAKEOPTS}
|
||||||
|
|
||||||
FROM scratch AS telegabber
|
FROM scratch AS telegabber
|
||||||
COPY --from=build /src/release/telegabber /usr/local/bin/
|
COPY --from=build /src/telegabber /usr/local/bin/
|
||||||
ENTRYPOINT ["/usr/local/bin/telegabber"]
|
ENTRYPOINT ["/usr/local/bin/telegabber"]
|
||||||
|
|
||||||
FROM scratch AS binaries
|
FROM scratch AS binaries
|
||||||
|
|
|
||||||
13
Makefile
13
Makefile
|
|
@ -1,13 +1,12 @@
|
||||||
.PHONY: all test
|
.PHONY: all test
|
||||||
|
|
||||||
COMMIT := $(shell git rev-parse --short HEAD)
|
COMMIT := $(shell git rev-parse --short HEAD)
|
||||||
TD_COMMIT := "5bbfc1cf5dab94f82e02f3430ded7241d4653551"
|
TD_COMMIT := "8517026415e75a8eec567774072cbbbbb52376c1"
|
||||||
VERSION := "v1.12.8"
|
VERSION := "v1.8.1"
|
||||||
MAKEOPTS := "-j4"
|
MAKEOPTS := "-j4"
|
||||||
|
|
||||||
all:
|
all:
|
||||||
mkdir -p release
|
go build -ldflags "-X main.commit=${COMMIT}" -o telegabber
|
||||||
go build -ldflags "-X main.commit=${COMMIT}" -o release/telegabber
|
|
||||||
|
|
||||||
test:
|
test:
|
||||||
go test -v ./config ./ ./telegram ./xmpp ./xmpp/gateway ./persistence ./telegram/formatter ./badger
|
go test -v ./config ./ ./telegram ./xmpp ./xmpp/gateway ./persistence ./telegram/formatter ./badger
|
||||||
|
|
@ -17,9 +16,3 @@ lint:
|
||||||
|
|
||||||
build_indocker:
|
build_indocker:
|
||||||
docker build --build-arg "TD_COMMIT=${TD_COMMIT}" --build-arg "VERSION=${VERSION}" --build-arg "MAKEOPTS=${MAKEOPTS}" --output=release --target binaries .
|
docker build --build-arg "TD_COMMIT=${TD_COMMIT}" --build-arg "VERSION=${VERSION}" --build-arg "MAKEOPTS=${MAKEOPTS}" --output=release --target binaries .
|
||||||
|
|
||||||
build_indocker_staging:
|
|
||||||
DOCKER_BUILDKIT=1 docker build --build-arg "TD_COMMIT=${TD_COMMIT}" --build-arg "MAKEOPTS=${MAKEOPTS}" --network host --output=release --target binaries -f staging.Dockerfile .
|
|
||||||
|
|
||||||
build_tdlib:
|
|
||||||
DOCKER_BUILDKIT=1 docker build --build-arg "TD_COMMIT=${TD_COMMIT}" --build-arg "MAKEOPTS=${MAKEOPTS}" --output=tdlib --target binaries -f tdlib.Dockerfile .
|
|
||||||
|
|
|
||||||
7
go.mod
7
go.mod
|
|
@ -4,7 +4,6 @@ go 1.19
|
||||||
|
|
||||||
require (
|
require (
|
||||||
github.com/dgraph-io/badger/v4 v4.1.0
|
github.com/dgraph-io/badger/v4 v4.1.0
|
||||||
github.com/google/uuid v1.1.1
|
|
||||||
github.com/pkg/errors v0.9.1
|
github.com/pkg/errors v0.9.1
|
||||||
github.com/santhosh-tekuri/jsonschema v1.2.4
|
github.com/santhosh-tekuri/jsonschema v1.2.4
|
||||||
github.com/sirupsen/logrus v1.4.2
|
github.com/sirupsen/logrus v1.4.2
|
||||||
|
|
@ -24,6 +23,7 @@ require (
|
||||||
github.com/golang/protobuf v1.3.2 // indirect
|
github.com/golang/protobuf v1.3.2 // indirect
|
||||||
github.com/golang/snappy v0.0.3 // indirect
|
github.com/golang/snappy v0.0.3 // indirect
|
||||||
github.com/google/flatbuffers v1.12.1 // indirect
|
github.com/google/flatbuffers v1.12.1 // indirect
|
||||||
|
github.com/google/uuid v1.1.1 // indirect
|
||||||
github.com/klauspost/compress v1.12.3 // indirect
|
github.com/klauspost/compress v1.12.3 // indirect
|
||||||
github.com/konsorten/go-windows-terminal-sequences v1.0.2 // indirect
|
github.com/konsorten/go-windows-terminal-sequences v1.0.2 // indirect
|
||||||
go.opencensus.io v0.22.5 // indirect
|
go.opencensus.io v0.22.5 // indirect
|
||||||
|
|
@ -33,6 +33,5 @@ require (
|
||||||
nhooyr.io/websocket v1.6.5 // indirect
|
nhooyr.io/websocket v1.6.5 // indirect
|
||||||
)
|
)
|
||||||
|
|
||||||
replace gosrc.io/xmpp => dev.narayana.im/narayana/go-xmpp v0.0.0-20240512132113-6725c3862314
|
replace gosrc.io/xmpp => dev.narayana.im/narayana/go-xmpp v0.0.0-20220524203317-306b4ff58e8f
|
||||||
|
replace github.com/zelenin/go-tdlib => dev.narayana.im/narayana/go-tdlib v0.0.0-20230730021136-47da33180615
|
||||||
replace github.com/zelenin/go-tdlib => dev.narayana.im/narayana/go-tdlib v0.0.0-20240124222245-b4c12addb061
|
|
||||||
|
|
|
||||||
8
go.sum
8
go.sum
|
|
@ -1,16 +1,8 @@
|
||||||
cloud.google.com/go v0.26.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw=
|
cloud.google.com/go v0.26.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw=
|
||||||
dev.narayana.im/narayana/go-tdlib v0.0.0-20230730021136-47da33180615 h1:RRUZJSro+k8FkazNx7QEYLVoO4wZtchvsd0Y2RBWjeU=
|
dev.narayana.im/narayana/go-tdlib v0.0.0-20230730021136-47da33180615 h1:RRUZJSro+k8FkazNx7QEYLVoO4wZtchvsd0Y2RBWjeU=
|
||||||
dev.narayana.im/narayana/go-tdlib v0.0.0-20230730021136-47da33180615/go.mod h1:Xs8fXbk5n7VaPyrSs9DP7QYoBScWYsjX+lUcWmx1DIU=
|
dev.narayana.im/narayana/go-tdlib v0.0.0-20230730021136-47da33180615/go.mod h1:Xs8fXbk5n7VaPyrSs9DP7QYoBScWYsjX+lUcWmx1DIU=
|
||||||
dev.narayana.im/narayana/go-tdlib v0.0.0-20231111182840-bc2f985e6268 h1:NCbc2bYuUGQsb/3z5SCIia3N34Ktwq3FwaUAfgF/WEU=
|
|
||||||
dev.narayana.im/narayana/go-tdlib v0.0.0-20231111182840-bc2f985e6268/go.mod h1:Xs8fXbk5n7VaPyrSs9DP7QYoBScWYsjX+lUcWmx1DIU=
|
|
||||||
dev.narayana.im/narayana/go-tdlib v0.0.0-20240124222245-b4c12addb061 h1:CWAQT74LwQne/3Po5KXDvudu3N0FBWm3XZZZhtl5j2w=
|
|
||||||
dev.narayana.im/narayana/go-tdlib v0.0.0-20240124222245-b4c12addb061/go.mod h1:Xs8fXbk5n7VaPyrSs9DP7QYoBScWYsjX+lUcWmx1DIU=
|
|
||||||
dev.narayana.im/narayana/go-xmpp v0.0.0-20220524203317-306b4ff58e8f h1:6249ajbMjgYz53Oq0IjTvjHXbxTfu29Mj1J/6swRHs4=
|
dev.narayana.im/narayana/go-xmpp v0.0.0-20220524203317-306b4ff58e8f h1:6249ajbMjgYz53Oq0IjTvjHXbxTfu29Mj1J/6swRHs4=
|
||||||
dev.narayana.im/narayana/go-xmpp v0.0.0-20220524203317-306b4ff58e8f/go.mod h1:L3NFMqYOxyLz3JGmgFyWf7r9htE91zVGiK40oW4RwdY=
|
dev.narayana.im/narayana/go-xmpp v0.0.0-20220524203317-306b4ff58e8f/go.mod h1:L3NFMqYOxyLz3JGmgFyWf7r9htE91zVGiK40oW4RwdY=
|
||||||
dev.narayana.im/narayana/go-xmpp v0.0.0-20240131013505-18c46e6c59fd h1:+UW+E7JjI88aH4beDn1cw6D8rs1I061hN91HU4Y4pT8=
|
|
||||||
dev.narayana.im/narayana/go-xmpp v0.0.0-20240131013505-18c46e6c59fd/go.mod h1:L3NFMqYOxyLz3JGmgFyWf7r9htE91zVGiK40oW4RwdY=
|
|
||||||
dev.narayana.im/narayana/go-xmpp v0.0.0-20240512132113-6725c3862314 h1:29/NjOGOUDceO73Hk4Nj4uVa1je8MULJlsDSvKxSN/k=
|
|
||||||
dev.narayana.im/narayana/go-xmpp v0.0.0-20240512132113-6725c3862314/go.mod h1:L3NFMqYOxyLz3JGmgFyWf7r9htE91zVGiK40oW4RwdY=
|
|
||||||
github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU=
|
github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU=
|
||||||
github.com/agnivade/wasmbrowsertest v0.3.1/go.mod h1:zQt6ZTdl338xxRaMW395qccVE2eQm0SjC/SDz0mPWQI=
|
github.com/agnivade/wasmbrowsertest v0.3.1/go.mod h1:zQt6ZTdl338xxRaMW395qccVE2eQm0SjC/SDz0mPWQI=
|
||||||
github.com/cespare/xxhash/v2 v2.1.1/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=
|
github.com/cespare/xxhash/v2 v2.1.1/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=
|
||||||
|
|
|
||||||
|
|
@ -3,7 +3,6 @@ package persistence
|
||||||
import (
|
import (
|
||||||
"github.com/pkg/errors"
|
"github.com/pkg/errors"
|
||||||
"io/ioutil"
|
"io/ioutil"
|
||||||
"sync"
|
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"dev.narayana.im/narayana/telegabber/yamldb"
|
"dev.narayana.im/narayana/telegabber/yamldb"
|
||||||
|
|
@ -35,29 +34,17 @@ type SessionsMap struct {
|
||||||
|
|
||||||
// Session is a key-values subtree
|
// Session is a key-values subtree
|
||||||
type Session struct {
|
type Session struct {
|
||||||
Login string `yaml:":login"`
|
Login string `yaml:":login"`
|
||||||
Timezone string `yaml:":timezone"`
|
Timezone string `yaml:":timezone"`
|
||||||
KeepOnline bool `yaml:":keeponline"`
|
KeepOnline bool `yaml:":keeponline"`
|
||||||
RawMessages bool `yaml:":rawmessages"`
|
RawMessages bool `yaml:":rawmessages"`
|
||||||
AsciiArrows bool `yaml:":asciiarrows"`
|
AsciiArrows bool `yaml:":asciiarrows"`
|
||||||
OOBMode bool `yaml:":oobmode"`
|
OOBMode bool `yaml:":oobmode"`
|
||||||
Carbons bool `yaml:":carbons"`
|
Carbons bool `yaml:":carbons"`
|
||||||
HideIds bool `yaml:":hideids"`
|
HideIds bool `yaml:":hideids"`
|
||||||
Receipts bool `yaml:":receipts"`
|
|
||||||
NativeEdits bool `yaml:":nativeedits"`
|
|
||||||
IgnoredChats []int64 `yaml:":ignoredchats"`
|
|
||||||
ignoredChatsMap map[int64]bool `yaml:"-"`
|
|
||||||
|
|
||||||
IgnoreGroupDeletions bool `yaml:":ignoregroupdeletions"`
|
|
||||||
}
|
}
|
||||||
|
|
||||||
const (
|
var configKeys = []string{
|
||||||
PropertyTypeUnknown byte = iota
|
|
||||||
PropertyTypeString
|
|
||||||
PropertyTypeBool
|
|
||||||
)
|
|
||||||
|
|
||||||
var ConfigKeys = []string{
|
|
||||||
"timezone",
|
"timezone",
|
||||||
"keeponline",
|
"keeponline",
|
||||||
"rawmessages",
|
"rawmessages",
|
||||||
|
|
@ -65,27 +52,17 @@ var ConfigKeys = []string{
|
||||||
"oobmode",
|
"oobmode",
|
||||||
"carbons",
|
"carbons",
|
||||||
"hideids",
|
"hideids",
|
||||||
"receipts",
|
|
||||||
"nativeedits",
|
|
||||||
"ignoregroupdeletions",
|
|
||||||
}
|
}
|
||||||
|
|
||||||
var sessionDB *SessionsYamlDB
|
var sessionDB *SessionsYamlDB
|
||||||
var sessionsLock sync.Mutex
|
|
||||||
|
|
||||||
// SessionMarshaller implementation for YamlDB
|
// SessionMarshaller implementation for YamlDB
|
||||||
func SessionMarshaller() ([]byte, error) {
|
func SessionMarshaller() ([]byte, error) {
|
||||||
cleanedMap := SessionsMap{}
|
cleanedMap := SessionsMap{}
|
||||||
emptySessionsMap(&cleanedMap)
|
emptySessionsMap(&cleanedMap)
|
||||||
|
|
||||||
sessionsLock.Lock()
|
|
||||||
defer sessionsLock.Unlock()
|
|
||||||
for jid, session := range sessionDB.Data.Sessions {
|
for jid, session := range sessionDB.Data.Sessions {
|
||||||
if session.Login != "" {
|
if session.Login != "" {
|
||||||
session.IgnoredChats = make([]int64, 0, len(session.ignoredChatsMap))
|
|
||||||
for chatID := range session.ignoredChatsMap {
|
|
||||||
session.IgnoredChats = append(session.IgnoredChats, chatID)
|
|
||||||
}
|
|
||||||
cleanedMap.Sessions[jid] = session
|
cleanedMap.Sessions[jid] = session
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
@ -127,16 +104,6 @@ func initYamlDB(path string, dataPtr *SessionsMap) (*SessionsYamlDB, error) {
|
||||||
emptySessionsMap(dataPtr)
|
emptySessionsMap(dataPtr)
|
||||||
}
|
}
|
||||||
|
|
||||||
// convert ignored users slice to map
|
|
||||||
for jid, session := range dataPtr.Sessions {
|
|
||||||
session.ignoredChatsMap = make(map[int64]bool)
|
|
||||||
for _, chatID := range session.IgnoredChats {
|
|
||||||
session.ignoredChatsMap[chatID] = true
|
|
||||||
}
|
|
||||||
session.IgnoredChats = nil
|
|
||||||
dataPtr.Sessions[jid] = session
|
|
||||||
}
|
|
||||||
|
|
||||||
return &SessionsYamlDB{
|
return &SessionsYamlDB{
|
||||||
YamlDB: yamldb.YamlDB{
|
YamlDB: yamldb.YamlDB{
|
||||||
Path: path,
|
Path: path,
|
||||||
|
|
@ -148,13 +115,6 @@ func initYamlDB(path string, dataPtr *SessionsMap) (*SessionsYamlDB, error) {
|
||||||
|
|
||||||
// Get retrieves a session value
|
// Get retrieves a session value
|
||||||
func (s *Session) Get(key string) (string, error) {
|
func (s *Session) Get(key string) (string, error) {
|
||||||
sessionsLock.Lock()
|
|
||||||
defer sessionsLock.Unlock()
|
|
||||||
|
|
||||||
return s.get(key)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (s *Session) get(key string) (string, error) {
|
|
||||||
switch key {
|
switch key {
|
||||||
case "timezone":
|
case "timezone":
|
||||||
return s.Timezone, nil
|
return s.Timezone, nil
|
||||||
|
|
@ -170,12 +130,6 @@ func (s *Session) get(key string) (string, error) {
|
||||||
return fromBool(s.Carbons), nil
|
return fromBool(s.Carbons), nil
|
||||||
case "hideids":
|
case "hideids":
|
||||||
return fromBool(s.HideIds), nil
|
return fromBool(s.HideIds), nil
|
||||||
case "receipts":
|
|
||||||
return fromBool(s.Receipts), nil
|
|
||||||
case "nativeedits":
|
|
||||||
return fromBool(s.NativeEdits), nil
|
|
||||||
case "ignoregroupdeletions":
|
|
||||||
return fromBool(s.IgnoreGroupDeletions), nil
|
|
||||||
}
|
}
|
||||||
|
|
||||||
return "", errors.New("Unknown session property")
|
return "", errors.New("Unknown session property")
|
||||||
|
|
@ -183,12 +137,9 @@ func (s *Session) get(key string) (string, error) {
|
||||||
|
|
||||||
// ToMap converts the session to a map
|
// ToMap converts the session to a map
|
||||||
func (s *Session) ToMap() map[string]string {
|
func (s *Session) ToMap() map[string]string {
|
||||||
sessionsLock.Lock()
|
|
||||||
defer sessionsLock.Unlock()
|
|
||||||
|
|
||||||
m := make(map[string]string)
|
m := make(map[string]string)
|
||||||
for _, configKey := range ConfigKeys {
|
for _, configKey := range configKeys {
|
||||||
value, _ := s.get(configKey)
|
value, _ := s.Get(configKey)
|
||||||
m[configKey] = value
|
m[configKey] = value
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -197,9 +148,6 @@ func (s *Session) ToMap() map[string]string {
|
||||||
|
|
||||||
// Set sets a session value
|
// Set sets a session value
|
||||||
func (s *Session) Set(key string, value string) (string, error) {
|
func (s *Session) Set(key string, value string) (string, error) {
|
||||||
sessionsLock.Lock()
|
|
||||||
defer sessionsLock.Unlock()
|
|
||||||
|
|
||||||
switch key {
|
switch key {
|
||||||
case "timezone":
|
case "timezone":
|
||||||
s.Timezone = value
|
s.Timezone = value
|
||||||
|
|
@ -246,44 +194,11 @@ func (s *Session) Set(key string, value string) (string, error) {
|
||||||
}
|
}
|
||||||
s.HideIds = b
|
s.HideIds = b
|
||||||
return value, nil
|
return value, nil
|
||||||
case "receipts":
|
|
||||||
b, err := toBool(value)
|
|
||||||
if err != nil {
|
|
||||||
return "", err
|
|
||||||
}
|
|
||||||
s.Receipts = b
|
|
||||||
return value, nil
|
|
||||||
case "nativeedits":
|
|
||||||
b, err := toBool(value)
|
|
||||||
if err != nil {
|
|
||||||
return "", err
|
|
||||||
}
|
|
||||||
s.NativeEdits = b
|
|
||||||
return value, nil
|
|
||||||
case "ignoregroupdeletions":
|
|
||||||
b, err := toBool(value)
|
|
||||||
if err != nil {
|
|
||||||
return "", err
|
|
||||||
}
|
|
||||||
s.IgnoreGroupDeletions = b
|
|
||||||
return value, nil
|
|
||||||
}
|
}
|
||||||
|
|
||||||
return "", errors.New("Unknown session property")
|
return "", errors.New("Unknown session property")
|
||||||
}
|
}
|
||||||
|
|
||||||
// PropertyType determines the property type
|
|
||||||
func PropertyType(key string) byte {
|
|
||||||
switch key {
|
|
||||||
case "timezone":
|
|
||||||
return PropertyTypeString
|
|
||||||
case "keeponline", "rawmessages", "asciiarrows", "oobmode", "carbons", "hideids",
|
|
||||||
"receipts", "nativeedits", "ignoregroupdeletions":
|
|
||||||
return PropertyTypeBool
|
|
||||||
}
|
|
||||||
return PropertyTypeUnknown
|
|
||||||
}
|
|
||||||
|
|
||||||
// TimezoneToLocation tries to convert config timezone to location
|
// TimezoneToLocation tries to convert config timezone to location
|
||||||
func (s *Session) TimezoneToLocation() *time.Location {
|
func (s *Session) TimezoneToLocation() *time.Location {
|
||||||
time, err := time.Parse("-07:00", s.Timezone)
|
time, err := time.Parse("-07:00", s.Timezone)
|
||||||
|
|
@ -295,51 +210,6 @@ func (s *Session) TimezoneToLocation() *time.Location {
|
||||||
return zeroLocation
|
return zeroLocation
|
||||||
}
|
}
|
||||||
|
|
||||||
// IgnoreChat adds a chat id to ignore list, returns false if already ignored
|
|
||||||
func (s *Session) IgnoreChat(chatID int64) bool {
|
|
||||||
sessionsLock.Lock()
|
|
||||||
defer sessionsLock.Unlock()
|
|
||||||
|
|
||||||
if s.ignoredChatsMap == nil {
|
|
||||||
s.ignoredChatsMap = make(map[int64]bool)
|
|
||||||
} else if _, ok := s.ignoredChatsMap[chatID]; ok {
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
|
|
||||||
s.ignoredChatsMap[chatID] = true
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
|
|
||||||
// UnignoreChat removes a chat id from ignore list, returns false if not already ignored
|
|
||||||
func (s *Session) UnignoreChat(chatID int64) bool {
|
|
||||||
sessionsLock.Lock()
|
|
||||||
defer sessionsLock.Unlock()
|
|
||||||
|
|
||||||
if s.ignoredChatsMap == nil {
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
|
|
||||||
if _, ok := s.ignoredChatsMap[chatID]; !ok {
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
|
|
||||||
delete(s.ignoredChatsMap, chatID)
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
|
|
||||||
// IsChatIgnored checks the chat id against the ignore list
|
|
||||||
func (s *Session) IsChatIgnored(chatID int64) bool {
|
|
||||||
sessionsLock.Lock()
|
|
||||||
defer sessionsLock.Unlock()
|
|
||||||
|
|
||||||
if s.ignoredChatsMap == nil {
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
|
|
||||||
_, ok := s.ignoredChatsMap[chatID]
|
|
||||||
return ok
|
|
||||||
}
|
|
||||||
|
|
||||||
func fromBool(b bool) string {
|
func fromBool(b bool) string {
|
||||||
if b {
|
if b {
|
||||||
return "true"
|
return "true"
|
||||||
|
|
|
||||||
|
|
@ -48,7 +48,6 @@ func TestSessionToMap(t *testing.T) {
|
||||||
Timezone: "klsf",
|
Timezone: "klsf",
|
||||||
RawMessages: true,
|
RawMessages: true,
|
||||||
OOBMode: true,
|
OOBMode: true,
|
||||||
Receipts: true,
|
|
||||||
}
|
}
|
||||||
m := session.ToMap()
|
m := session.ToMap()
|
||||||
sample := map[string]string{
|
sample := map[string]string{
|
||||||
|
|
@ -59,8 +58,6 @@ func TestSessionToMap(t *testing.T) {
|
||||||
"oobmode": "true",
|
"oobmode": "true",
|
||||||
"carbons": "false",
|
"carbons": "false",
|
||||||
"hideids": "false",
|
"hideids": "false",
|
||||||
"receipts": "true",
|
|
||||||
"nativeedits": "false",
|
|
||||||
}
|
}
|
||||||
if !reflect.DeepEqual(m, sample) {
|
if !reflect.DeepEqual(m, sample) {
|
||||||
t.Errorf("Map does not match the sample: %v", m)
|
t.Errorf("Map does not match the sample: %v", m)
|
||||||
|
|
@ -88,31 +85,3 @@ func TestSessionSetAbsent(t *testing.T) {
|
||||||
t.Error("There shouldn't come a donkey!")
|
t.Error("There shouldn't come a donkey!")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestSessionIgnore(t *testing.T) {
|
|
||||||
session := Session{}
|
|
||||||
if session.IsChatIgnored(3) {
|
|
||||||
t.Error("Shouldn't be ignored yet")
|
|
||||||
}
|
|
||||||
if !session.IgnoreChat(3) {
|
|
||||||
t.Error("Shouldn't have been ignored")
|
|
||||||
}
|
|
||||||
if session.IgnoreChat(3) {
|
|
||||||
t.Error("Shouldn't ignore second time")
|
|
||||||
}
|
|
||||||
if !session.IsChatIgnored(3) {
|
|
||||||
t.Error("Should be ignored already")
|
|
||||||
}
|
|
||||||
if session.IsChatIgnored(-145) {
|
|
||||||
t.Error("Wrong chat is ignored")
|
|
||||||
}
|
|
||||||
if !session.UnignoreChat(3) {
|
|
||||||
t.Error("Should successfully unignore")
|
|
||||||
}
|
|
||||||
if session.UnignoreChat(3) {
|
|
||||||
t.Error("Should unignore second time")
|
|
||||||
}
|
|
||||||
if session.IsChatIgnored(3) {
|
|
||||||
t.Error("Shouldn't be ignored already")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
|
||||||
|
|
@ -1,46 +0,0 @@
|
||||||
FROM golang:1.19-bullseye AS base
|
|
||||||
|
|
||||||
RUN apt-get update
|
|
||||||
RUN apt-get install -y libssl-dev cmake build-essential gperf libz-dev make git php
|
|
||||||
|
|
||||||
FROM base AS tdlib
|
|
||||||
|
|
||||||
ARG TD_COMMIT
|
|
||||||
ARG MAKEOPTS
|
|
||||||
RUN git clone https://github.com/tdlib/td /src/
|
|
||||||
RUN git -C /src/ checkout "${TD_COMMIT}"
|
|
||||||
RUN mkdir build
|
|
||||||
WORKDIR /build/
|
|
||||||
RUN cmake -DCMAKE_BUILD_TYPE=Release -DCMAKE_INSTALL_PREFIX=/compiled/ /src/
|
|
||||||
RUN cmake --build . --target prepare_cross_compiling ${MAKEOPTS}
|
|
||||||
WORKDIR /src/
|
|
||||||
RUN php SplitSource.php
|
|
||||||
WORKDIR /build/
|
|
||||||
RUN cmake --build . ${MAKEOPTS}
|
|
||||||
RUN make install
|
|
||||||
|
|
||||||
FROM base AS cache
|
|
||||||
ARG VERSION
|
|
||||||
COPY --from=tdlib /compiled/ /usr/local/
|
|
||||||
WORKDIR /src
|
|
||||||
RUN go env -w GOCACHE=/go-cache
|
|
||||||
RUN go env -w GOMODCACHE=/gomod-cache
|
|
||||||
RUN --mount=type=cache,target=/gomod-cache \
|
|
||||||
--mount=type=bind,source=./,target=/src,rw \
|
|
||||||
/bin/bash -c 'go mod tidy; go get -t'
|
|
||||||
|
|
||||||
FROM cache AS build
|
|
||||||
ARG MAKEOPTS
|
|
||||||
WORKDIR /src
|
|
||||||
RUN --mount=type=bind,source=./,target=/src,rw \
|
|
||||||
--mount=type=cache,target=/go-cache \
|
|
||||||
--mount=type=cache,target=/gomod-cache \
|
|
||||||
--mount=type=cache,destination=/src/release \
|
|
||||||
make ${MAKEOPTS}
|
|
||||||
|
|
||||||
FROM build AS release
|
|
||||||
RUN --mount=type=cache,destination=/src/release \
|
|
||||||
cp /src/release/telegabber /
|
|
||||||
|
|
||||||
FROM scratch AS binaries
|
|
||||||
COPY --from=release /telegabber /
|
|
||||||
|
|
@ -1,23 +0,0 @@
|
||||||
FROM golang:1.19-bullseye AS base
|
|
||||||
|
|
||||||
RUN apt-get update
|
|
||||||
RUN apt-get install -y libssl-dev cmake build-essential gperf libz-dev make git php
|
|
||||||
|
|
||||||
FROM base AS tdlib
|
|
||||||
|
|
||||||
ARG TD_COMMIT
|
|
||||||
ARG MAKEOPTS
|
|
||||||
RUN git clone https://github.com/tdlib/td /src/
|
|
||||||
RUN git -C /src/ checkout "${TD_COMMIT}"
|
|
||||||
RUN mkdir build
|
|
||||||
WORKDIR /build/
|
|
||||||
RUN cmake -DCMAKE_BUILD_TYPE=Release -DCMAKE_INSTALL_PREFIX=/compiled/ /src/
|
|
||||||
RUN cmake --build . --target prepare_cross_compiling ${MAKEOPTS}
|
|
||||||
WORKDIR /src/
|
|
||||||
RUN php SplitSource.php
|
|
||||||
WORKDIR /build/
|
|
||||||
RUN cmake --build . ${MAKEOPTS}
|
|
||||||
RUN make install
|
|
||||||
|
|
||||||
FROM scratch AS binaries
|
|
||||||
COPY --from=tdlib /compiled/ /
|
|
||||||
|
|
@ -12,11 +12,10 @@ import (
|
||||||
"dev.narayana.im/narayana/telegabber/xmpp"
|
"dev.narayana.im/narayana/telegabber/xmpp"
|
||||||
|
|
||||||
log "github.com/sirupsen/logrus"
|
log "github.com/sirupsen/logrus"
|
||||||
"github.com/zelenin/go-tdlib/client"
|
|
||||||
goxmpp "gosrc.io/xmpp"
|
goxmpp "gosrc.io/xmpp"
|
||||||
)
|
)
|
||||||
|
|
||||||
var version string = "1.12.8"
|
var version string = "1.8.1"
|
||||||
var commit string
|
var commit string
|
||||||
|
|
||||||
var sm *goxmpp.StreamManager
|
var sm *goxmpp.StreamManager
|
||||||
|
|
@ -61,14 +60,11 @@ func main() {
|
||||||
log.Fatal(err)
|
log.Fatal(err)
|
||||||
}
|
}
|
||||||
|
|
||||||
client.SetLogVerbosityLevel(&client.SetLogVerbosityLevelRequest{
|
|
||||||
NewVerbosityLevel: stringToTdlibLogConstant(config.Telegram.Loglevel),
|
|
||||||
})
|
|
||||||
SetLogrusLevel(config.XMPP.Loglevel)
|
SetLogrusLevel(config.XMPP.Loglevel)
|
||||||
|
|
||||||
log.Infof("Starting telegabber version %v", version)
|
log.Infof("Starting telegabber version %v", version)
|
||||||
|
|
||||||
sm, component, err = xmpp.NewComponent(config.XMPP, config.Telegram, *idsPath, version)
|
sm, component, err = xmpp.NewComponent(config.XMPP, config.Telegram, *idsPath)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Fatal(err)
|
log.Fatal(err)
|
||||||
}
|
}
|
||||||
|
|
@ -93,25 +89,6 @@ func main() {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
var tdlibLogConstants = map[string]int32{
|
|
||||||
":fatal": 0,
|
|
||||||
":error": 1,
|
|
||||||
":warn": 2,
|
|
||||||
":info": 3,
|
|
||||||
":debug": 4,
|
|
||||||
":verbose": 5,
|
|
||||||
":all": 1023,
|
|
||||||
}
|
|
||||||
|
|
||||||
func stringToTdlibLogConstant(c string) int32 {
|
|
||||||
level, ok := tdlibLogConstants[c]
|
|
||||||
if !ok {
|
|
||||||
level = 0
|
|
||||||
}
|
|
||||||
|
|
||||||
return level
|
|
||||||
}
|
|
||||||
|
|
||||||
func exit() {
|
func exit() {
|
||||||
xmpp.Close(component)
|
xmpp.Close(component)
|
||||||
close(cleanupDone)
|
close(cleanupDone)
|
||||||
|
|
|
||||||
|
|
@ -1,19 +0,0 @@
|
||||||
package main
|
|
||||||
|
|
||||||
import (
|
|
||||||
"testing"
|
|
||||||
)
|
|
||||||
|
|
||||||
func TestTdlibLogInfo(t *testing.T) {
|
|
||||||
tdlibConstant := stringToTdlibLogConstant(":info")
|
|
||||||
if tdlibConstant != 3 {
|
|
||||||
t.Errorf("Wrong TDlib constant for info")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestTdlibLogInvalid(t *testing.T) {
|
|
||||||
tdlibConstant := stringToTdlibLogConstant("ziz")
|
|
||||||
if tdlibConstant != 0 {
|
|
||||||
t.Errorf("Unknown strings should return fatal loglevel")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
43
telegram/cache/cache.go
vendored
43
telegram/cache/cache.go
vendored
|
|
@ -16,8 +16,7 @@ type Status struct {
|
||||||
// Cache allows operating the chats and users cache in
|
// Cache allows operating the chats and users cache in
|
||||||
// a thread-safe manner
|
// a thread-safe manner
|
||||||
type Cache struct {
|
type Cache struct {
|
||||||
ownChats map[int64]*client.Chat
|
chats map[int64]*client.Chat
|
||||||
auxChats map[int64]*client.Chat
|
|
||||||
users map[int64]*client.User
|
users map[int64]*client.User
|
||||||
statuses map[int64]*Status
|
statuses map[int64]*Status
|
||||||
chatsLock sync.Mutex
|
chatsLock sync.Mutex
|
||||||
|
|
@ -28,8 +27,7 @@ type Cache struct {
|
||||||
// NewCache initializes a cache
|
// NewCache initializes a cache
|
||||||
func NewCache() *Cache {
|
func NewCache() *Cache {
|
||||||
return &Cache{
|
return &Cache{
|
||||||
ownChats: map[int64]*client.Chat{},
|
chats: map[int64]*client.Chat{},
|
||||||
auxChats: map[int64]*client.Chat{},
|
|
||||||
users: map[int64]*client.User{},
|
users: map[int64]*client.User{},
|
||||||
statuses: map[int64]*Status{},
|
statuses: map[int64]*Status{},
|
||||||
}
|
}
|
||||||
|
|
@ -42,23 +40,7 @@ func (cache *Cache) ChatsKeys() []int64 {
|
||||||
defer cache.chatsLock.Unlock()
|
defer cache.chatsLock.Unlock()
|
||||||
|
|
||||||
var keys []int64
|
var keys []int64
|
||||||
for id := range cache.ownChats {
|
for id := range cache.chats {
|
||||||
keys = append(keys, id)
|
|
||||||
}
|
|
||||||
for id := range cache.auxChats {
|
|
||||||
keys = append(keys, id)
|
|
||||||
}
|
|
||||||
return keys
|
|
||||||
}
|
|
||||||
|
|
||||||
// OwnChatsKeys grabs only own chat ids synchronously to avoid lockups
|
|
||||||
// while they are used
|
|
||||||
func (cache *Cache) OwnChatsKeys() []int64 {
|
|
||||||
cache.chatsLock.Lock()
|
|
||||||
defer cache.chatsLock.Unlock()
|
|
||||||
|
|
||||||
var keys []int64
|
|
||||||
for id := range cache.ownChats {
|
|
||||||
keys = append(keys, id)
|
keys = append(keys, id)
|
||||||
}
|
}
|
||||||
return keys
|
return keys
|
||||||
|
|
@ -102,10 +84,7 @@ func (cache *Cache) GetChat(id int64) (*client.Chat, bool) {
|
||||||
cache.chatsLock.Lock()
|
cache.chatsLock.Lock()
|
||||||
defer cache.chatsLock.Unlock()
|
defer cache.chatsLock.Unlock()
|
||||||
|
|
||||||
chat, ok := cache.ownChats[id]
|
chat, ok := cache.chats[id]
|
||||||
if !ok {
|
|
||||||
chat, ok = cache.auxChats[id]
|
|
||||||
}
|
|
||||||
return chat, ok
|
return chat, ok
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -128,21 +107,11 @@ func (cache *Cache) GetStatus(id int64) (*Status, bool) {
|
||||||
}
|
}
|
||||||
|
|
||||||
// SetChat stores a chat in the cache
|
// SetChat stores a chat in the cache
|
||||||
func (cache *Cache) SetChat(id int64, chat *client.Chat, own bool) {
|
func (cache *Cache) SetChat(id int64, chat *client.Chat) {
|
||||||
cache.chatsLock.Lock()
|
cache.chatsLock.Lock()
|
||||||
defer cache.chatsLock.Unlock()
|
defer cache.chatsLock.Unlock()
|
||||||
|
|
||||||
if own {
|
cache.chats[id] = chat
|
||||||
cache.ownChats[id] = chat
|
|
||||||
// move from aux to own, but not vice versa
|
|
||||||
// (own: true means that presences for the chat are needed
|
|
||||||
// for sure, false means just "not necessarily")
|
|
||||||
if _, ok := cache.auxChats[id]; ok {
|
|
||||||
delete(cache.auxChats, id)
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
cache.auxChats[id] = chat
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// SetUser stores a user in the cache
|
// SetUser stores a user in the cache
|
||||||
|
|
|
||||||
|
|
@ -2,6 +2,7 @@ package telegram
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"github.com/pkg/errors"
|
"github.com/pkg/errors"
|
||||||
|
"hash/maphash"
|
||||||
"path/filepath"
|
"path/filepath"
|
||||||
"strconv"
|
"strconv"
|
||||||
"sync"
|
"sync"
|
||||||
|
|
@ -15,53 +16,31 @@ import (
|
||||||
"gosrc.io/xmpp"
|
"gosrc.io/xmpp"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
var logConstants = map[string]int32{
|
||||||
|
":fatal": 0,
|
||||||
|
":error": 1,
|
||||||
|
":warn": 2,
|
||||||
|
":info": 3,
|
||||||
|
":debug": 4,
|
||||||
|
":verbose": 5,
|
||||||
|
":all": 1023,
|
||||||
|
}
|
||||||
|
|
||||||
|
func stringToLogConstant(c string) int32 {
|
||||||
|
level, ok := logConstants[c]
|
||||||
|
if !ok {
|
||||||
|
level = 0
|
||||||
|
}
|
||||||
|
|
||||||
|
return level
|
||||||
|
}
|
||||||
|
|
||||||
// DelayedStatus describes an online status expiring on timeout
|
// DelayedStatus describes an online status expiring on timeout
|
||||||
type DelayedStatus struct {
|
type DelayedStatus struct {
|
||||||
TimestampOnline int64
|
TimestampOnline int64
|
||||||
TimestampExpired int64
|
TimestampExpired int64
|
||||||
}
|
}
|
||||||
|
|
||||||
// HashedAvatar stores a SHA-1 hash and a Telegram file ID
|
|
||||||
type HashedAvatar struct {
|
|
||||||
Hash string
|
|
||||||
File int32
|
|
||||||
}
|
|
||||||
|
|
||||||
// NewId stores message ids and timestamps of their additions so old ones can be truncated to save memory
|
|
||||||
type newId struct {
|
|
||||||
Id int64
|
|
||||||
Ts int64
|
|
||||||
lock sync.Mutex
|
|
||||||
ownLock sync.Mutex
|
|
||||||
locked bool
|
|
||||||
fired bool
|
|
||||||
}
|
|
||||||
|
|
||||||
func newNewId() *newId {
|
|
||||||
return &newId{Ts: time.Now().Unix()}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (i *newId) Lock() {
|
|
||||||
i.ownLock.Lock()
|
|
||||||
if i.fired {
|
|
||||||
i.ownLock.Unlock()
|
|
||||||
return
|
|
||||||
}
|
|
||||||
i.locked = true
|
|
||||||
i.ownLock.Unlock()
|
|
||||||
i.lock.Lock()
|
|
||||||
}
|
|
||||||
|
|
||||||
func (i *newId) Unlock() {
|
|
||||||
i.ownLock.Lock()
|
|
||||||
if i.locked {
|
|
||||||
i.lock.Unlock()
|
|
||||||
i.locked = false
|
|
||||||
i.fired = true
|
|
||||||
}
|
|
||||||
i.ownLock.Unlock()
|
|
||||||
}
|
|
||||||
|
|
||||||
// Client stores the metadata for lazily invoked TDlib instance
|
// Client stores the metadata for lazily invoked TDlib instance
|
||||||
type Client struct {
|
type Client struct {
|
||||||
client *client.Client
|
client *client.Client
|
||||||
|
|
@ -74,33 +53,16 @@ type Client struct {
|
||||||
jid string
|
jid string
|
||||||
Session *persistence.Session
|
Session *persistence.Session
|
||||||
resources map[string]bool
|
resources map[string]bool
|
||||||
|
outbox map[string]string
|
||||||
content *config.TelegramContentConfig
|
content *config.TelegramContentConfig
|
||||||
cache *cache.Cache
|
cache *cache.Cache
|
||||||
online bool
|
online bool
|
||||||
|
|
||||||
loginWizard *loginWizardMetadata
|
|
||||||
|
|
||||||
lastAuthorizationStateType string
|
|
||||||
|
|
||||||
outbox map[string]string
|
|
||||||
editOutbox map[string]string
|
|
||||||
|
|
||||||
DelayedStatuses map[int64]*DelayedStatus
|
DelayedStatuses map[int64]*DelayedStatus
|
||||||
DelayedStatusesLock sync.Mutex
|
DelayedStatusesLock sync.Mutex
|
||||||
|
|
||||||
lastMsgHashes map[int64]uint64
|
lastMsgHashes map[int64]uint64
|
||||||
lastMsgIds map[int64]string
|
msgHashSeed maphash.Seed
|
||||||
|
|
||||||
LastBotCmdString string
|
|
||||||
|
|
||||||
XmppClientFeatures map[string]*[]string
|
|
||||||
XmppClientFeaturesLock sync.Mutex
|
|
||||||
|
|
||||||
AvatarHashes map[int64]*HashedAvatar
|
|
||||||
AvatarHashesLock sync.Mutex
|
|
||||||
|
|
||||||
MessageIdChanges map[int64]map[int64]*newId
|
|
||||||
MessageIdChangesLock sync.Mutex
|
|
||||||
|
|
||||||
locks clientLocks
|
locks clientLocks
|
||||||
SendMessageLock sync.Mutex
|
SendMessageLock sync.Mutex
|
||||||
|
|
@ -111,27 +73,20 @@ type clientLocks struct {
|
||||||
chatMessageLocks map[int64]*sync.Mutex
|
chatMessageLocks map[int64]*sync.Mutex
|
||||||
resourcesLock sync.Mutex
|
resourcesLock sync.Mutex
|
||||||
outboxLock sync.Mutex
|
outboxLock sync.Mutex
|
||||||
editOutboxLock sync.Mutex
|
|
||||||
lastMsgHashesLock sync.Mutex
|
lastMsgHashesLock sync.Mutex
|
||||||
lastMsgIdsLock sync.RWMutex
|
|
||||||
|
|
||||||
authorizerReadLock sync.Mutex
|
authorizerReadLock sync.Mutex
|
||||||
authorizerWriteLock sync.Mutex
|
authorizerWriteLock sync.Mutex
|
||||||
|
|
||||||
loginWizardReadLock sync.Mutex
|
|
||||||
loginWizardWriteLock sync.Mutex
|
|
||||||
}
|
|
||||||
|
|
||||||
type loginWizardMetadata struct {
|
|
||||||
nextStage chan string
|
|
||||||
chanBusy bool
|
|
||||||
commandSent bool
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// NewClient instantiates a Telegram App
|
// NewClient instantiates a Telegram App
|
||||||
func NewClient(conf config.TelegramConfig, jid string, component *xmpp.Component, session *persistence.Session) (*Client, error) {
|
func NewClient(conf config.TelegramConfig, jid string, component *xmpp.Component, session *persistence.Session) (*Client, error) {
|
||||||
var options []client.Option
|
var options []client.Option
|
||||||
|
|
||||||
|
options = append(options, client.WithLogVerbosity(&client.SetLogVerbosityLevelRequest{
|
||||||
|
NewVerbosityLevel: stringToLogConstant(conf.Loglevel),
|
||||||
|
}))
|
||||||
|
|
||||||
if conf.Tdlib.Client.CatchTimeout != 0 {
|
if conf.Tdlib.Client.CatchTimeout != 0 {
|
||||||
options = append(options, client.WithCatchTimeout(
|
options = append(options, client.WithCatchTimeout(
|
||||||
time.Duration(conf.Tdlib.Client.CatchTimeout)*time.Second,
|
time.Duration(conf.Tdlib.Client.CatchTimeout)*time.Second,
|
||||||
|
|
@ -172,22 +127,18 @@ func NewClient(conf config.TelegramConfig, jid string, component *xmpp.Component
|
||||||
}
|
}
|
||||||
|
|
||||||
return &Client{
|
return &Client{
|
||||||
parameters: ¶meters,
|
parameters: ¶meters,
|
||||||
xmpp: component,
|
xmpp: component,
|
||||||
jid: jid,
|
jid: jid,
|
||||||
Session: session,
|
Session: session,
|
||||||
resources: make(map[string]bool),
|
resources: make(map[string]bool),
|
||||||
content: &conf.Content,
|
outbox: make(map[string]string),
|
||||||
cache: cache.NewCache(),
|
content: &conf.Content,
|
||||||
outbox: make(map[string]string),
|
cache: cache.NewCache(),
|
||||||
editOutbox: make(map[string]string),
|
options: options,
|
||||||
options: options,
|
DelayedStatuses: make(map[int64]*DelayedStatus),
|
||||||
DelayedStatuses: make(map[int64]*DelayedStatus),
|
lastMsgHashes: make(map[int64]uint64),
|
||||||
lastMsgHashes: make(map[int64]uint64),
|
msgHashSeed: maphash.MakeSeed(),
|
||||||
lastMsgIds: make(map[int64]string),
|
|
||||||
XmppClientFeatures: make(map[string]*[]string),
|
|
||||||
AvatarHashes: make(map[int64]*HashedAvatar),
|
|
||||||
MessageIdChanges: make(map[int64]map[int64]*newId),
|
|
||||||
locks: clientLocks{
|
locks: clientLocks{
|
||||||
chatMessageLocks: make(map[int64]*sync.Mutex),
|
chatMessageLocks: make(map[int64]*sync.Mutex),
|
||||||
},
|
},
|
||||||
|
|
|
||||||
19
telegram/client_test.go
Normal file
19
telegram/client_test.go
Normal file
|
|
@ -0,0 +1,19 @@
|
||||||
|
package telegram
|
||||||
|
|
||||||
|
import (
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestLogInfo(t *testing.T) {
|
||||||
|
tdlibConstant := stringToLogConstant(":info")
|
||||||
|
if tdlibConstant != 3 {
|
||||||
|
t.Errorf("Wrong TDlib constant for info")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestLogInvalid(t *testing.T) {
|
||||||
|
tdlibConstant := stringToLogConstant("ziz")
|
||||||
|
if tdlibConstant != 0 {
|
||||||
|
t.Errorf("Unknown strings should return fatal loglevel")
|
||||||
|
}
|
||||||
|
}
|
||||||
File diff suppressed because it is too large
Load diff
|
|
@ -2,6 +2,7 @@ package telegram
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"github.com/pkg/errors"
|
"github.com/pkg/errors"
|
||||||
|
"strconv"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"dev.narayana.im/narayana/telegabber/xmpp/gateway"
|
"dev.narayana.im/narayana/telegabber/xmpp/gateway"
|
||||||
|
|
@ -68,10 +69,10 @@ func (stateHandler *clientAuthorizer) Handle(c *client.Client, state client.Auth
|
||||||
return nil
|
return nil
|
||||||
|
|
||||||
case client.TypeAuthorizationStateLoggingOut:
|
case client.TypeAuthorizationStateLoggingOut:
|
||||||
return nil
|
return client.ErrNotSupportedAuthorizationState
|
||||||
|
|
||||||
case client.TypeAuthorizationStateClosing:
|
case client.TypeAuthorizationStateClosing:
|
||||||
return nil
|
return client.ErrNotSupportedAuthorizationState
|
||||||
|
|
||||||
case client.TypeAuthorizationStateClosed:
|
case client.TypeAuthorizationStateClosed:
|
||||||
return client.ErrNotSupportedAuthorizationState
|
return client.ErrNotSupportedAuthorizationState
|
||||||
|
|
@ -121,7 +122,6 @@ func (c *Client) Connect(resource string) error {
|
||||||
}
|
}
|
||||||
|
|
||||||
go c.interactor()
|
go c.interactor()
|
||||||
log.Warn("Interactor launched")
|
|
||||||
|
|
||||||
c.authorizer.TdlibParameters <- c.parameters
|
c.authorizer.TdlibParameters <- c.parameters
|
||||||
c.locks.authorizerWriteLock.Unlock()
|
c.locks.authorizerWriteLock.Unlock()
|
||||||
|
|
@ -129,7 +129,6 @@ func (c *Client) Connect(resource string) error {
|
||||||
tdlibClient, err := client.NewClient(c.authorizer, c.options...)
|
tdlibClient, err := client.NewClient(c.authorizer, c.options...)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
c.locks.authorizationReady.Unlock()
|
c.locks.authorizationReady.Unlock()
|
||||||
c.wizardStageOrPrompt("cancel", "")
|
|
||||||
return errors.Wrap(err, "Couldn't initialize a Telegram client instance")
|
return errors.Wrap(err, "Couldn't initialize a Telegram client instance")
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -138,8 +137,6 @@ func (c *Client) Connect(resource string) error {
|
||||||
// stage 3: if a client is succesfully created, AuthorizationStateReady is already reached
|
// stage 3: if a client is succesfully created, AuthorizationStateReady is already reached
|
||||||
log.Warn("Authorization successful!")
|
log.Warn("Authorization successful!")
|
||||||
|
|
||||||
c.wizardStageOrPrompt("success", "")
|
|
||||||
|
|
||||||
c.me, err = c.client.GetMe()
|
c.me, err = c.client.GetMe()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Error("Could not retrieve me info")
|
log.Error("Could not retrieve me info")
|
||||||
|
|
@ -153,17 +150,15 @@ func (c *Client) Connect(resource string) error {
|
||||||
c.addResource(resource)
|
c.addResource(resource)
|
||||||
|
|
||||||
go func() {
|
go func() {
|
||||||
chats, err := c.client.GetChats(&client.GetChatsRequest{
|
_, err = c.client.GetChats(&client.GetChatsRequest{
|
||||||
Limit: chatsLimit,
|
Limit: chatsLimit,
|
||||||
})
|
})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Errorf("Could not retrieve chats: %v", err)
|
log.Errorf("Could not retrieve chats: %v", err)
|
||||||
} else {
|
|
||||||
log.Infof("Obtained ≈%v chats for initialization", chats.TotalCount)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
gateway.SubscribeToTransport(c.xmpp, c.jid)
|
gateway.SubscribeToTransport(c.xmpp, c.jid)
|
||||||
c.sendPresence(gateway.SPStatus("Logged in as: " + c.Session.Login))
|
gateway.SendPresence(c.xmpp, c.jid, gateway.SPStatus("Logged in as: "+c.Session.Login))
|
||||||
}()
|
}()
|
||||||
|
|
||||||
return nil
|
return nil
|
||||||
|
|
@ -185,8 +180,8 @@ func (c *Client) TryLogin(resource string, login string) error {
|
||||||
time.Sleep(1e5)
|
time.Sleep(1e5)
|
||||||
}
|
}
|
||||||
|
|
||||||
c.locks.authorizerWriteLock.Lock()
|
c.locks.authorizerReadLock.Lock()
|
||||||
defer c.locks.authorizerWriteLock.Unlock()
|
defer c.locks.authorizerReadLock.Unlock()
|
||||||
|
|
||||||
if c.authorizer == nil {
|
if c.authorizer == nil {
|
||||||
return errors.New(TelegramNotInitialized)
|
return errors.New(TelegramNotInitialized)
|
||||||
|
|
@ -231,9 +226,13 @@ func (c *Client) Disconnect(resource string, quit bool) bool {
|
||||||
log.Warn("Disconnecting from Telegram network...")
|
log.Warn("Disconnecting from Telegram network...")
|
||||||
|
|
||||||
// we're offline (unsubscribe if logout)
|
// we're offline (unsubscribe if logout)
|
||||||
for _, id := range c.cache.OwnChatsKeys() {
|
for _, id := range c.cache.ChatsKeys() {
|
||||||
args := gateway.SimplePresence(id, "unavailable")
|
gateway.SendPresence(
|
||||||
c.sendPresence(args...)
|
c.xmpp,
|
||||||
|
c.jid,
|
||||||
|
gateway.SPFrom(strconv.FormatInt(id, 10)),
|
||||||
|
gateway.SPType("unavailable"),
|
||||||
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
c.close()
|
c.close()
|
||||||
|
|
@ -260,8 +259,6 @@ func (c *Client) interactor() {
|
||||||
log.Infof("Telegram authorization state: %#v", stateType)
|
log.Infof("Telegram authorization state: %#v", stateType)
|
||||||
log.Debugf("%#v", state)
|
log.Debugf("%#v", state)
|
||||||
|
|
||||||
c.lastAuthorizationStateType = stateType
|
|
||||||
|
|
||||||
switch stateType {
|
switch stateType {
|
||||||
// stage 0: set login
|
// stage 0: set login
|
||||||
case client.TypeAuthorizationStateWaitPhoneNumber:
|
case client.TypeAuthorizationStateWaitPhoneNumber:
|
||||||
|
|
@ -269,12 +266,12 @@ func (c *Client) interactor() {
|
||||||
if c.Session.Login != "" {
|
if c.Session.Login != "" {
|
||||||
c.authorizer.PhoneNumber <- c.Session.Login
|
c.authorizer.PhoneNumber <- c.Session.Login
|
||||||
} else {
|
} else {
|
||||||
c.wizardStageOrPrompt("login", "Please, enter your Telegram login via /login 12345, or use the Login Wizard via Ad-Hoc commands")
|
gateway.SendServiceMessage(c.jid, "Please, enter your Telegram login via /login 12345", c.xmpp)
|
||||||
}
|
}
|
||||||
// stage 1: wait for auth code
|
// stage 1: wait for auth code
|
||||||
case client.TypeAuthorizationStateWaitCode:
|
case client.TypeAuthorizationStateWaitCode:
|
||||||
log.Warn("Waiting for authorization code...")
|
log.Warn("Waiting for authorization code...")
|
||||||
c.wizardStageOrPrompt("code", "Please, enter authorization code via /code 12345")
|
gateway.SendServiceMessage(c.jid, "Please, enter authorization code via /code 12345", c.xmpp)
|
||||||
// stage 1b: wait for registration
|
// stage 1b: wait for registration
|
||||||
case client.TypeAuthorizationStateWaitRegistration:
|
case client.TypeAuthorizationStateWaitRegistration:
|
||||||
log.Warn("Waiting for full name...")
|
log.Warn("Waiting for full name...")
|
||||||
|
|
@ -282,7 +279,7 @@ func (c *Client) interactor() {
|
||||||
// stage 2: wait for 2fa
|
// stage 2: wait for 2fa
|
||||||
case client.TypeAuthorizationStateWaitPassword:
|
case client.TypeAuthorizationStateWaitPassword:
|
||||||
log.Warn("Waiting for 2FA password...")
|
log.Warn("Waiting for 2FA password...")
|
||||||
c.wizardStageOrPrompt("password", "Please, enter 2FA passphrase via /password 12345")
|
gateway.SendServiceMessage(c.jid, "Please, enter 2FA passphrase via /password 12345", c.xmpp)
|
||||||
}
|
}
|
||||||
c.locks.authorizerReadLock.Unlock()
|
c.locks.authorizerReadLock.Unlock()
|
||||||
}
|
}
|
||||||
|
|
@ -301,7 +298,6 @@ func (c *Client) forceClose() {
|
||||||
func (c *Client) close() {
|
func (c *Client) close() {
|
||||||
c.locks.authorizerWriteLock.Lock()
|
c.locks.authorizerWriteLock.Lock()
|
||||||
if c.authorizer != nil && !c.authorizer.isClosed {
|
if c.authorizer != nil && !c.authorizer.isClosed {
|
||||||
log.Debug("Closing authorizer")
|
|
||||||
c.authorizer.Close()
|
c.authorizer.Close()
|
||||||
}
|
}
|
||||||
c.locks.authorizerWriteLock.Unlock()
|
c.locks.authorizerWriteLock.Unlock()
|
||||||
|
|
@ -316,7 +312,6 @@ func (c *Client) close() {
|
||||||
}
|
}
|
||||||
|
|
||||||
func (c *Client) cancelAuth() {
|
func (c *Client) cancelAuth() {
|
||||||
c.StopLoginWizard()
|
|
||||||
c.close()
|
c.close()
|
||||||
c.Session.Login = ""
|
c.Session.Login = ""
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -8,31 +8,15 @@ import (
|
||||||
"github.com/zelenin/go-tdlib/client"
|
"github.com/zelenin/go-tdlib/client"
|
||||||
)
|
)
|
||||||
|
|
||||||
type insertionType int
|
// Insertion is a piece of text in given position
|
||||||
|
type Insertion struct {
|
||||||
const (
|
|
||||||
insertionOpening insertionType = iota
|
|
||||||
insertionClosing
|
|
||||||
insertionUnpaired
|
|
||||||
)
|
|
||||||
|
|
||||||
type MarkupModeType int
|
|
||||||
|
|
||||||
const (
|
|
||||||
MarkupModeXEP0393 MarkupModeType = iota
|
|
||||||
MarkupModeMarkdown
|
|
||||||
)
|
|
||||||
|
|
||||||
// insertion is a piece of text in given position
|
|
||||||
type insertion struct {
|
|
||||||
Offset int32
|
Offset int32
|
||||||
Runes []rune
|
Runes []rune
|
||||||
Type insertionType
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// insertionStack contains the sequence of insertions
|
// InsertionStack contains the sequence of insertions
|
||||||
// from the start or from the end
|
// from the start or from the end
|
||||||
type insertionStack []*insertion
|
type InsertionStack []*Insertion
|
||||||
|
|
||||||
var boldRunesMarkdown = []rune("**")
|
var boldRunesMarkdown = []rune("**")
|
||||||
var boldRunesXEP0393 = []rune("*")
|
var boldRunesXEP0393 = []rune("*")
|
||||||
|
|
@ -40,18 +24,13 @@ var italicRunes = []rune("_")
|
||||||
var strikeRunesMarkdown = []rune("~~")
|
var strikeRunesMarkdown = []rune("~~")
|
||||||
var strikeRunesXEP0393 = []rune("~")
|
var strikeRunesXEP0393 = []rune("~")
|
||||||
var codeRunes = []rune("`")
|
var codeRunes = []rune("`")
|
||||||
var preRunesStart = []rune("```\n")
|
var preRuneStart = []rune("```\n")
|
||||||
var preRunesEnd = []rune("\n```")
|
var preRuneEnd = []rune("\n```")
|
||||||
var quoteRunes = []rune("> ")
|
|
||||||
var newlineRunes = []rune("\n")
|
|
||||||
var doubleNewlineRunes = []rune("\n\n")
|
|
||||||
var newlineCode = rune(0x0000000a)
|
|
||||||
var bmpCeil = rune(0x0000ffff)
|
|
||||||
|
|
||||||
// rebalance pumps all the values until the given offset to current stack (growing
|
// rebalance pumps all the values until the given offset to current stack (growing
|
||||||
// from start) from given stack (growing from end); should be called
|
// from start) from given stack (growing from end); should be called
|
||||||
// before any insertions to the current stack at the given offset
|
// before any insertions to the current stack at the given offset
|
||||||
func (s insertionStack) rebalance(s2 insertionStack, offset int32) (insertionStack, insertionStack) {
|
func (s InsertionStack) rebalance(s2 InsertionStack, offset int32) (InsertionStack, InsertionStack) {
|
||||||
for len(s2) > 0 && s2[len(s2)-1].Offset <= offset {
|
for len(s2) > 0 && s2[len(s2)-1].Offset <= offset {
|
||||||
s = append(s, s2[len(s2)-1])
|
s = append(s, s2[len(s2)-1])
|
||||||
s2 = s2[:len(s2)-1]
|
s2 = s2[:len(s2)-1]
|
||||||
|
|
@ -62,10 +41,10 @@ func (s insertionStack) rebalance(s2 insertionStack, offset int32) (insertionSta
|
||||||
|
|
||||||
// NewIterator is a second order function that sequentially scans and returns
|
// NewIterator is a second order function that sequentially scans and returns
|
||||||
// stack elements; starts returning nil when elements are ended
|
// stack elements; starts returning nil when elements are ended
|
||||||
func (s insertionStack) NewIterator() func() *insertion {
|
func (s InsertionStack) NewIterator() func() *Insertion {
|
||||||
i := -1
|
i := -1
|
||||||
|
|
||||||
return func() *insertion {
|
return func() *Insertion {
|
||||||
i++
|
i++
|
||||||
if i < len(s) {
|
if i < len(s) {
|
||||||
return s[i]
|
return s[i]
|
||||||
|
|
@ -141,10 +120,21 @@ func MergeAdjacentEntities(entities []*client.TextEntity) []*client.TextEntity {
|
||||||
}
|
}
|
||||||
|
|
||||||
// ClaspDirectives to the following span as required by XEP-0393
|
// ClaspDirectives to the following span as required by XEP-0393
|
||||||
func ClaspDirectives(doubledRunes []rune, entities []*client.TextEntity) []*client.TextEntity {
|
func ClaspDirectives(text string, entities []*client.TextEntity) []*client.TextEntity {
|
||||||
alignedEntities := make([]*client.TextEntity, len(entities))
|
alignedEntities := make([]*client.TextEntity, len(entities))
|
||||||
copy(alignedEntities, entities)
|
copy(alignedEntities, entities)
|
||||||
|
|
||||||
|
// transform the source text into a form with uniform runes and code points,
|
||||||
|
// by duplicating the Basic Multilingual Plane
|
||||||
|
doubledRunes := make([]rune, 0, len(text)*2)
|
||||||
|
|
||||||
|
for _, cp := range text {
|
||||||
|
if cp > 0x0000ffff {
|
||||||
|
doubledRunes = append(doubledRunes, cp, cp)
|
||||||
|
} else {
|
||||||
|
doubledRunes = append(doubledRunes, cp)
|
||||||
|
}
|
||||||
|
}
|
||||||
for i, entity := range alignedEntities {
|
for i, entity := range alignedEntities {
|
||||||
var dirty bool
|
var dirty bool
|
||||||
endOffset := entity.Offset + entity.Length
|
endOffset := entity.Offset + entity.Length
|
||||||
|
|
@ -177,89 +167,18 @@ func ClaspDirectives(doubledRunes []rune, entities []*client.TextEntity) []*clie
|
||||||
return alignedEntities
|
return alignedEntities
|
||||||
}
|
}
|
||||||
|
|
||||||
func markupBraces(entity *client.TextEntity, lbrace, rbrace []rune) []*insertion {
|
func markupBraces(entity *client.TextEntity, lbrace, rbrace []rune) (*Insertion, *Insertion) {
|
||||||
return []*insertion{
|
return &Insertion{
|
||||||
&insertion{
|
|
||||||
Offset: entity.Offset,
|
Offset: entity.Offset,
|
||||||
Runes: lbrace,
|
Runes: lbrace,
|
||||||
Type: insertionOpening,
|
}, &Insertion{
|
||||||
},
|
|
||||||
&insertion{
|
|
||||||
Offset: entity.Offset + entity.Length,
|
Offset: entity.Offset + entity.Length,
|
||||||
Runes: rbrace,
|
Runes: rbrace,
|
||||||
Type: insertionClosing,
|
}
|
||||||
},
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func quotePrependNewlines(entity *client.TextEntity, doubledRunes []rune, markupMode MarkupModeType) []*insertion {
|
// EntityToMarkdown generates the wrapping Markdown tags
|
||||||
if len(doubledRunes) == 0 {
|
func EntityToMarkdown(entity *client.TextEntity) (*Insertion, *Insertion) {
|
||||||
return []*insertion{}
|
|
||||||
}
|
|
||||||
|
|
||||||
startRunes := []rune("\n> ")
|
|
||||||
if entity.Offset == 0 || doubledRunes[entity.Offset-1] == newlineCode {
|
|
||||||
startRunes = quoteRunes
|
|
||||||
}
|
|
||||||
insertions := []*insertion{
|
|
||||||
&insertion{
|
|
||||||
Offset: entity.Offset,
|
|
||||||
Runes: startRunes,
|
|
||||||
Type: insertionUnpaired,
|
|
||||||
},
|
|
||||||
}
|
|
||||||
|
|
||||||
entityEnd := entity.Offset + entity.Length
|
|
||||||
entityEndInt := int(entityEnd)
|
|
||||||
|
|
||||||
var wasNewline bool
|
|
||||||
// last newline is omitted, there's no need to put quote mark after the quote
|
|
||||||
for i := entity.Offset; i < entityEnd-1; i++ {
|
|
||||||
isNewline := doubledRunes[i] == newlineCode
|
|
||||||
if (isNewline && markupMode == MarkupModeXEP0393) || (wasNewline && isNewline && markupMode == MarkupModeMarkdown) {
|
|
||||||
insertions = append(insertions, &insertion{
|
|
||||||
Offset: i + 1,
|
|
||||||
Runes: quoteRunes,
|
|
||||||
Type: insertionUnpaired,
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
if isNewline {
|
|
||||||
wasNewline = true
|
|
||||||
} else {
|
|
||||||
wasNewline = false
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
var rbrace []rune
|
|
||||||
if len(doubledRunes) > entityEndInt {
|
|
||||||
if doubledRunes[entityEnd] == newlineCode {
|
|
||||||
if markupMode == MarkupModeMarkdown && len(doubledRunes) > entityEndInt+1 && doubledRunes[entityEndInt+1] != newlineCode {
|
|
||||||
rbrace = newlineRunes
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
if markupMode == MarkupModeMarkdown {
|
|
||||||
rbrace = doubleNewlineRunes
|
|
||||||
} else {
|
|
||||||
rbrace = newlineRunes
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
insertions = append(insertions, &insertion{
|
|
||||||
Offset: entityEnd,
|
|
||||||
Runes: rbrace,
|
|
||||||
Type: insertionClosing,
|
|
||||||
})
|
|
||||||
|
|
||||||
return insertions
|
|
||||||
}
|
|
||||||
|
|
||||||
// entityToMarkdown generates the wrapping Markdown tags
|
|
||||||
func entityToMarkdown(entity *client.TextEntity, doubledRunes []rune, markupMode MarkupModeType) []*insertion {
|
|
||||||
if entity == nil || entity.Type == nil {
|
|
||||||
return []*insertion{}
|
|
||||||
}
|
|
||||||
|
|
||||||
switch entity.Type.TextEntityTypeType() {
|
switch entity.Type.TextEntityTypeType() {
|
||||||
case client.TypeTextEntityTypeBold:
|
case client.TypeTextEntityTypeBold:
|
||||||
return markupBraces(entity, boldRunesMarkdown, boldRunesMarkdown)
|
return markupBraces(entity, boldRunesMarkdown, boldRunesMarkdown)
|
||||||
|
|
@ -270,24 +189,22 @@ func entityToMarkdown(entity *client.TextEntity, doubledRunes []rune, markupMode
|
||||||
case client.TypeTextEntityTypeCode:
|
case client.TypeTextEntityTypeCode:
|
||||||
return markupBraces(entity, codeRunes, codeRunes)
|
return markupBraces(entity, codeRunes, codeRunes)
|
||||||
case client.TypeTextEntityTypePre:
|
case client.TypeTextEntityTypePre:
|
||||||
return markupBraces(entity, preRunesStart, preRunesEnd)
|
return markupBraces(entity, preRuneStart, preRuneEnd)
|
||||||
case client.TypeTextEntityTypePreCode:
|
case client.TypeTextEntityTypePreCode:
|
||||||
preCode, _ := entity.Type.(*client.TextEntityTypePreCode)
|
preCode, _ := entity.Type.(*client.TextEntityTypePreCode)
|
||||||
return markupBraces(entity, []rune("\n```"+preCode.Language+"\n"), preRunesEnd)
|
return markupBraces(entity, []rune("\n```"+preCode.Language+"\n"), codeRunes)
|
||||||
case client.TypeTextEntityTypeBlockQuote:
|
|
||||||
return quotePrependNewlines(entity, doubledRunes, MarkupModeMarkdown)
|
|
||||||
case client.TypeTextEntityTypeTextUrl:
|
case client.TypeTextEntityTypeTextUrl:
|
||||||
textURL, _ := entity.Type.(*client.TextEntityTypeTextUrl)
|
textURL, _ := entity.Type.(*client.TextEntityTypeTextUrl)
|
||||||
return markupBraces(entity, []rune("["), []rune("]("+textURL.Url+")"))
|
return markupBraces(entity, []rune("["), []rune("]("+textURL.Url+")"))
|
||||||
}
|
}
|
||||||
|
|
||||||
return []*insertion{}
|
return nil, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// entityToXEP0393 generates the wrapping XEP-0393 tags
|
// EntityToXEP0393 generates the wrapping XEP-0393 tags
|
||||||
func entityToXEP0393(entity *client.TextEntity, doubledRunes []rune, markupMode MarkupModeType) []*insertion {
|
func EntityToXEP0393(entity *client.TextEntity) (*Insertion, *Insertion) {
|
||||||
if entity == nil || entity.Type == nil {
|
if entity == nil || entity.Type == nil {
|
||||||
return []*insertion{}
|
return nil, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
switch entity.Type.TextEntityTypeType() {
|
switch entity.Type.TextEntityTypeType() {
|
||||||
|
|
@ -300,59 +217,33 @@ func entityToXEP0393(entity *client.TextEntity, doubledRunes []rune, markupMode
|
||||||
case client.TypeTextEntityTypeCode:
|
case client.TypeTextEntityTypeCode:
|
||||||
return markupBraces(entity, codeRunes, codeRunes)
|
return markupBraces(entity, codeRunes, codeRunes)
|
||||||
case client.TypeTextEntityTypePre:
|
case client.TypeTextEntityTypePre:
|
||||||
return markupBraces(entity, preRunesStart, preRunesEnd)
|
return markupBraces(entity, preRuneStart, preRuneEnd)
|
||||||
case client.TypeTextEntityTypePreCode:
|
case client.TypeTextEntityTypePreCode:
|
||||||
preCode, _ := entity.Type.(*client.TextEntityTypePreCode)
|
preCode, _ := entity.Type.(*client.TextEntityTypePreCode)
|
||||||
return markupBraces(entity, []rune("\n```"+preCode.Language+"\n"), preRunesEnd)
|
return markupBraces(entity, []rune("\n```"+preCode.Language+"\n"), codeRunes)
|
||||||
case client.TypeTextEntityTypeBlockQuote:
|
|
||||||
return quotePrependNewlines(entity, doubledRunes, MarkupModeXEP0393)
|
|
||||||
case client.TypeTextEntityTypeTextUrl:
|
case client.TypeTextEntityTypeTextUrl:
|
||||||
textURL, _ := entity.Type.(*client.TextEntityTypeTextUrl)
|
textURL, _ := entity.Type.(*client.TextEntityTypeTextUrl)
|
||||||
// non-standard, Pidgin-specific
|
// non-standard, Pidgin-specific
|
||||||
return markupBraces(entity, []rune{}, []rune(" <"+textURL.Url+">"))
|
return markupBraces(entity, []rune{}, []rune(" <"+textURL.Url+">"))
|
||||||
}
|
}
|
||||||
|
|
||||||
return []*insertion{}
|
return nil, nil
|
||||||
}
|
|
||||||
|
|
||||||
// transform the source text into a form with uniform runes and code points,
|
|
||||||
// by duplicating anything beyond the Basic Multilingual Plane
|
|
||||||
func textToDoubledRunes(text string) []rune {
|
|
||||||
doubledRunes := make([]rune, 0, len(text)*2)
|
|
||||||
for _, cp := range text {
|
|
||||||
if cp > bmpCeil {
|
|
||||||
doubledRunes = append(doubledRunes, cp, cp)
|
|
||||||
} else {
|
|
||||||
doubledRunes = append(doubledRunes, cp)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return doubledRunes
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Format traverses an already sorted list of entities and wraps the text in a markup
|
// Format traverses an already sorted list of entities and wraps the text in a markup
|
||||||
func Format(
|
func Format(
|
||||||
sourceText string,
|
sourceText string,
|
||||||
entities []*client.TextEntity,
|
entities []*client.TextEntity,
|
||||||
markupMode MarkupModeType,
|
entityToMarkup func(*client.TextEntity) (*Insertion, *Insertion),
|
||||||
) string {
|
) string {
|
||||||
if len(entities) == 0 {
|
if len(entities) == 0 {
|
||||||
return sourceText
|
return sourceText
|
||||||
}
|
}
|
||||||
|
|
||||||
var entityToMarkup func(*client.TextEntity, []rune, MarkupModeType) []*insertion
|
mergedEntities := SortEntities(ClaspDirectives(sourceText, MergeAdjacentEntities(SortEntities(entities))))
|
||||||
if markupMode == MarkupModeXEP0393 {
|
|
||||||
entityToMarkup = entityToXEP0393
|
|
||||||
} else {
|
|
||||||
entityToMarkup = entityToMarkdown
|
|
||||||
}
|
|
||||||
|
|
||||||
doubledRunes := textToDoubledRunes(sourceText)
|
startStack := make(InsertionStack, 0, len(sourceText))
|
||||||
|
endStack := make(InsertionStack, 0, len(sourceText))
|
||||||
mergedEntities := SortEntities(ClaspDirectives(doubledRunes, MergeAdjacentEntities(SortEntities(entities))))
|
|
||||||
|
|
||||||
startStack := make(insertionStack, 0, len(sourceText))
|
|
||||||
endStack := make(insertionStack, 0, len(sourceText))
|
|
||||||
|
|
||||||
// convert entities to a stack of brackets
|
// convert entities to a stack of brackets
|
||||||
var maxEndOffset int32
|
var maxEndOffset int32
|
||||||
|
|
@ -369,70 +260,36 @@ func Format(
|
||||||
|
|
||||||
startStack, endStack = startStack.rebalance(endStack, entity.Offset)
|
startStack, endStack = startStack.rebalance(endStack, entity.Offset)
|
||||||
|
|
||||||
insertions := entityToMarkup(entity, doubledRunes, markupMode)
|
startInsertion, endInsertion := entityToMarkup(entity)
|
||||||
if len(insertions) > 1 {
|
if startInsertion != nil {
|
||||||
startStack = append(startStack, insertions[0:len(insertions)-1]...)
|
startStack = append(startStack, startInsertion)
|
||||||
}
|
}
|
||||||
if len(insertions) > 0 {
|
if endInsertion != nil {
|
||||||
endStack = append(endStack, insertions[len(insertions)-1])
|
endStack = append(endStack, endInsertion)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
// flush the closing brackets that still remain in endStack
|
// flush the closing brackets that still remain in endStack
|
||||||
startStack, endStack = startStack.rebalance(endStack, maxEndOffset)
|
startStack, endStack = startStack.rebalance(endStack, maxEndOffset)
|
||||||
// sort unpaired insertions
|
|
||||||
sort.SliceStable(startStack, func(i int, j int) bool {
|
|
||||||
ins1 := startStack[i]
|
|
||||||
ins2 := startStack[j]
|
|
||||||
if ins1.Type == insertionUnpaired && ins2.Type == insertionUnpaired {
|
|
||||||
return ins1.Offset < ins2.Offset
|
|
||||||
}
|
|
||||||
if ins1.Type == insertionUnpaired {
|
|
||||||
if ins1.Offset == ins2.Offset {
|
|
||||||
if ins2.Type == insertionOpening { // > **
|
|
||||||
return true
|
|
||||||
} else if ins2.Type == insertionClosing { // **>
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
return ins1.Offset < ins2.Offset
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if ins2.Type == insertionUnpaired {
|
|
||||||
if ins1.Offset == ins2.Offset {
|
|
||||||
if ins1.Type == insertionOpening { // > **
|
|
||||||
return false
|
|
||||||
} else if ins1.Type == insertionClosing { // **>
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
return ins1.Offset < ins2.Offset
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return false
|
|
||||||
})
|
|
||||||
|
|
||||||
// merge brackets into text
|
// merge brackets into text
|
||||||
markupRunes := make([]rune, 0, len(sourceText))
|
markupRunes := make([]rune, 0, len(sourceText))
|
||||||
|
|
||||||
nextInsertion := startStack.NewIterator()
|
nextInsertion := startStack.NewIterator()
|
||||||
insertion := nextInsertion()
|
insertion := nextInsertion()
|
||||||
var skipNext bool
|
var runeI int32
|
||||||
|
|
||||||
for i, cp := range doubledRunes {
|
for _, cp := range sourceText {
|
||||||
if skipNext {
|
for insertion != nil && insertion.Offset <= runeI {
|
||||||
skipNext = false
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
|
|
||||||
for insertion != nil && int(insertion.Offset) <= i {
|
|
||||||
markupRunes = append(markupRunes, insertion.Runes...)
|
markupRunes = append(markupRunes, insertion.Runes...)
|
||||||
insertion = nextInsertion()
|
insertion = nextInsertion()
|
||||||
}
|
}
|
||||||
|
|
||||||
markupRunes = append(markupRunes, cp)
|
markupRunes = append(markupRunes, cp)
|
||||||
// skip two UTF-16 code units (not points actually!) if needed
|
// skip two UTF-16 code units (not points actually!) if needed
|
||||||
if cp > bmpCeil {
|
if cp > 0x0000ffff {
|
||||||
skipNext = true
|
runeI += 2
|
||||||
|
} else {
|
||||||
|
runeI++
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
for insertion != nil {
|
for insertion != nil {
|
||||||
|
|
|
||||||
|
|
@ -7,7 +7,7 @@ import (
|
||||||
)
|
)
|
||||||
|
|
||||||
func TestNoFormatting(t *testing.T) {
|
func TestNoFormatting(t *testing.T) {
|
||||||
markup := Format("abc\ndef", []*client.TextEntity{}, MarkupModeMarkdown)
|
markup := Format("abc\ndef", []*client.TextEntity{}, EntityToMarkdown)
|
||||||
if markup != "abc\ndef" {
|
if markup != "abc\ndef" {
|
||||||
t.Errorf("No formatting expected, but: %v", markup)
|
t.Errorf("No formatting expected, but: %v", markup)
|
||||||
}
|
}
|
||||||
|
|
@ -20,7 +20,7 @@ func TestFormattingSimple(t *testing.T) {
|
||||||
Length: 4,
|
Length: 4,
|
||||||
Type: &client.TextEntityTypeBold{},
|
Type: &client.TextEntityTypeBold{},
|
||||||
},
|
},
|
||||||
}, MarkupModeMarkdown)
|
}, EntityToMarkdown)
|
||||||
if markup != "👙**🐧🐖**" {
|
if markup != "👙**🐧🐖**" {
|
||||||
t.Errorf("Wrong simple formatting: %v", markup)
|
t.Errorf("Wrong simple formatting: %v", markup)
|
||||||
}
|
}
|
||||||
|
|
@ -40,7 +40,7 @@ func TestFormattingAdjacent(t *testing.T) {
|
||||||
Url: "https://narayana.im/",
|
Url: "https://narayana.im/",
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
}, MarkupModeMarkdown)
|
}, EntityToMarkdown)
|
||||||
if markup != "a👙_🐧_[🐖](https://narayana.im/)" {
|
if markup != "a👙_🐧_[🐖](https://narayana.im/)" {
|
||||||
t.Errorf("Wrong adjacent formatting: %v", markup)
|
t.Errorf("Wrong adjacent formatting: %v", markup)
|
||||||
}
|
}
|
||||||
|
|
@ -63,18 +63,18 @@ func TestFormattingAdjacentAndNested(t *testing.T) {
|
||||||
Length: 2,
|
Length: 2,
|
||||||
Type: &client.TextEntityTypeItalic{},
|
Type: &client.TextEntityTypeItalic{},
|
||||||
},
|
},
|
||||||
}, MarkupModeMarkdown)
|
}, EntityToMarkdown)
|
||||||
if markup != "```\n**👙**🐧\n```_🐖_" {
|
if markup != "```\n**👙**🐧\n```_🐖_" {
|
||||||
t.Errorf("Wrong adjacent&nested formatting: %v", markup)
|
t.Errorf("Wrong adjacent&nested formatting: %v", markup)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestRebalanceTwoZero(t *testing.T) {
|
func TestRebalanceTwoZero(t *testing.T) {
|
||||||
s1 := insertionStack{
|
s1 := InsertionStack{
|
||||||
&insertion{Offset: 7},
|
&Insertion{Offset: 7},
|
||||||
&insertion{Offset: 8},
|
&Insertion{Offset: 8},
|
||||||
}
|
}
|
||||||
s2 := insertionStack{}
|
s2 := InsertionStack{}
|
||||||
s1, s2 = s1.rebalance(s2, 7)
|
s1, s2 = s1.rebalance(s2, 7)
|
||||||
if !(len(s1) == 2 && len(s2) == 0 && s1[0].Offset == 7 && s1[1].Offset == 8) {
|
if !(len(s1) == 2 && len(s2) == 0 && s1[0].Offset == 7 && s1[1].Offset == 8) {
|
||||||
t.Errorf("Wrong rebalance 2–0: %#v %#v", s1, s2)
|
t.Errorf("Wrong rebalance 2–0: %#v %#v", s1, s2)
|
||||||
|
|
@ -82,13 +82,13 @@ func TestRebalanceTwoZero(t *testing.T) {
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestRebalanceNeeded(t *testing.T) {
|
func TestRebalanceNeeded(t *testing.T) {
|
||||||
s1 := insertionStack{
|
s1 := InsertionStack{
|
||||||
&insertion{Offset: 7},
|
&Insertion{Offset: 7},
|
||||||
&insertion{Offset: 8},
|
&Insertion{Offset: 8},
|
||||||
}
|
}
|
||||||
s2 := insertionStack{
|
s2 := InsertionStack{
|
||||||
&insertion{Offset: 10},
|
&Insertion{Offset: 10},
|
||||||
&insertion{Offset: 9},
|
&Insertion{Offset: 9},
|
||||||
}
|
}
|
||||||
s1, s2 = s1.rebalance(s2, 9)
|
s1, s2 = s1.rebalance(s2, 9)
|
||||||
if !(len(s1) == 3 && len(s2) == 1 &&
|
if !(len(s1) == 3 && len(s2) == 1 &&
|
||||||
|
|
@ -99,13 +99,13 @@ func TestRebalanceNeeded(t *testing.T) {
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestRebalanceNotNeeded(t *testing.T) {
|
func TestRebalanceNotNeeded(t *testing.T) {
|
||||||
s1 := insertionStack{
|
s1 := InsertionStack{
|
||||||
&insertion{Offset: 7},
|
&Insertion{Offset: 7},
|
||||||
&insertion{Offset: 8},
|
&Insertion{Offset: 8},
|
||||||
}
|
}
|
||||||
s2 := insertionStack{
|
s2 := InsertionStack{
|
||||||
&insertion{Offset: 10},
|
&Insertion{Offset: 10},
|
||||||
&insertion{Offset: 9},
|
&Insertion{Offset: 9},
|
||||||
}
|
}
|
||||||
s1, s2 = s1.rebalance(s2, 8)
|
s1, s2 = s1.rebalance(s2, 8)
|
||||||
if !(len(s1) == 2 && len(s2) == 2 &&
|
if !(len(s1) == 2 && len(s2) == 2 &&
|
||||||
|
|
@ -116,13 +116,13 @@ func TestRebalanceNotNeeded(t *testing.T) {
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestRebalanceLate(t *testing.T) {
|
func TestRebalanceLate(t *testing.T) {
|
||||||
s1 := insertionStack{
|
s1 := InsertionStack{
|
||||||
&insertion{Offset: 7},
|
&Insertion{Offset: 7},
|
||||||
&insertion{Offset: 8},
|
&Insertion{Offset: 8},
|
||||||
}
|
}
|
||||||
s2 := insertionStack{
|
s2 := InsertionStack{
|
||||||
&insertion{Offset: 10},
|
&Insertion{Offset: 10},
|
||||||
&insertion{Offset: 9},
|
&Insertion{Offset: 9},
|
||||||
}
|
}
|
||||||
s1, s2 = s1.rebalance(s2, 10)
|
s1, s2 = s1.rebalance(s2, 10)
|
||||||
if !(len(s1) == 4 && len(s2) == 0 &&
|
if !(len(s1) == 4 && len(s2) == 0 &&
|
||||||
|
|
@ -133,7 +133,7 @@ func TestRebalanceLate(t *testing.T) {
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestIteratorEmpty(t *testing.T) {
|
func TestIteratorEmpty(t *testing.T) {
|
||||||
s := insertionStack{}
|
s := InsertionStack{}
|
||||||
g := s.NewIterator()
|
g := s.NewIterator()
|
||||||
v := g()
|
v := g()
|
||||||
if v != nil {
|
if v != nil {
|
||||||
|
|
@ -142,9 +142,9 @@ func TestIteratorEmpty(t *testing.T) {
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestIterator(t *testing.T) {
|
func TestIterator(t *testing.T) {
|
||||||
s := insertionStack{
|
s := InsertionStack{
|
||||||
&insertion{Offset: 7},
|
&Insertion{Offset: 7},
|
||||||
&insertion{Offset: 8},
|
&Insertion{Offset: 8},
|
||||||
}
|
}
|
||||||
g := s.NewIterator()
|
g := s.NewIterator()
|
||||||
v := g()
|
v := g()
|
||||||
|
|
@ -208,7 +208,7 @@ func TestSortEmpty(t *testing.T) {
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestNoFormattingXEP0393(t *testing.T) {
|
func TestNoFormattingXEP0393(t *testing.T) {
|
||||||
markup := Format("abc\ndef", []*client.TextEntity{}, MarkupModeXEP0393)
|
markup := Format("abc\ndef", []*client.TextEntity{}, EntityToXEP0393)
|
||||||
if markup != "abc\ndef" {
|
if markup != "abc\ndef" {
|
||||||
t.Errorf("No formatting expected, but: %v", markup)
|
t.Errorf("No formatting expected, but: %v", markup)
|
||||||
}
|
}
|
||||||
|
|
@ -221,7 +221,7 @@ func TestFormattingXEP0393Simple(t *testing.T) {
|
||||||
Length: 4,
|
Length: 4,
|
||||||
Type: &client.TextEntityTypeBold{},
|
Type: &client.TextEntityTypeBold{},
|
||||||
},
|
},
|
||||||
}, MarkupModeXEP0393)
|
}, EntityToXEP0393)
|
||||||
if markup != "👙*🐧🐖*" {
|
if markup != "👙*🐧🐖*" {
|
||||||
t.Errorf("Wrong simple formatting: %v", markup)
|
t.Errorf("Wrong simple formatting: %v", markup)
|
||||||
}
|
}
|
||||||
|
|
@ -241,7 +241,7 @@ func TestFormattingXEP0393Adjacent(t *testing.T) {
|
||||||
Url: "https://narayana.im/",
|
Url: "https://narayana.im/",
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
}, MarkupModeXEP0393)
|
}, EntityToXEP0393)
|
||||||
if markup != "a👙_🐧_🐖 <https://narayana.im/>" {
|
if markup != "a👙_🐧_🐖 <https://narayana.im/>" {
|
||||||
t.Errorf("Wrong adjacent formatting: %v", markup)
|
t.Errorf("Wrong adjacent formatting: %v", markup)
|
||||||
}
|
}
|
||||||
|
|
@ -264,7 +264,7 @@ func TestFormattingXEP0393AdjacentAndNested(t *testing.T) {
|
||||||
Length: 2,
|
Length: 2,
|
||||||
Type: &client.TextEntityTypeItalic{},
|
Type: &client.TextEntityTypeItalic{},
|
||||||
},
|
},
|
||||||
}, MarkupModeXEP0393)
|
}, EntityToXEP0393)
|
||||||
if markup != "```\n*👙*🐧\n```_🐖_" {
|
if markup != "```\n*👙*🐧\n```_🐖_" {
|
||||||
t.Errorf("Wrong adjacent&nested formatting: %v", markup)
|
t.Errorf("Wrong adjacent&nested formatting: %v", markup)
|
||||||
}
|
}
|
||||||
|
|
@ -287,7 +287,7 @@ func TestFormattingXEP0393AdjacentItalicBoldItalic(t *testing.T) {
|
||||||
Length: 69,
|
Length: 69,
|
||||||
Type: &client.TextEntityTypeItalic{},
|
Type: &client.TextEntityTypeItalic{},
|
||||||
},
|
},
|
||||||
}, MarkupModeXEP0393)
|
}, EntityToXEP0393)
|
||||||
if markup != "_раса двуногих крысолюдей, *которую так редко замечают, что многие отрицают само их существование*_" {
|
if markup != "_раса двуногих крысолюдей, *которую так редко замечают, что многие отрицают само их существование*_" {
|
||||||
t.Errorf("Wrong adjacent italic/bold-italic formatting: %v", markup)
|
t.Errorf("Wrong adjacent italic/bold-italic formatting: %v", markup)
|
||||||
}
|
}
|
||||||
|
|
@ -315,7 +315,7 @@ func TestFormattingXEP0393MultipleAdjacent(t *testing.T) {
|
||||||
Length: 1,
|
Length: 1,
|
||||||
Type: &client.TextEntityTypeItalic{},
|
Type: &client.TextEntityTypeItalic{},
|
||||||
},
|
},
|
||||||
}, MarkupModeXEP0393)
|
}, EntityToXEP0393)
|
||||||
if markup != "a*bcd*_e_" {
|
if markup != "a*bcd*_e_" {
|
||||||
t.Errorf("Wrong multiple adjacent formatting: %v", markup)
|
t.Errorf("Wrong multiple adjacent formatting: %v", markup)
|
||||||
}
|
}
|
||||||
|
|
@ -343,7 +343,7 @@ func TestFormattingXEP0393Intersecting(t *testing.T) {
|
||||||
Length: 1,
|
Length: 1,
|
||||||
Type: &client.TextEntityTypeBold{},
|
Type: &client.TextEntityTypeBold{},
|
||||||
},
|
},
|
||||||
}, MarkupModeXEP0393)
|
}, EntityToXEP0393)
|
||||||
if markup != "a*b*_*cd*e_" {
|
if markup != "a*b*_*cd*e_" {
|
||||||
t.Errorf("Wrong intersecting formatting: %v", markup)
|
t.Errorf("Wrong intersecting formatting: %v", markup)
|
||||||
}
|
}
|
||||||
|
|
@ -361,7 +361,7 @@ func TestFormattingXEP0393InlineCode(t *testing.T) {
|
||||||
Length: 25,
|
Length: 25,
|
||||||
Type: &client.TextEntityTypePre{},
|
Type: &client.TextEntityTypePre{},
|
||||||
},
|
},
|
||||||
}, MarkupModeXEP0393)
|
}, EntityToXEP0393)
|
||||||
if markup != "Is `Gajim` a thing?\n\n```\necho 'Hello'\necho 'world'\n```\n\nhruck(" {
|
if markup != "Is `Gajim` a thing?\n\n```\necho 'Hello'\necho 'world'\n```\n\nhruck(" {
|
||||||
t.Errorf("Wrong intersecting formatting: %v", markup)
|
t.Errorf("Wrong intersecting formatting: %v", markup)
|
||||||
}
|
}
|
||||||
|
|
@ -374,7 +374,7 @@ func TestFormattingMarkdownStrikethrough(t *testing.T) {
|
||||||
Length: 3,
|
Length: 3,
|
||||||
Type: &client.TextEntityTypeStrikethrough{},
|
Type: &client.TextEntityTypeStrikethrough{},
|
||||||
},
|
},
|
||||||
}, MarkupModeMarkdown)
|
}, EntityToMarkdown)
|
||||||
if markup != "Everyone ~~dis~~likes cake." {
|
if markup != "Everyone ~~dis~~likes cake." {
|
||||||
t.Errorf("Wrong strikethrough formatting: %v", markup)
|
t.Errorf("Wrong strikethrough formatting: %v", markup)
|
||||||
}
|
}
|
||||||
|
|
@ -387,14 +387,14 @@ func TestFormattingXEP0393Strikethrough(t *testing.T) {
|
||||||
Length: 3,
|
Length: 3,
|
||||||
Type: &client.TextEntityTypeStrikethrough{},
|
Type: &client.TextEntityTypeStrikethrough{},
|
||||||
},
|
},
|
||||||
}, MarkupModeXEP0393)
|
}, EntityToXEP0393)
|
||||||
if markup != "Everyone ~dis~likes cake." {
|
if markup != "Everyone ~dis~likes cake." {
|
||||||
t.Errorf("Wrong strikethrough formatting: %v", markup)
|
t.Errorf("Wrong strikethrough formatting: %v", markup)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestClaspLeft(t *testing.T) {
|
func TestClaspLeft(t *testing.T) {
|
||||||
text := textToDoubledRunes("a b c")
|
text := "a b c"
|
||||||
entities := []*client.TextEntity{
|
entities := []*client.TextEntity{
|
||||||
&client.TextEntity{
|
&client.TextEntity{
|
||||||
Offset: 1,
|
Offset: 1,
|
||||||
|
|
@ -409,7 +409,7 @@ func TestClaspLeft(t *testing.T) {
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestClaspBoth(t *testing.T) {
|
func TestClaspBoth(t *testing.T) {
|
||||||
text := textToDoubledRunes("a b c")
|
text := "a b c"
|
||||||
entities := []*client.TextEntity{
|
entities := []*client.TextEntity{
|
||||||
&client.TextEntity{
|
&client.TextEntity{
|
||||||
Offset: 1,
|
Offset: 1,
|
||||||
|
|
@ -424,7 +424,7 @@ func TestClaspBoth(t *testing.T) {
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestClaspNotNeeded(t *testing.T) {
|
func TestClaspNotNeeded(t *testing.T) {
|
||||||
text := textToDoubledRunes(" abc ")
|
text := " abc "
|
||||||
entities := []*client.TextEntity{
|
entities := []*client.TextEntity{
|
||||||
&client.TextEntity{
|
&client.TextEntity{
|
||||||
Offset: 1,
|
Offset: 1,
|
||||||
|
|
@ -439,7 +439,7 @@ func TestClaspNotNeeded(t *testing.T) {
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestClaspNested(t *testing.T) {
|
func TestClaspNested(t *testing.T) {
|
||||||
text := textToDoubledRunes("a b c")
|
text := "a b c"
|
||||||
entities := []*client.TextEntity{
|
entities := []*client.TextEntity{
|
||||||
&client.TextEntity{
|
&client.TextEntity{
|
||||||
Offset: 1,
|
Offset: 1,
|
||||||
|
|
@ -459,7 +459,7 @@ func TestClaspNested(t *testing.T) {
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestClaspEmoji(t *testing.T) {
|
func TestClaspEmoji(t *testing.T) {
|
||||||
text := textToDoubledRunes("a 🐖 c")
|
text := "a 🐖 c"
|
||||||
entities := []*client.TextEntity{
|
entities := []*client.TextEntity{
|
||||||
&client.TextEntity{
|
&client.TextEntity{
|
||||||
Offset: 1,
|
Offset: 1,
|
||||||
|
|
@ -472,111 +472,3 @@ func TestClaspEmoji(t *testing.T) {
|
||||||
t.Errorf("Wrong claspemoji: %#v", entities)
|
t.Errorf("Wrong claspemoji: %#v", entities)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestNoNewlineBlockquoteXEP0393(t *testing.T) {
|
|
||||||
markup := Format("yes it can i think", []*client.TextEntity{
|
|
||||||
&client.TextEntity{
|
|
||||||
Offset: 4,
|
|
||||||
Length: 6,
|
|
||||||
Type: &client.TextEntityTypeBlockQuote{},
|
|
||||||
},
|
|
||||||
}, MarkupModeXEP0393)
|
|
||||||
if markup != "yes \n> it can\n i think" {
|
|
||||||
t.Errorf("Wrong blockquote formatting: %v", markup)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestNoNewlineBlockquoteMarkdown(t *testing.T) {
|
|
||||||
markup := Format("yes it can i think", []*client.TextEntity{
|
|
||||||
&client.TextEntity{
|
|
||||||
Offset: 4,
|
|
||||||
Length: 6,
|
|
||||||
Type: &client.TextEntityTypeBlockQuote{},
|
|
||||||
},
|
|
||||||
}, MarkupModeMarkdown)
|
|
||||||
if markup != "yes \n> it can\n\n i think" {
|
|
||||||
t.Errorf("Wrong blockquote formatting: %v", markup)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestMultilineBlockquoteXEP0393(t *testing.T) {
|
|
||||||
markup := Format("hruck\npuck\n\nshuck\ntext", []*client.TextEntity{
|
|
||||||
&client.TextEntity{
|
|
||||||
Offset: 0,
|
|
||||||
Length: 17,
|
|
||||||
Type: &client.TextEntityTypeBlockQuote{},
|
|
||||||
},
|
|
||||||
}, MarkupModeXEP0393)
|
|
||||||
if markup != "> hruck\n> puck\n> \n> shuck\ntext" {
|
|
||||||
t.Errorf("Wrong blockquote formatting: %v", markup)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestMultilineBlockquoteMarkdown(t *testing.T) {
|
|
||||||
markup := Format("hruck\npuck\n\nshuck\ntext", []*client.TextEntity{
|
|
||||||
&client.TextEntity{
|
|
||||||
Offset: 0,
|
|
||||||
Length: 17,
|
|
||||||
Type: &client.TextEntityTypeBlockQuote{},
|
|
||||||
},
|
|
||||||
}, MarkupModeMarkdown)
|
|
||||||
if markup != "> hruck\npuck\n\n> shuck\n\ntext" {
|
|
||||||
t.Errorf("Wrong blockquote formatting: %v", markup)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestMixedBlockquoteXEP0393(t *testing.T) {
|
|
||||||
markup := Format("hruck\npuck\nshuck\ntext", []*client.TextEntity{
|
|
||||||
&client.TextEntity{
|
|
||||||
Offset: 0,
|
|
||||||
Length: 16,
|
|
||||||
Type: &client.TextEntityTypeBlockQuote{},
|
|
||||||
},
|
|
||||||
&client.TextEntity{
|
|
||||||
Offset: 0,
|
|
||||||
Length: 16,
|
|
||||||
Type: &client.TextEntityTypeBold{},
|
|
||||||
},
|
|
||||||
&client.TextEntity{
|
|
||||||
Offset: 0,
|
|
||||||
Length: 10,
|
|
||||||
Type: &client.TextEntityTypeItalic{},
|
|
||||||
},
|
|
||||||
&client.TextEntity{
|
|
||||||
Offset: 7,
|
|
||||||
Length: 2,
|
|
||||||
Type: &client.TextEntityTypeStrikethrough{},
|
|
||||||
},
|
|
||||||
}, MarkupModeXEP0393)
|
|
||||||
if markup != "> *_hruck\n> p~uc~k_\n> shuck*\ntext" {
|
|
||||||
t.Errorf("Wrong blockquote formatting: %v", markup)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestMixedBlockquoteMarkdown(t *testing.T) {
|
|
||||||
markup := Format("hruck\npuck\nshuck\ntext", []*client.TextEntity{
|
|
||||||
&client.TextEntity{
|
|
||||||
Offset: 0,
|
|
||||||
Length: 16,
|
|
||||||
Type: &client.TextEntityTypeBlockQuote{},
|
|
||||||
},
|
|
||||||
&client.TextEntity{
|
|
||||||
Offset: 0,
|
|
||||||
Length: 16,
|
|
||||||
Type: &client.TextEntityTypeBold{},
|
|
||||||
},
|
|
||||||
&client.TextEntity{
|
|
||||||
Offset: 0,
|
|
||||||
Length: 10,
|
|
||||||
Type: &client.TextEntityTypeItalic{},
|
|
||||||
},
|
|
||||||
&client.TextEntity{
|
|
||||||
Offset: 7,
|
|
||||||
Length: 2,
|
|
||||||
Type: &client.TextEntityTypeStrikethrough{},
|
|
||||||
},
|
|
||||||
}, MarkupModeMarkdown)
|
|
||||||
if markup != "> **_hruck\np~~uc~~k_\nshuck**\n\ntext" {
|
|
||||||
t.Errorf("Wrong blockquote formatting: %v", markup)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
|
||||||
|
|
@ -55,31 +55,6 @@ func (c *Client) cleanTempFile(path string) {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func (c *Client) sendMarker(chatId, messageId int64, typ gateway.MarkerType) {
|
|
||||||
xmppId, err := gateway.IdsDB.GetByTgIds(c.Session.Login, c.jid, chatId, messageId)
|
|
||||||
if err != nil {
|
|
||||||
xmppId = strconv.FormatInt(messageId, 10)
|
|
||||||
}
|
|
||||||
|
|
||||||
var stringType string
|
|
||||||
if typ == gateway.MarkerTypeReceived {
|
|
||||||
stringType = "received"
|
|
||||||
} else if typ == gateway.MarkerTypeDisplayed {
|
|
||||||
stringType = "displayed"
|
|
||||||
}
|
|
||||||
log.WithFields(log.Fields{
|
|
||||||
"xmppId": xmppId,
|
|
||||||
}).Debugf("marker: %s", stringType)
|
|
||||||
|
|
||||||
gateway.SendMessageMarker(
|
|
||||||
c.jid,
|
|
||||||
strconv.FormatInt(chatId, 10),
|
|
||||||
c.xmpp,
|
|
||||||
typ,
|
|
||||||
xmppId,
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (c *Client) updateHandler() {
|
func (c *Client) updateHandler() {
|
||||||
listener := c.client.GetListener()
|
listener := c.client.GetListener()
|
||||||
defer listener.Close()
|
defer listener.Close()
|
||||||
|
|
@ -166,12 +141,6 @@ func (c *Client) updateHandler() {
|
||||||
uhOh()
|
uhOh()
|
||||||
}
|
}
|
||||||
c.updateChatTitle(typedUpdate)
|
c.updateChatTitle(typedUpdate)
|
||||||
case client.TypeUpdateChatReadOutbox:
|
|
||||||
typedUpdate, ok := update.(*client.UpdateChatReadOutbox)
|
|
||||||
if !ok {
|
|
||||||
uhOh()
|
|
||||||
}
|
|
||||||
c.updateChatReadOutbox(typedUpdate)
|
|
||||||
default:
|
default:
|
||||||
// log only handled types
|
// log only handled types
|
||||||
continue
|
continue
|
||||||
|
|
@ -186,13 +155,13 @@ func (c *Client) updateHandler() {
|
||||||
func (c *Client) updateUser(update *client.UpdateUser) {
|
func (c *Client) updateUser(update *client.UpdateUser) {
|
||||||
c.cache.SetUser(update.User.Id, update.User)
|
c.cache.SetUser(update.User.Id, update.User)
|
||||||
show, status, presenceType := c.userStatusToText(update.User.Status, update.User.Id)
|
show, status, presenceType := c.userStatusToText(update.User.Status, update.User.Id)
|
||||||
go c.ProcessStatusUpdate(update.User.Id, status, show, false, gateway.SPType(presenceType))
|
go c.ProcessStatusUpdate(update.User.Id, status, show, gateway.SPType(presenceType))
|
||||||
}
|
}
|
||||||
|
|
||||||
// user status changed
|
// user status changed
|
||||||
func (c *Client) updateUserStatus(update *client.UpdateUserStatus) {
|
func (c *Client) updateUserStatus(update *client.UpdateUserStatus) {
|
||||||
show, status, presenceType := c.userStatusToText(update.Status, update.UserId)
|
show, status, presenceType := c.userStatusToText(update.Status, update.UserId)
|
||||||
go c.ProcessStatusUpdate(update.UserId, status, show, false, gateway.SPImmed(false), gateway.SPType(presenceType))
|
go c.ProcessStatusUpdate(update.UserId, status, show, gateway.SPImmed(false), gateway.SPType(presenceType))
|
||||||
}
|
}
|
||||||
|
|
||||||
// new chat discovered
|
// new chat discovered
|
||||||
|
|
@ -206,14 +175,14 @@ func (c *Client) updateNewChat(update *client.UpdateNewChat) {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
c.cache.SetChat(update.Chat.Id, update.Chat, true)
|
c.cache.SetChat(update.Chat.Id, update.Chat)
|
||||||
|
|
||||||
if update.Chat.Positions != nil && len(update.Chat.Positions) > 0 {
|
if update.Chat.Positions != nil && len(update.Chat.Positions) > 0 {
|
||||||
c.subscribeToID(update.Chat.Id, update.Chat)
|
c.subscribeToID(update.Chat.Id, update.Chat)
|
||||||
}
|
}
|
||||||
|
|
||||||
if update.Chat.Id < 0 {
|
if update.Chat.Id < 0 {
|
||||||
c.ProcessStatusUpdate(update.Chat.Id, update.Chat.Title, "chat", true)
|
c.ProcessStatusUpdate(update.Chat.Id, update.Chat.Title, "chat")
|
||||||
}
|
}
|
||||||
}()
|
}()
|
||||||
}
|
}
|
||||||
|
|
@ -235,9 +204,6 @@ func (c *Client) updateChatLastMessage(update *client.UpdateChatLastMessage) {
|
||||||
// message received
|
// message received
|
||||||
func (c *Client) updateNewMessage(update *client.UpdateNewMessage) {
|
func (c *Client) updateNewMessage(update *client.UpdateNewMessage) {
|
||||||
chatId := update.Message.ChatId
|
chatId := update.Message.ChatId
|
||||||
if c.Session.IsChatIgnored(chatId) {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
// guarantee sequential message delivering per chat
|
// guarantee sequential message delivering per chat
|
||||||
lock := c.getChatMessageLock(chatId)
|
lock := c.getChatMessageLock(chatId)
|
||||||
|
|
@ -245,23 +211,10 @@ func (c *Client) updateNewMessage(update *client.UpdateNewMessage) {
|
||||||
lock.Lock()
|
lock.Lock()
|
||||||
defer lock.Unlock()
|
defer lock.Unlock()
|
||||||
|
|
||||||
var forceCmd bool
|
|
||||||
if c.LastBotCmdString != "" && update.Message.IsOutgoing {
|
|
||||||
if update.Message.Content.MessageContentType() == client.TypeMessageText {
|
|
||||||
textMessage, _ := update.Message.Content.(*client.MessageText)
|
|
||||||
|
|
||||||
if textMessage.Text != nil && textMessage.Text.Text == c.LastBotCmdString {
|
|
||||||
forceCmd = true
|
|
||||||
c.LastBotCmdString = ""
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// ignore self outgoing messages
|
// ignore self outgoing messages
|
||||||
if update.Message.IsOutgoing &&
|
if update.Message.IsOutgoing &&
|
||||||
update.Message.SendingState != nil &&
|
update.Message.SendingState != nil &&
|
||||||
update.Message.SendingState.MessageSendingStateType() == client.TypeMessageSendingStatePending &&
|
update.Message.SendingState.MessageSendingStateType() == client.TypeMessageSendingStatePending {
|
||||||
!forceCmd {
|
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -270,29 +223,23 @@ func (c *Client) updateNewMessage(update *client.UpdateNewMessage) {
|
||||||
}).Warn("New message from chat")
|
}).Warn("New message from chat")
|
||||||
|
|
||||||
c.ProcessIncomingMessage(chatId, update.Message)
|
c.ProcessIncomingMessage(chatId, update.Message)
|
||||||
|
|
||||||
|
c.updateLastMessageHash(update.Message.ChatId, update.Message.Id, update.Message.Content)
|
||||||
}()
|
}()
|
||||||
}
|
}
|
||||||
|
|
||||||
// message content updated
|
// message content updated
|
||||||
func (c *Client) updateMessageContent(update *client.UpdateMessageContent) {
|
func (c *Client) updateMessageContent(update *client.UpdateMessageContent) {
|
||||||
if c.Session.IsChatIgnored(update.ChatId) {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
markupFunction := c.getFormatter()
|
markupFunction := c.getFormatter()
|
||||||
|
|
||||||
log.Debugf("newContent: %#v", update.NewContent)
|
defer c.updateLastMessageHash(update.ChatId, update.MessageId, update.NewContent)
|
||||||
|
|
||||||
lock := c.getChatMessageLock(update.ChatId)
|
|
||||||
lock.Lock()
|
|
||||||
lock.Unlock()
|
|
||||||
c.SendMessageLock.Lock()
|
c.SendMessageLock.Lock()
|
||||||
c.SendMessageLock.Unlock()
|
c.SendMessageLock.Unlock()
|
||||||
|
xmppId, err := gateway.IdsDB.GetByTgIds(c.Session.Login, c.jid, update.ChatId, update.MessageId)
|
||||||
xmppId, xmppIdErr := gateway.IdsDB.GetByTgIds(c.Session.Login, c.jid, update.ChatId, update.MessageId)
|
|
||||||
var ignoredResource string
|
var ignoredResource string
|
||||||
if xmppIdErr == nil {
|
if err == nil {
|
||||||
ignoredResource = c.popFromEditOutbox(xmppId)
|
ignoredResource = c.popFromOutbox(xmppId)
|
||||||
} else {
|
} else {
|
||||||
log.Infof("Couldn't retrieve XMPP message ids for %v, an echo may happen", update.MessageId)
|
log.Infof("Couldn't retrieve XMPP message ids for %v, an echo may happen", update.MessageId)
|
||||||
}
|
}
|
||||||
|
|
@ -304,117 +251,28 @@ func (c *Client) updateMessageContent(update *client.UpdateMessageContent) {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
if update.NewContent.MessageContentType() == client.TypeMessageText {
|
if update.NewContent.MessageContentType() == client.TypeMessageText && c.hasLastMessageHashChanged(update.ChatId, update.MessageId, update.NewContent) {
|
||||||
textContent := update.NewContent.(*client.MessageText)
|
textContent := update.NewContent.(*client.MessageText)
|
||||||
log.Debugf("textContent: %#v", textContent.Text)
|
var editChar string
|
||||||
|
if c.Session.AsciiArrows {
|
||||||
var replaceId string
|
editChar = "e "
|
||||||
sId := strconv.FormatInt(update.MessageId, 10)
|
} else {
|
||||||
var isCarbon bool
|
editChar = "✎ "
|
||||||
|
}
|
||||||
go func() {
|
text := editChar + fmt.Sprintf("%v | %s", update.MessageId, formatter.Format(
|
||||||
message, messageErr := c.client.GetMessage(&client.GetMessageRequest{
|
textContent.Text.Text,
|
||||||
ChatId: update.ChatId,
|
textContent.Text.Entities,
|
||||||
MessageId: update.MessageId,
|
markupFunction,
|
||||||
})
|
))
|
||||||
if messageErr != nil {
|
for _, jid := range jids {
|
||||||
// odnako za vremya puti
|
gateway.SendMessage(jid, strconv.FormatInt(update.ChatId, 10), text, "e"+strconv.FormatInt(update.MessageId, 10), c.xmpp, nil, false)
|
||||||
// sobaka mogla podrasti
|
}
|
||||||
c.MessageIdChangesLock.Lock()
|
|
||||||
idsMap, idsMapOk := c.MessageIdChanges[update.ChatId]
|
|
||||||
hadNoId := false
|
|
||||||
if idsMapOk {
|
|
||||||
newId, newIdOk := idsMap[update.MessageId]
|
|
||||||
if newIdOk {
|
|
||||||
if newId.Id == 0 {
|
|
||||||
hadNoId = true
|
|
||||||
c.MessageIdChangesLock.Unlock()
|
|
||||||
newId.Lock()
|
|
||||||
}
|
|
||||||
log.Infof("falling back to updated message id: %v/%v->%v", update.ChatId, update.MessageId, newId.Id)
|
|
||||||
message, messageErr = c.client.GetMessage(&client.GetMessageRequest{
|
|
||||||
ChatId: update.ChatId,
|
|
||||||
MessageId: newId.Id,
|
|
||||||
})
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if !hadNoId {
|
|
||||||
c.MessageIdChangesLock.Unlock()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
var prefix string
|
|
||||||
if messageErr == nil {
|
|
||||||
if message.EditDate == 0 {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
log.Debugf("editDate: %v", message.EditDate)
|
|
||||||
|
|
||||||
isCarbon = c.isCarbonsEnabled() && message.IsOutgoing
|
|
||||||
// reply correction support in clients is suboptimal yet, so cut them out for now
|
|
||||||
prefix, _ = c.messageToPrefix(message, "", "", true)
|
|
||||||
} else {
|
|
||||||
log.Errorf("No message %v/%v found, cannot reliably determine if it is a carbon and if it is edited: %v", update.ChatId, update.MessageId, messageErr.Error())
|
|
||||||
}
|
|
||||||
|
|
||||||
// use XEP-0308 edits only if the last message is edited for sure, fallback otherwise
|
|
||||||
if c.Session.NativeEdits {
|
|
||||||
lastXmppId, ok := c.getLastChatMessageId(update.ChatId)
|
|
||||||
if xmppIdErr != nil {
|
|
||||||
xmppId = sId
|
|
||||||
}
|
|
||||||
if ok && lastXmppId == xmppId {
|
|
||||||
replaceId = xmppId
|
|
||||||
} else {
|
|
||||||
log.Infof("Mismatching message ids: %v %v, falling back to separate edit message", lastXmppId, xmppId)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
var text strings.Builder
|
|
||||||
|
|
||||||
if replaceId == "" {
|
|
||||||
var editChar string
|
|
||||||
if c.Session.AsciiArrows {
|
|
||||||
editChar = "e"
|
|
||||||
} else {
|
|
||||||
editChar = "✎"
|
|
||||||
}
|
|
||||||
text.WriteString(fmt.Sprintf("%s %v | ", editChar, update.MessageId))
|
|
||||||
} else if prefix != "" {
|
|
||||||
text.WriteString(prefix)
|
|
||||||
text.WriteString(c.getPrefixSeparator(update.ChatId))
|
|
||||||
}
|
|
||||||
|
|
||||||
text.WriteString(formatter.Format(
|
|
||||||
textContent.Text.Text,
|
|
||||||
textContent.Text.Entities,
|
|
||||||
markupFunction,
|
|
||||||
))
|
|
||||||
|
|
||||||
sChatId := strconv.FormatInt(update.ChatId, 10)
|
|
||||||
for _, jid := range jids {
|
|
||||||
gateway.SendMessage(jid, sChatId, text.String(), "e"+sId, c.xmpp, nil, replaceId, isCarbon, false)
|
|
||||||
}
|
|
||||||
}()
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// message(s) deleted
|
// message(s) deleted
|
||||||
func (c *Client) updateDeleteMessages(update *client.UpdateDeleteMessages) {
|
func (c *Client) updateDeleteMessages(update *client.UpdateDeleteMessages) {
|
||||||
if update.IsPermanent {
|
if update.IsPermanent {
|
||||||
for _, deleteId := range update.MessageIds {
|
|
||||||
c.tryUnlockMessageId(update.ChatId, deleteId)
|
|
||||||
}
|
|
||||||
|
|
||||||
if c.Session.IsChatIgnored(update.ChatId) {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
if c.Session.IgnoreGroupDeletions {
|
|
||||||
chatType, chatTypeErr := c.GetChatType(update.ChatId, false)
|
|
||||||
if chatTypeErr == nil && (chatType == ChatTypeBasicGroup || chatType == ChatTypeSupergroup) {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
var deleteChar string
|
var deleteChar string
|
||||||
if c.Session.AsciiArrows {
|
if c.Session.AsciiArrows {
|
||||||
deleteChar = "X "
|
deleteChar = "X "
|
||||||
|
|
@ -436,39 +294,19 @@ func (c *Client) updateAuthorizationState(update *client.UpdateAuthorizationStat
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// clean uploaded files
|
||||||
func (c *Client) updateMessageSendSucceeded(update *client.UpdateMessageSendSucceeded) {
|
func (c *Client) updateMessageSendSucceeded(update *client.UpdateMessageSendSucceeded) {
|
||||||
// replace message ID in local database
|
|
||||||
log.Debugf("replace message %v with %v", update.OldMessageId, update.Message.Id)
|
log.Debugf("replace message %v with %v", update.OldMessageId, update.Message.Id)
|
||||||
if err := gateway.IdsDB.ReplaceTgId(c.Session.Login, c.jid, update.Message.ChatId, update.OldMessageId, update.Message.Id); err != nil {
|
if err := gateway.IdsDB.ReplaceTgId(c.Session.Login, c.jid, update.Message.ChatId, update.OldMessageId, update.Message.Id); err != nil {
|
||||||
log.Errorf("failed to replace %v with %v: %v", update.OldMessageId, update.Message.Id, err.Error())
|
log.Errorf("failed to replace %v with %v: %v", update.OldMessageId, update.Message.Id, err.Error())
|
||||||
}
|
}
|
||||||
|
|
||||||
c.MessageIdChangesLock.Lock()
|
|
||||||
idsMap, ok := c.MessageIdChanges[update.Message.ChatId]
|
|
||||||
if !ok {
|
|
||||||
idsMap = make(map[int64]*newId)
|
|
||||||
c.MessageIdChanges[update.Message.ChatId] = idsMap
|
|
||||||
}
|
|
||||||
id, ok := idsMap[update.OldMessageId]
|
|
||||||
if !ok {
|
|
||||||
id = newNewId()
|
|
||||||
idsMap[update.OldMessageId] = id
|
|
||||||
}
|
|
||||||
id.Id = update.Message.Id
|
|
||||||
c.MessageIdChangesLock.Unlock()
|
|
||||||
|
|
||||||
c.sendMarker(update.Message.ChatId, update.Message.Id, gateway.MarkerTypeReceived)
|
|
||||||
|
|
||||||
// clean uploaded files
|
|
||||||
file, _ := c.contentToFile(update.Message.Content)
|
file, _ := c.contentToFile(update.Message.Content)
|
||||||
if file != nil && file.Local != nil {
|
if file != nil && file.Local != nil {
|
||||||
c.cleanTempFile(file.Local.Path)
|
c.cleanTempFile(file.Local.Path)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
func (c *Client) updateMessageSendFailed(update *client.UpdateMessageSendFailed) {
|
func (c *Client) updateMessageSendFailed(update *client.UpdateMessageSendFailed) {
|
||||||
c.tryUnlockMessageId(update.Message.ChatId, update.OldMessageId)
|
|
||||||
|
|
||||||
// clean uploaded files
|
|
||||||
file, _ := c.contentToFile(update.Message.Content)
|
file, _ := c.contentToFile(update.Message.Content)
|
||||||
if file != nil && file.Local != nil {
|
if file != nil && file.Local != nil {
|
||||||
c.cleanTempFile(file.Local.Path)
|
c.cleanTempFile(file.Local.Path)
|
||||||
|
|
@ -480,9 +318,9 @@ func (c *Client) updateChatTitle(update *client.UpdateChatTitle) {
|
||||||
gateway.SetNickname(c.jid, strconv.FormatInt(update.ChatId, 10), update.Title, c.xmpp)
|
gateway.SetNickname(c.jid, strconv.FormatInt(update.ChatId, 10), update.Title, c.xmpp)
|
||||||
|
|
||||||
// set also the status (for group chats only)
|
// set also the status (for group chats only)
|
||||||
chat, user, _ := c.GetContactByID(update.ChatId, nil, false)
|
chat, user, _ := c.GetContactByID(update.ChatId, nil)
|
||||||
if user == nil {
|
if user == nil {
|
||||||
c.ProcessStatusUpdate(update.ChatId, update.Title, "chat", false, gateway.SPImmed(true))
|
c.ProcessStatusUpdate(update.ChatId, update.Title, "chat", gateway.SPImmed(true))
|
||||||
}
|
}
|
||||||
|
|
||||||
// update chat title in the cache
|
// update chat title in the cache
|
||||||
|
|
@ -490,19 +328,3 @@ func (c *Client) updateChatTitle(update *client.UpdateChatTitle) {
|
||||||
chat.Title = update.Title
|
chat.Title = update.Title
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func (c *Client) updateChatReadOutbox(update *client.UpdateChatReadOutbox) {
|
|
||||||
c.sendMarker(update.ChatId, update.LastReadOutboxMessageId, gateway.MarkerTypeDisplayed)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (c *Client) tryUnlockMessageId(chatId, messageId int64) {
|
|
||||||
c.MessageIdChangesLock.Lock()
|
|
||||||
idsMap, ok := c.MessageIdChanges[chatId]
|
|
||||||
if ok {
|
|
||||||
id, ok := idsMap[messageId]
|
|
||||||
if ok {
|
|
||||||
id.Unlock()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
c.MessageIdChangesLock.Unlock()
|
|
||||||
}
|
|
||||||
|
|
|
||||||
|
|
@ -1,82 +0,0 @@
|
||||||
package telegram
|
|
||||||
|
|
||||||
import (
|
|
||||||
"dev.narayana.im/narayana/telegabber/xmpp/gateway"
|
|
||||||
|
|
||||||
log "github.com/sirupsen/logrus"
|
|
||||||
"github.com/zelenin/go-tdlib/client"
|
|
||||||
)
|
|
||||||
|
|
||||||
// StartLoginWizard initiates a loginWizard object
|
|
||||||
func (c *Client) StartLoginWizard(inCommand bool) {
|
|
||||||
if c.loginWizard == nil {
|
|
||||||
c.loginWizard = &loginWizardMetadata{
|
|
||||||
nextStage: make(chan string, 1),
|
|
||||||
commandSent: inCommand,
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
c.loginWizard.commandSent = inCommand
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// StopLoginWizard safely destroys the loginWizard object
|
|
||||||
func (c *Client) StopLoginWizard() {
|
|
||||||
c.locks.loginWizardReadLock.Lock()
|
|
||||||
c.locks.loginWizardWriteLock.Lock()
|
|
||||||
if c.loginWizard != nil {
|
|
||||||
close(c.loginWizard.nextStage)
|
|
||||||
c.loginWizard = nil
|
|
||||||
}
|
|
||||||
c.locks.loginWizardReadLock.Unlock()
|
|
||||||
c.locks.loginWizardWriteLock.Unlock()
|
|
||||||
}
|
|
||||||
|
|
||||||
// GetLoginWizardNextStage waits for the next stage from the channel
|
|
||||||
func (c *Client) GetLoginWizardNextStage() string {
|
|
||||||
c.locks.loginWizardReadLock.Lock()
|
|
||||||
defer c.locks.loginWizardReadLock.Unlock()
|
|
||||||
|
|
||||||
if c.loginWizard != nil {
|
|
||||||
if c.loginWizard.commandSent {
|
|
||||||
log.Debugf("waiting for nextStage...")
|
|
||||||
nextStage := <-c.loginWizard.nextStage
|
|
||||||
c.loginWizard.commandSent = false
|
|
||||||
c.loginWizard.chanBusy = false
|
|
||||||
log.Debugf("yielded stage %v", nextStage)
|
|
||||||
return nextStage
|
|
||||||
} else {
|
|
||||||
if c.lastAuthorizationStateType == client.TypeAuthorizationStateWaitPhoneNumber ||
|
|
||||||
c.lastAuthorizationStateType == client.TypeAuthorizationStateClosing ||
|
|
||||||
c.Session.Login == "" {
|
|
||||||
return "login"
|
|
||||||
}
|
|
||||||
switch c.lastAuthorizationStateType {
|
|
||||||
case client.TypeAuthorizationStateWaitCode:
|
|
||||||
return "code"
|
|
||||||
case client.TypeAuthorizationStateWaitPassword:
|
|
||||||
return "password"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return ""
|
|
||||||
}
|
|
||||||
|
|
||||||
func (c *Client) wizardStageOrPrompt(stage, message string) {
|
|
||||||
c.locks.loginWizardWriteLock.Lock()
|
|
||||||
if c.loginWizard == nil {
|
|
||||||
c.locks.loginWizardWriteLock.Unlock()
|
|
||||||
if message != "" {
|
|
||||||
gateway.SendServiceMessage(c.jid, message, c.xmpp)
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
if !c.loginWizard.chanBusy {
|
|
||||||
log.Debugf("writing wizard stage %v", stage)
|
|
||||||
c.loginWizard.nextStage <- stage
|
|
||||||
} else {
|
|
||||||
log.Warn("Skipping stage %v, wizard cannot keep up", stage)
|
|
||||||
}
|
|
||||||
c.loginWizard.chanBusy = true
|
|
||||||
c.locks.loginWizardWriteLock.Unlock()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
File diff suppressed because it is too large
Load diff
|
|
@ -431,17 +431,20 @@ func TestMessageToPrefix1(t *testing.T) {
|
||||||
Id: 42,
|
Id: 42,
|
||||||
IsOutgoing: true,
|
IsOutgoing: true,
|
||||||
ForwardInfo: &client.MessageForwardInfo{
|
ForwardInfo: &client.MessageForwardInfo{
|
||||||
Origin: &client.MessageOriginHiddenUser{
|
Origin: &client.MessageForwardOriginHiddenUser{
|
||||||
SenderName: "ziz",
|
SenderName: "ziz",
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
prefix, gatewayReply := (&Client{Session: &persistence.Session{}}).messageToPrefix(&message, "", "", false)
|
prefix, replyStart, replyEnd := (&Client{Session: &persistence.Session{}}).messageToPrefix(&message, "", "", nil)
|
||||||
if prefix != "➡ 42 | fwd: ziz" {
|
if prefix != "➡ 42 | fwd: ziz" {
|
||||||
t.Errorf("Wrong prefix: %v", prefix)
|
t.Errorf("Wrong prefix: %v", prefix)
|
||||||
}
|
}
|
||||||
if gatewayReply != nil {
|
if replyStart != 0 {
|
||||||
t.Errorf("Reply is not nil: %v", gatewayReply)
|
t.Errorf("Wrong replyStart: %v", replyStart)
|
||||||
|
}
|
||||||
|
if replyEnd != 0 {
|
||||||
|
t.Errorf("Wrong replyEnd: %v", replyEnd)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -449,17 +452,20 @@ func TestMessageToPrefix2(t *testing.T) {
|
||||||
message := client.Message{
|
message := client.Message{
|
||||||
Id: 56,
|
Id: 56,
|
||||||
ForwardInfo: &client.MessageForwardInfo{
|
ForwardInfo: &client.MessageForwardInfo{
|
||||||
Origin: &client.MessageOriginChannel{
|
Origin: &client.MessageForwardOriginChannel{
|
||||||
AuthorSignature: "zaz",
|
AuthorSignature: "zaz",
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
prefix, gatewayReply := (&Client{Session: &persistence.Session{}}).messageToPrefix(&message, "y.jpg", "", false)
|
prefix, replyStart, replyEnd := (&Client{Session: &persistence.Session{}}).messageToPrefix(&message, "y.jpg", "", nil)
|
||||||
if prefix != "⬅ 56 | fwd: (zaz) | preview: y.jpg" {
|
if prefix != "⬅ 56 | fwd: (zaz) | preview: y.jpg" {
|
||||||
t.Errorf("Wrong prefix: %v", prefix)
|
t.Errorf("Wrong prefix: %v", prefix)
|
||||||
}
|
}
|
||||||
if gatewayReply != nil {
|
if replyStart != 0 {
|
||||||
t.Errorf("Reply is not nil: %v", gatewayReply)
|
t.Errorf("Wrong replyStart: %v", replyStart)
|
||||||
|
}
|
||||||
|
if replyEnd != 0 {
|
||||||
|
t.Errorf("Wrong replyEnd: %v", replyEnd)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -467,17 +473,20 @@ func TestMessageToPrefix3(t *testing.T) {
|
||||||
message := client.Message{
|
message := client.Message{
|
||||||
Id: 56,
|
Id: 56,
|
||||||
ForwardInfo: &client.MessageForwardInfo{
|
ForwardInfo: &client.MessageForwardInfo{
|
||||||
Origin: &client.MessageOriginChannel{
|
Origin: &client.MessageForwardOriginChannel{
|
||||||
AuthorSignature: "zuz",
|
AuthorSignature: "zuz",
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
prefix, gatewayReply := (&Client{Session: &persistence.Session{AsciiArrows: true}}).messageToPrefix(&message, "", "a.jpg", false)
|
prefix, replyStart, replyEnd := (&Client{Session: &persistence.Session{AsciiArrows: true}}).messageToPrefix(&message, "", "a.jpg", nil)
|
||||||
if prefix != "< 56 | fwd: (zuz) | file: a.jpg" {
|
if prefix != "< 56 | fwd: (zuz) | file: a.jpg" {
|
||||||
t.Errorf("Wrong prefix: %v", prefix)
|
t.Errorf("Wrong prefix: %v", prefix)
|
||||||
}
|
}
|
||||||
if gatewayReply != nil {
|
if replyStart != 0 {
|
||||||
t.Errorf("Reply is not nil: %v", gatewayReply)
|
t.Errorf("Wrong replyStart: %v", replyStart)
|
||||||
|
}
|
||||||
|
if replyEnd != 0 {
|
||||||
|
t.Errorf("Wrong replyEnd: %v", replyEnd)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -486,12 +495,15 @@ func TestMessageToPrefix4(t *testing.T) {
|
||||||
Id: 23,
|
Id: 23,
|
||||||
IsOutgoing: true,
|
IsOutgoing: true,
|
||||||
}
|
}
|
||||||
prefix, gatewayReply := (&Client{Session: &persistence.Session{AsciiArrows: true}}).messageToPrefix(&message, "", "", false)
|
prefix, replyStart, replyEnd := (&Client{Session: &persistence.Session{AsciiArrows: true}}).messageToPrefix(&message, "", "", nil)
|
||||||
if prefix != "> 23" {
|
if prefix != "> 23" {
|
||||||
t.Errorf("Wrong prefix: %v", prefix)
|
t.Errorf("Wrong prefix: %v", prefix)
|
||||||
}
|
}
|
||||||
if gatewayReply != nil {
|
if replyStart != 0 {
|
||||||
t.Errorf("Reply is not nil: %v", gatewayReply)
|
t.Errorf("Wrong replyStart: %v", replyStart)
|
||||||
|
}
|
||||||
|
if replyEnd != 0 {
|
||||||
|
t.Errorf("Wrong replyEnd: %v", replyEnd)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -499,101 +511,52 @@ func TestMessageToPrefix5(t *testing.T) {
|
||||||
message := client.Message{
|
message := client.Message{
|
||||||
Id: 560,
|
Id: 560,
|
||||||
ForwardInfo: &client.MessageForwardInfo{
|
ForwardInfo: &client.MessageForwardInfo{
|
||||||
Origin: &client.MessageOriginChat{
|
Origin: &client.MessageForwardOriginChat{
|
||||||
AuthorSignature: "zyz",
|
AuthorSignature: "zyz",
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
prefix, gatewayReply := (&Client{Session: &persistence.Session{AsciiArrows: true}}).messageToPrefix(&message, "h.jpg", "a.jpg", false)
|
prefix, replyStart, replyEnd := (&Client{Session: &persistence.Session{AsciiArrows: true}}).messageToPrefix(&message, "h.jpg", "a.jpg", nil)
|
||||||
if prefix != "< 560 | fwd: (zyz) | preview: h.jpg | file: a.jpg" {
|
if prefix != "< 560 | fwd: (zyz) | preview: h.jpg | file: a.jpg" {
|
||||||
t.Errorf("Wrong prefix: %v", prefix)
|
t.Errorf("Wrong prefix: %v", prefix)
|
||||||
}
|
}
|
||||||
if gatewayReply != nil {
|
if replyStart != 0 {
|
||||||
t.Errorf("Reply is not nil: %v", gatewayReply)
|
t.Errorf("Wrong replyStart: %v", replyStart)
|
||||||
|
}
|
||||||
|
if replyEnd != 0 {
|
||||||
|
t.Errorf("Wrong replyEnd: %v", replyEnd)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestMessageToPrefix6(t *testing.T) {
|
func TestMessageToPrefix6(t *testing.T) {
|
||||||
message := client.Message{
|
message := client.Message{
|
||||||
Id: 23,
|
Id: 23,
|
||||||
ChatId: 25,
|
IsOutgoing: true,
|
||||||
IsOutgoing: true,
|
ReplyToMessageId: 42,
|
||||||
ReplyTo: &client.MessageReplyToMessage{
|
}
|
||||||
ChatId: 41,
|
reply := client.Message{
|
||||||
Quote: &client.TextQuote{
|
Id: 42,
|
||||||
Text: &client.FormattedText{
|
Content: &client.MessageText{
|
||||||
Text: "tist\nuz\niz",
|
Text: &client.FormattedText{
|
||||||
},
|
Text: "tist",
|
||||||
},
|
|
||||||
Origin: &client.MessageOriginHiddenUser{
|
|
||||||
SenderName: "ziz",
|
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
prefix, gatewayReply := (&Client{Session: &persistence.Session{AsciiArrows: true}}).messageToPrefix(&message, "", "", false)
|
prefix, replyStart, replyEnd := (&Client{Session: &persistence.Session{AsciiArrows: true}}).messageToPrefix(&message, "", "", &reply)
|
||||||
if prefix != "> 23 | reply: ziz @ unknown contact: TDlib instance is offline | tist uz iz" {
|
if prefix != "> 23 | reply: 42 | | tist" {
|
||||||
t.Errorf("Wrong prefix: %v", prefix)
|
t.Errorf("Wrong prefix: %v", prefix)
|
||||||
}
|
}
|
||||||
if gatewayReply != nil {
|
if replyStart != 4 {
|
||||||
t.Errorf("Reply is not nil: %v", gatewayReply)
|
t.Errorf("Wrong replyStart: %v", replyStart)
|
||||||
}
|
}
|
||||||
}
|
if replyEnd != 26 {
|
||||||
|
t.Errorf("Wrong replyEnd: %v", replyEnd)
|
||||||
func TestMessageToPrefix7(t *testing.T) {
|
|
||||||
message := client.Message{
|
|
||||||
Id: 23,
|
|
||||||
ChatId: 42,
|
|
||||||
IsOutgoing: true,
|
|
||||||
ReplyTo: &client.MessageReplyToMessage{
|
|
||||||
ChatId: 41,
|
|
||||||
Content: &client.MessageText{
|
|
||||||
Text: &client.FormattedText{
|
|
||||||
Text: "tist",
|
|
||||||
},
|
|
||||||
},
|
|
||||||
Origin: &client.MessageOriginChannel{
|
|
||||||
AuthorSignature: "zaz",
|
|
||||||
},
|
|
||||||
},
|
|
||||||
}
|
|
||||||
prefix, gatewayReply := (&Client{Session: &persistence.Session{AsciiArrows: true}}).messageToPrefix(&message, "", "", false)
|
|
||||||
if prefix != "> 23 | reply: (zaz) @ unknown contact: TDlib instance is offline | tist" {
|
|
||||||
t.Errorf("Wrong prefix: %v", prefix)
|
|
||||||
}
|
|
||||||
if gatewayReply != nil {
|
|
||||||
t.Errorf("Reply is not nil: %v", gatewayReply)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestMessageToPrefix8(t *testing.T) {
|
|
||||||
message := client.Message{
|
|
||||||
Id: 23,
|
|
||||||
ChatId: 42,
|
|
||||||
IsOutgoing: true,
|
|
||||||
ReplyTo: &client.MessageReplyToMessage{
|
|
||||||
ChatId: 41,
|
|
||||||
Content: &client.MessageText{
|
|
||||||
Text: &client.FormattedText{
|
|
||||||
Text: "tist",
|
|
||||||
},
|
|
||||||
},
|
|
||||||
Origin: &client.MessageOriginChannel{
|
|
||||||
AuthorSignature: "zuz",
|
|
||||||
},
|
|
||||||
},
|
|
||||||
}
|
|
||||||
prefix, gatewayReply := (&Client{Session: &persistence.Session{AsciiArrows: true}}).messageToPrefix(&message, "", "", true)
|
|
||||||
if prefix != "> 23" {
|
|
||||||
t.Errorf("Wrong prefix: %v", prefix)
|
|
||||||
}
|
|
||||||
if gatewayReply != nil {
|
|
||||||
t.Errorf("Reply is not nil: %v", gatewayReply)
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func GetSenderIdEmpty(t *testing.T) {
|
func GetSenderIdEmpty(t *testing.T) {
|
||||||
message := client.Message{}
|
message := client.Message{}
|
||||||
senderId := (&Client{}).getMessageSenderId(&message)
|
senderId := (&Client{}).getSenderId(&message)
|
||||||
if senderId != 0 {
|
if senderId != 0 {
|
||||||
t.Errorf("Wrong sender id: %v", senderId)
|
t.Errorf("Wrong sender id: %v", senderId)
|
||||||
}
|
}
|
||||||
|
|
@ -605,7 +568,7 @@ func GetSenderIdUser(t *testing.T) {
|
||||||
UserId: 42,
|
UserId: 42,
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
senderId := (&Client{}).getMessageSenderId(&message)
|
senderId := (&Client{}).getSenderId(&message)
|
||||||
if senderId != 42 {
|
if senderId != 42 {
|
||||||
t.Errorf("Wrong sender id: %v", senderId)
|
t.Errorf("Wrong sender id: %v", senderId)
|
||||||
}
|
}
|
||||||
|
|
@ -617,7 +580,7 @@ func GetSenderIdChat(t *testing.T) {
|
||||||
ChatId: -42,
|
ChatId: -42,
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
senderId := (&Client{}).getMessageSenderId(&message)
|
senderId := (&Client{}).getSenderId(&message)
|
||||||
if senderId != -42 {
|
if senderId != -42 {
|
||||||
t.Errorf("Wrong sender id: %v", senderId)
|
t.Errorf("Wrong sender id: %v", senderId)
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -39,11 +39,10 @@ var sizeRegex = regexp.MustCompile("\\A([0-9]+) ?([KMGTPE]?B?)\\z")
|
||||||
|
|
||||||
// NewComponent starts a new component and wraps it in
|
// NewComponent starts a new component and wraps it in
|
||||||
// a stream manager that you should start yourself
|
// a stream manager that you should start yourself
|
||||||
func NewComponent(conf config.XMPPConfig, tc config.TelegramConfig, idsPath string, version string) (*xmpp.StreamManager, *xmpp.Component, error) {
|
func NewComponent(conf config.XMPPConfig, tc config.TelegramConfig, idsPath string) (*xmpp.StreamManager, *xmpp.Component, error) {
|
||||||
var err error
|
var err error
|
||||||
|
|
||||||
gateway.Jid, err = stanza.NewJid(conf.Jid)
|
gateway.Jid, err = stanza.NewJid(conf.Jid)
|
||||||
gateway.Version = version
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, nil, err
|
return nil, nil, err
|
||||||
}
|
}
|
||||||
|
|
@ -142,24 +141,11 @@ func heartbeat(component *xmpp.Component) {
|
||||||
chatID,
|
chatID,
|
||||||
session.LastSeenStatus(delayedStatus.TimestampOnline),
|
session.LastSeenStatus(delayedStatus.TimestampOnline),
|
||||||
"away",
|
"away",
|
||||||
true,
|
|
||||||
)
|
)
|
||||||
delete(session.DelayedStatuses, chatID)
|
delete(session.DelayedStatuses, chatID)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
session.DelayedStatusesLock.Unlock()
|
session.DelayedStatusesLock.Unlock()
|
||||||
|
|
||||||
// shrink message id maps
|
|
||||||
session.MessageIdChangesLock.Lock()
|
|
||||||
for _, idsMap := range session.MessageIdChanges {
|
|
||||||
for oldMessageId, newId := range idsMap {
|
|
||||||
if newId.Ts < now - 60 {
|
|
||||||
newId.Unlock()
|
|
||||||
delete(idsMap, oldMessageId)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
session.MessageIdChangesLock.Unlock()
|
|
||||||
}
|
}
|
||||||
sessionLock.Unlock()
|
sessionLock.Unlock()
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -213,20 +213,6 @@ type QueryRegisterRemove struct {
|
||||||
XMLName xml.Name `xml:"remove"`
|
XMLName xml.Name `xml:"remove"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// EntityTime is from XEP-0202
|
|
||||||
type EntityTime struct {
|
|
||||||
XMLName xml.Name `xml:"urn:xmpp:time time"`
|
|
||||||
Tzo string `xml:"tzo"`
|
|
||||||
Utc string `xml:"utc"`
|
|
||||||
ResultSet *stanza.ResultSet `xml:"set,omitempty"`
|
|
||||||
}
|
|
||||||
|
|
||||||
// AttachTo is from XEP-0367
|
|
||||||
type AttachTo struct {
|
|
||||||
XMLName xml.Name `xml:"urn:xmpp:message-attaching:1 attach-to"`
|
|
||||||
Id string `xml:"id,attr"`
|
|
||||||
}
|
|
||||||
|
|
||||||
// Namespace is a namespace!
|
// Namespace is a namespace!
|
||||||
func (c PresenceNickExtension) Namespace() string {
|
func (c PresenceNickExtension) Namespace() string {
|
||||||
return c.XMLName.Space
|
return c.XMLName.Space
|
||||||
|
|
@ -292,26 +278,11 @@ func (c QueryRegister) GetSet() *stanza.ResultSet {
|
||||||
return c.ResultSet
|
return c.ResultSet
|
||||||
}
|
}
|
||||||
|
|
||||||
// Namespace is a namespace!
|
|
||||||
func (c EntityTime) Namespace() string {
|
|
||||||
return c.XMLName.Space
|
|
||||||
}
|
|
||||||
|
|
||||||
// GetSet getsets!
|
|
||||||
func (c EntityTime) GetSet() *stanza.ResultSet {
|
|
||||||
return c.ResultSet
|
|
||||||
}
|
|
||||||
|
|
||||||
// Name is a packet name
|
// Name is a packet name
|
||||||
func (ClientMessage) Name() string {
|
func (ClientMessage) Name() string {
|
||||||
return "message"
|
return "message"
|
||||||
}
|
}
|
||||||
|
|
||||||
// Namespace is a namespace!
|
|
||||||
func (c AttachTo) Namespace() string {
|
|
||||||
return c.XMLName.Space
|
|
||||||
}
|
|
||||||
|
|
||||||
// NewReplyFallback initializes a fallback range
|
// NewReplyFallback initializes a fallback range
|
||||||
func NewReplyFallback(start uint64, end uint64) Fallback {
|
func NewReplyFallback(start uint64, end uint64) Fallback {
|
||||||
return Fallback{
|
return Fallback{
|
||||||
|
|
@ -391,16 +362,4 @@ func init() {
|
||||||
"jabber:iq:register",
|
"jabber:iq:register",
|
||||||
"query",
|
"query",
|
||||||
}, QueryRegister{})
|
}, QueryRegister{})
|
||||||
|
|
||||||
// entity time
|
|
||||||
stanza.TypeRegistry.MapExtension(stanza.PKTIQ, xml.Name{
|
|
||||||
"urn:xmpp:time",
|
|
||||||
"time",
|
|
||||||
}, EntityTime{})
|
|
||||||
|
|
||||||
// attach-to
|
|
||||||
stanza.TypeRegistry.MapExtension(stanza.PKTMessage, xml.Name{
|
|
||||||
"urn:xmpp:message-attaching:1",
|
|
||||||
"attach-to",
|
|
||||||
}, AttachTo{})
|
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -3,14 +3,12 @@ package gateway
|
||||||
import (
|
import (
|
||||||
"encoding/xml"
|
"encoding/xml"
|
||||||
"github.com/pkg/errors"
|
"github.com/pkg/errors"
|
||||||
"strconv"
|
|
||||||
"strings"
|
"strings"
|
||||||
"sync"
|
"sync"
|
||||||
|
|
||||||
"dev.narayana.im/narayana/telegabber/badger"
|
"dev.narayana.im/narayana/telegabber/badger"
|
||||||
"dev.narayana.im/narayana/telegabber/xmpp/extensions"
|
"dev.narayana.im/narayana/telegabber/xmpp/extensions"
|
||||||
|
|
||||||
"github.com/google/uuid"
|
|
||||||
log "github.com/sirupsen/logrus"
|
log "github.com/sirupsen/logrus"
|
||||||
"github.com/soheilhy/args"
|
"github.com/soheilhy/args"
|
||||||
"gosrc.io/xmpp"
|
"gosrc.io/xmpp"
|
||||||
|
|
@ -24,24 +22,7 @@ type Reply struct {
|
||||||
End uint64
|
End uint64
|
||||||
}
|
}
|
||||||
|
|
||||||
type MarkerType byte
|
|
||||||
|
|
||||||
const (
|
|
||||||
MarkerTypeReceived MarkerType = iota
|
|
||||||
MarkerTypeDisplayed
|
|
||||||
)
|
|
||||||
|
|
||||||
type marker struct {
|
|
||||||
Type MarkerType
|
|
||||||
Id string
|
|
||||||
}
|
|
||||||
|
|
||||||
const NSNick string = "http://jabber.org/protocol/nick"
|
const NSNick string = "http://jabber.org/protocol/nick"
|
||||||
const NodeVCard4 string = "urn:xmpp:vcard4"
|
|
||||||
const NodeAvatarMetadata string = "urn:xmpp:avatar:metadata"
|
|
||||||
const NodeAvatarMetadataNotify string = NodeAvatarMetadata + "+notify"
|
|
||||||
const NodeAvatarData string = "urn:xmpp:avatar:data"
|
|
||||||
const NSCommand string = "http://jabber.org/protocol/commands"
|
|
||||||
|
|
||||||
// Queue stores presences to send later
|
// Queue stores presences to send later
|
||||||
var Queue = make(map[string]*stanza.Presence)
|
var Queue = make(map[string]*stanza.Presence)
|
||||||
|
|
@ -50,9 +31,6 @@ var QueueLock = sync.Mutex{}
|
||||||
// Jid stores the component's JID object
|
// Jid stores the component's JID object
|
||||||
var Jid *stanza.Jid
|
var Jid *stanza.Jid
|
||||||
|
|
||||||
// Version stores this software's version
|
|
||||||
var Version string
|
|
||||||
|
|
||||||
// IdsDB provides a disk-backed bidirectional dictionary of Telegram and XMPP ids
|
// IdsDB provides a disk-backed bidirectional dictionary of Telegram and XMPP ids
|
||||||
var IdsDB badger.IdsDB
|
var IdsDB badger.IdsDB
|
||||||
|
|
||||||
|
|
@ -64,42 +42,26 @@ var DirtySessions = false
|
||||||
var MessageOutgoingPermissionVersion = 0
|
var MessageOutgoingPermissionVersion = 0
|
||||||
|
|
||||||
// SendMessage creates and sends a message stanza
|
// SendMessage creates and sends a message stanza
|
||||||
func SendMessage(to string, from string, body string, id string, component *xmpp.Component, reply *Reply, replaceId string, isCarbon, requestReceipt bool) {
|
func SendMessage(to string, from string, body string, id string, component *xmpp.Component, reply *Reply, isCarbon bool) {
|
||||||
sendMessageWrapper(to, from, body, id, component, reply, nil, "", replaceId, isCarbon, requestReceipt)
|
sendMessageWrapper(to, from, body, id, component, reply, "", isCarbon)
|
||||||
}
|
}
|
||||||
|
|
||||||
// SendServiceMessage creates and sends a simple message stanza from transport
|
// SendServiceMessage creates and sends a simple message stanza from transport
|
||||||
func SendServiceMessage(to string, body string, component *xmpp.Component) {
|
func SendServiceMessage(to string, body string, component *xmpp.Component) {
|
||||||
var id string
|
sendMessageWrapper(to, "", body, "", component, nil, "", false)
|
||||||
if uuid, err := uuid.NewRandom(); err == nil {
|
|
||||||
id = uuid.String()
|
|
||||||
}
|
|
||||||
sendMessageWrapper(to, "", body, id, component, nil, nil, "", "", false, false)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// SendTextMessage creates and sends a simple message stanza
|
// SendTextMessage creates and sends a simple message stanza
|
||||||
func SendTextMessage(to string, from string, body string, component *xmpp.Component) {
|
func SendTextMessage(to string, from string, body string, component *xmpp.Component) {
|
||||||
var id string
|
sendMessageWrapper(to, from, body, "", component, nil, "", false)
|
||||||
if uuid, err := uuid.NewRandom(); err == nil {
|
|
||||||
id = uuid.String()
|
|
||||||
}
|
|
||||||
sendMessageWrapper(to, from, body, id, component, nil, nil, "", "", false, false)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// SendMessageWithOOB creates and sends a message stanza with OOB URL
|
// SendMessageWithOOB creates and sends a message stanza with OOB URL
|
||||||
func SendMessageWithOOB(to string, from string, body string, id string, component *xmpp.Component, reply *Reply, oob, replaceId string, isCarbon, requestReceipt bool) {
|
func SendMessageWithOOB(to string, from string, body string, id string, component *xmpp.Component, reply *Reply, oob string, isCarbon bool) {
|
||||||
sendMessageWrapper(to, from, body, id, component, reply, nil, oob, replaceId, isCarbon, requestReceipt)
|
sendMessageWrapper(to, from, body, id, component, reply, oob, isCarbon)
|
||||||
}
|
}
|
||||||
|
|
||||||
// SendMessageMarker creates and sends a message stanza with a XEP-0333 marker
|
func sendMessageWrapper(to string, from string, body string, id string, component *xmpp.Component, reply *Reply, oob string, isCarbon bool) {
|
||||||
func SendMessageMarker(to string, from string, component *xmpp.Component, markerType MarkerType, markerId string) {
|
|
||||||
sendMessageWrapper(to, from, "", "", component, nil, &marker{
|
|
||||||
Type: markerType,
|
|
||||||
Id: markerId,
|
|
||||||
}, "", "", false, false)
|
|
||||||
}
|
|
||||||
|
|
||||||
func sendMessageWrapper(to string, from string, body string, id string, component *xmpp.Component, reply *Reply, marker *marker, oob, replaceId string, isCarbon, requestReceipt bool) {
|
|
||||||
toJid, err := stanza.NewJid(to)
|
toJid, err := stanza.NewJid(to)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.WithFields(log.Fields{
|
log.WithFields(log.Fields{
|
||||||
|
|
@ -157,23 +119,9 @@ func sendMessageWrapper(to string, from string, body string, id string, componen
|
||||||
message.Extensions = append(message.Extensions, extensions.NewReplyFallback(reply.Start, reply.End))
|
message.Extensions = append(message.Extensions, extensions.NewReplyFallback(reply.Start, reply.End))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if marker != nil {
|
|
||||||
if marker.Type == MarkerTypeReceived {
|
|
||||||
message.Extensions = append(message.Extensions, stanza.MarkReceived{ID: marker.Id})
|
|
||||||
} else if marker.Type == MarkerTypeDisplayed {
|
|
||||||
message.Extensions = append(message.Extensions, stanza.MarkDisplayed{ID: marker.Id})
|
|
||||||
message.Extensions = append(message.Extensions, stanza.ReceiptReceived{ID: marker.Id})
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if !isCarbon && toJid.Resource != "" {
|
if !isCarbon && toJid.Resource != "" {
|
||||||
message.Extensions = append(message.Extensions, stanza.HintNoCopy{})
|
message.Extensions = append(message.Extensions, stanza.HintNoCopy{})
|
||||||
}
|
}
|
||||||
if requestReceipt {
|
|
||||||
message.Extensions = append(message.Extensions, stanza.Markable{})
|
|
||||||
}
|
|
||||||
if replaceId != "" {
|
|
||||||
message.Extensions = append(message.Extensions, extensions.Replace{Id: replaceId})
|
|
||||||
}
|
|
||||||
|
|
||||||
if isCarbon {
|
if isCarbon {
|
||||||
carbonMessage := extensions.ClientMessage{
|
carbonMessage := extensions.ClientMessage{
|
||||||
|
|
@ -395,20 +343,6 @@ func SendPresence(component *xmpp.Component, to string, args ...args.V) error {
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// SPAppendFrom appends numeric from and resource to varargs
|
|
||||||
func SPAppendFrom(oldArgs []args.V, id int64) []args.V {
|
|
||||||
newArgs := append(oldArgs, SPFrom(strconv.FormatInt(id, 10)))
|
|
||||||
newArgs = append(newArgs, SPResource(Jid.Resource))
|
|
||||||
return newArgs
|
|
||||||
}
|
|
||||||
|
|
||||||
// SimplePresence crafts simple presence varargs
|
|
||||||
func SimplePresence(from int64, typ string) []args.V {
|
|
||||||
args := []args.V{SPType(typ)}
|
|
||||||
args = SPAppendFrom(args, from)
|
|
||||||
return args
|
|
||||||
}
|
|
||||||
|
|
||||||
// ResumableSend tries to resume the connection once and sends the packet again
|
// ResumableSend tries to resume the connection once and sends the packet again
|
||||||
func ResumableSend(component *xmpp.Component, packet stanza.Packet) error {
|
func ResumableSend(component *xmpp.Component, packet stanza.Packet) error {
|
||||||
err := component.Send(packet)
|
err := component.Send(packet)
|
||||||
|
|
@ -443,46 +377,3 @@ func SplitJID(from string) (string, string, bool) {
|
||||||
}
|
}
|
||||||
return fromJid.Bare(), fromJid.Resource, true
|
return fromJid.Bare(), fromJid.Resource, true
|
||||||
}
|
}
|
||||||
|
|
||||||
// SendPubSubAvatarNotification encourages clients to fetch an avatar
|
|
||||||
func SendPubSubAvatarNotification(component *xmpp.Component, jid string, chatId int64, sha1 string, size int64) {
|
|
||||||
info := stanza.Node{
|
|
||||||
XMLName: xml.Name{Local: "info"},
|
|
||||||
Attrs: []xml.Attr{
|
|
||||||
xml.Attr{Name: xml.Name{Local: "bytes"}, Value: strconv.FormatInt(size, 10)},
|
|
||||||
xml.Attr{Name: xml.Name{Local: "height"}, Value: "160"},
|
|
||||||
xml.Attr{Name: xml.Name{Local: "id"}, Value: sha1},
|
|
||||||
xml.Attr{Name: xml.Name{Local: "type"}, Value: "image/jpeg"},
|
|
||||||
xml.Attr{Name: xml.Name{Local: "width"}, Value: "160"},
|
|
||||||
},
|
|
||||||
}
|
|
||||||
log.WithFields(log.Fields{
|
|
||||||
"chatId": chatId,
|
|
||||||
}).Debugf("%#v", info)
|
|
||||||
|
|
||||||
event := &stanza.PubSubEvent{
|
|
||||||
EventElement: &stanza.ItemsEvent{
|
|
||||||
Node: NodeAvatarMetadata,
|
|
||||||
Items: []stanza.ItemEvent{
|
|
||||||
stanza.ItemEvent{
|
|
||||||
Id: sha1,
|
|
||||||
Any: &stanza.Node{
|
|
||||||
XMLName: xml.Name{Local: "metadata", Space: NodeAvatarMetadata},
|
|
||||||
Nodes: []stanza.Node{info},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
}
|
|
||||||
|
|
||||||
message := stanza.Message{
|
|
||||||
Attrs: stanza.Attrs{
|
|
||||||
From: strconv.FormatInt(chatId, 10) + "@" + Jid.Bare(),
|
|
||||||
To: jid,
|
|
||||||
Type: stanza.MessageTypeHeadline,
|
|
||||||
},
|
|
||||||
Extensions: []stanza.MsgExtension{event},
|
|
||||||
}
|
|
||||||
|
|
||||||
_ = ResumableSend(component, message)
|
|
||||||
}
|
|
||||||
|
|
|
||||||
930
xmpp/handlers.go
930
xmpp/handlers.go
File diff suppressed because it is too large
Load diff
|
|
@ -1,101 +0,0 @@
|
||||||
package xmpp
|
|
||||||
|
|
||||||
import (
|
|
||||||
"fmt"
|
|
||||||
|
|
||||||
"dev.narayana.im/narayana/telegabber/telegram"
|
|
||||||
"dev.narayana.im/narayana/telegabber/xmpp/gateway"
|
|
||||||
|
|
||||||
log "github.com/sirupsen/logrus"
|
|
||||||
"gosrc.io/xmpp"
|
|
||||||
"gosrc.io/xmpp/stanza"
|
|
||||||
)
|
|
||||||
|
|
||||||
func loginWizardPayload(bare string, requestForm *stanza.Form, resource string) (payload *stanza.Command, cancelSend bool, returnSession *telegram.Client) {
|
|
||||||
payload = &stanza.Command{
|
|
||||||
SessionId: "loginwizard",
|
|
||||||
Node: "loginwizard",
|
|
||||||
}
|
|
||||||
|
|
||||||
session, ok := sessions[bare]
|
|
||||||
if ok {
|
|
||||||
returnSession = session
|
|
||||||
|
|
||||||
if requestForm == nil {
|
|
||||||
session.StartLoginWizard(false)
|
|
||||||
cancelSend = true
|
|
||||||
} else {
|
|
||||||
if len(requestForm.Fields) != 1 {
|
|
||||||
setCommandPayloadError(payload, "Hey, don't tinker with the form!")
|
|
||||||
return
|
|
||||||
}
|
|
||||||
field := requestForm.Fields[0]
|
|
||||||
if field != nil {
|
|
||||||
if len(field.ValuesList) < 1 {
|
|
||||||
setCommandPayloadError(payload, "No value")
|
|
||||||
return
|
|
||||||
}
|
|
||||||
switch field.Var {
|
|
||||||
case "login", "code", "password":
|
|
||||||
default:
|
|
||||||
setCommandPayloadError(payload, "Unknown field")
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
session.StartLoginWizard(true)
|
|
||||||
response, success := session.ProcessTransportCommand(fmt.Sprintf("/%v %v", field.Var, field.ValuesList[0]), resource)
|
|
||||||
if !success {
|
|
||||||
setCommandPayloadError(payload, response)
|
|
||||||
session.StopLoginWizard()
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
cancelSend = true
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
setCommandPayloadError(payload, fmt.Sprintf("Session is not initialized, add the transport (%v) to contacts first", gateway.Jid.Bare()))
|
|
||||||
}
|
|
||||||
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
func sendLoginWizardResponse(component *xmpp.Component, answer *stanza.IQ, session *telegram.Client) {
|
|
||||||
payload := &stanza.Command{
|
|
||||||
SessionId: "loginwizard",
|
|
||||||
Node: "loginwizard",
|
|
||||||
}
|
|
||||||
|
|
||||||
nextStage := "login"
|
|
||||||
if session != nil {
|
|
||||||
nextStage = session.GetLoginWizardNextStage()
|
|
||||||
}
|
|
||||||
log.Debugf("nextStage: %v", nextStage)
|
|
||||||
|
|
||||||
if nextStage == "cancel" {
|
|
||||||
setCommandPayloadError(payload, "Cancelled")
|
|
||||||
session.StopLoginWizard()
|
|
||||||
} else if nextStage == "success" {
|
|
||||||
payload.Status = stanza.CommandStatusCompleted
|
|
||||||
session.StopLoginWizard()
|
|
||||||
} else {
|
|
||||||
required := ""
|
|
||||||
form := stanza.Form{
|
|
||||||
Type: stanza.FormTypeForm,
|
|
||||||
Title: "Login Wizard",
|
|
||||||
Fields: []*stanza.Field{
|
|
||||||
&stanza.Field{
|
|
||||||
Var: nextStage,
|
|
||||||
Label: nextStage,
|
|
||||||
Required: &required,
|
|
||||||
},
|
|
||||||
},
|
|
||||||
}
|
|
||||||
payload.Status = stanza.CommandStatusExecuting
|
|
||||||
payload.CommandElements = append(payload.CommandElements, &form)
|
|
||||||
}
|
|
||||||
|
|
||||||
answer.Payload = payload
|
|
||||||
|
|
||||||
gateway.ResumableSend(component, answer)
|
|
||||||
}
|
|
||||||
Loading…
Reference in a new issue