Skip to content

Commit

Permalink
fix: use separate config for each cobra command.
Browse files Browse the repository at this point in the history
  • Loading branch information
evan-buss committed Jun 18, 2022
1 parent 0ea9fd4 commit 62a7a4c
Show file tree
Hide file tree
Showing 5 changed files with 95 additions and 75 deletions.
7 changes: 6 additions & 1 deletion cmd/openbooks/cli.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,14 +7,15 @@ import (
"os"
"strings"

"github.com/davecgh/go-spew/spew"
"github.com/evan-buss/openbooks/cli"
"github.com/spf13/cobra"
)

var cliConfig cli.Config

func init() {
rootCmd.AddCommand(cliCmd)
desktopCmd.AddCommand(cliCmd)
cliCmd.AddCommand(downloadCmd)
cliCmd.AddCommand(searchCmd)

Expand All @@ -35,6 +36,10 @@ var cliCmd = &cobra.Command{
cliConfig.Server = globalFlags.Server
cliConfig.Log = globalFlags.Log
cliConfig.SearchBot = globalFlags.SearchBot

if debug {
spew.Dump(cliConfig)
}
},
Run: func(cmd *cobra.Command, args []string) {
cli.StartInteractive(cliConfig)
Expand Down
56 changes: 33 additions & 23 deletions cmd/openbooks/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,11 @@ package main

import (
"fmt"
"math/rand"
"os"
"path"
"time"
"path/filepath"

"github.com/brianvoe/gofakeit/v5"
"github.com/davecgh/go-spew/spew"
"github.com/evan-buss/openbooks/desktop"
"github.com/evan-buss/openbooks/server"
"github.com/spf13/cobra"
Expand All @@ -28,28 +27,47 @@ type GlobalFlags struct {
SearchBot string
}

var debug bool
var globalFlags GlobalFlags
var desktopConfig server.Config

func init() {
rootCmd.PersistentFlags().StringVarP(&globalFlags.UserName, "name", "n", generateUserName(), "Use a name that isn't randomly generated. One word only.")
rootCmd.PersistentFlags().StringVarP(&globalFlags.Server, "server", "s", "irc.irchighway.net", "IRC server to connect to.")
rootCmd.PersistentFlags().BoolVarP(&globalFlags.Log, "log", "l", false, "Save raw IRC logs for each client connection.")
rootCmd.PersistentFlags().StringVar(&globalFlags.SearchBot, "searchbot", "search", "The IRC bot that handles search queries. Try 'searchook' if 'search' is down.")
desktopCmd.PersistentFlags().BoolVar(&debug, "debug", false, "Enable debug mode.")
desktopCmd.PersistentFlags().StringVarP(&globalFlags.UserName, "name", "n", generateUserName(), "Use a name that isn't randomly generated. One word only.")
desktopCmd.PersistentFlags().StringVarP(&globalFlags.Server, "server", "s", "irc.irchighway.net", "IRC server to connect to.")
desktopCmd.PersistentFlags().BoolVarP(&globalFlags.Log, "log", "l", false, "Save raw IRC logs for each client connection.")
desktopCmd.PersistentFlags().StringVar(&globalFlags.SearchBot, "searchbot", "search", "The IRC bot that handles search queries. Try 'searchook' if 'search' is down.")

homeDir, err := os.UserHomeDir()
if err != nil {
panic(fmt.Errorf("unable to determine $HOME directory %w", err))
}
downloadDir := filepath.Join(homeDir, "Downloads")

desktopCmd.Flags().StringVarP(&desktopConfig.Port, "port", "p", "5228", "Set the local network port for browser mode.")
desktopCmd.Flags().IntP("rate-limit", "r", 10, "The number of seconds to wait between searches to reduce strain on IRC search servers. Minimum is 10 seconds.")
desktopCmd.Flags().StringVarP(&desktopConfig.DownloadDir, "dir", "d", downloadDir, "The directory where eBooks are saved.")
}

var rootCmd = &cobra.Command{
var desktopCmd = &cobra.Command{
Use: "openbooks",
Short: "Quickly and easily download eBooks from IRCHighway.",
Long: "Runs OpenBooks in desktop mode. This allows you to run OpenBooks like a regular desktop application. This functionality utilizes your OS's native browser renderer and as such may not work on certain operating systems.",
PreRun: func(cmd *cobra.Command, args []string) {
bindGlobalFlags()
serverConfig.DisableBrowserDownloads = true
serverConfig.Basepath = "/"
serverConfig.Persist = true
bindGlobalFlags(&desktopConfig)
rateLimit, _ := cmd.Flags().GetInt("rate-limit")
ensureValidRate(rateLimit, &desktopConfig)
desktopConfig.DisableBrowserDownloads = true
desktopConfig.Basepath = "/"
desktopConfig.Persist = true
},
Run: func(cmd *cobra.Command, args []string) {
go server.Start(serverConfig)
desktop.StartWebView(fmt.Sprintf("http://127.0.0.1:%s", path.Join(serverConfig.Port+serverConfig.Basepath)), false)
if debug {
spew.Dump(desktopConfig)
}

go server.Start(desktopConfig)
desktop.StartWebView(fmt.Sprintf("http://127.0.0.1:%s", path.Join(desktopConfig.Port+desktopConfig.Basepath)), debug)
},
Version: version,
}
Expand All @@ -58,16 +76,8 @@ func main() {
// Don't block if launched from explorer.
cobra.MousetrapHelpText = ""

if err := rootCmd.Execute(); err != nil {
if err := desktopCmd.Execute(); err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
}

// Generate a random username to avoid IRC name collisions if multiple users are hosting
// at the same time.
func generateUserName() string {
rand.Seed(time.Now().UnixNano())
gofakeit.Seed(int64(rand.Int()))
return fmt.Sprintf("%s_%s", gofakeit.Adjective(), gofakeit.Noun())
}
56 changes: 7 additions & 49 deletions cmd/openbooks/server.go
Original file line number Diff line number Diff line change
@@ -1,61 +1,46 @@
package main

import (
"fmt"
"os"
"path"
"path/filepath"
"time"

"github.com/evan-buss/openbooks/server"
"github.com/evan-buss/openbooks/util"

"github.com/spf13/cobra"
"github.com/spf13/pflag"
)

var openBrowser = false
var serverConfig server.Config

func init() {
rootCmd.AddCommand(serverCmd)
// rootCmd.AddCommand(desktopCmd)
desktopCmd.AddCommand(serverCmd)

sharedFlags := pflag.NewFlagSet("", pflag.ExitOnError)
sharedFlags.StringVarP(&serverConfig.Port, "port", "p", "5228", "Set the local network port for browser mode.")
sharedFlags.IntP("rate-limit", "r", 10, "The number of seconds to wait between searches to reduce strain on IRC search servers. Minimum is 10 seconds.")

serverCmd.Flags().AddFlagSet(sharedFlags)
serverCmd.Flags().StringVarP(&serverConfig.Port, "port", "p", "5228", "Set the local network port for browser mode.")
serverCmd.Flags().IntP("rate-limit", "r", 10, "The number of seconds to wait between searches to reduce strain on IRC search servers. Minimum is 10 seconds.")
serverCmd.Flags().BoolVar(&serverConfig.DisableBrowserDownloads, "no-browser-downloads", false, "The browser won't recieve and download eBook files, but they are still saved to the defined 'dir' path.")
serverCmd.Flags().StringVar(&serverConfig.Basepath, "basepath", "/", `Base path where the application is accessible. For example "/openbooks/".`)
serverCmd.Flags().BoolVarP(&openBrowser, "browser", "b", false, "Open the browser on server start.")
serverCmd.Flags().BoolVar(&serverConfig.Persist, "persist", false, "Persist eBooks in 'dir'. Default is to delete after sending.")
serverCmd.Flags().StringVarP(&serverConfig.DownloadDir, "dir", "d", filepath.Join(os.TempDir(), "openbooks"), "The directory where eBooks are saved when persist enabled.")

homeDir, err := os.UserHomeDir()
if err != nil {
panic(fmt.Errorf("unable to determine HOME directory %w", err))
}
downloadDir := filepath.Join(homeDir, "Downloads")

rootCmd.Flags().AddFlagSet(sharedFlags)
rootCmd.Flags().StringVarP(&serverConfig.DownloadDir, "dir", "d", downloadDir, "The directory where eBooks are saved.")
serverCmd.LocalFlags().StringVarP(&serverConfig.DownloadDir, "dir", "d", filepath.Join(os.TempDir(), "openbooks"), "The directory where eBooks are saved when persist enabled.")
}

var serverCmd = &cobra.Command{
Use: "server",
Short: "Run OpenBooks in server mode.",
Long: "Run OpenBooks in server mode. This allows you to use a web interface to search and download eBooks.",
PreRun: func(cmd *cobra.Command, args []string) {
bindGlobalFlags()
bindGlobalFlags(&serverConfig)
rateLimit, _ := cmd.Flags().GetInt("rate-limit")
ensureValidRate(rateLimit, &serverConfig)
// If cli flag isn't set (default value) check for the presence of an
// environment variable and use it if found.
if serverConfig.Basepath == cmd.Flag("basepath").DefValue {
if envPath, present := os.LookupEnv("BASE_PATH"); present {
serverConfig.Basepath = envPath
}
}
ensureValidRate(cmd)
serverConfig.Basepath = sanitizePath(serverConfig.Basepath)
},
Run: func(cmd *cobra.Command, args []string) {
Expand All @@ -67,30 +52,3 @@ var serverCmd = &cobra.Command{
server.Start(serverConfig)
},
}

func bindGlobalFlags() {
serverConfig.Version = fmt.Sprintf("OpenBooks Server %s", ircVersion)
serverConfig.UserName = globalFlags.UserName
serverConfig.Log = globalFlags.Log
serverConfig.Server = globalFlags.Server
serverConfig.SearchBot = globalFlags.SearchBot
}

func ensureValidRate(cmd *cobra.Command) {
rateLimit, _ := cmd.Flags().GetInt("rate-limit")

// If user enters a limit that's too low, set to default of 10 seconds.
if rateLimit < 10 {
rateLimit = 10
}

serverConfig.SearchTimeout = time.Duration(rateLimit) * time.Second
}

func sanitizePath(basepath string) string {
cleaned := path.Clean(basepath)
if cleaned == "/" {
return cleaned
}
return cleaned + "/"
}
47 changes: 47 additions & 0 deletions cmd/openbooks/util.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
package main

import (
"fmt"
"math/rand"
"path"
"time"

"github.com/brianvoe/gofakeit/v5"
"github.com/evan-buss/openbooks/server"
)

// Generate a random username to avoid IRC name collisions if multiple users are hosting
// at the same time.
func generateUserName() string {
rand.Seed(time.Now().UnixNano())
gofakeit.Seed(int64(rand.Int()))
return fmt.Sprintf("%s_%s", gofakeit.Adjective(), gofakeit.Noun())
}

// Update a server config struct from globalFlags
func bindGlobalFlags(config *server.Config) {
config.Version = fmt.Sprintf("OpenBooks Server %s", ircVersion)
config.UserName = globalFlags.UserName
config.Log = globalFlags.Log
config.Server = globalFlags.Server
config.SearchBot = globalFlags.SearchBot
}

// Make sure the server config has a valid rate limit.
func ensureValidRate(rateLimit int, config *server.Config) {

// If user enters a limit that's too low, set to default of 10 seconds.
if rateLimit < 10 {
rateLimit = 10
}

config.SearchTimeout = time.Duration(rateLimit) * time.Second
}

func sanitizePath(basepath string) string {
cleaned := path.Clean(basepath)
if cleaned == "/" {
return cleaned
}
return cleaned + "/"
}
4 changes: 2 additions & 2 deletions server/app/src/state/store.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { Action, configureStore, ThunkAction } from "@reduxjs/toolkit";
import { configureStore } from "@reduxjs/toolkit";
import throttle from "lodash/throttle";
import historyReducer from "./historySlice";
import notificationReducer from "./notificationSlice";
Expand All @@ -7,7 +7,7 @@ import stateReducer from "./stateSlice";
import { enableMapSet } from "immer";
import { getWebsocketURL } from "./util";
import { openbooksApi } from "./api";
import { setupListeners } from "@reduxjs/toolkit/dist/query";
import { setupListeners } from "@reduxjs/toolkit/query/react";
import { useDispatch } from "react-redux";

enableMapSet();
Expand Down

0 comments on commit 62a7a4c

Please sign in to comment.