Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add ability to control playback using command-line flags #403

Merged
merged 9 commits into from
Jun 13, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
142 changes: 74 additions & 68 deletions backend/app.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,25 +12,22 @@ import (
"slices"
"time"

"github.com/dweymouth/supersonic/backend/ipc"
"github.com/dweymouth/supersonic/backend/mediaprovider"
"github.com/dweymouth/supersonic/backend/player"
"github.com/dweymouth/supersonic/backend/player/mpv"
"github.com/dweymouth/supersonic/backend/util"
"github.com/fsnotify/fsnotify"
"github.com/google/uuid"

"github.com/20after4/configdir"
"github.com/zalando/go-keyring"
)

const (
configFile = "config.toml"
portableDir = "supersonic_portable"
sessionDir = "session"
sessionLockFile = ".lock"
sessionActivateFile = ".activate"
savedQueueFile = "saved_queue.json"
themesDir = "themes"
configFile = "config.toml"
portableDir = "supersonic_portable"
savedQueueFile = "saved_queue.json"
themesDir = "themes"
)

var (
Expand All @@ -46,6 +43,7 @@ type App struct {
LocalPlayer *mpv.Player
UpdateChecker UpdateChecker
MPRISHandler *MPRISHandler
ipcServer ipc.IPCServer

// UI callbacks to be set in main
OnReactivate func()
Expand Down Expand Up @@ -83,26 +81,6 @@ func StartupApp(appName, displayAppName, appVersionTag, latestReleaseURL string)
configdir.MakePath(confDir)
configdir.MakePath(cacheDir)

sessionPath := path.Join(confDir, sessionDir)
if _, err := os.Stat(path.Join(sessionPath, sessionLockFile)); err == nil {
log.Println("Another instance is running. Reactivating it...")
reactivateFile := path.Join(sessionPath, sessionActivateFile)
if f, err := os.Create(reactivateFile); err == nil {
f.Close()
}
time.Sleep(750 * time.Millisecond)
if _, err := os.Stat(reactivateFile); err == nil {
log.Println("No other instance responded. Starting as normal...")
os.RemoveAll(sessionPath)
} else {
return nil, ErrAnotherInstance
}
}

log.Printf("Starting %s...", appName)
log.Printf("Using config dir: %s", confDir)
log.Printf("Using cache dir: %s", cacheDir)

a := &App{
appName: appName,
appVersionTag: appVersionTag,
Expand All @@ -112,19 +90,24 @@ func StartupApp(appName, displayAppName, appVersionTag, latestReleaseURL string)
}
a.bgrndCtx, a.cancel = context.WithCancel(context.Background())
a.readConfig()
a.startConfigWriter(a.bgrndCtx)

if !a.Config.Application.AllowMultiInstance {
log.Println("Creating session lock file")
os.MkdirAll(sessionPath, 0770)
if f, err := os.Create(path.Join(sessionPath, sessionLockFile)); err == nil {
f.Close()
} else {
log.Printf("error creating session file: %s", err.Error())
cli, _ := ipc.Connect()
if HaveCommandLineOptions() {
if err := a.checkFlagsAndSendIPCMsg(cli); err != nil {
// we were supposed to control another instance and couldn't
log.Fatalf("error sending IPC message: %s", err.Error())
}
a.startSessionWatcher(sessionPath)
return nil, ErrAnotherInstance
} else if cli != nil && !a.Config.Application.AllowMultiInstance {
log.Println("Another instance is running. Reactivating it...")
cli.Show()
return nil, ErrAnotherInstance
}

log.Printf("Starting %s...", appName)
log.Printf("Using config dir: %s", confDir)
log.Printf("Using cache dir: %s", cacheDir)

a.UpdateChecker = NewUpdateChecker(appVersionTag, latestReleaseURL, &a.Config.Application.LastCheckedVersion)
a.UpdateChecker.Start(a.bgrndCtx, 24*time.Hour)

Expand All @@ -144,13 +127,28 @@ func StartupApp(appName, displayAppName, appVersionTag, latestReleaseURL string)
_, _ = a.ImageManager.GetCoverThumbnail(coverID)
})

// Start IPC server if another not already running in a different instance
if cli == nil {
ipc.DestroyConn() // cleanup socket possibly orphaned by crashed process
listener, err := ipc.Listen()
if err == nil {
a.ipcServer = ipc.NewServer(a.PlaybackManager, a.callOnReactivate,
func() { _ = a.callOnExit() })
go a.ipcServer.Serve(listener)
} else {
log.Printf("error starting IPC server: %s", err.Error())
}
}

// OS media center integrations
a.setupMPRIS(displayAppName)
InitMPMediaHandler(a.PlaybackManager, func(id string) (string, error) {
a.ImageManager.GetCoverThumbnail(id) // ensure image is cached locally
return a.ImageManager.GetCoverArtUrl(id)
})

a.startConfigWriter(a.bgrndCtx)

return a, nil
}

Expand Down Expand Up @@ -196,26 +194,6 @@ func (a *App) readConfig() {
a.Config = cfg
}

func (a *App) startSessionWatcher(sessionPath string) {
if sessionWatch, err := fsnotify.NewWatcher(); err == nil {
sessionWatch.Add(sessionPath)
go func() {
for {
select {
case <-a.bgrndCtx.Done():
return
case <-sessionWatch.Events:
activatePath := path.Join(sessionPath, sessionActivateFile)
if _, err := os.Stat(activatePath); err == nil {
os.Remove(path.Join(sessionPath, sessionActivateFile))
a.callOnReactivate()
}
}
}
}()
}
}

// periodically save config file so abnormal exit won't lose settings
func (a *App) startConfigWriter(ctx context.Context) {
tick := time.NewTicker(2 * time.Minute)
Expand All @@ -239,6 +217,17 @@ func (a *App) callOnReactivate() {
}
}

func (a *App) callOnExit() error {
if a.OnExit == nil {
return errors.New("no quit handler registered")
}
go func() {
time.Sleep(10 * time.Millisecond)
a.OnExit()
}()
return nil
}

func (a *App) initMPV() error {
p := mpv.NewWithClientName(a.appName)
c := a.Config.LocalPlayback
Expand Down Expand Up @@ -314,16 +303,7 @@ func (a *App) setupMPRIS(mprisAppName string) {
return a.ImageManager.GetCoverArtUrl(id)
}
a.MPRISHandler.OnRaise = func() error { a.callOnReactivate(); return nil }
a.MPRISHandler.OnQuit = func() error {
if a.OnExit == nil {
return errors.New("no quit handler registered")
}
go func() {
time.Sleep(10 * time.Millisecond)
a.OnExit()
}()
return nil
}
a.MPRISHandler.OnQuit = a.callOnExit
a.MPRISHandler.Start()
}

Expand All @@ -346,6 +326,9 @@ func (a *App) DeleteServerCacheDir(serverID uuid.UUID) error {
}

func (a *App) Shutdown() {
if a.ipcServer != nil {
a.ipcServer.Shutdown(a.bgrndCtx)
}
a.MPRISHandler.Shutdown()
a.PlaybackManager.DisableCallbacks()
if a.Config.Application.SavePlayQueue {
Expand All @@ -362,7 +345,6 @@ func (a *App) Shutdown() {
a.cancel()
a.LocalPlayer.Destroy()
a.Config.WriteConfigFile(a.configFilePath())
os.RemoveAll(path.Join(a.configDir, sessionDir))
}

func (a *App) LoadSavedPlayQueue() error {
Expand Down Expand Up @@ -397,6 +379,30 @@ func (a *App) SaveConfigFile() {
a.lastWrittenCfg = *a.Config
}

func (a *App) checkFlagsAndSendIPCMsg(cli *ipc.Client) error {
if cli == nil {
return errors.New("no IPC connection")
}
switch {
case *FlagPlay:
return cli.Play()
case *FlagPause:
return cli.Pause()
case *FlagPlayPause:
return cli.PlayPause()
case *FlagPrevious:
return cli.SeekBackOrPrevious()
case *FlagNext:
return cli.SeekNext()
case VolumeCLIArg >= 0:
return cli.SetVolume(VolumeCLIArg)
case SeekToCLIArg >= 0:
return cli.SeekSeconds(SeekToCLIArg)
default:
return nil
}
}

func (a *App) configFilePath() string {
return path.Join(a.configDir, configFile)
}
Expand Down
41 changes: 41 additions & 0 deletions backend/cmdlineoptions.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
package backend

import (
"flag"
"strconv"
)

var (
VolumeCLIArg int = -1
SeekToCLIArg float64 = -1

FlagPlay = flag.Bool("play", false, "unpause or begin playback")
FlagPause = flag.Bool("pause", false, "pause playback")
FlagPlayPause = flag.Bool("play-pause", false, "toggle play/pause state")
FlagPrevious = flag.Bool("previous", false, "seek to previous track or beginning of current")
FlagNext = flag.Bool("next", false, "seek to next track")
FlagVersion = flag.Bool("version", false, "print app version and exit")
FlagHelp = flag.Bool("help", false, "print command line options and exit")
)

func init() {
flag.Func("volume", "sets the playback volume (0-100)", func(s string) error {
v, err := strconv.Atoi(s)
VolumeCLIArg = v
return err
})

flag.Func("seek-to", "seeks to the given position in seconds in the current file (0.0 - <trackDur>)", func(s string) error {
v, err := strconv.ParseFloat(s, 64)
SeekToCLIArg = v
return err
})
}

func HaveCommandLineOptions() bool {
visitedAny := false
flag.Visit(func(*flag.Flag) {
visitedAny = true
})
return visitedAny
}
29 changes: 29 additions & 0 deletions backend/ipc/api.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
package ipc

import "fmt"

const (
PingPath = "/ping"
PlayPath = "/transport/play"
PlayPausePath = "/transport/playpause"
PausePath = "/transport/pause"
StopPath = "/transport/stop"
PreviousPath = "/transport/previous"
NextPath = "/transport/next"
TimePosPath = "/transport/timepos" // ?s=<seconds>
VolumePath = "/volume" // ?v=<vol>
ShowPath = "/window/show"
QuitPath = "/window/quit"
)

type Response struct {
Error string `json:"error"`
}

func SetVolumePath(vol int) string {
return fmt.Sprintf("%s?v=%d", VolumePath, vol)
}

func SeekToSecondsPath(secs float64) string {
return fmt.Sprintf("%s?s=%0.2f", TimePosPath, secs)
}
Loading
Loading