override config entries with cli args

use getconfig instead of settings file
This commit is contained in:
lukas 2021-09-09 23:33:04 +02:00
parent 2706929bb4
commit aa49d601ab
7 changed files with 156 additions and 111 deletions

View File

@ -4,6 +4,7 @@ import (
"encoding/json" "encoding/json"
"fmt" "fmt"
"openmediacenter/apiGo/api/types" "openmediacenter/apiGo/api/types"
"openmediacenter/apiGo/config"
"openmediacenter/apiGo/database" "openmediacenter/apiGo/database"
"openmediacenter/apiGo/database/settings" "openmediacenter/apiGo/database/settings"
"openmediacenter/apiGo/videoparser" "openmediacenter/apiGo/videoparser"
@ -88,8 +89,8 @@ func getSettingsFromDB() {
MediacenterName: sett.MediacenterName, MediacenterName: sett.MediacenterName,
VideoPath: serverVideoPath, VideoPath: serverVideoPath,
TVShowPath: serverTVShowPath, TVShowPath: serverTVShowPath,
TVShowEnabled: settings.TVShowsEnabled(), TVShowEnabled: !config.GetConfig().Features.DisableTVSupport,
FullDeleteEnabled: settings.VideosDeletable(), FullDeleteEnabled: config.GetConfig().Features.FullyDeletableVideos,
} }
str, _ := json.Marshal(res) str, _ := json.Marshal(res)

View File

@ -2,13 +2,13 @@ package api
import ( import (
"fmt" "fmt"
"openmediacenter/apiGo/config"
"openmediacenter/apiGo/database" "openmediacenter/apiGo/database"
"openmediacenter/apiGo/database/settings"
) )
func AddTvshowHandlers() { func AddTvshowHandlers() {
// do not add handlers if tvshows not enabled // do not add handlers if tvshows not enabled
if !settings.TVShowsEnabled() { if config.GetConfig().Features.DisableTVSupport {
return return
} }

View File

@ -5,8 +5,8 @@ import (
"fmt" "fmt"
"net/url" "net/url"
"openmediacenter/apiGo/api/types" "openmediacenter/apiGo/api/types"
"openmediacenter/apiGo/config"
"openmediacenter/apiGo/database" "openmediacenter/apiGo/database"
"openmediacenter/apiGo/database/settings"
"os" "os"
"strconv" "strconv"
) )
@ -448,7 +448,7 @@ func addToVideoHandlers() {
} }
// only allow deletion of video if cli flag is set, independent of passed api arg // only allow deletion of video if cli flag is set, independent of passed api arg
if settings.VideosDeletable() && args.FullyDelete { if config.GetConfig().Features.FullyDeletableVideos && args.FullyDelete {
// get physical path of video to delete // get physical path of video to delete
query = fmt.Sprintf("SELECT movie_url FROM videos WHERE movie_id=%d", args.MovieId) query = fmt.Sprintf("SELECT movie_url FROM videos WHERE movie_id=%d", args.MovieId)
var vidpath string var vidpath string

View File

@ -2,6 +2,7 @@ package config
import ( import (
"errors" "errors"
"flag"
"fmt" "fmt"
"github.com/pelletier/go-toml/v2" "github.com/pelletier/go-toml/v2"
"os" "os"
@ -15,18 +16,40 @@ type DatabaseT struct {
DBHost string DBHost string
} }
type FileConfT struct { type FeaturesT struct {
Database DatabaseT DisableTVSupport bool
FullyDeletableVideos bool
} }
func defaultConig() *FileConfT { type GeneralT struct {
return &FileConfT{Database: DatabaseT{ VerboseLogging bool
DBName: "mediacenter", ReindexPrefix string
DBPassword: "mediapassword", }
DBUser: "mediacenteruser",
DBPort: 3306, type FileConfT struct {
DBHost: "127.0.0.1", Database DatabaseT
}} General GeneralT
Features FeaturesT
}
func defaultConfig() *FileConfT {
return &FileConfT{
Database: DatabaseT{
DBName: "mediacenter",
DBPassword: "mediapassword",
DBUser: "mediacenteruser",
DBPort: 3306,
DBHost: "127.0.0.1",
},
General: GeneralT{
VerboseLogging: false,
ReindexPrefix: "/var/www/openmediacenter",
},
Features: FeaturesT{
DisableTVSupport: false,
FullyDeletableVideos: false,
},
}
} }
var liveConf FileConfT var liveConf FileConfT
@ -44,32 +67,11 @@ func Init() {
// check if config exists on local dir // check if config exists on local dir
dat, err = os.ReadFile(cfgname) dat, err = os.ReadFile(cfgname)
if err != nil { if err != nil {
// config really doesn't exist! generateNewConfig(cfgpath, cfgname)
fmt.Printf("config not existing -- generating new empty config at %s%s\n", cfgpath, cfgname)
// generate new default config
obj, _ := toml.Marshal(defaultConig())
liveConf = *defaultConig()
err := os.WriteFile(cfgpath+cfgname, obj, 777)
if err != nil {
if errors.Is(err, os.ErrPermission) {
// permisson denied to create file try to create at current dir
err = os.WriteFile(cfgname, obj, 777)
if err != nil {
fmt.Println("failed to create default config file!")
} else {
fmt.Println("config file created at .")
}
} else {
fmt.Println(err.Error())
}
}
} else { } else {
// ok decode local config // ok decode local config
decodeConfig(&dat) decodeConfig(&dat)
} }
} else { } else {
// other error // other error
fmt.Println(err.Error()) fmt.Println(err.Error())
@ -77,6 +79,32 @@ func Init() {
} else { } else {
decodeConfig(&dat) decodeConfig(&dat)
} }
handleCommandLineArguments()
}
func generateNewConfig(cfgpath string, cfgname string) {
// config really doesn't exist!
fmt.Printf("config not existing -- generating new empty config at %s%s\n", cfgpath, cfgname)
// generate new default config
obj, _ := toml.Marshal(defaultConfig())
liveConf = *defaultConfig()
err := os.WriteFile(cfgpath+cfgname, obj, 777)
if err != nil {
if errors.Is(err, os.ErrPermission) {
// permisson denied to create file try to create at current dir
err = os.WriteFile(cfgname, obj, 777)
if err != nil {
fmt.Println("failed to create default config file!")
} else {
fmt.Println("config file created at .")
}
} else {
fmt.Println(err.Error())
}
}
} }
func decodeConfig(bin *[]byte) { func decodeConfig(bin *[]byte) {
@ -85,7 +113,7 @@ func decodeConfig(bin *[]byte) {
err := toml.Unmarshal(*bin, &config) err := toml.Unmarshal(*bin, &config)
if err != nil { if err != nil {
fmt.Println(err) fmt.Println(err)
liveConf = *defaultConfig()
} else { } else {
fmt.Println("Successfully loaded config file!") fmt.Println("Successfully loaded config file!")
@ -93,6 +121,86 @@ func decodeConfig(bin *[]byte) {
} }
} }
// handleCommandLineArguments let cli args override the config
func handleCommandLineArguments() {
// get a defaultconfig obj to set defaults
dconf := defaultConfig()
const (
DBHost = "DBHost"
DBPort = "DBPort"
DBUser = "DBUser"
DBPassword = "DBPassword"
DBName = "DBName"
Verbose = "v"
ReindexPrefix = "ReindexPrefix"
DisableTVSupport = "DisableTVSupport"
FullyDeletableVideos = "FullyDeletableVideos"
)
dbhostPtr := flag.String(DBHost, dconf.Database.DBHost, "database host name")
dbPortPtr := flag.Int(DBPort, int(dconf.Database.DBPort), "database port")
dbUserPtr := flag.String(DBUser, dconf.Database.DBUser, "database username")
dbPassPtr := flag.String(DBPassword, dconf.Database.DBPassword, "database username")
dbNamePtr := flag.String(DBName, dconf.Database.DBName, "database name")
verbosePtr := flag.Bool(Verbose, dconf.General.VerboseLogging, "Verbose log output")
pathPrefix := flag.String(ReindexPrefix, dconf.General.ReindexPrefix, "Prefix path for videos to reindex")
disableTVShowSupport := flag.Bool(DisableTVSupport, dconf.Features.DisableTVSupport, "Disable the TVShow support and pages")
videosFullyDeletable := flag.Bool(FullyDeletableVideos, dconf.Features.FullyDeletableVideos, "Allow deletion from harddisk")
flag.Parse()
if isFlagPassed(DBHost) {
liveConf.Database.DBHost = *dbhostPtr
}
if isFlagPassed(DBPort) {
liveConf.Database.DBPort = uint16(*dbPortPtr)
}
if isFlagPassed(DBName) {
liveConf.Database.DBName = *dbNamePtr
}
if isFlagPassed(DBUser) {
liveConf.Database.DBUser = *dbUserPtr
}
if isFlagPassed(DBPassword) {
liveConf.Database.DBPassword = *dbPassPtr
}
if isFlagPassed(Verbose) {
liveConf.General.VerboseLogging = *verbosePtr
}
if isFlagPassed(ReindexPrefix) {
liveConf.General.ReindexPrefix = *pathPrefix
}
if isFlagPassed(DisableTVSupport) {
liveConf.Features.DisableTVSupport = *disableTVShowSupport
}
if isFlagPassed(FullyDeletableVideos) {
liveConf.Features.FullyDeletableVideos = *videosFullyDeletable
}
}
// isFlagPassed check whether a flag was passed
func isFlagPassed(name string) bool {
found := false
flag.Visit(func(f *flag.Flag) {
if f.Name == name {
found = true
}
})
return found
}
func GetConfig() *FileConfT { func GetConfig() *FileConfT {
return &liveConf return &liveConf
} }

View File

@ -5,23 +5,14 @@ import (
"fmt" "fmt"
_ "github.com/go-sql-driver/mysql" _ "github.com/go-sql-driver/mysql"
"openmediacenter/apiGo/api/types" "openmediacenter/apiGo/api/types"
"openmediacenter/apiGo/config"
) )
var db *sql.DB var db *sql.DB
var DBName string var DBName string
// store the command line parameter for Videoprefix func InitDB() {
var SettingsVideoPrefix = "" dbconf := config.GetConfig().Database
type DatabaseConfig struct {
DBHost string
DBPort int
DBUser string
DBPassword string
DBName string
}
func InitDB(dbconf *DatabaseConfig) {
DBName = dbconf.DBName DBName = dbconf.DBName
// Open up our database connection. // Open up our database connection.
@ -128,6 +119,6 @@ func GetSettings() (result types.SettingsType, PathPrefix string, sizes types.Se
result.TMDBGrabbing = TMDBGrabbing != 0 result.TMDBGrabbing = TMDBGrabbing != 0
result.PasswordEnabled = result.Password != "-1" result.PasswordEnabled = result.Password != "-1"
result.DarkMode = DarkMode != 0 result.DarkMode = DarkMode != 0
PathPrefix = SettingsVideoPrefix PathPrefix = config.GetConfig().General.ReindexPrefix
return return
} }

View File

@ -1,20 +0,0 @@
package settings
var tvShowEnabled bool
var videosDeletable bool
func TVShowsEnabled() bool {
return tvShowEnabled
}
func SetTVShowEnabled(enabled bool) {
tvShowEnabled = enabled
}
func VideosDeletable() bool {
return videosDeletable
}
func SetVideosDeletable(deletable bool) {
videosDeletable = deletable
}

View File

@ -1,14 +1,12 @@
package main package main
import ( import (
"flag"
"fmt" "fmt"
"log" "log"
"net/http" "net/http"
"openmediacenter/apiGo/api" "openmediacenter/apiGo/api"
"openmediacenter/apiGo/config" "openmediacenter/apiGo/config"
"openmediacenter/apiGo/database" "openmediacenter/apiGo/database"
settings2 "openmediacenter/apiGo/database/settings"
"openmediacenter/apiGo/static" "openmediacenter/apiGo/static"
"openmediacenter/apiGo/videoparser" "openmediacenter/apiGo/videoparser"
) )
@ -17,18 +15,13 @@ func main() {
fmt.Println("init OpenMediaCenter server") fmt.Println("init OpenMediaCenter server")
port := 8081 port := 8081
db, verbose, pathPrefix := handleCommandLineArguments()
// todo some verbosity logger or sth
config.Init() config.Init()
fmt.Printf("Use verbose output: %t\n", verbose) // todo some verbosity logger or sth
fmt.Printf("Videopath prefix: %s\n", *pathPrefix) fmt.Printf("Use verbose output: %t\n", config.GetConfig().General.VerboseLogging)
fmt.Printf("Videopath prefix: %s\n", config.GetConfig().General.ReindexPrefix)
// set pathprefix in database settings object database.InitDB()
database.SettingsVideoPrefix = *pathPrefix
database.InitDB(db)
defer database.Close() defer database.Close()
api.AddVideoHandlers() api.AddVideoHandlers()
@ -47,31 +40,3 @@ func main() {
fmt.Printf("OpenMediacenter server up and running on port %d\n", port) fmt.Printf("OpenMediacenter server up and running on port %d\n", port)
log.Fatal(http.ListenAndServe(fmt.Sprintf(":%d", port), nil)) log.Fatal(http.ListenAndServe(fmt.Sprintf(":%d", port), nil))
} }
func handleCommandLineArguments() (*database.DatabaseConfig, bool, *string) {
dbhostPtr := flag.String("DBHost", "127.0.0.1", "database host name")
dbPortPtr := flag.Int("DBPort", 3306, "database port")
dbUserPtr := flag.String("DBUser", "mediacenteruser", "database username")
dbPassPtr := flag.String("DBPassword", "mediapassword", "database username")
dbNamePtr := flag.String("DBName", "mediacenter", "database name")
verbosePtr := flag.Bool("v", true, "Verbose log output")
pathPrefix := flag.String("ReindexPrefix", "/var/www/openmediacenter", "Prefix path for videos to reindex")
disableTVShowSupport := flag.Bool("DisableTVSupport", false, "Disable the TVShow support and pages")
videosFullyDeletable := flag.Bool("FullyDeletableVideos", false, "Allow deletion from harddisk")
flag.Parse()
settings2.SetTVShowEnabled(!*disableTVShowSupport)
settings2.SetVideosDeletable(*videosFullyDeletable)
return &database.DatabaseConfig{
DBHost: *dbhostPtr,
DBPort: *dbPortPtr,
DBUser: *dbUserPtr,
DBPassword: *dbPassPtr,
DBName: *dbNamePtr,
}, *verbosePtr, pathPrefix
}