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

Start browser on server start #1832

Merged
Merged
Show file tree
Hide file tree
Changes from 7 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
1 change: 1 addition & 0 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ require (
github.com/json-iterator/go v1.1.9
github.com/mattn/go-sqlite3 v1.14.6
github.com/natefinch/pie v0.0.0-20170715172608-9a0d72014007
github.com/pkg/browser v0.0.0-20210911075715-681adbf594b8
github.com/remeh/sizedwaitgroup v1.0.0
github.com/robertkrimen/otto v0.0.0-20200922221731-ef014fd054ac
github.com/rs/cors v1.6.0
Expand Down
3 changes: 3 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -554,6 +554,8 @@ github.com/pierrec/lz4/v4 v4.1.4/go.mod h1:gZWDp/Ze/IJXGXf23ltt2EXimqmTUXEy0GFuR
github.com/pierrec/lz4/v4 v4.1.7/go.mod h1:gZWDp/Ze/IJXGXf23ltt2EXimqmTUXEy0GFuRQyBid4=
github.com/pkg/browser v0.0.0-20180916011732-0a3d74bf9ce4/go.mod h1:4OwLy04Bl9Ef3GJJCoec+30X3LQs/0/m4HFRt/2LUSA=
github.com/pkg/browser v0.0.0-20210115035449-ce105d075bb4/go.mod h1:N6UoU20jOqggOuDwUaBQpluzLNDqif3kq9z2wpdYEfQ=
github.com/pkg/browser v0.0.0-20210911075715-681adbf594b8 h1:KoWmjvw+nsYOo29YJK9vDA65RGE3NrOnUtO7a+RF9HU=
github.com/pkg/browser v0.0.0-20210911075715-681adbf594b8/go.mod h1:HKlIX3XHQyzLZPlr7++PzdhaXEj94dEiJgZDTsxEqUI=
github.com/pkg/errors v0.8.0/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
github.com/pkg/errors v0.8.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4=
Expand Down Expand Up @@ -901,6 +903,7 @@ golang.org/x/sys v0.0.0-20210423082822-04245dca01da/go.mod h1:h1NjWce9XRLGQEsW7w
golang.org/x/sys v0.0.0-20210521090106-6ca3eb03dfc2/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20210525143221-35b2ab0089ea/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20210616045830-e2b7044e8c71/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20210630005230-0f9fa26af87c h1:F1jZWGFhYfh0Ci55sIpILtKKK8p3i2/krTr0H1rg74I=
golang.org/x/sys v0.0.0-20210630005230-0f9fa26af87c/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
Expand Down
1 change: 1 addition & 0 deletions graphql/documents/data/config.graphql
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ fragment ConfigGeneralData on ConfigGeneralResult {
previewPreset
maxTranscodeSize
maxStreamingTranscodeSize
nobrowser
writeImageThumbnails
apiKey
username
Expand Down
4 changes: 4 additions & 0 deletions graphql/schema/types/config.graphql
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,8 @@ input ConfigGeneralInput {
logAccess: Boolean!
"""True if galleries should be created from folders with images"""
createGalleriesFromFolders: Boolean!
"""True if we should not auto-open a browser window on startup"""
nobrowser: Boolean
kermieisinthehouse marked this conversation as resolved.
Show resolved Hide resolved
"""Array of video file extensions"""
videoExtensions: [String!]
"""Array of image file extensions"""
Expand Down Expand Up @@ -172,6 +174,8 @@ type ConfigGeneralResult {
galleryExtensions: [String!]!
"""True if galleries should be created from folders with images"""
createGalleriesFromFolders: Boolean!
""""True if we should not auto-open a browser window on startup"""
nobrowser: Boolean!
"""Array of file regexp to exclude from Video Scans"""
excludes: [String!]!
"""Array of file regexp to exclude from Image Scans"""
Expand Down
2 changes: 2 additions & 0 deletions pkg/api/resolver_mutation_configure.go
Original file line number Diff line number Diff line change
Expand Up @@ -94,6 +94,8 @@ func (r *mutationResolver) ConfigureGeneral(ctx context.Context, input models.Co

c.Set(config.CalculateMD5, input.CalculateMd5)

c.Set(config.NoBrowser, input.Nobrowser)

if input.ParallelTasks != nil {
c.Set(config.ParallelTasks, *input.ParallelTasks)
}
Expand Down
1 change: 1 addition & 0 deletions pkg/api/resolver_query_configuration.go
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,7 @@ func makeConfigGeneralResult() *models.ConfigGeneralResult {
PreviewPreset: config.GetPreviewPreset(),
MaxTranscodeSize: &maxTranscodeSize,
MaxStreamingTranscodeSize: &maxStreamingTranscodeSize,
Nobrowser: config.GetNoBrowserFlag(),
WriteImageThumbnails: config.IsWriteImageThumbnails(),
APIKey: config.GetAPIKey(),
Username: config.GetUsername(),
Expand Down
38 changes: 36 additions & 2 deletions pkg/api/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,11 @@ import (
"errors"
"fmt"
"io/fs"
"io/ioutil"
"net/http"
"os"
"path"
"runtime"
"runtime/debug"
"strconv"
"strings"
Expand All @@ -23,6 +25,7 @@ import (
"github.com/go-chi/chi"
"github.com/go-chi/chi/middleware"
"github.com/gorilla/websocket"
"github.com/pkg/browser"
"github.com/rs/cors"
"github.com/stashapp/stash/pkg/logger"
"github.com/stashapp/stash/pkg/manager"
Expand Down Expand Up @@ -242,12 +245,31 @@ func Start(uiBox embed.FS, loginUIBox embed.FS) {
printVersion()
printLatestVersion()
logger.Infof("stash is listening on " + address)
if tlsConfig != nil {
displayAddress = "https://" + displayAddress + "/"
} else {
displayAddress = "http://" + displayAddress + "/"
}

// This can be done before actually starting the server, as modern browsers will
// automatically reload the page if a local port is closed at page load and then opened.
if !c.GetNoBrowserFlag() {
if !IsServerDockerized() {
// make sure we aren't root
if !(os.Getuid() == 0) {
kermieisinthehouse marked this conversation as resolved.
Show resolved Hide resolved
err = browser.OpenURL(displayAddress)
if err != nil {
logger.Error("Could not open browser: " + err.Error())
}
}
}
}

if tlsConfig != nil {
logger.Infof("stash is running at https://" + displayAddress + "/")
logger.Infof("stash is running at " + displayAddress)
logger.Error(server.ListenAndServeTLS("", ""))
} else {
logger.Infof("stash is running at http://" + displayAddress + "/")
logger.Infof("stash is running at " + displayAddress)
logger.Error(server.ListenAndServe())
}
}()
Expand Down Expand Up @@ -353,3 +375,15 @@ func getProxyPrefix(headers http.Header) string {

return prefix
}

func IsServerDockerized() bool {
if runtime.GOOS == "linux" {
_, dockerEnvErr := os.Stat("/.dockerenv")
cgroups, _ := ioutil.ReadFile("/proc/self/cgroup")
if !os.IsNotExist(dockerEnvErr) || strings.Contains(string(cgroups), "docker") {
return true
}
}

return false
}
12 changes: 12 additions & 0 deletions pkg/manager/config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -151,6 +151,10 @@ const DLNADefaultEnabled = "dlna.default_enabled"
const DLNADefaultIPWhitelist = "dlna.default_whitelist"
const DLNAInterfaces = "dlna.interfaces"

// Desktop Integration Options
const NoBrowser = "nobrowser"
const NoBrowserDefault = false

// Logging options
const LogFile = "logFile"
const LogOut = "logOut"
Expand Down Expand Up @@ -223,6 +227,12 @@ func (i *Instance) GetCPUProfilePath() string {
return i.cpuProfilePath
}

func (i *Instance) GetNoBrowserFlag() bool {
i.Lock()
defer i.Unlock()
return viper.GetBool("nobrowser")
kermieisinthehouse marked this conversation as resolved.
Show resolved Hide resolved
}

func (i *Instance) Set(key string, value interface{}) {
i.Lock()
defer i.Unlock()
Expand Down Expand Up @@ -1028,6 +1038,8 @@ func (i *Instance) setDefaultValues(write bool) error {
// Set generated to the metadata path for backwards compat
viper.SetDefault(Generated, viper.GetString(Metadata))

viper.SetDefault(NoBrowser, NoBrowserDefault)

// Set default scrapers and plugins paths
viper.SetDefault(ScrapersPath, defaultScrapersPath)
viper.SetDefault(PluginsPath, defaultPluginsPath)
Expand Down
25 changes: 25 additions & 0 deletions pkg/manager/config/init.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ var once sync.Once
type flagStruct struct {
configFilePath string
cpuProfilePath string
nobrowser bool
}

func Initialize() (*Instance, error) {
Expand All @@ -41,6 +42,7 @@ func Initialize() (*Instance, error) {
}

if !instance.isNewSystem {
setExistingSystemDefaults(instance)
err = instance.SetInitialConfig()
}
})
Expand Down Expand Up @@ -95,13 +97,36 @@ func initConfig(flags flagStruct) error {
return nil
}

// setExistingSystemDefaults sets config options that are new and unset in an existing install,
// but should have a separate default than for brand-new systems, to maintain behavior.
func setExistingSystemDefaults(instance *Instance) {
if !instance.isNewSystem {
configDirtied := false

// Existing systems as of the introduction of auto-browser open should retain existing
// behavior and not start the browser automatically.
if !viper.InConfig("nobrowser") {
configDirtied = true
viper.Set("nobrowser", "true")
}

if configDirtied {
err := viper.WriteConfig()
if err != nil {
logger.Errorf("Could not save existing system defaults: %s", err.Error())
}
}
}
}

func initFlags() flagStruct {
flags := flagStruct{}

pflag.IP("host", net.IPv4(0, 0, 0, 0), "ip address for the host")
pflag.Int("port", 9999, "port to serve from")
pflag.StringVarP(&flags.configFilePath, "config", "c", "", "config file to use")
pflag.StringVar(&flags.cpuProfilePath, "cpuprofile", "", "write cpu profile to file")
pflag.BoolVar(&flags.nobrowser, "nobrowser", false, "Don't open a browser window after launch")
kermieisinthehouse marked this conversation as resolved.
Show resolved Hide resolved

pflag.Parse()
if err := viper.BindPFlags(pflag.CommandLine); err != nil {
Expand Down
21 changes: 21 additions & 0 deletions ui/v2.5/src/components/Settings/SettingsConfigurationPanel.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,7 @@ export const SettingsConfigurationPanel: React.FC = () => {
const [metadataPath, setMetadataPath] = useState<string | undefined>(
undefined
);
const [nobrowser, setNoBrowserFlag] = useState<boolean>(false);
const [cachePath, setCachePath] = useState<string | undefined>(undefined);
const [calculateMD5, setCalculateMD5] = useState<boolean>(false);
const [videoFileNamingAlgorithm, setVideoFileNamingAlgorithm] = useState<
Expand Down Expand Up @@ -166,6 +167,7 @@ export const SettingsConfigurationPanel: React.FC = () => {
previewPreset: (previewPreset as GQL.PreviewPreset) ?? undefined,
maxTranscodeSize,
maxStreamingTranscodeSize,
nobrowser,
writeImageThumbnails,
username,
password,
Expand Down Expand Up @@ -219,6 +221,7 @@ export const SettingsConfigurationPanel: React.FC = () => {
setUsername(conf.general.username);
setPassword(conf.general.password);
setMaxSessionAge(conf.general.maxSessionAge);
setNoBrowserFlag(conf.general.nobrowser);
setTrustedProxies(conf.general.trustedProxies ?? undefined);
setLogFile(conf.general.logFile ?? undefined);
setLogOut(conf.general.logOut);
Expand Down Expand Up @@ -1097,6 +1100,24 @@ export const SettingsConfigurationPanel: React.FC = () => {

<hr />

<h4>{intl.formatMessage({ id: "config.general.startup" })}</h4>
<Form.Group>
<Form.Check
id="skip-browser"
checked={nobrowser}
label={intl.formatMessage({
id: "config.general.skip_opening_browser",
})}
onChange={() => setNoBrowserFlag(!nobrowser)}
/>
<Form.Text className="text-muted">
{intl.formatMessage({
id: "config.general.skip_opening_browser_on_startup",
})}
</Form.Text>
</Form.Group>
<hr />

kermieisinthehouse marked this conversation as resolved.
Show resolved Hide resolved
<Button variant="primary" onClick={() => onSave()}>
<FormattedMessage id="actions.save" />
</Button>
Expand Down
3 changes: 3 additions & 0 deletions ui/v2.5/src/locales/en-GB.json
Original file line number Diff line number Diff line change
Expand Up @@ -241,6 +241,9 @@
"scraper_user_agent": "Scraper User Agent",
"scraper_user_agent_desc": "User-Agent string used during scrape http requests",
"scraping": "Scraping",
"skip_opening_browser": "Skip Opening Browser",
"skip_opening_browser_on_startup": "Skip auto-opening browser during startup",
"startup": "Start-Up",
"sqlite_location": "File location for the SQLite database (requires restart)",
"video_ext_desc": "Comma-delimited list of file extensions that will be identified as videos.",
"video_ext_head": "Video Extensions",
Expand Down
19 changes: 19 additions & 0 deletions vendor/github.com/pkg/browser/.github/workflows/push.yml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

23 changes: 23 additions & 0 deletions vendor/github.com/pkg/browser/LICENSE

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

55 changes: 55 additions & 0 deletions vendor/github.com/pkg/browser/README.md

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading