repair ack, refactor e2e tests

This commit is contained in:
kulikov0 committed 2026-09-12 20:36:19 +02:00
1 parent 9e5357eaa8
commit 88a0b5f1b9
42 files changed
+1732 -792

No files matched your search

+149 -7
View File
@@ -39,13 +39,16 @@ type Client struct {
HTTP *http.Client
LogFn func(string, ...any)
portal string
sessid string
userAgent string
instanceID string
email string
password string
credsPath string
portal string
sessid string
userAgent string
instanceID string
email string
password string
credsPath string
chatID string
conferenceID string
selfUserID string
}
type JoinResult struct {
@@ -69,6 +72,13 @@ type callInfo struct {
GuestLink string
}
type PullConfigResult struct {
WebSocket string
ChannelID string
Hostname string
Revision int
}
type slbRequest struct {
UserToken string `json:"userToken"`
IsOneToOne bool `json:"isOneToOne"`
@@ -115,6 +125,8 @@ func (c *Client) JoinAsGuest(alias, displayName string) (JoinResult, error) {
if err != nil {
return res, err
}
c.chatID = conf.ChatID
c.conferenceID = conf.ConferenceID
userToken, err := c.registerGuest(conf, displayName)
if err != nil {
return res, err
@@ -134,6 +146,7 @@ func (c *Client) JoinAsHost(alias string) (JoinResult, error) {
return res, err
}
c.LogFn("[host] conference chatId=%s conferenceId=%s", conf.ChatID, conf.ConferenceID)
c.chatID = conf.ChatID
callToken, userToken, err := c.getCallToken(conf.ChatID)
if err != nil {
return res, err
@@ -154,6 +167,7 @@ func (c *Client) CreateAndJoin() (JoinResult, string, error) {
if err != nil {
return res, "", err
}
c.chatID = info.ChatID
guestLink := info.GuestLink
if guestLink == "" {
guestLink, err = c.getGuestLink(info.ChatID)
@@ -216,6 +230,15 @@ func (c *Client) restForm(action string, form url.Values) ([]byte, int, error) {
return c.do("POST", endpoint, "application/x-www-form-urlencoded", strings.NewReader(form.Encode()))
}
func (c *Client) restFormAuthed(action string, form url.Values) ([]byte, int, error) {
endpoint := c.portal + "/rest/" + action + ".json"
if c.sessid != "" {
form.Set("sessid", c.sessid)
endpoint += "?sessid=" + url.QueryEscape(c.sessid)
}
return c.do("POST", endpoint, "application/x-www-form-urlencoded", strings.NewReader(form.Encode()))
}
func (c *Client) ajaxAction(action string, form url.Values) ([]byte, int, error) {
endpoint := c.portal + "/bitrix/services/main/ajax.php?action=" + action
if c.sessid != "" {
@@ -426,6 +449,125 @@ func (c *Client) createRoom() (callInfo, error) {
return info, nil
}
func (c *Client) KickUser(userID string) error {
if c.chatID == "" {
return fmt.Errorf("kick: no active chatId")
}
if userID == "" {
return fmt.Errorf("kick: empty userId")
}
form := url.Values{}
form.Set("chatId", c.chatID)
form.Set("userId", userID)
body, status, err := c.withRelogin(func() ([]byte, int, error) {
return c.ajaxAction("im.v2.Chat.deleteUser", form)
})
if err != nil {
return err
}
var out struct {
Status string `json:"status"`
Errors []struct {
Code json.Number `json:"code"`
Message string `json:"message"`
} `json:"errors"`
}
if err := json.Unmarshal(body, &out); err != nil {
return fmt.Errorf("kick: %w (status %d, body %s)", err, status, common.BodySnippet(body))
}
if len(out.Errors) > 0 {
return fmt.Errorf("kick: chatId=%s userId=%s rejected (status %d, %s %s)", c.chatID, userID, status, out.Errors[0].Code.String(), out.Errors[0].Message)
}
c.LogFn("[kick] removed userId=%s from chatId=%s", userID, c.chatID)
return nil
}
func (c *Client) SelfUserID() (string, error) {
if c.selfUserID != "" {
return c.selfUserID, nil
}
id, err := c.currentUserID()
if err != nil {
return "", err
}
c.selfUserID = id
return id, nil
}
func (c *Client) callHash() string {
if c.HTTP == nil || c.HTTP.Jar == nil {
return ""
}
u, err := url.Parse(c.portal)
if err != nil {
return ""
}
for _, ck := range c.HTTP.Jar.Cookies(u) {
if ck.Name == "BITRIX_CALL_HASH" {
return ck.Value
}
}
return ""
}
func (c *Client) PullConfig() (PullConfigResult, error) {
var pc PullConfigResult
form := url.Values{}
form.Set("CACHE", "N")
var body []byte
var status int
var err error
if hash := c.callHash(); hash != "" {
form.Set("call_auth_id", hash)
form.Set("videoconf_id", c.conferenceID)
form.Set("call_chat_id", c.chatID)
body, status, err = c.restForm("pull.config.get", form)
} else {
body, status, err = c.withRelogin(func() ([]byte, int, error) {
return c.restFormAuthed("pull.config.get", form)
})
}
if err != nil {
return pc, err
}
var out struct {
Result struct {
Server struct {
WebSocket string `json:"websocket"`
} `json:"server"`
API struct {
RevisionWeb int `json:"revision_web"`
} `json:"api"`
Channels struct {
Shared struct {
ID string `json:"id"`
} `json:"shared"`
Private struct {
ID string `json:"id"`
} `json:"private"`
} `json:"channels"`
} `json:"result"`
Error string `json:"error"`
}
if err := json.Unmarshal(body, &out); err != nil {
return pc, fmt.Errorf("pull config: %w (status %d, body %s)", err, status, common.BodySnippet(body))
}
if out.Result.Server.WebSocket == "" || out.Result.Channels.Private.ID == "" {
return pc, fmt.Errorf("pull config: missing websocket/channel (status %d, body %s)", status, common.BodySnippet(body))
}
pc.WebSocket = out.Result.Server.WebSocket
pc.ChannelID = out.Result.Channels.Private.ID
if out.Result.Channels.Shared.ID != "" {
pc.ChannelID += "/" + out.Result.Channels.Shared.ID
}
pc.Revision = out.Result.API.RevisionWeb
pc.Hostname = c.portal
if u, perr := url.Parse(c.portal); perr == nil && u.Host != "" {
pc.Hostname = u.Host
}
return pc, nil
}
func (c *Client) getGuestLink(chatID string) (string, error) {
form := url.Values{}
form.Set("chatId", chatID)
+40
View File
@@ -0,0 +1,40 @@
package bitrix
import "sync"
type KickManager struct {
kick func(userID string) error
selfID string
logFn func(string, ...any)
mu sync.Mutex
active string
}
func NewKickManager(kick func(userID string) error, selfID string, logFn func(string, ...any)) *KickManager {
return &KickManager{kick: kick, selfID: selfID, logFn: logFn}
}
func (m *KickManager) OnUserJoined(userID string) {
if userID == "" || userID == m.selfID {
return
}
m.mu.Lock()
old := m.active
if old == userID {
m.mu.Unlock()
return
}
m.active = userID
m.mu.Unlock()
if old == "" {
m.logFn("[bx] active call guest userId=%s", userID)
return
}
if err := m.kick(old); err != nil {
m.logFn("[bx] kick failed userId=%s: %v", old, err)
return
}
m.logFn("[bx] kicked previous guest userId=%s, new active=%s", old, userID)
}
+215
View File
@@ -0,0 +1,215 @@
package bitrix
import (
"encoding/binary"
"encoding/json"
"fmt"
"net/http"
"net/url"
"strings"
"sync"
"github.com/gorilla/websocket"
"whitelist-bypass/relay/common"
)
const (
pullWireVarint = 0
pullWireFixed64 = 1
pullWireBytes = 2
pullWireFixed32 = 5
pullMaxDepth = 8
)
type PullClient struct {
cfg PullConfigResult
ua string
origin string
logFn func(string, ...any)
mu sync.Mutex
ws *websocket.Conn
closed bool
onUsersAnswered func([]string)
onUserLeave func(string)
}
func NewPullClient(cfg PullConfigResult, ua, origin string, logFn func(string, ...any)) *PullClient {
return &PullClient{cfg: cfg, ua: ua, origin: origin, logFn: logFn}
}
func (p *PullClient) SetOnUsersAnswered(fn func([]string)) { p.onUsersAnswered = fn }
func (p *PullClient) SetOnUserLeave(fn func(string)) { p.onUserLeave = fn }
func (p *PullClient) dialURL() string {
q := url.Values{}
q.Set("CHANNEL_ID", p.cfg.ChannelID)
q.Set("binaryMode", "true")
if p.cfg.Hostname != "" {
q.Set("hostname", p.cfg.Hostname)
}
if p.cfg.Revision > 0 {
q.Set("revision", fmt.Sprintf("%d", p.cfg.Revision))
}
sep := "?"
if strings.Contains(p.cfg.WebSocket, "?") {
sep = "&"
}
return p.cfg.WebSocket + sep + q.Encode()
}
func (p *PullClient) connect() error {
headers := http.Header{}
if p.ua != "" {
headers.Set("User-Agent", p.ua)
}
if p.origin != "" {
headers.Set("Origin", p.origin)
}
conn, resp, err := websocket.DefaultDialer.Dial(p.dialURL(), headers)
if err != nil {
if resp != nil {
return fmt.Errorf("subws2 dial: %w, status %d", err, resp.StatusCode)
}
return fmt.Errorf("subws2 dial: %w", err)
}
p.mu.Lock()
p.ws = conn
p.mu.Unlock()
p.logFn("[bx] subws2 connected")
return nil
}
func (p *PullClient) Run() error {
if err := p.connect(); err != nil {
return err
}
for {
p.mu.Lock()
ws := p.ws
closed := p.closed
p.mu.Unlock()
if closed || ws == nil {
return nil
}
_, data, err := ws.ReadMessage()
if err != nil {
p.mu.Lock()
closed = p.closed
p.mu.Unlock()
if closed {
return nil
}
return fmt.Errorf("subws2 read: %w", err)
}
p.handleFrame(data)
}
}
func (p *PullClient) Close() {
p.mu.Lock()
p.closed = true
ws := p.ws
p.ws = nil
p.mu.Unlock()
if ws != nil {
common.CloseWS(ws)
}
}
func (p *PullClient) handleFrame(frame []byte) {
for _, body := range extractPullBodies(frame) {
var msg struct {
ModuleID string `json:"module_id"`
Command string `json:"command"`
Params struct {
Senders []struct {
SenderID json.Number `json:"senderId"`
} `json:"senders"`
UserID json.Number `json:"userId"`
} `json:"params"`
}
if err := json.Unmarshal(body, &msg); err != nil {
continue
}
switch {
case msg.ModuleID == "call" && strings.Contains(msg.Command, "usersAnswered"):
var ids []string
for _, s := range msg.Params.Senders {
if id := s.SenderID.String(); id != "" {
ids = append(ids, id)
}
}
if len(ids) > 0 && p.onUsersAnswered != nil {
p.onUsersAnswered(ids)
}
case msg.ModuleID == "im" && msg.Command == "chatUserLeave":
if uid := msg.Params.UserID.String(); uid != "" && p.onUserLeave != nil {
p.onUserLeave(uid)
}
}
}
}
func extractPullBodies(buf []byte) [][]byte {
return collectPullBodies(buf, nil, 0)
}
func collectPullBodies(buf []byte, out [][]byte, depth int) [][]byte {
if depth > pullMaxDepth {
return out
}
for len(buf) > 0 {
value, rest, ok := nextPullField(buf)
if !ok {
return out
}
buf = rest
switch {
case len(value) == 0:
case value[0] == '{':
out = append(out, value)
default:
out = collectPullBodies(value, out, depth+1)
}
}
return out
}
func nextPullField(buf []byte) (value, rest []byte, ok bool) {
tag, n := binary.Uvarint(buf)
if n <= 0 {
return nil, nil, false
}
buf = buf[n:]
switch tag & 7 {
case pullWireVarint:
_, m := binary.Uvarint(buf)
if m <= 0 {
return nil, nil, false
}
return nil, buf[m:], true
case pullWireFixed64:
return skipPullFixed(buf, 8)
case pullWireFixed32:
return skipPullFixed(buf, 4)
case pullWireBytes:
l, m := binary.Uvarint(buf)
if m <= 0 || l > uint64(len(buf)-m) {
return nil, nil, false
}
end := m + int(l)
return buf[m:end], buf[end:], true
}
return nil, nil, false
}
func skipPullFixed(buf []byte, size int) (value, rest []byte, ok bool) {
if len(buf) < size {
return nil, nil, false
}
return nil, buf[size:], true
}
+2
View File
@@ -115,6 +115,8 @@ func (s *Signal) SetOnDataChannel(fn func(*webrtc.DataChannel)) {
}
}
func (s *Signal) LocalUserID() string { return s.lk.Join().LocalUserID }
func (s *Signal) PubReliableDC() *webrtc.DataChannel {
s.mu.Lock()
defer s.mu.Unlock()