-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmain.go
More file actions
799 lines (670 loc) · 19.8 KB
/
main.go
File metadata and controls
799 lines (670 loc) · 19.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
/* SPDX-License-Identifier: MPL-2.0
* Copyright 2025 Tejus Pratap <tejzpr@gmail.com>
*
* See CONTRIBUTORS.md for full contributor list.
*/
// Package main provides a web-based example application for the Webex Calling API.
// It demonstrates call history, call settings, voicemail, contacts, and real-time
// call control (register, dial, hold, transfer, DTMF) using the Webex Go SDK.
//
// Usage:
//
// go run main.go
//
// Then open http://localhost:8090 in your browser.
package main
import (
"context"
"embed"
"encoding/json"
"fmt"
"io/fs"
"log"
"net/http"
"os"
"os/signal"
"sync"
"syscall"
"time"
"github.com/gorilla/websocket"
webex "github.com/WebexCommunity/webex-go-sdk/v2"
"github.com/WebexCommunity/webex-go-sdk/v2/calling"
)
//go:embed static/*
var staticFiles embed.FS
// appState holds the server-side state
type appState struct {
mu sync.RWMutex
client *webex.WebexClient
callingClient *calling.CallingClient
line *calling.Line
activeCall *calling.Call
accessToken string
activeWSConn *websocket.Conn // audio bridge WS, closed on shutdown
}
var state = &appState{}
func main() {
// Serve embedded static files
staticFS, err := fs.Sub(staticFiles, "static")
if err != nil {
log.Fatal(err)
}
mux := http.NewServeMux()
mux.Handle("/", http.FileServer(http.FS(staticFS)))
// API endpoints
mux.HandleFunc("/api/connect", handleConnect)
mux.HandleFunc("/api/disconnect", handleDisconnect)
mux.HandleFunc("/api/status", handleStatus)
// REST API endpoints
mux.HandleFunc("/api/call-history", handleCallHistory)
mux.HandleFunc("/api/call-settings/dnd", handleDND)
mux.HandleFunc("/api/call-settings/call-waiting", handleCallWaiting)
mux.HandleFunc("/api/call-settings/call-forward", handleCallForward)
mux.HandleFunc("/api/voicemail/list", handleVoicemailList)
mux.HandleFunc("/api/voicemail/summary", handleVoicemailSummary)
mux.HandleFunc("/api/contacts", handleContacts)
// Call control endpoints
mux.HandleFunc("/api/register", handleRegister)
mux.HandleFunc("/api/deregister", handleDeregister)
mux.HandleFunc("/api/deregister-all", handleDeregisterAll)
mux.HandleFunc("/api/dial", handleDial)
mux.HandleFunc("/api/end", handleEnd)
mux.HandleFunc("/api/hold", handleHold)
mux.HandleFunc("/api/resume", handleResume)
mux.HandleFunc("/api/mute", handleMute)
mux.HandleFunc("/api/unmute", handleUnmute)
mux.HandleFunc("/api/dtmf", handleDTMF)
mux.HandleFunc("/api/transfer", handleTransfer)
// Audio bridge WebSocket
mux.HandleFunc("/ws/audio", handleAudioWS)
addr := ":8095"
server := &http.Server{Addr: addr, Handler: mux}
// Graceful shutdown on SIGINT/SIGTERM
go func() {
sigCh := make(chan os.Signal, 1)
signal.Notify(sigCh, syscall.SIGINT, syscall.SIGTERM)
sig := <-sigCh
log.Printf("Received %v, shutting down...", sig)
// Close the audio bridge WebSocket so HandleSignaling unblocks
state.mu.Lock()
if state.activeWSConn != nil {
_ = state.activeWSConn.Close()
}
if state.callingClient != nil {
log.Println("Auto-deregistering calling client...")
_ = state.callingClient.Shutdown()
log.Println("Calling client shut down.")
}
state.mu.Unlock()
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
if err := server.Shutdown(ctx); err != nil {
log.Printf("HTTP server shutdown error: %v", err)
}
// Force exit if goroutines are still hanging
time.Sleep(2 * time.Second)
log.Println("Force exiting.")
os.Exit(0)
}()
log.Printf("Webex Calling Example running at http://localhost%s", addr)
if err := server.ListenAndServe(); err != http.ErrServerClosed {
log.Fatal(err)
}
log.Println("Server stopped.")
}
// ---- Helper ----
func jsonResponse(w http.ResponseWriter, status int, data interface{}) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(status)
_ = json.NewEncoder(w).Encode(data)
}
func jsonError(w http.ResponseWriter, status int, msg string) {
jsonResponse(w, status, map[string]string{"error": msg})
}
func requireClient(w http.ResponseWriter) bool {
state.mu.RLock()
defer state.mu.RUnlock()
if state.client == nil {
jsonError(w, http.StatusBadRequest, "Not connected. Enter your access token first.")
return false
}
return true
}
// ---- Connection ----
func handleConnect(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
jsonError(w, http.StatusMethodNotAllowed, "POST required")
return
}
var req struct {
AccessToken string `json:"accessToken"`
}
if err := json.NewDecoder(r.Body).Decode(&req); err != nil || req.AccessToken == "" {
jsonError(w, http.StatusBadRequest, "accessToken is required")
return
}
client, err := webex.NewClient(req.AccessToken, nil)
if err != nil {
jsonError(w, http.StatusInternalServerError, fmt.Sprintf("Failed to create client: %v", err))
return
}
state.mu.Lock()
state.client = client
state.accessToken = req.AccessToken
state.callingClient = nil
state.line = nil
state.activeCall = nil
state.mu.Unlock()
jsonResponse(w, http.StatusOK, map[string]string{"status": "connected"})
}
func handleDisconnect(w http.ResponseWriter, r *http.Request) {
state.mu.Lock()
if state.callingClient != nil {
_ = state.callingClient.Shutdown()
}
state.client = nil
state.callingClient = nil
state.line = nil
state.activeCall = nil
state.accessToken = ""
state.mu.Unlock()
jsonResponse(w, http.StatusOK, map[string]string{"status": "disconnected"})
}
func handleStatus(w http.ResponseWriter, r *http.Request) {
state.mu.RLock()
defer state.mu.RUnlock()
resp := map[string]interface{}{
"connected": state.client != nil,
"registered": false,
"callActive": false,
}
if state.line != nil {
resp["registered"] = state.line.IsRegistered()
resp["lineId"] = state.line.LineID
resp["deviceId"] = state.line.GetDeviceID()
}
if state.activeCall != nil {
resp["callActive"] = true
resp["callId"] = state.activeCall.GetCallID()
resp["callState"] = string(state.activeCall.GetState())
resp["callDirection"] = string(state.activeCall.GetDirection())
resp["muted"] = state.activeCall.IsMuted()
resp["held"] = state.activeCall.IsHeld()
}
jsonResponse(w, http.StatusOK, resp)
}
// ---- REST APIs ----
func handleCallHistory(w http.ResponseWriter, r *http.Request) {
if !requireClient(w) {
return
}
state.mu.RLock()
client := state.client
state.mu.RUnlock()
data, err := client.Calling().CallHistory().GetCallHistoryData(7, 10, calling.SortDESC, calling.SortByStartTime)
if err != nil {
jsonError(w, http.StatusInternalServerError, fmt.Sprintf("Error: %v", err))
return
}
jsonResponse(w, http.StatusOK, data)
}
func handleDND(w http.ResponseWriter, r *http.Request) {
if !requireClient(w) {
return
}
state.mu.RLock()
client := state.client
state.mu.RUnlock()
if r.Method == http.MethodGet {
data, err := client.Calling().CallSettings().GetDoNotDisturbSetting()
if err != nil {
jsonError(w, http.StatusInternalServerError, fmt.Sprintf("Error: %v", err))
return
}
jsonResponse(w, http.StatusOK, data)
return
}
if r.Method == http.MethodPut {
var req struct {
Enabled bool `json:"enabled"`
}
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
jsonError(w, http.StatusBadRequest, "Invalid request body")
return
}
data, err := client.Calling().CallSettings().SetDoNotDisturbSetting(req.Enabled)
if err != nil {
jsonError(w, http.StatusInternalServerError, fmt.Sprintf("Error: %v", err))
return
}
jsonResponse(w, http.StatusOK, data)
return
}
jsonError(w, http.StatusMethodNotAllowed, "GET or PUT required")
}
func handleCallWaiting(w http.ResponseWriter, r *http.Request) {
if !requireClient(w) {
return
}
state.mu.RLock()
client := state.client
state.mu.RUnlock()
data, err := client.Calling().CallSettings().GetCallWaitingSetting()
if err != nil {
jsonError(w, http.StatusInternalServerError, fmt.Sprintf("Error: %v", err))
return
}
jsonResponse(w, http.StatusOK, data)
}
func handleCallForward(w http.ResponseWriter, r *http.Request) {
if !requireClient(w) {
return
}
state.mu.RLock()
client := state.client
state.mu.RUnlock()
data, err := client.Calling().CallSettings().GetCallForwardSetting()
if err != nil {
jsonError(w, http.StatusInternalServerError, fmt.Sprintf("Error: %v", err))
return
}
jsonResponse(w, http.StatusOK, data)
}
func handleVoicemailList(w http.ResponseWriter, r *http.Request) {
if !requireClient(w) {
return
}
state.mu.RLock()
client := state.client
state.mu.RUnlock()
data, err := client.Calling().Voicemail().GetVoicemailList(0, 20, calling.SortDESC)
if err != nil {
jsonError(w, http.StatusInternalServerError, fmt.Sprintf("Error: %v", err))
return
}
jsonResponse(w, http.StatusOK, data)
}
func handleVoicemailSummary(w http.ResponseWriter, r *http.Request) {
if !requireClient(w) {
return
}
state.mu.RLock()
client := state.client
state.mu.RUnlock()
data, err := client.Calling().Voicemail().GetVoicemailSummary()
if err != nil {
jsonError(w, http.StatusInternalServerError, fmt.Sprintf("Error: %v", err))
return
}
jsonResponse(w, http.StatusOK, data)
}
func handleContacts(w http.ResponseWriter, r *http.Request) {
if !requireClient(w) {
return
}
state.mu.RLock()
client := state.client
state.mu.RUnlock()
data, err := client.Calling().Contacts().GetContacts()
if err != nil {
jsonError(w, http.StatusInternalServerError, fmt.Sprintf("Error: %v", err))
return
}
jsonResponse(w, http.StatusOK, data)
}
// ---- Call Control ----
func handleRegister(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
jsonError(w, http.StatusMethodNotAllowed, "POST required")
return
}
if !requireClient(w) {
return
}
var req struct {
PrimaryMobiusURL string `json:"primaryMobiusUrl"`
ClientDeviceURI string `json:"clientDeviceUri"`
}
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
jsonError(w, http.StatusBadRequest, "Invalid request body")
return
}
state.mu.Lock()
client := state.client
state.mu.Unlock()
cc := client.Calling().CallingClient(&calling.CallingClientConfig{
ClientDeviceURI: req.ClientDeviceURI,
})
if req.PrimaryMobiusURL != "" {
cc.SetMobiusServers([]string{req.PrimaryMobiusURL}, nil)
} else {
if err := cc.DiscoverMobiusServers(); err != nil {
jsonError(w, http.StatusInternalServerError, fmt.Sprintf("Discovery failed: %v", err))
return
}
}
line, err := cc.CreateLine()
if err != nil {
jsonError(w, http.StatusInternalServerError, fmt.Sprintf("Registration failed: %v", err))
return
}
state.mu.Lock()
state.callingClient = cc
state.line = line
state.mu.Unlock()
// Connect Mercury WebSocket for Mobius call events (ROAP answers, call progress, etc.)
// The SDK handles WDM URL wiring, event filtering, and routing internally.
go func() {
if err := cc.ConnectMercury(client.Mercury()); err != nil {
log.Printf("Mercury connection failed: %v", err)
}
}()
jsonResponse(w, http.StatusOK, map[string]interface{}{
"status": "registered",
"lineId": line.LineID,
"deviceId": line.GetDeviceID(),
})
}
func handleDeregister(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
jsonError(w, http.StatusMethodNotAllowed, "POST required")
return
}
state.mu.Lock()
if state.callingClient != nil {
_ = state.callingClient.Shutdown()
}
state.callingClient = nil
state.line = nil
state.activeCall = nil
state.mu.Unlock()
jsonResponse(w, http.StatusOK, map[string]string{"status": "deregistered"})
}
func handleDeregisterAll(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
jsonError(w, http.StatusMethodNotAllowed, "POST required")
return
}
if !requireClient(w) {
return
}
state.mu.RLock()
client := state.client
state.mu.RUnlock()
// Create a temporary CallingClient to discover Mobius and clean up devices
cc := client.Calling().CallingClient(&calling.CallingClientConfig{})
if err := cc.DiscoverMobiusServers(); err != nil {
jsonError(w, http.StatusInternalServerError, fmt.Sprintf("Discovery failed: %v", err))
return
}
deleted, err := cc.DeregisterAllDevices()
if err != nil {
jsonError(w, http.StatusInternalServerError, fmt.Sprintf("Deregister all failed: %v", err))
return
}
// Also clean up local state
state.mu.Lock()
if state.callingClient != nil {
_ = state.callingClient.Shutdown()
}
state.callingClient = nil
state.line = nil
state.activeCall = nil
state.mu.Unlock()
jsonResponse(w, http.StatusOK, map[string]interface{}{
"status": "deregistered_all",
"deleted": deleted,
})
}
func handleDial(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
jsonError(w, http.StatusMethodNotAllowed, "POST required")
return
}
if !requireClient(w) {
return
}
var req struct {
Address string `json:"address"`
CallType string `json:"callType"`
}
if err := json.NewDecoder(r.Body).Decode(&req); err != nil || req.Address == "" {
jsonError(w, http.StatusBadRequest, "address is required")
return
}
state.mu.RLock()
cc := state.callingClient
line := state.line
state.mu.RUnlock()
if cc == nil || line == nil {
jsonError(w, http.StatusBadRequest, "Not registered. Register a line first.")
return
}
address, ct, err := calling.NormalizeAddress(req.Address)
if err != nil {
jsonError(w, http.StatusBadRequest, fmt.Sprintf("Invalid address: %v", err))
return
}
log.Printf("Dial: normalized address=%s type=%s", address, ct)
call, err := cc.MakeCall(line, &calling.CallDetails{
Type: ct,
Address: address,
})
if err != nil {
jsonError(w, http.StatusInternalServerError, fmt.Sprintf("Dial failed: %v", err))
return
}
state.mu.Lock()
state.activeCall = call
state.mu.Unlock()
// Clear activeCall when remote party disconnects
// (AudioBridge detach is handled automatically by CallingClient)
call.Emitter.On(string(calling.CallEventDisconnect), func(d interface{}) {
log.Printf("Call disconnected by remote party, clearing activeCall")
state.mu.Lock()
if state.activeCall == call {
state.activeCall = nil
}
state.mu.Unlock()
})
jsonResponse(w, http.StatusOK, map[string]interface{}{
"status": "dialing",
"callId": call.GetCallID(),
"correlationId": call.GetCorrelationID(),
})
}
func handleEnd(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
jsonError(w, http.StatusMethodNotAllowed, "POST required")
return
}
state.mu.Lock()
call := state.activeCall
state.mu.Unlock()
if call == nil {
jsonError(w, http.StatusBadRequest, "No active call")
return
}
if err := call.End(); err != nil {
jsonError(w, http.StatusInternalServerError, fmt.Sprintf("End failed: %v", err))
return
}
state.mu.Lock()
state.activeCall = nil
state.mu.Unlock()
jsonResponse(w, http.StatusOK, map[string]string{"status": "ended"})
}
func handleHold(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
jsonError(w, http.StatusMethodNotAllowed, "POST required")
return
}
state.mu.RLock()
call := state.activeCall
state.mu.RUnlock()
if call == nil {
jsonError(w, http.StatusBadRequest, "No active call")
return
}
if err := call.Hold(); err != nil {
jsonError(w, http.StatusInternalServerError, fmt.Sprintf("Hold failed: %v", err))
return
}
jsonResponse(w, http.StatusOK, map[string]string{"status": "held"})
}
func handleResume(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
jsonError(w, http.StatusMethodNotAllowed, "POST required")
return
}
state.mu.RLock()
call := state.activeCall
state.mu.RUnlock()
if call == nil {
jsonError(w, http.StatusBadRequest, "No active call")
return
}
if err := call.Resume(); err != nil {
jsonError(w, http.StatusInternalServerError, fmt.Sprintf("Resume failed: %v", err))
return
}
jsonResponse(w, http.StatusOK, map[string]string{"status": "resumed"})
}
func handleMute(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
jsonError(w, http.StatusMethodNotAllowed, "POST required")
return
}
state.mu.RLock()
call := state.activeCall
state.mu.RUnlock()
if call == nil {
jsonError(w, http.StatusBadRequest, "No active call")
return
}
call.Mute()
jsonResponse(w, http.StatusOK, map[string]string{"status": "muted"})
}
func handleUnmute(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
jsonError(w, http.StatusMethodNotAllowed, "POST required")
return
}
state.mu.RLock()
call := state.activeCall
state.mu.RUnlock()
if call == nil {
jsonError(w, http.StatusBadRequest, "No active call")
return
}
call.Unmute()
jsonResponse(w, http.StatusOK, map[string]string{"status": "unmuted"})
}
func handleDTMF(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
jsonError(w, http.StatusMethodNotAllowed, "POST required")
return
}
var req struct {
Digit string `json:"digit"`
}
if err := json.NewDecoder(r.Body).Decode(&req); err != nil || req.Digit == "" {
jsonError(w, http.StatusBadRequest, "digit is required")
return
}
state.mu.RLock()
call := state.activeCall
state.mu.RUnlock()
if call == nil {
jsonError(w, http.StatusBadRequest, "No active call")
return
}
if err := call.SendDigit(req.Digit); err != nil {
jsonError(w, http.StatusInternalServerError, fmt.Sprintf("DTMF failed: %v", err))
return
}
jsonResponse(w, http.StatusOK, map[string]string{"status": "sent", "digit": req.Digit})
}
// ---- Audio Bridge (WebSocket + WebRTC relay) ----
var wsUpgrader = websocket.Upgrader{
CheckOrigin: func(r *http.Request) bool { return true },
}
// wsTransport adapts gorilla/websocket to calling.SignalingTransport.
type wsTransport struct{ conn *websocket.Conn }
func (t *wsTransport) ReadMessage() ([]byte, error) {
_, data, err := t.conn.ReadMessage()
return data, err
}
func (t *wsTransport) WriteMessage(data []byte) error {
return t.conn.WriteMessage(websocket.TextMessage, data)
}
// handleAudioWS creates an AudioBridge and delegates signaling to the SDK.
func handleAudioWS(w http.ResponseWriter, r *http.Request) {
conn, err := wsUpgrader.Upgrade(w, r, nil)
if err != nil {
log.Printf("Audio WS upgrade failed: %v", err)
return
}
defer func() { _ = conn.Close() }()
log.Println("Audio WebSocket connected")
state.mu.Lock()
state.activeWSConn = conn
state.mu.Unlock()
defer func() {
state.mu.Lock()
state.activeWSConn = nil
state.mu.Unlock()
}()
bridge, err := calling.NewAudioBridge(nil)
if err != nil {
log.Printf("Audio bridge: failed to create: %v", err)
return
}
defer func() { _ = bridge.Close() }()
// Register bridge with CallingClient for automatic call↔bridge binding
state.mu.RLock()
cc := state.callingClient
state.mu.RUnlock()
if cc != nil {
cc.SetAudioBridge(bridge)
}
// Blocks until the WebSocket closes
if err := bridge.HandleSignaling(&wsTransport{conn: conn}); err != nil {
log.Printf("Audio bridge signaling ended: %v", err)
}
if cc != nil {
cc.ClearAudioBridge()
}
log.Println("Audio WebSocket disconnected")
}
func handleTransfer(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
jsonError(w, http.StatusMethodNotAllowed, "POST required")
return
}
var req struct {
TransferType string `json:"transferType"`
TransferTarget string `json:"transferTarget"`
TransferCallID string `json:"transferCallId"`
}
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
jsonError(w, http.StatusBadRequest, "Invalid request body")
return
}
state.mu.RLock()
call := state.activeCall
state.mu.RUnlock()
if call == nil {
jsonError(w, http.StatusBadRequest, "No active call")
return
}
tt := calling.TransferTypeBlind
if req.TransferType == "CONSULT" {
tt = calling.TransferTypeConsult
}
if err := call.CompleteTransfer(tt, req.TransferCallID, req.TransferTarget); err != nil {
jsonError(w, http.StatusInternalServerError, fmt.Sprintf("Transfer failed: %v", err))
return
}
jsonResponse(w, http.StatusOK, map[string]string{"status": "transferred"})
}