aliyunpan/internal/config/pan_config.go

593 lines
16 KiB
Go
Raw Normal View History

2021-10-10 10:48:53 +08:00
// Copyright (c) 2020 tickstep.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
2023-10-07 16:42:43 +08:00
// http://www.apache.org/licenses/LICENSE-2.0
2021-10-10 10:48:53 +08:00
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package config
import (
"fmt"
2024-07-03 21:42:48 +08:00
"github.com/adrg/xdg"
2021-10-10 10:48:53 +08:00
jsoniter "github.com/json-iterator/go"
"github.com/tickstep/aliyunpan-api/aliyunpan"
"github.com/tickstep/aliyunpan/cmder/cmdutil"
"github.com/tickstep/aliyunpan/cmder/cmdutil/jsonhelper"
2022-06-26 11:51:34 +08:00
"github.com/tickstep/aliyunpan/internal/utils"
"github.com/tickstep/aliyunpan/library/homedir"
2021-10-10 10:48:53 +08:00
"github.com/tickstep/library-go/logger"
"github.com/tickstep/library-go/requester"
"os"
2024-07-03 21:42:48 +08:00
"path"
2021-10-10 10:48:53 +08:00
"path/filepath"
"runtime"
"strings"
"sync"
)
const (
2024-07-03 21:42:48 +08:00
// EnvDownloadDir 配置下载环境变量
EnvDownloadDir = "ALIYUNPAN_DOWNLOAD_DIR"
2021-10-10 10:48:53 +08:00
// EnvVerbose 启用调试环境变量
EnvVerbose = "ALIYUNPAN_VERBOSE"
// EnvConfigDir 配置路径环境变量
EnvConfigDir = "ALIYUNPAN_CONFIG_DIR"
// ConfigName 配置文件名
ConfigName = "aliyunpan_config.json"
// ConfigVersion 配置文件版本
ConfigVersion string = "1.0"
2022-01-31 12:09:28 +08:00
// DefaultFileUploadParallelNum 默认的文件上传并发数量
2022-01-15 21:50:28 +08:00
DefaultFileUploadParallelNum = 10
// MaxFileUploadParallelNum 最大文件上传并发数量。过大会被阿里云盘风控,导致无法上传
MaxFileUploadParallelNum = 20
2022-01-15 21:50:28 +08:00
// DefaultFileDownloadParallelNum 默认的文件下载并发数量
DefaultFileDownloadParallelNum = 5
2022-01-31 12:09:28 +08:00
// MaxFileDownloadParallelNum 最大文件下载并发数量。过大会被阿里云盘风控,导致无法下载
MaxFileDownloadParallelNum = 20
2022-01-31 12:09:28 +08:00
// DefaultTokenServiceWebHost 默认的token服务
2022-02-01 19:05:27 +08:00
DefaultTokenServiceWebHost = "https://api.tickstep.com"
2022-01-31 12:09:28 +08:00
//DefaultTokenServiceWebHost = "http://localhost:8977"
// DefaultVideoFileExtensions 默认的视频文件后缀
DefaultVideoFileExtensions = "mp4,flv,mkv,mov,rm,rmvb,wmv,wma,mv,asf,asx,mpg,mpeg,mpe,3gp,m4v,avi,vob"
2023-02-16 22:25:09 +08:00
// DefaultDeviceName 默认客户端名称
DefaultDeviceName = "Chrome浏览器"
2024-03-02 00:55:46 +08:00
// DefaultClientId 默认的clientId
DefaultClientId = "cf9f70e8fc61430f8ec5ab5cadf31375"
2021-10-10 10:48:53 +08:00
)
var (
CmdConfigVerbose = logger.New("CONFIG", EnvVerbose)
configFilePath = filepath.Join(GetConfigDir(), ConfigName)
// Config 配置信息, 由外部调用
Config = NewConfig(configFilePath)
)
type UpdateCheckInfo struct {
PreferUpdateSrv string `json:"preferUpdateSrv"` // 优先更新服务器github | tickstep
LatestVer string `json:"latestVer"` // 最后检测到的版本
CheckTime int64 `json:"checkTime"` // 最后检测的时间戳,单位为秒
}
// PanConfig 配置详情
type PanConfig struct {
ConfigVer string `json:"configVer"`
ActiveUID string `json:"activeUID"`
UserList PanUserList `json:"userList"`
CacheSize int `json:"cacheSize"` // 下载缓存
2022-01-15 21:50:28 +08:00
MaxDownloadParallel int `json:"maxDownloadParallel"` // 最大下载并发量,即同时下载文件最大数量
2021-10-10 10:48:53 +08:00
MaxUploadParallel int `json:"maxUploadParallel"` // 最大上传并发量,即同时上传文件最大数量
MaxDownloadRate int64 `json:"maxDownloadRate"` // 限制最大下载速度,单位 B/s, 即字节/每秒
MaxUploadRate int64 `json:"maxUploadRate"` // 限制最大上传速度,单位 B/s, 即字节/每秒
SaveDir string `json:"saveDir"` // 下载储存路径
2023-10-09 16:09:34 +08:00
Proxy string `json:"proxy"` // 代理
LocalAddrs string `json:"localAddrs"` // 本地网卡地址
PreferIPType string `json:"preferIPType"` // 优先IP类型IPv4或者IPv6
2021-10-10 10:48:53 +08:00
UpdateCheckInfo UpdateCheckInfo `json:"updateCheckInfo"`
VideoFileExtensions string `json:"videoFileExtensions"`
2022-12-19 19:40:42 +08:00
FileRecordConfig string `json:"fileRecordConfig"` // 上传、下载、同步文件的记录,包括失败和成功的
2023-02-16 22:25:09 +08:00
DeviceId string `json:"deviceId"` // 客户端ID用于标识登录客户端阿里单个账号最多允许10个客户端同时登录
DeviceName string `json:"deviceName"` // 客户端名称默认为Chrome浏览器
2024-03-02 00:55:46 +08:00
// Openapi客户端信息
ClientId string `json:"clientId"`
ClientSecret string `json:"clientSecret"`
2021-10-10 10:48:53 +08:00
configFilePath string
configFile *os.File
fileMu sync.Mutex
activeUser *PanUser
}
// NewConfig 返回 PanConfig 指针对象
func NewConfig(configFilePath string) *PanConfig {
c := &PanConfig{
configFilePath: configFilePath,
}
return c
}
// Init 初始化配置
func (c *PanConfig) Init() error {
return c.init()
}
// Reload 从文件重载配置
func (c *PanConfig) Reload() error {
return c.init()
}
// Close 关闭配置文件
func (c *PanConfig) Close() error {
if c.configFile != nil {
err := c.configFile.Close()
c.configFile = nil
return err
}
return nil
}
// Save 保存配置信息到配置文件
func (c *PanConfig) Save() error {
// 检测配置项是否合法, 不合法则自动修复
c.fix()
err := c.lazyOpenConfigFile()
if err != nil {
return err
}
c.fileMu.Lock()
defer c.fileMu.Unlock()
data, err := jsoniter.MarshalIndent(c, "", " ")
if err != nil {
// json数据生成失败
panic(err)
}
// 减掉多余的部分
err = c.configFile.Truncate(int64(len(data)))
if err != nil {
return err
}
_, err = c.configFile.Seek(0, os.SEEK_SET)
if err != nil {
return err
}
_, err = c.configFile.Write(data)
if err != nil {
return err
}
return nil
}
func (c *PanConfig) init() error {
if c.configFilePath == "" {
return ErrConfigFileNotExist
}
c.initDefaultConfig()
err := c.loadConfigFromFile()
if err != nil {
return err
}
// 设置全局代理
if c.Proxy != "" {
requester.SetGlobalProxy(c.Proxy)
}
2023-10-09 16:09:34 +08:00
// 设置域名解析策略 IPv4 or IPv6
t := requester.IPAny
if strings.ToLower(c.PreferIPType) == "ipv4" {
t = requester.IPv4
} else if strings.ToLower(c.PreferIPType) == "ipv6" {
t = requester.IPv6
}
requester.SetPreferIPType(t)
// 设置本地网卡地址
if c.LocalAddrs != "" {
ips := ParseLocalAddress(c.LocalAddrs, strings.ToLower(c.PreferIPType))
if len(ips) > 0 {
logger.Verboseln("bind local address list: ", ips)
requester.SetLocalTCPAddrList(ips...)
}
}
2021-10-10 10:48:53 +08:00
return nil
}
// lazyOpenConfigFile 打开配置文件
func (c *PanConfig) lazyOpenConfigFile() (err error) {
if c.configFile != nil {
return nil
}
c.fileMu.Lock()
2022-06-16 22:30:12 +08:00
os.MkdirAll(filepath.Dir(c.configFilePath), 0755)
c.configFile, err = os.OpenFile(c.configFilePath, os.O_CREATE|os.O_RDWR, 0755)
2021-10-10 10:48:53 +08:00
c.fileMu.Unlock()
if err != nil {
if os.IsPermission(err) {
return ErrConfigFileNoPermission
}
if os.IsExist(err) {
return ErrConfigFileNotExist
}
return err
}
return nil
}
// loadConfigFromFile 载入配置
func (c *PanConfig) loadConfigFromFile() (err error) {
err = c.lazyOpenConfigFile()
if err != nil {
return err
}
// 未初始化
info, err := c.configFile.Stat()
if err != nil {
return err
}
if info.Size() == 0 {
err = c.Save()
return err
}
c.fileMu.Lock()
defer c.fileMu.Unlock()
_, err = c.configFile.Seek(0, os.SEEK_SET)
if err != nil {
return err
}
err = jsonhelper.UnmarshalData(c.configFile, c)
if err != nil {
return ErrConfigContentsParseError
}
2023-02-16 22:25:09 +08:00
if c.DeviceName == "" {
c.DeviceName = DefaultDeviceName
}
2024-03-02 00:55:46 +08:00
if c.ClientId == "" {
c.ClientId = DefaultClientId
}
2021-10-10 10:48:53 +08:00
return nil
}
func (c *PanConfig) initDefaultConfig() {
2024-07-03 21:42:48 +08:00
//c.SaveDir = GetDefaultDownloadDir()
2021-10-10 10:48:53 +08:00
c.ConfigVer = ConfigVersion
c.VideoFileExtensions = DefaultVideoFileExtensions
2023-02-16 22:25:09 +08:00
c.DeviceId = RandomDeviceId() // 生成默认客户端ID
c.DeviceName = DefaultDeviceName
2024-03-02 00:55:46 +08:00
c.ClientId = DefaultClientId
2024-03-17 14:30:06 +08:00
c.FileRecordConfig = "2" // 默认关闭
2023-10-09 16:09:34 +08:00
c.PreferIPType = "ipv4" // 默认优先IPv4
2021-10-10 10:48:53 +08:00
}
// GetConfigDir 获取配置路径
func GetConfigDir() string {
// 按照以下顺序依次获取配置目录
2024-07-03 21:42:48 +08:00
// 1.环境变量ALIYUNPAN_CONFIG_DIR => 2. XDG_CONFIG_HOME/aliyunpan => 3. /etc/aliyunpan/ => 4. ~/.aliyunpan/ => 5.当前程序目录
// 1. 从环境变量读取
2021-10-10 10:48:53 +08:00
configDir, ok := os.LookupEnv(EnvConfigDir)
if ok {
if filepath.IsAbs(configDir) {
logger.Verboseln("use config dir from ALIYUNPAN_CONFIG_DIR env: ", configDir)
2021-10-10 10:48:53 +08:00
return configDir
}
// 如果不是绝对路径, 从程序目录寻找
configDir = cmdutil.ExecutablePathJoin(configDir)
logger.Verboseln("use config dir from ALIYUNPAN_CONFIG_DIR env: ", configDir)
2022-01-07 19:01:14 +08:00
return configDir
} else {
2024-07-03 21:42:48 +08:00
// 2. $XDG_CONFIG_HOME/aliyunpan
xdgConfigHome := path.Join(xdg.ConfigHome, "aliyunpan")
if IsFolderExist(xdgConfigHome) {
logger.Verboseln("use XDG home config dir: ", xdgConfigHome)
return xdgConfigHome
}
// 3. /etc/aliyunpan/
if runtime.GOOS == "linux" {
cd := "/etc/aliyunpan"
if IsFolderExist(cd) {
logger.Verboseln("use config dir: ", cd)
return cd
}
}
2024-07-03 21:42:48 +08:00
// 4. ~/.aliyunpan/
if runtime.GOOS == "linux" || runtime.GOOS == "windows" {
2022-01-31 12:09:28 +08:00
cd, er := homedir.Expand("~/.aliyunpan")
if er == nil {
if IsFolderExist(cd) {
logger.Verboseln("use config dir: ", cd)
return cd
}
}
}
2021-10-10 10:48:53 +08:00
}
2024-07-03 21:42:48 +08:00
// 5.当前程序所在目录
2022-01-07 19:01:14 +08:00
configDir = cmdutil.ExecutablePathJoin("")
logger.Verboseln("use config dir: ", configDir)
return configDir
2021-10-10 10:48:53 +08:00
}
2024-07-03 21:42:48 +08:00
// GetDefaultDownloadDir 获取默认的下载目录
func GetDefaultDownloadDir() string {
// 按照以下顺序依次获取下载目录
// 1.环境变量ALIYUNPAN_DOWNLOAD_DIR => 2. XDG_DOWNLOAD_DIR目录 => 3. (当前程序目录)/Downloads
downloadDir := ""
// 设置默认的下载路径
switch runtime.GOOS {
case "android":
// TODO: 获取完整的的下载路径
downloadDir = "/sdcard/Download"
return downloadDir
default:
// 1. 环境变量ALIYUNPAN_DOWNLOAD_DIR
d, ok := os.LookupEnv(EnvDownloadDir)
if ok {
logger.Verboseln("use download dir from ALIYUNPAN_DOWNLOAD_DIR env: ", d)
downloadDir = d
return downloadDir
} else {
// 2. $XDG_DOWNLOAD_DIR
xdgDownloadDir := path.Join(xdg.UserDirs.Download)
if IsFolderExist(xdgDownloadDir) {
logger.Verboseln("use XDG download dir: ", xdgDownloadDir)
return xdgDownloadDir
}
}
}
// 3. (当前程序目录)/Downloads
downloadDir = cmdutil.ExecutablePathJoin("Downloads")
logger.Verboseln("use default download dir: ", downloadDir)
return downloadDir
}
// GetDownloadDir 获取当前下载目录
func GetDownloadDir() string {
if Config.SaveDir == "" {
return GetDefaultDownloadDir()
}
return Config.SaveDir
}
2022-06-09 19:58:16 +08:00
// GetPluginDir 获取插件文件夹路径
2022-04-20 21:56:47 +08:00
func GetPluginDir() string {
return strings.TrimSuffix(GetConfigDir(), "/") + "/plugin"
}
2022-12-07 21:31:33 +08:00
// GetPluginKvFile 获取插件KV键值对存储文件
func GetPluginKvFile() string {
return GetPluginDir() + "/kv.bolt"
}
2022-06-09 19:58:16 +08:00
// GetSyncDriveDir 获取同步备份的文件夹路径
func GetSyncDriveDir() string {
return strings.TrimSuffix(GetConfigDir(), "/") + "/sync_drive"
}
2022-06-26 11:51:34 +08:00
// GetLogDir 获取日志文件目录路径
func GetLogDir() string {
return strings.TrimSuffix(GetConfigDir(), "/") + "/logs"
}
// GetLogFilePath 获取日志文件路径
func GetLogFilePath() string {
dirPath := GetLogDir()
if b, e := utils.PathExists(dirPath); e == nil {
if !b {
os.MkdirAll(dirPath, 0755)
}
}
return dirPath + "/" + "aliyunpan_verbose.log"
}
// GetLockerDir 获取文件锁路径
func GetLockerDir() string {
return strings.TrimSuffix(GetConfigDir(), "/")
}
2021-10-10 10:48:53 +08:00
func (c *PanConfig) ActiveUser() *PanUser {
if c.activeUser == nil {
if c.UserList == nil {
return nil
}
if c.ActiveUID == "" {
return nil
}
for _, u := range c.UserList {
if u.UserId == c.ActiveUID {
if u.PanClient() == nil {
// restore client
2024-03-02 00:55:46 +08:00
user, err := SetupUserByCookie(u.OpenapiToken, u.WebapiToken,
u.TicketId, u.UserId,
c.DeviceId, c.DeviceName,
c.ClientId, c.ClientSecret)
2021-10-10 10:48:53 +08:00
if err != nil {
logger.Verboseln("setup user error")
return nil
}
u.panClient = user.panClient
u.Nickname = user.Nickname
2024-04-01 22:46:24 +08:00
if u.ActiveDriveId == "" {
u.ActiveDriveId = user.DriveList.GetFileDriveId()
}
2021-10-10 10:48:53 +08:00
u.DriveList = user.DriveList
// check workdir valid or not
if user.IsFileDriveActive() {
fe, err1 := u.PanClient().OpenapiPanClient().FileInfoByPath(u.ActiveDriveId, u.Workdir)
2021-10-10 10:48:53 +08:00
if err1 != nil {
// default to root
u.Workdir = "/"
u.WorkdirFileEntity = *aliyunpan.NewFileEntityForRootDir()
} else {
u.WorkdirFileEntity = *fe
2024-04-02 09:42:08 +08:00
if u.Workdir == "" {
u.Workdir = "/"
}
2021-10-10 10:48:53 +08:00
}
2023-10-07 16:42:43 +08:00
} else if user.IsResourceDriveActive() {
fe, err1 := u.PanClient().OpenapiPanClient().FileInfoByPath(u.ActiveDriveId, u.ResourceWorkdir)
2023-10-07 16:42:43 +08:00
if err1 != nil {
// default to root
u.ResourceWorkdir = "/"
u.ResourceWorkdirFileEntity = *aliyunpan.NewFileEntityForRootDir()
} else {
u.ResourceWorkdirFileEntity = *fe
2024-04-02 09:42:08 +08:00
if u.ResourceWorkdir == "" {
u.ResourceWorkdir = "/"
}
2023-10-07 16:42:43 +08:00
}
2021-10-10 10:48:53 +08:00
} else if user.IsAlbumDriveActive() {
2024-03-02 00:55:46 +08:00
fe, err1 := u.PanClient().WebapiPanClient().FileInfoByPath(u.ActiveDriveId, u.AlbumWorkdir)
2021-10-10 10:48:53 +08:00
if err1 != nil {
// default to root
u.AlbumWorkdir = "/"
u.AlbumWorkdirFileEntity = *aliyunpan.NewFileEntityForRootDir()
} else {
u.AlbumWorkdirFileEntity = *fe
2024-04-02 09:42:08 +08:00
if u.AlbumWorkdir == "" {
u.AlbumWorkdir = "/"
}
2021-10-10 10:48:53 +08:00
}
}
}
c.activeUser = u
return u
}
}
2024-03-03 23:20:27 +08:00
return nil
2021-10-10 10:48:53 +08:00
}
return c.activeUser
}
func (c *PanConfig) SetActiveUser(user *PanUser) *PanUser {
needToInsert := true
for _, u := range c.UserList {
if u.UserId == user.UserId {
// update user info
u.Nickname = user.Nickname
2024-03-02 00:55:46 +08:00
u.WebapiToken = user.WebapiToken
u.OpenapiToken = user.OpenapiToken
u.TicketId = user.TicketId
2024-04-02 09:42:08 +08:00
if u.PanClient() != nil && user.PanClient() != nil {
u.UpdateClient(user.PanClient().OpenapiPanClient(), user.PanClient().WebapiPanClient())
}
2021-10-10 10:48:53 +08:00
needToInsert = false
break
}
}
if needToInsert {
// insert
c.UserList = append(c.UserList, user)
}
// setup active user
c.ActiveUID = user.UserId
// clear active user cache
c.activeUser = nil
// reload
return c.ActiveUser()
}
func (c *PanConfig) fix() {
}
// NumLogins 获取登录的用户数量
func (c *PanConfig) NumLogins() int {
return len(c.UserList)
}
// SwitchUser 切换登录用户
2024-04-02 09:42:08 +08:00
func (c *PanConfig) SwitchUser(uid string) (*PanUser, error) {
2021-10-10 10:48:53 +08:00
for _, u := range c.UserList {
2024-04-02 09:42:08 +08:00
if u.UserId == uid {
2021-10-10 10:48:53 +08:00
return c.SetActiveUser(u), nil
}
}
return nil, fmt.Errorf("未找到指定的账号")
}
// DeleteUser 删除用户,并自动切换登录用户为用户列表第一个
func (c *PanConfig) DeleteUser(uid string) (*PanUser, error) {
for idx, u := range c.UserList {
if u.UserId == uid {
// delete user from user list
c.UserList = append(c.UserList[:idx], c.UserList[idx+1:]...)
c.ActiveUID = ""
c.activeUser = nil
if len(c.UserList) > 0 {
2024-04-02 09:42:08 +08:00
c.SwitchUser(c.UserList[0].UserId)
2021-10-10 10:48:53 +08:00
}
return u, nil
}
}
return nil, fmt.Errorf("未找到指定的账号")
}
// HTTPClient 返回设置好的 HTTPClient
func (c *PanConfig) HTTPClient(ua string) *requester.HTTPClient {
client := requester.NewHTTPClient()
if ua != "" {
client.SetUserAgent(ua)
}
return client
2022-01-31 12:09:28 +08:00
}
func (c *PanConfig) GetVideoExtensionList() []string {
if c.VideoFileExtensions == "" {
return []string{}
}
exts := strings.Split(c.VideoFileExtensions, ",")
r := []string{}
for _, ex := range exts {
ex = strings.TrimSpace(ex)
if ex != "" {
r = append(r, strings.ToLower(ex))
}
}
return r
}