- Flutter 桌面端通过 dart:ffi 调用 Rust Core cdylib - 实现 ECDH P-256 密钥协商、HKDF 子密钥派生、AES-256-GCM 控制帧 - Android 被控端用派生密钥做控制帧加密与媒体包 MAC - 新增 libopus JNI 骨架,默认回退 MediaCodec - 新增 aosp/zhanxun/neutral 签名变体与系统 sharedUserId - 本机独立信令服务与设置页开关 - 新增 .gitignore 排除所有编译产物与打包目录
102 lines
1.9 KiB
Go
102 lines
1.9 KiB
Go
package relay
|
|
|
|
import (
|
|
"encoding/json"
|
|
"errors"
|
|
"sync"
|
|
"time"
|
|
)
|
|
|
|
type Message struct {
|
|
From string `json:"from"`
|
|
To string `json:"to"`
|
|
Payload json.RawMessage `json:"payload"`
|
|
CreatedAt time.Time `json:"createdAt"`
|
|
}
|
|
|
|
type Relay struct {
|
|
mu sync.Mutex
|
|
queues map[string][]Message
|
|
max int
|
|
expiry time.Duration
|
|
now func() time.Time
|
|
}
|
|
|
|
func New() *Relay {
|
|
return &Relay{
|
|
queues: make(map[string][]Message),
|
|
max: 256,
|
|
expiry: 5 * time.Minute,
|
|
now: time.Now,
|
|
}
|
|
}
|
|
|
|
func (r *Relay) Send(from, to string, payload json.RawMessage) error {
|
|
if to == "" {
|
|
return errors.New("目标设备不能为空")
|
|
}
|
|
if len(payload) == 0 || string(payload) == "null" {
|
|
return errors.New("中转内容不能为空")
|
|
}
|
|
message := Message{
|
|
From: from,
|
|
To: to,
|
|
Payload: append(json.RawMessage(nil), payload...),
|
|
CreatedAt: r.now(),
|
|
}
|
|
|
|
r.mu.Lock()
|
|
defer r.mu.Unlock()
|
|
r.pruneLocked(to)
|
|
queue := append(r.queues[to], message)
|
|
if len(queue) > r.max {
|
|
queue = queue[len(queue)-r.max:]
|
|
}
|
|
r.queues[to] = queue
|
|
return nil
|
|
}
|
|
|
|
func (r *Relay) Poll(to string, limit int) []Message {
|
|
if limit <= 0 || limit > 100 {
|
|
limit = 20
|
|
}
|
|
r.mu.Lock()
|
|
defer r.mu.Unlock()
|
|
r.pruneLocked(to)
|
|
queue := r.queues[to]
|
|
if len(queue) == 0 {
|
|
return []Message{}
|
|
}
|
|
if len(queue) > limit {
|
|
queue = queue[:limit]
|
|
}
|
|
messages := append([]Message(nil), queue...)
|
|
r.queues[to] = r.queues[to][len(messages):]
|
|
return messages
|
|
}
|
|
|
|
func (r *Relay) Size(to string) int {
|
|
r.mu.Lock()
|
|
defer r.mu.Unlock()
|
|
r.pruneLocked(to)
|
|
return len(r.queues[to])
|
|
}
|
|
|
|
func (r *Relay) pruneLocked(to string) {
|
|
queue := r.queues[to]
|
|
if len(queue) == 0 {
|
|
return
|
|
}
|
|
kept := queue[:0]
|
|
for _, message := range queue {
|
|
if r.now().Sub(message.CreatedAt) <= r.expiry {
|
|
kept = append(kept, message)
|
|
}
|
|
}
|
|
if len(kept) == 0 {
|
|
delete(r.queues, to)
|
|
} else {
|
|
r.queues[to] = kept
|
|
}
|
|
}
|