mirror of
https://github.com/MengMengCode/VoCat.git
synced 2026-08-13 03:13:43 +08:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
d8828ff26a | ||
|
|
337aa3c0ab | ||
|
|
97ca84bbfc |
@@ -76,8 +76,8 @@ func (s *Server) handleCallAction(w http.ResponseWriter, r *http.Request, config
|
||||
return true
|
||||
}
|
||||
duration = time.Duration(request.DurationSeconds) * time.Second
|
||||
if duration < time.Second || duration > maxCallDuration {
|
||||
writeError(w, http.StatusBadRequest, "invalid_duration", "duration_seconds must be between 1 and 600")
|
||||
if duration < 0 || duration > maxCallDuration {
|
||||
writeError(w, http.StatusBadRequest, "invalid_duration", "duration_seconds must be 0 (no automatic hang-up) or between 1 and 600")
|
||||
return true
|
||||
}
|
||||
command = "ATD" + number + ";"
|
||||
@@ -137,7 +137,9 @@ func (s *Server) handleCallAction(w http.ResponseWriter, r *http.Request, config
|
||||
if call, ok := result.(vowifi.Call); ok {
|
||||
callID = call.ID
|
||||
}
|
||||
go s.hangupVoWiFiAfter(config.ID, callID, duration)
|
||||
if duration > 0 {
|
||||
go s.hangupVoWiFiAfter(config.ID, callID, duration)
|
||||
}
|
||||
}
|
||||
s.recordAudit(r.Context(), "admin", "call."+action, "device", config.ID, "success", transport)
|
||||
writeJSON(w, http.StatusAccepted, map[string]any{"data": map[string]any{
|
||||
@@ -158,7 +160,9 @@ func (s *Server) handleCallAction(w http.ResponseWriter, r *http.Request, config
|
||||
return true
|
||||
}
|
||||
if action == "dial" {
|
||||
go s.hangupAfter(config.ID, physicalID, duration)
|
||||
if duration > 0 {
|
||||
go s.hangupAfter(config.ID, physicalID, duration)
|
||||
}
|
||||
}
|
||||
s.recordAudit(r.Context(), "admin", "call."+action, "device", config.ID, "success", transport)
|
||||
writeJSON(w, http.StatusAccepted, map[string]any{
|
||||
@@ -179,7 +183,7 @@ func resolveVoWiFiCallID(controller VoWiFiCallController, deviceID, id, required
|
||||
return "", err
|
||||
}
|
||||
for _, call := range calls {
|
||||
if requiredState == "" || call.State == requiredState {
|
||||
if call.State != "ended" && call.State != "failed" && (requiredState == "" || call.State == requiredState) {
|
||||
return call.ID, nil
|
||||
}
|
||||
}
|
||||
@@ -203,7 +207,11 @@ func (s *Server) hangupVoWiFiAfter(deviceID, callID string, duration time.Durati
|
||||
|
||||
func (s *Server) callTransport(deviceID string) string {
|
||||
if s.vowifi != nil {
|
||||
if state, err := s.vowifi.State(deviceID); err == nil && state.Enabled {
|
||||
// Enabled is only the desired card policy. Calls can use IMS only after
|
||||
// registration has actually completed; otherwise keep using the modem's
|
||||
// circuit-switched call path instead of routing into an unavailable IMS
|
||||
// session.
|
||||
if state, err := s.vowifi.State(deviceID); err == nil && state.IMSReady {
|
||||
return "vowifi"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,9 +1,11 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
|
||||
"vocat/internal/modem"
|
||||
"vocat/internal/vowifi"
|
||||
)
|
||||
|
||||
func TestParseCLCC(t *testing.T) {
|
||||
@@ -28,3 +30,44 @@ func TestValidDialNumber(t *testing.T) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestCallTransportRequiresIMSReady(t *testing.T) {
|
||||
controller := &fakeVoWiFiController{state: vowifi.State{Enabled: true}}
|
||||
server := &Server{vowifi: controller}
|
||||
if got := server.callTransport("ec20"); got != "cellular" {
|
||||
t.Fatalf("callTransport before IMS registration = %q, want cellular", got)
|
||||
}
|
||||
controller.state.IMSReady = true
|
||||
if got := server.callTransport("ec20"); got != "vowifi" {
|
||||
t.Fatalf("callTransport with IMS ready = %q, want vowifi", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestResolveVoWiFiCallIDIgnoresTerminalCalls(t *testing.T) {
|
||||
controller := &fakeCallController{calls: []vowifi.Call{
|
||||
{ID: "failed", State: "failed"},
|
||||
{ID: "active", State: "active"},
|
||||
}}
|
||||
got, err := resolveVoWiFiCallID(controller, "ec20", "", "")
|
||||
if err != nil || got != "active" {
|
||||
t.Fatalf("resolveVoWiFiCallID() = %q, %v; want active", got, err)
|
||||
}
|
||||
}
|
||||
|
||||
type fakeCallController struct {
|
||||
calls []vowifi.Call
|
||||
}
|
||||
|
||||
func (controller *fakeCallController) Calls(string) ([]vowifi.Call, error) {
|
||||
return controller.calls, nil
|
||||
}
|
||||
|
||||
func (*fakeCallController) DialCall(context.Context, string, string) (vowifi.Call, error) {
|
||||
return vowifi.Call{}, nil
|
||||
}
|
||||
|
||||
func (*fakeCallController) AnswerCall(context.Context, string, string) (vowifi.Call, error) {
|
||||
return vowifi.Call{}, nil
|
||||
}
|
||||
|
||||
func (*fakeCallController) HangupCall(context.Context, string, string) error { return nil }
|
||||
|
||||
@@ -11,6 +11,7 @@ import (
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"regexp"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
@@ -30,6 +31,8 @@ const (
|
||||
telegramMaxDialDuration = 10 * time.Minute
|
||||
)
|
||||
|
||||
var telegramTokenInURLPattern = regexp.MustCompile(`bot[0-9]{5,20}:[A-Za-z0-9_-]{20,128}`)
|
||||
|
||||
type telegramRuntimeConfig struct {
|
||||
Token string
|
||||
ChatID string
|
||||
@@ -146,6 +149,9 @@ func (bot *telegramBot) poll(ctx context.Context) {
|
||||
updates, pollErr := bot.getUpdates(pollContext, config, offset, 5)
|
||||
cancel()
|
||||
if pollErr != nil {
|
||||
if ctx.Err() != nil {
|
||||
return
|
||||
}
|
||||
bot.warn("poll Telegram updates", pollErr)
|
||||
if !waitTelegram(ctx, telegramPollInterval) {
|
||||
return
|
||||
@@ -970,7 +976,7 @@ func (bot *telegramBot) loadConfig(ctx context.Context) (telegramRuntimeConfig,
|
||||
func (bot *telegramBot) call(ctx context.Context, config telegramRuntimeConfig, method string, payload any, result any) error {
|
||||
base, err := validateTelegramAPIURL(ctx, config.BaseURL, config.Token, method)
|
||||
if err != nil {
|
||||
return err
|
||||
return redactTelegramError(err, config.Token)
|
||||
}
|
||||
body, err := json.Marshal(payload)
|
||||
if err != nil {
|
||||
@@ -982,13 +988,13 @@ func (bot *telegramBot) call(ctx context.Context, config telegramRuntimeConfig,
|
||||
}
|
||||
request, err := http.NewRequestWithContext(ctx, http.MethodPost, base.String(), bytes.NewReader(body))
|
||||
if err != nil {
|
||||
return err
|
||||
return redactTelegramError(err, config.Token)
|
||||
}
|
||||
request.Header.Set("Content-Type", "application/json")
|
||||
request.Header.Set("User-Agent", "vocat-telegram-bot/1")
|
||||
response, err := client.Do(request)
|
||||
if err != nil {
|
||||
return err
|
||||
return redactTelegramError(err, config.Token)
|
||||
}
|
||||
defer response.Body.Close()
|
||||
responseBody, err := io.ReadAll(io.LimitReader(response.Body, 2<<20))
|
||||
@@ -1042,7 +1048,7 @@ func (bot *telegramBot) warn(message string, err error) {
|
||||
return
|
||||
}
|
||||
now := time.Now()
|
||||
text := err.Error()
|
||||
text := redactTelegramText(err.Error(), "")
|
||||
bot.logMu.Lock()
|
||||
if text == bot.lastLogText && now.Sub(bot.lastLogTime) < time.Minute {
|
||||
bot.logMu.Unlock()
|
||||
@@ -1050,7 +1056,21 @@ func (bot *telegramBot) warn(message string, err error) {
|
||||
}
|
||||
bot.lastLogText, bot.lastLogTime = text, now
|
||||
bot.logMu.Unlock()
|
||||
bot.server.logger.Warn(message, "error", err)
|
||||
bot.server.logger.Warn(message, "error", text)
|
||||
}
|
||||
|
||||
func redactTelegramError(err error, token string) error {
|
||||
if err == nil {
|
||||
return nil
|
||||
}
|
||||
return errors.New(redactTelegramText(err.Error(), token))
|
||||
}
|
||||
|
||||
func redactTelegramText(value, token string) string {
|
||||
if strings.TrimSpace(token) != "" {
|
||||
value = strings.ReplaceAll(value, token, "[REDACTED]")
|
||||
}
|
||||
return telegramTokenInURLPattern.ReplaceAllString(value, "bot[REDACTED]")
|
||||
}
|
||||
|
||||
func parseTelegramCommand(text string) (string, string) {
|
||||
|
||||
@@ -2,6 +2,7 @@ package server
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
@@ -171,3 +172,12 @@ func TestTelegramExecutesInteractiveUSSDForConfiguredDevice(t *testing.T) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestTelegramErrorsRedactBotTokens(t *testing.T) {
|
||||
token := "1234567890:abcdefghijklmnopqrstuvwxyzABCDE"
|
||||
err := errors.New(`Post "https://api.telegram.org/bot` + token + `/getUpdates": context canceled`)
|
||||
redacted := redactTelegramError(err, token)
|
||||
if strings.Contains(redacted.Error(), token) || !strings.Contains(redacted.Error(), "bot[REDACTED]") {
|
||||
t.Fatalf("redacted error = %q", redacted)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -18,6 +18,8 @@ var (
|
||||
ErrCallState = errors.New("ims: call is not in the required state")
|
||||
)
|
||||
|
||||
const terminalCallRetention = 30 * time.Second
|
||||
|
||||
type imsCall struct {
|
||||
public vowifi.Call
|
||||
callID string
|
||||
@@ -37,11 +39,14 @@ type imsCall struct {
|
||||
func (session *Session) Calls() []vowifi.Call {
|
||||
session.callMu.Lock()
|
||||
defer session.callMu.Unlock()
|
||||
now := time.Now().UTC()
|
||||
calls := make([]vowifi.Call, 0, len(session.calls))
|
||||
for _, call := range session.calls {
|
||||
if call.public.State != "ended" && call.public.State != "failed" {
|
||||
calls = append(calls, call.public)
|
||||
for id, call := range session.calls {
|
||||
if call.public.EndedAt != nil && now.Sub(*call.public.EndedAt) > terminalCallRetention {
|
||||
delete(session.calls, id)
|
||||
continue
|
||||
}
|
||||
calls = append(calls, call.public)
|
||||
}
|
||||
sort.Slice(calls, func(i, j int) bool { return calls[i].StartedAt.Before(calls[j].StartedAt) })
|
||||
return calls
|
||||
@@ -144,13 +149,14 @@ func (session *Session) watchOutgoingCall(call *imsCall, key sipTransactionKey)
|
||||
case <-session.refreshContext.Done():
|
||||
return
|
||||
case <-timer.C:
|
||||
session.setCallState(call.callID, "failed")
|
||||
session.finishCall(call.callID, "failed", 0, "SIP INVITE transaction timed out")
|
||||
return
|
||||
case response := <-call.responses:
|
||||
if response == nil {
|
||||
continue
|
||||
}
|
||||
if response.StatusCode < 200 {
|
||||
session.setCallDiagnostic(call.callID, response.StatusCode, response.Reason)
|
||||
if response.StatusCode >= 180 {
|
||||
session.setCallState(call.callID, "ringing")
|
||||
}
|
||||
@@ -170,7 +176,7 @@ func (session *Session) watchOutgoingCall(call *imsCall, key sipTransactionKey)
|
||||
_ = session.sendACK(call)
|
||||
session.setCallState(call.callID, "active")
|
||||
} else {
|
||||
session.setCallState(call.callID, "failed")
|
||||
session.finishCall(call.callID, "failed", response.StatusCode, response.Reason)
|
||||
}
|
||||
return
|
||||
}
|
||||
@@ -223,18 +229,18 @@ func (session *Session) HangupCall(ctx context.Context, id string) error {
|
||||
if err := respond(response); err != nil {
|
||||
return err
|
||||
}
|
||||
session.setCallState(id, "ended")
|
||||
session.finishCall(id, "ended", 0, "")
|
||||
return nil
|
||||
}
|
||||
method := "BYE"
|
||||
if direction == "outgoing" && (state == "dialing" || state == "ringing") {
|
||||
method = "CANCEL"
|
||||
}
|
||||
if err := session.sendDialogRequest(ctx, call, method); err != nil {
|
||||
return err
|
||||
}
|
||||
session.setCallState(id, "ended")
|
||||
return nil
|
||||
err := session.sendDialogRequest(ctx, call, method)
|
||||
// A remote endpoint may already have removed the dialog and answer BYE with
|
||||
// 481. The local call must still leave the active list after a hang-up.
|
||||
session.finishCall(id, "ended", 0, "")
|
||||
return err
|
||||
}
|
||||
|
||||
func (session *Session) handleCallRequest(request *sipRequest, respond func([]byte) error) bool {
|
||||
@@ -280,7 +286,7 @@ func (session *Session) handleCallRequest(request *sipRequest, respond func([]by
|
||||
}
|
||||
}
|
||||
}
|
||||
session.setCallState(callID, "ended")
|
||||
session.finishCall(callID, "ended", 0, "")
|
||||
return true
|
||||
default:
|
||||
return false
|
||||
@@ -395,6 +401,34 @@ func (session *Session) setCallState(id, state string) {
|
||||
session.callMu.Lock()
|
||||
if call := session.calls[id]; call != nil {
|
||||
call.public.State = state
|
||||
if state != "ended" && state != "failed" {
|
||||
call.public.EndedAt = nil
|
||||
}
|
||||
}
|
||||
session.callMu.Unlock()
|
||||
}
|
||||
|
||||
func (session *Session) setCallDiagnostic(id string, code int, reason string) {
|
||||
session.callMu.Lock()
|
||||
if call := session.calls[id]; call != nil {
|
||||
call.public.SIPCode = code
|
||||
call.public.Reason = safeSIPDiagnostic(reason)
|
||||
}
|
||||
session.callMu.Unlock()
|
||||
}
|
||||
|
||||
func (session *Session) finishCall(id, state string, code int, reason string) {
|
||||
now := time.Now().UTC()
|
||||
session.callMu.Lock()
|
||||
if call := session.calls[id]; call != nil {
|
||||
call.public.State = state
|
||||
if code != 0 {
|
||||
call.public.SIPCode = code
|
||||
}
|
||||
if reason = safeSIPDiagnostic(reason); reason != "" {
|
||||
call.public.Reason = reason
|
||||
}
|
||||
call.public.EndedAt = &now
|
||||
}
|
||||
session.callMu.Unlock()
|
||||
}
|
||||
|
||||
@@ -4,6 +4,8 @@ import (
|
||||
"context"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"vocat/internal/vowifi"
|
||||
)
|
||||
|
||||
func TestIncomingCallCanRingAndAnswerWithoutAudio(t *testing.T) {
|
||||
@@ -60,8 +62,21 @@ func TestIncomingCallCanBeRejected(t *testing.T) {
|
||||
if !strings.HasPrefix(string(response), "SIP/2.0 486 Busy Here") {
|
||||
t.Fatalf("reject response = %q", response)
|
||||
}
|
||||
if len(session.Calls()) != 0 {
|
||||
t.Fatal("ended call remained active")
|
||||
calls := session.Calls()
|
||||
if len(calls) != 1 || calls[0].State != "ended" || calls[0].EndedAt == nil {
|
||||
t.Fatalf("terminal call status = %#v", calls)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRejectedOutgoingCallRetainsSIPReason(t *testing.T) {
|
||||
session := &Session{calls: make(map[string]*imsCall)}
|
||||
call := &imsCall{public: vowifi.Call{ID: "rejected", State: "dialing"}}
|
||||
session.calls[call.public.ID] = call
|
||||
session.finishCall(call.public.ID, "failed", 484, "Address Incomplete\r\nignored")
|
||||
calls := session.Calls()
|
||||
if len(calls) != 1 || calls[0].State != "failed" || calls[0].SIPCode != 484 ||
|
||||
calls[0].Reason != "Address Incomplete ignored" || calls[0].EndedAt == nil {
|
||||
t.Fatalf("rejected call = %#v", calls)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -368,11 +368,14 @@ type SMSSender interface {
|
||||
// Call describes one signalling-only IMS call. VoCat intentionally does not
|
||||
// open, capture, or relay an RTP media stream for extension call tests.
|
||||
type Call struct {
|
||||
ID string `json:"id"`
|
||||
Number string `json:"number"`
|
||||
Direction string `json:"direction"`
|
||||
State string `json:"state"`
|
||||
StartedAt time.Time `json:"started_at"`
|
||||
ID string `json:"id"`
|
||||
Number string `json:"number"`
|
||||
Direction string `json:"direction"`
|
||||
State string `json:"state"`
|
||||
StartedAt time.Time `json:"started_at"`
|
||||
SIPCode int `json:"sip_code,omitempty"`
|
||||
Reason string `json:"reason,omitempty"`
|
||||
EndedAt *time.Time `json:"ended_at,omitempty"`
|
||||
}
|
||||
|
||||
// CallController is an optional capability of an IMS session. Implementations
|
||||
|
||||
Reference in New Issue
Block a user