mirror of
https://github.com/yibaiba/hideck.git
synced 2026-12-05 08:01:10 +00:00
Hangup could return 204 while native VoLTE never emitted CallEnded, so the page stayed on 挂断中. Finish the phone-layer call after a successful hangup or reject, replay events when after_id is from a previous process, and apply restarted SSE ids instead of dropping them.
71 lines
1.5 KiB
Go
71 lines
1.5 KiB
Go
package api
|
|
|
|
import (
|
|
"encoding/json"
|
|
"fmt"
|
|
"net/http"
|
|
"strconv"
|
|
"strings"
|
|
"time"
|
|
|
|
"github.com/gin-gonic/gin"
|
|
"github.com/yibaiba/hideck/internal/phone"
|
|
)
|
|
|
|
const phoneEventHeartbeatInterval = 15 * time.Second
|
|
|
|
func (s *Server) handlePhoneEvents(c *gin.Context) {
|
|
if !s.requirePhone(c) {
|
|
return
|
|
}
|
|
backlog, stream, cancel := s.phone.Subscribe(phoneLastEventID(c))
|
|
defer cancel()
|
|
c.Header("Content-Type", "text/event-stream")
|
|
c.Header("Cache-Control", "no-cache")
|
|
c.Header("Connection", "keep-alive")
|
|
c.Header("X-Accel-Buffering", "no")
|
|
c.Status(http.StatusOK)
|
|
_, _ = fmt.Fprint(c.Writer, ": connected\n\n")
|
|
c.Writer.Flush()
|
|
for _, event := range backlog {
|
|
writePhoneEvent(c, event)
|
|
}
|
|
c.Writer.Flush()
|
|
heartbeat := time.NewTicker(phoneEventHeartbeatInterval)
|
|
defer heartbeat.Stop()
|
|
for {
|
|
select {
|
|
case event, ok := <-stream:
|
|
if !ok {
|
|
return
|
|
}
|
|
writePhoneEvent(c, event)
|
|
c.Writer.Flush()
|
|
case <-heartbeat.C:
|
|
_, _ = fmt.Fprint(c.Writer, ": heartbeat\n\n")
|
|
c.Writer.Flush()
|
|
case <-c.Request.Context().Done():
|
|
return
|
|
case <-s.shutdownCh:
|
|
return
|
|
}
|
|
}
|
|
}
|
|
|
|
func writePhoneEvent(c *gin.Context, event phone.Event) {
|
|
payload, err := json.Marshal(event)
|
|
if err != nil {
|
|
return
|
|
}
|
|
_, _ = fmt.Fprintf(c.Writer, "id: %d\nevent: %s\ndata: %s\n\n", event.ID, event.Type, payload)
|
|
}
|
|
|
|
func phoneLastEventID(c *gin.Context) uint64 {
|
|
value := strings.TrimSpace(c.GetHeader("Last-Event-ID"))
|
|
if value == "" {
|
|
value = strings.TrimSpace(c.Query("after_id"))
|
|
}
|
|
result, _ := strconv.ParseUint(value, 10, 64)
|
|
return result
|
|
}
|