8058
Ir
irvc / files
irvc / voice.go
2.6 KB
1package main 2 3import ( 4 "crypto/hmac" 5 "crypto/sha256" 6 "encoding/base64" 7 "encoding/json" 8 "fmt" 9 "net/http" 10 "strconv" 11 "time" 12 13 "github.com/gin-gonic/gin" 14) 15 16type videoGrant struct { 17 Room string `json:"room"` 18 RoomJoin bool `json:"roomJoin"` 19 CanPublish bool `json:"canPublish"` 20 CanSubscribe bool `json:"canSubscribe"` 21} 22 23type livekitClaims struct { 24 Exp int64 `json:"exp"` 25 Nbf int64 `json:"nbf"` 26 Iss string `json:"iss"` 27 Sub string `json:"sub"` 28 Jti string `json:"jti"` 29 Name string `json:"name"` 30 Video videoGrant `json:"video"` 31} 32 33// livekitToken builds a LiveKit access token (HS256 JWT) by hand. 34func livekitToken(apiKey, apiSecret, identity, name, room string) string { 35 now := time.Now() 36 claims := livekitClaims{ 37 Exp: now.Add(6 * time.Hour).Unix(), 38 Nbf: now.Add(-10 * time.Second).Unix(), 39 Iss: apiKey, 40 Sub: identity, 41 Jti: identity, 42 Name: name, 43 Video: videoGrant{ 44 Room: room, 45 RoomJoin: true, 46 CanPublish: true, 47 CanSubscribe: true, 48 }, 49 } 50 header, _ := json.Marshal(map[string]string{"alg": "HS256", "typ": "JWT"}) 51 payload, _ := json.Marshal(claims) 52 enc := base64.RawURLEncoding.EncodeToString 53 signingInput := enc(header) + "." + enc(payload) 54 mac := hmac.New(sha256.New, []byte(apiSecret)) 55 mac.Write([]byte(signingInput)) 56 return signingInput + "." + enc(mac.Sum(nil)) 57} 58 59func (s *Server) handleVoiceToken(c *gin.Context) { 60 channelID, err := strconv.ParseInt(c.Param("id"), 10, 64) 61 if err != nil { 62 c.JSON(http.StatusBadRequest, gin.H{"error": "bad channel"}) 63 return 64 } 65 var channelType, channelName string 66 if err := s.db.QueryRow(`SELECT type, name FROM channels WHERE id = ?`, channelID).Scan(&channelType, &channelName); err != nil { 67 c.JSON(http.StatusNotFound, gin.H{"error": "channel not found"}) 68 return 69 } 70 user := c.MustGet("user").(User) 71 // A DM call is a call in the DM, so it mints the same kind of token; only 72 // voice channels and the caller's own DMs may be joined. 73 if channelType == "dm" { 74 if _, ok := dmPeer(channelName, user.ID); !ok { 75 c.JSON(http.StatusForbidden, gin.H{"error": "forbidden"}) 76 return 77 } 78 } else if channelType != "voice" { 79 c.JSON(http.StatusBadRequest, gin.H{"error": "not a voice channel"}) 80 return 81 } 82 if s.cfg.LiveKitKey == "" || s.cfg.LiveKitSecret == "" || s.cfg.LiveKitURL == "" { 83 c.JSON(http.StatusServiceUnavailable, gin.H{"error": "voice not configured"}) 84 return 85 } 86 room := fmt.Sprintf("voice-%d", channelID) 87 token := livekitToken(s.cfg.LiveKitKey, s.cfg.LiveKitSecret, strconv.FormatInt(user.ID, 10), user.Username, room) 88 c.JSON(http.StatusOK, gin.H{"url": s.cfg.LiveKitURL, "token": token, "room": room}) 89}