Room defaults and personal relay limits now use the existing route controller. Hosts can set the room default; viewers can follow it or select a lower or higher personal limit, including zero. Lowering a limit uses the existing handoff, and retired connection attempts no longer consume a later viewer's opportunity. The candidate also preserves native sharing when its local preview fails, prefers a preview-compatible codec in Auto mode when the App supports it, and improves terminal shutdown, input failure feedback and attached-menu positioning. Validation: Web type checks, 1,936 frontend tests and the production Web build pass. Server, routing, Native host and media-edge tests and vet pass. Real three-viewer browser checks cover default/override synchronization, receive-only, signaling reconnect, downscaling to a chain and automatic recovery after increasing an exhausted route's limit. Narrow-screen, theme and visual-mode control previews were inspected. Current field investigations remain open: the niri-specific capture failure (#499), the Windows input-refusal trigger (#502), the UU title-only load report and the older capture/source-cadence reports. These are not claimed fixed by this release. ## Release notes **Piik, now in your pocket.** Piik App supports Android screen sharing, with touch controls for a friend's computer. **手机,也能开播。** Piik App 支持 Android 屏幕分享,也能用手机控制朋友的电脑。 ### English - Set a room-wide default relay limit. Viewers can follow it or set their own higher or lower limit; zero receives without forwarding. Limits still follow each device's capability, and route selection remains automatic. - Improve connection recovery when viewers join during route preparation or a peer connection is rebuilt. Canceled connection attempts no longer prevent later retries, and rebuilt routes require fresh media before showing as ready. - Keep native sharing active when the host's local preview cannot play. Automatic selection prefers a codec the browser can preview when the App supports it, and restoring a preview preserves its playback state. - Improve App shutdown when its terminal closes and complete macOS permission descriptions. - Retain useful remote-input failure feedback while pending key releases clear. Fix attached-menu scroll jumps, invisible tooltips intercepting clicks and volume guidance when source sound is unavailable. This update preserves the existing 2.x compatibility baseline. The new relay settings require an updated site; older pages retain their previous relay behavior. ### 中文 - 房主可以设置房间默认转发上限。观众可跟随默认,也可自行调高或调低;设为 0 时只接收、不转发。实际额度仍受设备能力约束,线路继续自动安排。 - 改善观众在建立线路期间加入,以及连接重建后的恢复。取消连接尝试后,后续连接仍可正常重试;重建后的线路收到新画面才会显示就绪。 - 房主本地预览无法播放时,原生分享继续。App 支持时,自动选择优先采用浏览器可预览的编码,恢复预览时保留原有播放状态。 - 改善终端关闭时 App 的退出流程,补齐 macOS 权限用途说明。 - 释放待处理按键期间保留远控失败提示;修复附属菜单导致的滚动跳动、不可见提示拦截点击,以及没有分享声音时的音量说明。 本次更新保持现有 2.x 兼容约定。新的转发设置需要更新站点,旧页面保留原有转发行为。
257 lines
8.4 KiB
Go
257 lines
8.4 KiB
Go
// Command piik-server is the Hosted Piik entry point: it loads the
|
|
// environment, serves the embedded Browser UI together with the signaling and
|
|
// room API, and performs ordered process shutdown.
|
|
//
|
|
// Two maintenance modes exit without serving: --check-config validates the
|
|
// environment (the release wrapper runs it as the service user before cutover)
|
|
// and --check-release compares this binary with the latest published
|
|
// release (see release.go).
|
|
package main
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"flag"
|
|
"fmt"
|
|
"io/fs"
|
|
"log"
|
|
"log/slog"
|
|
"os"
|
|
"path/filepath"
|
|
"strings"
|
|
"time"
|
|
|
|
"github.com/TNTcraftHIM/Piik/internal/diagnostics"
|
|
"github.com/TNTcraftHIM/Piik/internal/processsignal"
|
|
"github.com/TNTcraftHIM/Piik/internal/server/app"
|
|
"github.com/TNTcraftHIM/Piik/internal/server/config"
|
|
"github.com/TNTcraftHIM/Piik/internal/server/webassets"
|
|
"github.com/TNTcraftHIM/Piik/internal/tlsconfig"
|
|
)
|
|
|
|
// shutdownTimeout bounds the ordered stop (signaling, listener, room store).
|
|
// systemd's tracked TimeoutStopSec is 20s, so the process must be gone first.
|
|
const shutdownTimeout = 15 * time.Second
|
|
|
|
// environmentFile is read from the working directory, which systemd pins to the
|
|
// release directory. Hosted keeps its real values in the service secret store.
|
|
const environmentFile = ".env"
|
|
|
|
// The packager injects the product version and full source revision together.
|
|
var (
|
|
BuildVersion = "development"
|
|
BuildRevision = "development"
|
|
)
|
|
|
|
func main() {
|
|
checkConfig := flag.Bool("check-config", false, "validate the environment and exit")
|
|
checkRelease := flag.Bool("check-release", false,
|
|
"report whether a newer published release exists and exit")
|
|
apiURL := flag.String("api-url", defaultReleaseAPIURL,
|
|
"release metadata endpoint used by --check-release")
|
|
debug := flag.Bool("debug", false, "save opt-in server diagnostics to rotated files")
|
|
flag.Parse()
|
|
|
|
if err := loadEnvironmentFile(environmentFile); err != nil {
|
|
fail(err)
|
|
}
|
|
switch {
|
|
case *checkRelease:
|
|
os.Exit(checkDeployedRelease(context.Background(), *apiURL, os.Stdout))
|
|
case *checkConfig:
|
|
if _, err := config.Load(environment()); err != nil {
|
|
fail(err)
|
|
}
|
|
fmt.Println("config=ok")
|
|
default:
|
|
if err := serve(*debug); err != nil {
|
|
fail(err)
|
|
}
|
|
}
|
|
}
|
|
|
|
func fail(err error) {
|
|
fmt.Fprintln(os.Stderr, err)
|
|
os.Exit(1)
|
|
}
|
|
|
|
// serve runs the application until the first SIGINT or SIGTERM, then stops it
|
|
// with Close rather than End: durable room authority survives a restart.
|
|
func serve(debug bool) (returnedErr error) {
|
|
logger := slog.New(slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{ReplaceAttr: diagnostics.ReplaceAttr}))
|
|
var recorder *diagnostics.Recorder
|
|
if debug || serverDebugEnabled(os.Getenv("PIIK_DEBUG")) {
|
|
var err error
|
|
recorder, err = diagnostics.Open(serverLogDirectory(), "server", BuildRevision)
|
|
if err != nil {
|
|
return fmt.Errorf("Piik server diagnostics are unavailable: %w", err)
|
|
}
|
|
logger = slog.New(slog.NewMultiHandler(logger.Handler(), recorder.Logger().Handler()))
|
|
previous, previousWriter, previousFlags := slog.Default(), log.Writer(), log.Flags()
|
|
slog.SetDefault(logger)
|
|
dependencyLog := diagnostics.Writer("stdlib")
|
|
log.SetOutput(dependencyLog)
|
|
log.SetFlags(previousFlags)
|
|
fmt.Fprintln(os.Stderr, "Piik diagnostic log:", recorder.LogPath())
|
|
stopExport := watchDiagnosticExport(recorder)
|
|
defer func() {
|
|
stopExport()
|
|
_ = dependencyLog.Close()
|
|
returnedErr = errors.Join(returnedErr, exportServerDiagnostics(recorder), recorder.Close())
|
|
slog.SetDefault(previous)
|
|
log.SetOutput(previousWriter)
|
|
log.SetFlags(previousFlags)
|
|
}()
|
|
logger.Info("piik-server", "event", "start", "version", BuildVersion, "revision", BuildRevision)
|
|
}
|
|
defer func() {
|
|
logger.Info("piik-server", "event", "stopped", "failed", returnedErr != nil, diagnostics.Error(returnedErr))
|
|
}()
|
|
configuration, err := config.Load(environment())
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if recorder != nil {
|
|
recorder.Context("configuration", map[string]any{
|
|
"environment": configuration.Env, "port": configuration.Port,
|
|
"sqlite": configuration.RoomDatabasePath != "", "siteAccessProtected": configuration.SiteAccessPassword != "",
|
|
"maxViewers": configuration.MaxViewersPerRoom, "endpointCapacity": configuration.EndpointMediaCopyCapacity,
|
|
"sfu": configuration.SFU, "stunURLs": configuration.STUNURLs,
|
|
"natPrediction": configuration.NATPredictionEnabled,
|
|
})
|
|
}
|
|
server, err := app.New(app.Options{
|
|
Config: configuration,
|
|
Assets: webassets.FS(),
|
|
Logger: logger,
|
|
})
|
|
if err != nil {
|
|
return err
|
|
}
|
|
// Install ordered shutdown after startup; a stop during startup retains the
|
|
// operating system's default signal handling.
|
|
port, err := server.Listen(context.Background())
|
|
if err != nil {
|
|
return err
|
|
}
|
|
logger.Info("Piik server is listening", "event", "ready", "version", BuildVersion, "revision", BuildRevision,
|
|
"host", configuration.ListenHost, "port", port, "publicUrl", config.Origin(configuration.PublicBaseURL),
|
|
"sqlite", configuration.RoomDatabasePath != "", "siteAccessProtected", configuration.SiteAccessPassword != "",
|
|
"sfu", configuration.SFU != nil, "natPrediction", configuration.NATPredictionEnabled)
|
|
if configuration.TLS != nil {
|
|
logger.Info("HTTPS certificate", "sha256", tlsconfig.Fingerprint(configuration.TLS))
|
|
}
|
|
|
|
ctx, stop := processsignal.NotifyContext(context.Background())
|
|
// One bounded background lookup never delays serving. Join it before closing
|
|
// diagnostic outputs so shutdown cannot leave a late writer behind.
|
|
releaseChecked := make(chan struct{})
|
|
go func() {
|
|
defer close(releaseChecked)
|
|
result := checkRelease(ctx, BuildVersion, BuildRevision, defaultReleaseAPIURL, os.Getenv("GITHUB_TOKEN"), mirrorReleaseAPIURL)
|
|
if ctx.Err() == nil {
|
|
logReleaseNotice(logger, result)
|
|
}
|
|
}()
|
|
defer func() {
|
|
stop()
|
|
<-releaseChecked
|
|
}()
|
|
var serveErr error
|
|
select {
|
|
case <-ctx.Done():
|
|
case serveErr = <-server.Done():
|
|
}
|
|
shutdownCtx, cancel := context.WithTimeout(context.Background(), shutdownTimeout)
|
|
defer cancel()
|
|
return errors.Join(serveErr, server.Close(shutdownCtx))
|
|
}
|
|
|
|
func serverDebugEnabled(value string) bool {
|
|
for _, component := range strings.Split(value, ",") {
|
|
switch strings.TrimSpace(component) {
|
|
case "server", "route":
|
|
return true
|
|
}
|
|
}
|
|
return false
|
|
}
|
|
|
|
func serverLogDirectory() string {
|
|
if directory := strings.TrimSpace(os.Getenv("PIIK_LOG_DIR")); directory != "" {
|
|
return directory
|
|
}
|
|
if directories := filepath.SplitList(os.Getenv("LOGS_DIRECTORY")); len(directories) > 0 && directories[0] != "" {
|
|
return directories[0]
|
|
}
|
|
return "logs"
|
|
}
|
|
|
|
func exportServerDiagnostics(recorder *diagnostics.Recorder) error {
|
|
path, err := recorder.Export()
|
|
if err != nil {
|
|
fmt.Fprintln(os.Stderr, "Piik diagnostic export failed:", err)
|
|
return err
|
|
}
|
|
fmt.Fprintln(os.Stderr, "Piik diagnostic bundle:", path)
|
|
return nil
|
|
}
|
|
|
|
// environment is the process environment in the form config.Load expects.
|
|
func environment() map[string]string {
|
|
values := make(map[string]string)
|
|
for _, entry := range os.Environ() {
|
|
if name, value, found := strings.Cut(entry, "="); found {
|
|
values[name] = value
|
|
}
|
|
}
|
|
return values
|
|
}
|
|
|
|
// loadEnvironmentFile reads optional startup overrides. An absent file is the
|
|
// ordinary case and every other read failure stops startup. A name the process
|
|
// already carries is never overwritten, so a
|
|
// systemd EnvironmentFile still wins over a stale file in the release
|
|
// directory. The accepted syntax is DECISIONS D8: KEY=value lines, whole-line
|
|
// '#' comments, an optional 'export ' prefix, and a single- or double-quoted
|
|
// value. Quoted values keep their content verbatim; nothing is expanded.
|
|
func loadEnvironmentFile(name string) error {
|
|
content, err := os.ReadFile(name)
|
|
if errors.Is(err, fs.ErrNotExist) {
|
|
return nil
|
|
}
|
|
if err != nil {
|
|
return err
|
|
}
|
|
for _, line := range strings.Split(string(content), "\n") {
|
|
line = strings.TrimSpace(line)
|
|
line = strings.TrimSpace(strings.TrimPrefix(line, "export "))
|
|
if line == "" || strings.HasPrefix(line, "#") {
|
|
continue
|
|
}
|
|
key, value, assigned := strings.Cut(line, "=")
|
|
key = strings.TrimSpace(key)
|
|
if !assigned || key == "" {
|
|
continue
|
|
}
|
|
if _, present := os.LookupEnv(key); present {
|
|
continue
|
|
}
|
|
if err := os.Setenv(key, unquote(strings.TrimSpace(value))); err != nil {
|
|
return err
|
|
}
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// unquote removes one matching pair of surrounding single or double quotes.
|
|
func unquote(value string) string {
|
|
if len(value) < 2 || value[0] != value[len(value)-1] {
|
|
return value
|
|
}
|
|
if value[0] != '"' && value[0] != '\'' {
|
|
return value
|
|
}
|
|
return value[1 : len(value)-1]
|
|
}
|