179 lines
5.0 KiB
Go
179 lines
5.0 KiB
Go
package main
|
|
|
|
import (
|
|
"context"
|
|
"crypto/rand"
|
|
"crypto/subtle"
|
|
"encoding/hex"
|
|
"encoding/json"
|
|
"log"
|
|
"net"
|
|
"net/http"
|
|
"net/netip"
|
|
"os"
|
|
"strings"
|
|
"sync"
|
|
"time"
|
|
|
|
"alice-back/station/pcaudio"
|
|
)
|
|
|
|
const pcAudioConfigPath = "/data/opt/alice-backend/pc-audio.json"
|
|
const pcAudioLease = 5 * time.Second
|
|
|
|
var windowsAudio *pcAudioControl
|
|
|
|
type pcAudioControl struct {
|
|
mu sync.Mutex
|
|
token string
|
|
peer netip.Addr
|
|
desired pcaudio.Command
|
|
actual pcaudio.State
|
|
last time.Time
|
|
}
|
|
|
|
func loadPCControl() {
|
|
data, err := os.ReadFile(pcAudioConfigPath)
|
|
if os.IsNotExist(err) {
|
|
return
|
|
}
|
|
if err != nil {
|
|
log.Printf("PC audio configuration: %v", err)
|
|
return
|
|
}
|
|
var config struct{ Listen, Peer, Token string }
|
|
if json.Unmarshal(data, &config) != nil || len(config.Token) != 64 {
|
|
log.Print("Invalid PC audio configuration")
|
|
return
|
|
}
|
|
local, localErr := netip.ParseAddrPort(config.Listen)
|
|
peer, peerErr := netip.ParseAddr(config.Peer)
|
|
if localErr != nil || peerErr != nil || !local.Addr().Is4() || local.Addr().IsUnspecified() || local.Port() == 0 || !peer.Is4() {
|
|
log.Print("Invalid addresses for PC audio control")
|
|
return
|
|
}
|
|
listener, err := net.Listen("tcp4", local.String())
|
|
if err != nil {
|
|
log.Printf("PC audio control: %v", err)
|
|
return
|
|
}
|
|
windowsAudio = &pcAudioControl{token: config.Token, peer: peer, desired: newPCCommand(false)}
|
|
server := &http.Server{Handler: windowsAudio, ReadTimeout: 2 * time.Second, WriteTimeout: 2 * time.Second, MaxHeaderBytes: 4096}
|
|
go func() {
|
|
if err := server.Serve(listener); err != nil {
|
|
log.Printf("PC audio control: %v", err)
|
|
}
|
|
}()
|
|
log.Printf("PC audio control listening on %s", listener.Addr())
|
|
}
|
|
|
|
func newPCCommand(enabled bool) pcaudio.Command {
|
|
var id [16]byte
|
|
if _, err := rand.Read(id[:]); err != nil {
|
|
panic(err)
|
|
}
|
|
return pcaudio.Command{Revision: hex.EncodeToString(id[:]), Enabled: enabled}
|
|
}
|
|
|
|
func (c *pcAudioControl) expire(now time.Time) {
|
|
if c.desired.Enabled && now.Sub(c.last) >= pcAudioLease {
|
|
c.desired = newPCCommand(false)
|
|
}
|
|
}
|
|
|
|
func (c *pcAudioControl) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
|
if r.Method != http.MethodPost || r.URL.Path != pcaudio.Path {
|
|
http.NotFound(w, r)
|
|
return
|
|
}
|
|
remote, err := netip.ParseAddrPort(r.RemoteAddr)
|
|
token, bearer := strings.CutPrefix(r.Header.Get("Authorization"), "Bearer ")
|
|
if err != nil || !bearer || remote.Addr().Unmap() != c.peer || subtle.ConstantTimeCompare([]byte(token), []byte(c.token)) != 1 {
|
|
http.Error(w, "forbidden", http.StatusForbidden)
|
|
return
|
|
}
|
|
var state pcaudio.State
|
|
if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, 1024)).Decode(&state); err != nil {
|
|
http.Error(w, "invalid state", http.StatusBadRequest)
|
|
return
|
|
}
|
|
c.mu.Lock()
|
|
now := time.Now()
|
|
c.expire(now)
|
|
c.last = now
|
|
c.actual = state
|
|
desired := c.desired
|
|
c.mu.Unlock()
|
|
w.Header().Set("Content-Type", "application/json")
|
|
_ = json.NewEncoder(w).Encode(desired)
|
|
}
|
|
|
|
func (c *pcAudioControl) run(ctx context.Context, action string) json.RawMessage {
|
|
c.mu.Lock()
|
|
now := time.Now()
|
|
c.expire(now)
|
|
if action == "stop" && c.desired.Enabled {
|
|
c.desired = newPCCommand(false)
|
|
}
|
|
if now.Sub(c.last) >= pcAudioLease {
|
|
c.mu.Unlock()
|
|
return json.RawMessage(`{"error":"pc_agent_offline","hint":"Запусти агент Алисы на компьютере Windows."}`)
|
|
}
|
|
if action == "status" {
|
|
data, _ := json.Marshal(map[string]any{"ok": true, "enabled": c.actual.Enabled, "error": c.actual.Error})
|
|
c.mu.Unlock()
|
|
return data
|
|
}
|
|
if c.desired.Enabled != (action == "start") || c.actual.Error != "" {
|
|
c.desired = newPCCommand(action == "start")
|
|
}
|
|
command := c.desired
|
|
c.mu.Unlock()
|
|
|
|
ctx, cancel := context.WithTimeout(ctx, 5*time.Second)
|
|
defer cancel()
|
|
ticker := time.NewTicker(100 * time.Millisecond)
|
|
defer ticker.Stop()
|
|
for {
|
|
c.mu.Lock()
|
|
current, actual := c.desired, c.actual
|
|
c.mu.Unlock()
|
|
if current != command {
|
|
return json.RawMessage(`{"error":"pc_audio_command_replaced"}`)
|
|
}
|
|
if actual.Revision == command.Revision {
|
|
if actual.Error != "" || actual.Enabled != command.Enabled {
|
|
c.mu.Lock()
|
|
if command.Enabled && c.desired == command {
|
|
c.desired = newPCCommand(false)
|
|
}
|
|
c.mu.Unlock()
|
|
return json.RawMessage(`{"error":"pc_audio_sender_failed"}`)
|
|
}
|
|
data, _ := json.Marshal(map[string]any{"ok": true, "enabled": actual.Enabled})
|
|
return data
|
|
}
|
|
select {
|
|
case <-ctx.Done():
|
|
c.mu.Lock()
|
|
if command.Enabled && c.desired == command {
|
|
c.desired = newPCCommand(false)
|
|
}
|
|
c.mu.Unlock()
|
|
return json.RawMessage(`{"error":"pc_audio_timeout"}`)
|
|
case <-ticker.C:
|
|
}
|
|
}
|
|
}
|
|
|
|
func pcAudioTool(ctx context.Context, arguments json.RawMessage) json.RawMessage {
|
|
var args struct{ Action string }
|
|
if json.Unmarshal(arguments, &args) != nil || (args.Action != "start" && args.Action != "stop" && args.Action != "status") {
|
|
return json.RawMessage(`{"error":"invalid_pc_audio_action"}`)
|
|
}
|
|
if windowsAudio == nil {
|
|
return json.RawMessage(`{"error":"pc_audio_unconfigured"}`)
|
|
}
|
|
return windowsAudio.run(ctx, args.Action)
|
|
}
|