arcast/internal/command/player/run.go

100 lines
2.4 KiB
Go
Raw Permalink Normal View History

2023-12-13 20:07:22 +01:00
package player
import (
"fmt"
"os"
"forge.cadoles.com/arcad/arcast/pkg/browser/lorca"
"forge.cadoles.com/arcad/arcast/pkg/server"
"github.com/pkg/errors"
"github.com/urfave/cli/v2"
"gitlab.com/wpetit/goweb/logger"
)
func Run() *cli.Command {
defaults := lorca.NewOptions()
return &cli.Command{
Name: "run",
Flags: []cli.Flag{
&cli.StringSliceFlag{
Name: "additional-chrome-arg",
EnvVars: []string{"ARCAST_DESKTOP_ADDITIONAL_CHROME_ARGS"},
Value: cli.NewStringSlice("incognito"),
},
&cli.StringFlag{
Name: "instance-id",
EnvVars: []string{"ARCAST_DESKTOP_INSTANCE_ID"},
Value: "",
},
2023-12-13 20:07:22 +01:00
&cli.IntFlag{
Name: "window-height",
EnvVars: []string{"ARCAST_DESKTOP_WINDOW_HEIGHT"},
Value: defaults.Height,
2023-12-13 20:07:22 +01:00
},
&cli.IntFlag{
Name: "window-width",
EnvVars: []string{"ARCAST_DESKTOP_WINDOW_WIDTH"},
Value: defaults.Width,
2023-12-13 20:07:22 +01:00
},
},
Action: func(ctx *cli.Context) error {
windowHeight := ctx.Int("window-height")
windowWidth := ctx.Int("window-width")
chromeArgs := addFlagsPrefix(ctx.StringSlice("additional-chrome-arg")...)
browser := lorca.NewBrowser(
lorca.WithAdditionalChromeArgs(chromeArgs...),
lorca.WithWindowSize(windowWidth, windowHeight),
)
if err := browser.Start(); err != nil {
return errors.Wrap(err, "could not start browser")
}
go func() {
browser.Wait()
logger.Warn(ctx.Context, "browser was closed")
os.Exit(1)
}()
defer func() {
logger.Info(ctx.Context, "stopping browser")
if err := browser.Stop(); err != nil {
logger.Error(ctx.Context, "could not stop browser", logger.CapturedE(errors.WithStack(err)))
}
}()
instanceID := ctx.String("instance-id")
if instanceID == "" {
instanceID = server.NewRandomInstanceID()
}
server := server.New(browser, server.WithInstanceID(instanceID))
2023-12-13 20:07:22 +01:00
if err := server.Start(); err != nil {
return errors.Wrap(err, "could not start server")
}
defer func() {
if err := server.Stop(); err != nil {
logger.Error(ctx.Context, "could not stop server", logger.CapturedE(errors.WithStack(err)))
}
}()
if err := server.Wait(); err != nil {
return errors.Wrap(err, "could not wait for server")
}
return nil
},
}
}
func addFlagsPrefix(stripped ...string) []string {
flags := make([]string, len(stripped))
for i, s := range stripped {
flags[i] = fmt.Sprintf("--%s", s)
}
return flags
}