~cytrogen/ytm

ytm/config.go -rw-r--r-- 1.7 KiB
f884dc98 — HallowDem Initial commit: YTM - YouTube Music Downloader a month ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
package main

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

	"github.com/BurntSushi/toml"
)

type Config struct {
	MusicRoot        string   `toml:"music_root"`
	Categories       []string `toml:"categories"`
	YtdlpPath        string   `toml:"ytdlp_path"`
	HTTPTimeout      int      `toml:"http_timeout"`
	MaxArtistResults int      `toml:"max_artist_results"`
	MaxAlbumResults  int      `toml:"max_album_results"`
}

var cfg *Config

func defaultConfig() Config {
	return Config{
		MusicRoot:        "D:/Music/",
		Categories:       []string{"C-Rock", "J-Pop", "K-Pop", "Other", "Game Music"},
		YtdlpPath:        "yt-dlp",
		HTTPTimeout:      30,
		MaxArtistResults: 8,
		MaxAlbumResults:  10,
	}
}

const defaultConfigTOML = `# YTM 配置文件

# 音乐下载根目录
music_root = "D:/Music/"

# 音乐分类(对应根目录下的子文件夹)
categories = ["C-Rock", "J-Pop", "K-Pop", "Other", "Game Music"]

# yt-dlp 可执行文件路径
ytdlp_path = "yt-dlp"

# HTTP 请求超时(秒)
http_timeout = 30

# 搜索结果最大数量
max_artist_results = 8
max_album_results = 10
`

func configPath() string {
	exe, err := os.Executable()
	if err != nil {
		return "config.toml"
	}
	return filepath.Join(filepath.Dir(exe), "config.toml")
}

func loadConfig() *Config {
	c := defaultConfig()
	path := configPath()

	if _, err := os.Stat(path); os.IsNotExist(err) {
		if err := os.WriteFile(path, []byte(defaultConfigTOML), 0644); err == nil {
			fmt.Printf("已生成默认配置文件: %s\n", path)
		}
		return &c
	}

	if _, err := toml.DecodeFile(path, &c); err != nil {
		fmt.Printf("读取配置文件失败: %v,使用默认配置\n", err)
		d := defaultConfig()
		return &d
	}

	return &c
}