Skip to content

Commit

Permalink
feat: aixifan_config.json Config
Browse files Browse the repository at this point in the history
  • Loading branch information
yzqzss committed Dec 12, 2024
1 parent f175994 commit eaf0785
Show file tree
Hide file tree
Showing 3 changed files with 94 additions and 0 deletions.
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
- [ ] m3u8 Downloader
- [ ] ffmpeg concat
- [ ] CLI Tools
- [X] `aixifan_config.json` Config
- [ ] Download
- [ ] IA S3 Upload
- [ ] Login for higher quality
66 changes: 66 additions & 0 deletions pkg/config/config.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
package config

import (
"encoding/json"
"log/slog"
"os"
"path"
)

type Config struct {
DownloadsHomeDir string `json:"downloads_home_dir"`
IaKeyFile string `json:"ia_key_file"`
CookiesFile string `json:"cookies_file"`
}

func NewConfig() *Config {
iaKeyFile := ".aixifan_ia_keys.txt"
cookiesFile := ".cookies.txt"
home, err := os.UserHomeDir()
if err != nil {
slog.Info("Failed to get user home dir, using current dir instead")
home = "."
}
iaKeyFile = path.Join(home, iaKeyFile)
cookiesFile = path.Join(home, cookiesFile)

return &Config{
DownloadsHomeDir: "aixifan_downloads",
IaKeyFile: iaKeyFile,
CookiesFile: cookiesFile,
}
}

func (config *Config) Save() error {
json_data, err := json.Marshal(config)
if err != nil {
return err
}
err = os.WriteFile("aixifan_config.json", json_data, 0644)
return err
}

func LoadConfig() (*Config, error) {
json_data, err := os.ReadFile("aixifan_config.json")
if err != nil {
return nil, err
}
var config Config
err = json.Unmarshal(json_data, &config)
return &config, err
}

func LoadOrNewConfig() (*Config, error) {
config, err := LoadConfig()
if err != nil {
slog.Info("Failed to load config, creating new one")
config = NewConfig()
err = config.Save()
}
return config, err
}

func (c *Config) MakeDownloadsHomeDir() error {
err := os.MkdirAll(c.DownloadsHomeDir, 0755)
return err
}
27 changes: 27 additions & 0 deletions pkg/config/config_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
package config

import (
"os"
"testing"
)

func Test_Config(t *testing.T) {
config := NewConfig()
config.Save()
defer os.Remove("aixifan_config.json")

if _, err := os.Stat("aixifan_config.json"); err != nil {
t.Fatal(err)
return
}

config_loaded, err := LoadConfig()
if err != nil {
t.Fatal(err)
return
}

if config_loaded.DownloadsHomeDir != config.DownloadsHomeDir {
t.Fatal("DownloadsHomeDir not match")
}
}

0 comments on commit eaf0785

Please sign in to comment.