From 1c6f6c772c5821384f9532fa857b73c608db80eb Mon Sep 17 00:00:00 2001 From: xiaoyaofenfen <1254525673@qq.com> Date: Sat, 10 Dec 2022 14:07:28 +0800 Subject: [PATCH] refractor login routine --- cmder/cmder_helper.go | 98 --------------------------------- internal/command/album.go | 2 +- internal/command/cd.go | 6 +- internal/command/command.go | 8 +-- internal/command/download.go | 2 +- internal/command/drive_list.go | 5 +- internal/command/export_file.go | 10 ++-- internal/command/import_file.go | 2 +- internal/command/locate.go | 2 +- internal/command/login.go | 11 ++-- internal/command/ls_search.go | 2 +- internal/command/mkdir.go | 4 +- internal/command/mv.go | 3 +- internal/command/quota.go | 5 +- internal/command/recycle.go | 2 +- internal/command/rename.go | 3 +- internal/command/rm.go | 2 +- internal/command/share.go | 2 +- internal/command/sync.go | 2 +- internal/command/token.go | 6 +- internal/command/tree.go | 2 +- internal/command/upload.go | 4 +- internal/command/user_info.go | 10 ++-- internal/command/utils.go | 97 ++++++++++++++++++++++++++++++++ internal/command/webdav.go | 4 +- main.go | 12 ++-- 26 files changed, 148 insertions(+), 158 deletions(-) diff --git a/cmder/cmder_helper.go b/cmder/cmder_helper.go index f1fe128..46d0d5b 100644 --- a/cmder/cmder_helper.go +++ b/cmder/cmder_helper.go @@ -1,39 +1,11 @@ package cmder import ( - "fmt" - "github.com/tickstep/aliyunpan-api/aliyunpan" - "github.com/tickstep/aliyunpan-api/aliyunpan/apierror" - "github.com/tickstep/aliyunpan/cmder/cmdliner" - "github.com/tickstep/aliyunpan/internal/config" - "github.com/tickstep/aliyunpan/internal/functions/panlogin" - "github.com/tickstep/library-go/logger" "github.com/urfave/cli" - "sync" ) var ( appInstance *cli.App - - saveConfigMutex *sync.Mutex = new(sync.Mutex) - - ReloadConfigFunc = func(c *cli.Context) error { - err := config.Config.Reload() - if err != nil { - fmt.Printf("重载配置错误: %s\n", err) - } - return nil - } - - SaveConfigFunc = func(c *cli.Context) error { - saveConfigMutex.Lock() - defer saveConfigMutex.Unlock() - err := config.Config.Save() - if err != nil { - fmt.Printf("保存配置错误: %s\n", err) - } - return nil - } ) func SetApp(app *cli.App) { @@ -43,73 +15,3 @@ func SetApp(app *cli.App) { func App() *cli.App { return appInstance } - -func DoLoginHelper(refreshToken string) (refreshTokenStr string, webToken aliyunpan.WebLoginToken, error error) { - line := cmdliner.NewLiner() - defer line.Close() - - if refreshToken == "" { - refreshToken, error = line.State.Prompt("请输入RefreshToken, 回车键提交 > ") - if error != nil { - return - } - } - - // app login - atoken, apperr := aliyunpan.GetAccessTokenFromRefreshToken(refreshToken) - if apperr != nil { - if apperr.Code == apierror.ApiCodeTokenExpiredCode || apperr.Code == apierror.ApiCodeRefreshTokenExpiredCode { - fmt.Println("Token过期,需要重新登录") - } else { - fmt.Println("Token登录失败:", apperr) - } - return "", webToken, fmt.Errorf("登录失败") - } - refreshTokenStr = refreshToken - return refreshTokenStr, *atoken, nil -} - -func TryLogin() *config.PanUser { - // can do automatically login? - for _, u := range config.Config.UserList { - if u.UserId == config.Config.ActiveUID { - // login - _, webToken, err := DoLoginHelper(u.RefreshToken) - if err != nil { - logger.Verboseln("automatically login use saved refresh token error ", err) - if u.TokenId != "" { - logger.Verboseln("try to login use tokenId") - h := panlogin.NewLoginHelper(config.DefaultTokenServiceWebHost) - r, e := h.GetRefreshToken(u.TokenId) - if e != nil { - logger.Verboseln("try to login use tokenId error", e) - break - } - refreshToken, e := h.ParseSecureRefreshToken("", r.SecureRefreshToken) - if e != nil { - logger.Verboseln("try to parse refresh token error", e) - break - } - _, webToken, err = DoLoginHelper(refreshToken) - if err != nil { - logger.Verboseln("try to use refresh token from tokenId error", e) - break - } - fmt.Println("Token重新自动登录成功") - // save new refresh token - u.RefreshToken = refreshToken - } - break - } - // success - u.WebToken = webToken - - // save - SaveConfigFunc(nil) - // reload - ReloadConfigFunc(nil) - return config.Config.ActiveUser() - } - } - return nil -} diff --git a/internal/command/album.go b/internal/command/album.go index 110b825..9339e04 100644 --- a/internal/command/album.go +++ b/internal/command/album.go @@ -46,7 +46,7 @@ func CmdAlbum() cli.Command { Usage: "相簿(Beta)", UsageText: cmder.App().Name + " album", Category: "阿里云盘", - Before: cmder.ReloadConfigFunc, + Before: ReloadConfigFunc, Action: func(c *cli.Context) error { cli.ShowCommandHelp(c, c.Command.Name) return nil diff --git a/internal/command/cd.go b/internal/command/cd.go index ffa457c..f213856 100644 --- a/internal/command/cd.go +++ b/internal/command/cd.go @@ -43,8 +43,8 @@ func CmdCd() cli.Command { 切换根目录: aliyunpan cd / `, - Before: cmder.ReloadConfigFunc, - After: cmder.SaveConfigFunc, + Before: ReloadConfigFunc, + After: SaveConfigFunc, Action: func(c *cli.Context) error { if c.NArg() == 0 { cli.ShowCommandHelp(c, c.Command.Name) @@ -73,7 +73,7 @@ func CmdPwd() cli.Command { Usage: "输出工作目录", UsageText: cmder.App().Name + " pwd", Category: "阿里云盘", - Before: cmder.ReloadConfigFunc, + Before: ReloadConfigFunc, Action: func(c *cli.Context) error { if config.Config.ActiveUser() == nil { fmt.Println("未登录账号") diff --git a/internal/command/command.go b/internal/command/command.go index 058eee9..da71e6a 100644 --- a/internal/command/command.go +++ b/internal/command/command.go @@ -97,7 +97,7 @@ func newRapidUploadItem(rapidUploadShareLink string) (*RapidUploadItem, error) { item.FileSha1 = strings.TrimSpace(parts[1]) // size - if size,e := strconv.ParseInt(parts[2], 10, 64); e == nil{ + if size, e := strconv.ParseInt(parts[2], 10, 64); e == nil { item.FileSize = size } else { return nil, fmt.Errorf("文件大小错误: %s", rapidUploadShareLink) @@ -131,7 +131,6 @@ func (r *RapidUploadItem) createRapidUploadLink(hideRelativePath bool) string { p := r.FilePath p = strings.ReplaceAll(p, "\\", "/") - fileName := path.Base(p) dirPath := path.Dir(p) @@ -160,8 +159,8 @@ func CmdConfig() cli.Command { Usage: "显示和修改程序配置项", Description: "显示和修改程序配置项", Category: "配置", - Before: cmder.ReloadConfigFunc, - After: cmder.SaveConfigFunc, + Before: ReloadConfigFunc, + After: SaveConfigFunc, Action: func(c *cli.Context) error { fmt.Printf("----\n运行 %s config set 可进行设置配置\n\n当前配置:\n", cmder.App().Name) config.Config.PrintTable() @@ -283,7 +282,6 @@ func CmdConfig() cli.Command { } } - func CmdTool() cli.Command { return cli.Command{ Name: "tool", diff --git a/internal/command/download.go b/internal/command/download.go index e39895b..4b979e1 100644 --- a/internal/command/download.go +++ b/internal/command/download.go @@ -109,7 +109,7 @@ func CmdDownload() cli.Command { 5)排除 myfile.txt 文件:-exn "^myfile.txt$" `, Category: "阿里云盘", - Before: cmder.ReloadConfigFunc, + Before: ReloadConfigFunc, Action: func(c *cli.Context) error { if c.NArg() == 0 { cli.ShowCommandHelp(c, c.Command.Name) diff --git a/internal/command/drive_list.go b/internal/command/drive_list.go index cba76ad..2a5b56b 100644 --- a/internal/command/drive_list.go +++ b/internal/command/drive_list.go @@ -17,7 +17,6 @@ import ( "fmt" "github.com/olekukonko/tablewriter" "github.com/tickstep/aliyunpan-api/aliyunpan" - "github.com/tickstep/aliyunpan/cmder" "github.com/tickstep/aliyunpan/cmder/cmdtable" "github.com/tickstep/aliyunpan/internal/config" "github.com/urfave/cli" @@ -38,8 +37,8 @@ func CmdDrive() cli.Command { aliyunpan drive `, Category: "阿里云盘账号", - Before: cmder.ReloadConfigFunc, - After: cmder.SaveConfigFunc, + Before: ReloadConfigFunc, + After: SaveConfigFunc, Action: func(c *cli.Context) error { inputData := c.Args().Get(0) targetDriveId := strings.TrimSpace(inputData) diff --git a/internal/command/export_file.go b/internal/command/export_file.go index 7b6c10f..8316f3e 100644 --- a/internal/command/export_file.go +++ b/internal/command/export_file.go @@ -28,7 +28,6 @@ import ( "time" ) - func CmdExport() cli.Command { return cli.Command{ Name: "export", @@ -50,7 +49,7 @@ func CmdExport() cli.Command { aliyunpan export / /Users/tickstep/Downloads/export_files.txt `, Category: "阿里云盘", - Before: cmder.ReloadConfigFunc, + Before: ReloadConfigFunc, Action: func(c *cli.Context) error { if c.NArg() < 2 { cli.ShowCommandHelp(c, c.Command.Name) @@ -75,12 +74,11 @@ func CmdExport() cli.Command { } } - func RunExportFiles(driveId string, overwrite bool, panPaths []string, saveLocalFilePath string) { activeUser := config.Config.ActiveUser() panClient := activeUser.PanClient() - lfi,_ := os.Stat(saveLocalFilePath) + lfi, _ := os.Stat(saveLocalFilePath) realSaveFilePath := saveLocalFilePath if lfi != nil { if lfi.IsDir() { @@ -94,7 +92,7 @@ func RunExportFiles(driveId string, overwrite bool, panPaths []string, saveLocal } else { // create file localDir := path.Dir(saveLocalFilePath) - dirFs,_ := os.Stat(localDir) + dirFs, _ := os.Stat(localDir) if dirFs != nil { if !dirFs.IsDir() { fmt.Println("指定的保存文件路径不合法") @@ -117,7 +115,7 @@ func RunExportFiles(driveId string, overwrite bool, panPaths []string, saveLocal return } - for _,panPath := range panPaths { + for _, panPath := range panPaths { panPath = activeUser.PathJoin(driveId, panPath) panClient.FilesDirectoriesRecurseList(driveId, panPath, func(depth int, _ string, fd *aliyunpan.FileEntity, apiError *apierror.ApiError) bool { if apiError != nil { diff --git a/internal/command/import_file.go b/internal/command/import_file.go index 7e19eb6..50b6b45 100644 --- a/internal/command/import_file.go +++ b/internal/command/import_file.go @@ -64,7 +64,7 @@ func CmdImport() cli.Command { aliyunpan import -saveto=/ /Users/tickstep/Downloads/export_files.txt `, Category: "阿里云盘", - Before: cmder.ReloadConfigFunc, + Before: ReloadConfigFunc, Action: func(c *cli.Context) error { if c.NArg() < 1 { cli.ShowCommandHelp(c, c.Command.Name) diff --git a/internal/command/locate.go b/internal/command/locate.go index 30521d5..48d2edf 100644 --- a/internal/command/locate.go +++ b/internal/command/locate.go @@ -49,7 +49,7 @@ func CmdLocateUrl() cli.Command { aliyunpan locate -saveto "/Volumes/Downloads/file_url.txt" /我的资源 `, Category: "阿里云盘", - Before: cmder.ReloadConfigFunc, + Before: ReloadConfigFunc, Action: func(c *cli.Context) error { if c.NArg() == 0 { cli.ShowCommandHelp(c, c.Command.Name) diff --git a/internal/command/login.go b/internal/command/login.go index 89333de..e94a8b9 100644 --- a/internal/command/login.go +++ b/internal/command/login.go @@ -16,7 +16,6 @@ package command import ( "fmt" "github.com/tickstep/aliyunpan-api/aliyunpan" - "github.com/tickstep/aliyunpan/cmder" "github.com/tickstep/aliyunpan/cmder/cmdliner" "github.com/tickstep/aliyunpan/internal/config" "github.com/tickstep/aliyunpan/internal/functions/panlogin" @@ -42,8 +41,8 @@ func CmdLogin() cli.Command { aliyunpan login -QrCode `, Category: "阿里云盘账号", - Before: cmder.ReloadConfigFunc, // 每次进行登录动作的时候需要调用刷新配置 - After: cmder.SaveConfigFunc, // 登录完成需要调用保存配置 + Before: ReloadConfigFunc, // 每次进行登录动作的时候需要调用刷新配置 + After: SaveConfigFunc, // 登录完成需要调用保存配置 Action: func(c *cli.Context) error { refreshTokenStr := "" if refreshTokenStr == "" { @@ -93,8 +92,8 @@ func CmdLogout() cli.Command { Usage: "退出阿里帐号", Description: "退出当前登录的帐号", Category: "阿里云盘账号", - Before: cmder.ReloadConfigFunc, - After: cmder.SaveConfigFunc, + Before: ReloadConfigFunc, + After: SaveConfigFunc, Action: func(c *cli.Context) error { if config.Config.NumLogins() == 0 { fmt.Println("未设置任何帐号, 不能退出") @@ -183,6 +182,6 @@ func RunLogin(useQrCodeLogin bool, refreshToken string) (tokenId, refreshTokenSt tokenId = qrCodeUrlResult.TokenId } - refreshTokenStr, webToken, error = cmder.DoLoginHelper(refreshToken) + refreshTokenStr, webToken, error = DoLoginHelper(refreshToken) return } diff --git a/internal/command/ls_search.go b/internal/command/ls_search.go index d5e8fbc..b88efda 100644 --- a/internal/command/ls_search.go +++ b/internal/command/ls_search.go @@ -69,7 +69,7 @@ func CmdLs() cli.Command { aliyunpan ll /我的资源 `, Category: "阿里云盘", - Before: cmder.ReloadConfigFunc, + Before: ReloadConfigFunc, Action: func(c *cli.Context) error { if config.Config.ActiveUser() == nil { fmt.Println("未登录账号") diff --git a/internal/command/mkdir.go b/internal/command/mkdir.go index 2c9a0f2..3246cad 100644 --- a/internal/command/mkdir.go +++ b/internal/command/mkdir.go @@ -29,7 +29,7 @@ func CmdMkdir() cli.Command { Usage: "创建目录", UsageText: cmder.App().Name + " mkdir <目录>", Category: "阿里云盘", - Before: cmder.ReloadConfigFunc, + Before: ReloadConfigFunc, Action: func(c *cli.Context) error { if c.NArg() == 0 { cli.ShowCommandHelp(c, c.Command.Name) @@ -59,7 +59,7 @@ func RunMkdir(driveId, name string) { rs := &aliyunpan.MkdirResult{} err := apierror.NewFailedApiError("") - rs, err = activeUser.PanClient().MkdirRecursive(driveId,"", "", 0, pathSlice) + rs, err = activeUser.PanClient().MkdirRecursive(driveId, "", "", 0, pathSlice) if err != nil { fmt.Println("创建文件夹失败:" + err.Error()) diff --git a/internal/command/mv.go b/internal/command/mv.go index ff87ecb..86a2ebe 100644 --- a/internal/command/mv.go +++ b/internal/command/mv.go @@ -16,7 +16,6 @@ package command import ( "fmt" "github.com/tickstep/aliyunpan-api/aliyunpan" - "github.com/tickstep/aliyunpan/cmder" "github.com/tickstep/aliyunpan/cmder/cmdtable" "github.com/tickstep/aliyunpan/internal/config" "github.com/urfave/cli" @@ -43,7 +42,7 @@ func CmdMv() cli.Command { aliyunpan mv /我的资源/*.png /我的图片 `, Category: "阿里云盘", - Before: cmder.ReloadConfigFunc, + Before: ReloadConfigFunc, Action: func(c *cli.Context) error { if c.NArg() <= 1 { cli.ShowCommandHelp(c, c.Command.Name) diff --git a/internal/command/quota.go b/internal/command/quota.go index 9076d2c..0eed92d 100644 --- a/internal/command/quota.go +++ b/internal/command/quota.go @@ -15,7 +15,6 @@ package command import ( "fmt" - "github.com/tickstep/aliyunpan/cmder" "github.com/tickstep/aliyunpan/internal/config" "github.com/tickstep/library-go/converter" "github.com/urfave/cli" @@ -34,7 +33,7 @@ func CmdQuota() cli.Command { Usage: "获取当前帐号空间配额", Description: "获取网盘的总储存空间, 和已使用的储存空间", Category: "阿里云盘账号", - Before: cmder.ReloadConfigFunc, + Before: ReloadConfigFunc, Action: func(c *cli.Context) error { if config.Config.ActiveUser() == nil { fmt.Println("未登录账号") @@ -59,6 +58,6 @@ func RunGetQuotaInfo() (quotaInfo *QuotaInfo, error error) { } return &QuotaInfo{ UsedSize: int64(user.UsedSize), - Quota: int64(user.TotalSize), + Quota: int64(user.TotalSize), }, nil } diff --git a/internal/command/recycle.go b/internal/command/recycle.go index 19377a1..ff80729 100644 --- a/internal/command/recycle.go +++ b/internal/command/recycle.go @@ -45,7 +45,7 @@ func CmdRecycle() cli.Command { aliyunpan recycle delete -all `, Category: "阿里云盘", - Before: cmder.ReloadConfigFunc, + Before: ReloadConfigFunc, Action: func(c *cli.Context) error { if c.NumFlags() <= 0 || c.NArg() <= 0 { cli.ShowCommandHelp(c, c.Command.Name) diff --git a/internal/command/rename.go b/internal/command/rename.go index a88135e..0780519 100644 --- a/internal/command/rename.go +++ b/internal/command/rename.go @@ -16,7 +16,6 @@ package command import ( "fmt" "github.com/tickstep/aliyunpan-api/aliyunpan/apiutil" - "github.com/tickstep/aliyunpan/cmder" "github.com/tickstep/aliyunpan/internal/config" "github.com/urfave/cli" "path" @@ -40,7 +39,7 @@ func CmdRename() cli.Command { aliyunpan rename /test/1.mp4 /test/2.mp4 `, Category: "阿里云盘", - Before: cmder.ReloadConfigFunc, + Before: ReloadConfigFunc, Action: func(c *cli.Context) error { if c.NArg() != 2 { cli.ShowCommandHelp(c, c.Command.Name) diff --git a/internal/command/rm.go b/internal/command/rm.go index 6653c13..cf3f728 100644 --- a/internal/command/rm.go +++ b/internal/command/rm.go @@ -49,7 +49,7 @@ func CmdRm() cli.Command { aliyunpan rm /我的资源/*.zip `, Category: "阿里云盘", - Before: cmder.ReloadConfigFunc, + Before: ReloadConfigFunc, Action: func(c *cli.Context) error { if c.NArg() == 0 { cli.ShowCommandHelp(c, c.Command.Name) diff --git a/internal/command/share.go b/internal/command/share.go index 218bb92..1ef6854 100644 --- a/internal/command/share.go +++ b/internal/command/share.go @@ -36,7 +36,7 @@ func CmdShare() cli.Command { Usage: "分享文件/目录", UsageText: cmder.App().Name + " share", Category: "阿里云盘", - Before: cmder.ReloadConfigFunc, + Before: ReloadConfigFunc, Action: func(c *cli.Context) error { cli.ShowCommandHelp(c, c.Command.Name) return nil diff --git a/internal/command/sync.go b/internal/command/sync.go index f1731eb..2e482fa 100644 --- a/internal/command/sync.go +++ b/internal/command/sync.go @@ -50,7 +50,7 @@ func CmdSync() cli.Command { aliyunpan sync start -h `, Category: "阿里云盘", - Before: cmder.ReloadConfigFunc, + Before: ReloadConfigFunc, Action: func(c *cli.Context) error { cli.ShowCommandHelp(c, c.Command.Name) return nil diff --git a/internal/command/token.go b/internal/command/token.go index 1fbd3f7..9214381 100644 --- a/internal/command/token.go +++ b/internal/command/token.go @@ -30,7 +30,7 @@ func CmdToken() cli.Command { Usage: "Token相关操作", UsageText: cmder.App().Name + " token", Category: "阿里云盘账号", - Before: cmder.ReloadConfigFunc, + Before: ReloadConfigFunc, Action: func(c *cli.Context) error { cli.ShowCommandHelp(c, c.Command.Name) return nil @@ -76,7 +76,7 @@ func CmdToken() cli.Command { // RunTokenUpdate 执行Token更新 func RunTokenUpdate(modeFlag string) { - cmder.ReloadConfigFunc(nil) + ReloadConfigFunc(nil) // 获取当前插件 pluginManger := plugins.NewPluginManager(config.GetPluginDir()) @@ -125,5 +125,5 @@ func RunTokenUpdate(modeFlag string) { logger.Verbosef("UserTokenRefreshFinishCallback error: " + er.Error()) } } - cmder.SaveConfigFunc(nil) + SaveConfigFunc(nil) } diff --git a/internal/command/tree.go b/internal/command/tree.go index 7f49948..8f4f466 100644 --- a/internal/command/tree.go +++ b/internal/command/tree.go @@ -34,7 +34,7 @@ func CmdTree() cli.Command { aliyunpan tree -fp /我的资源 `, Category: "阿里云盘", - Before: cmder.ReloadConfigFunc, + Before: ReloadConfigFunc, Action: func(c *cli.Context) error { if config.Config.ActiveUser() == nil { fmt.Println("未登录账号") diff --git a/internal/command/upload.go b/internal/command/upload.go index 8ef57b8..2566c58 100644 --- a/internal/command/upload.go +++ b/internal/command/upload.go @@ -155,7 +155,7 @@ func CmdUpload() cli.Command { 5)排除 myfile.txt 文件:-exn "^myfile.txt$" `, Category: "阿里云盘", - Before: cmder.ReloadConfigFunc, + Before: ReloadConfigFunc, Action: func(c *cli.Context) error { if c.NArg() < 2 { cli.ShowCommandHelp(c, c.Command.Name) @@ -214,7 +214,7 @@ func CmdRapidUpload() cli.Command { aliyunpan rapidupload "aliyunpan://file.dmg|752FCCBFB2436A6FFCA3B287831D4FAA5654B07E|7005440|pan_folder" "aliyunpan://file1.dmg|752FCCBFB2436A6FFCA3B287831D4FAA5654B07E|7005440|pan_folder" `, Category: "阿里云盘", - Before: cmder.ReloadConfigFunc, + Before: ReloadConfigFunc, Action: func(c *cli.Context) error { if c.NArg() <= 0 { cli.ShowCommandHelp(c, c.Command.Name) diff --git a/internal/command/user_info.go b/internal/command/user_info.go index 9a2585f..0439259 100644 --- a/internal/command/user_info.go +++ b/internal/command/user_info.go @@ -29,7 +29,7 @@ func CmdLoglist() cli.Command { Usage: "列出帐号列表", Description: "列出所有已登录的阿里账号", Category: "阿里云盘账号", - Before: cmder.ReloadConfigFunc, + Before: ReloadConfigFunc, Action: func(c *cli.Context) error { fmt.Println(config.Config.UserList.String()) return nil @@ -50,8 +50,8 @@ func CmdSu() cli.Command { aliyunpan su `, Category: "阿里云盘账号", - Before: cmder.ReloadConfigFunc, - After: cmder.SaveConfigFunc, + Before: ReloadConfigFunc, + After: SaveConfigFunc, Action: func(c *cli.Context) error { if c.NArg() >= 2 { cli.ShowCommandHelp(c, c.Command.Name) @@ -102,7 +102,7 @@ func CmdSu() cli.Command { } if switchedUser == nil { - switchedUser = cmder.TryLogin() + switchedUser = TryLogin() } if switchedUser != nil { @@ -122,7 +122,7 @@ func CmdWho() cli.Command { Usage: "获取当前帐号", Description: "获取当前帐号的信息", Category: "阿里云盘账号", - Before: cmder.ReloadConfigFunc, + Before: ReloadConfigFunc, Action: func(c *cli.Context) error { if config.Config.ActiveUser() == nil { fmt.Println("未登录账号") diff --git a/internal/command/utils.go b/internal/command/utils.go index 58d78df..cfba6fa 100644 --- a/internal/command/utils.go +++ b/internal/command/utils.go @@ -16,20 +16,45 @@ package command import ( "fmt" "github.com/tickstep/aliyunpan-api/aliyunpan" + "github.com/tickstep/aliyunpan-api/aliyunpan/apierror" + "github.com/tickstep/aliyunpan/cmder/cmdliner" "github.com/tickstep/aliyunpan/internal/config" + "github.com/tickstep/aliyunpan/internal/functions/panlogin" "github.com/tickstep/aliyunpan/internal/plugins" "github.com/tickstep/aliyunpan/internal/utils" "github.com/tickstep/library-go/logger" + "github.com/urfave/cli" "math/rand" "net/url" "path" "path/filepath" "strings" + "sync" "time" ) var ( panCommandVerbose = logger.New("PANCOMMAND", config.EnvVerbose) + + saveConfigMutex *sync.Mutex = new(sync.Mutex) + + ReloadConfigFunc = func(c *cli.Context) error { + err := config.Config.Reload() + if err != nil { + fmt.Printf("重载配置错误: %s\n", err) + } + return nil + } + + SaveConfigFunc = func(c *cli.Context) error { + saveConfigMutex.Lock() + defer saveConfigMutex.Unlock() + err := config.Config.Save() + if err != nil { + fmt.Printf("保存配置错误: %s\n", err) + } + return nil + } ) // RunTestShellPattern 执行测试通配符 @@ -160,3 +185,75 @@ func isIncludeFile(pattern string, fileName string) bool { func isMatchWildcardPattern(name string) bool { return strings.ContainsAny(name, "*") || strings.ContainsAny(name, "?") || strings.ContainsAny(name, "[") } + +// DoLoginHelper 登录助手,使用token进行登录 +func DoLoginHelper(refreshToken string) (refreshTokenStr string, webToken aliyunpan.WebLoginToken, error error) { + line := cmdliner.NewLiner() + defer line.Close() + + if refreshToken == "" { + refreshToken, error = line.State.Prompt("请输入RefreshToken, 回车键提交 > ") + if error != nil { + return + } + } + + // app login + atoken, apperr := aliyunpan.GetAccessTokenFromRefreshToken(refreshToken) + if apperr != nil { + if apperr.Code == apierror.ApiCodeTokenExpiredCode || apperr.Code == apierror.ApiCodeRefreshTokenExpiredCode { + fmt.Println("Token过期,需要重新登录") + } else { + fmt.Println("Token登录失败:", apperr) + } + return "", webToken, fmt.Errorf("登录失败") + } + refreshTokenStr = refreshToken + return refreshTokenStr, *atoken, nil +} + +// TryLogin 尝试登录,基础应用支持的各类登录方式进行尝试成功登录 +func TryLogin() *config.PanUser { + // can do automatically login? + for _, u := range config.Config.UserList { + if u.UserId == config.Config.ActiveUID { + // login + _, webToken, err := DoLoginHelper(u.RefreshToken) + if err != nil { + logger.Verboseln("automatically login use saved refresh token error ", err) + if u.TokenId != "" { + logger.Verboseln("try to login use tokenId") + h := panlogin.NewLoginHelper(config.DefaultTokenServiceWebHost) + r, e := h.GetRefreshToken(u.TokenId) + if e != nil { + logger.Verboseln("try to login use tokenId error", e) + break + } + refreshToken, e := h.ParseSecureRefreshToken("", r.SecureRefreshToken) + if e != nil { + logger.Verboseln("try to parse refresh token error", e) + break + } + _, webToken, err = DoLoginHelper(refreshToken) + if err != nil { + logger.Verboseln("try to use refresh token from tokenId error", e) + break + } + fmt.Println("Token重新自动登录成功") + // save new refresh token + u.RefreshToken = refreshToken + } + break + } + // success + u.WebToken = webToken + + // save + SaveConfigFunc(nil) + // reload + ReloadConfigFunc(nil) + return config.Config.ActiveUser() + } + } + return nil +} diff --git a/internal/command/webdav.go b/internal/command/webdav.go index 8cbf1da..bc8d23d 100644 --- a/internal/command/webdav.go +++ b/internal/command/webdav.go @@ -30,8 +30,8 @@ func CmdWebdav() cli.Command { Usage: "在线网盘服务", Description: "webdav在线网盘服务", Category: "阿里云盘", - Before: cmder.ReloadConfigFunc, - After: cmder.SaveConfigFunc, + Before: ReloadConfigFunc, + After: SaveConfigFunc, Action: func(c *cli.Context) error { fmt.Print(` 本文命令可以让阿里云盘变身为webdav协议的文件服务器。这样你可以把阿里云盘挂载为Windows、Linux、Mac系统的磁盘,可以通过NAS系统做文件管理或文件同步等等。 diff --git a/main.go b/main.go index 2161a7f..a196561 100644 --- a/main.go +++ b/main.go @@ -75,16 +75,16 @@ func init() { } func checkLoginExpiredAndRelogin() { - cmder.ReloadConfigFunc(nil) + command.ReloadConfigFunc(nil) activeUser := config.Config.ActiveUser() if activeUser == nil || activeUser.UserId == "" { // maybe expired, try to login - cmder.TryLogin() + command.TryLogin() } else { // 刷新过期Token并保存到配置文件 command.RefreshTokenInNeed(activeUser) } - cmder.SaveConfigFunc(nil) + command.SaveConfigFunc(nil) } func main() { @@ -301,7 +301,7 @@ func main() { fmt.Printf("提示: 输入 help 获取帮助.\n") // check update - cmder.ReloadConfigFunc(c) + command.ReloadConfigFunc(c) if config.Config.UpdateCheckInfo.LatestVer != "" { if utils.ParseVersionNum(config.Config.UpdateCheckInfo.LatestVer) > utils.ParseVersionNum(config.AppVersion) { fmt.Printf("\n当前的软件版本为:%s, 现在有新版本 %s 可供更新,强烈推荐进行更新!(可以输入 update 命令进行更新)\n\n", @@ -322,7 +322,7 @@ func main() { config.Config.UpdateCheckInfo.CheckTime = nowTime // save - cmder.SaveConfigFunc(c) + command.SaveConfigFunc(c) } }() @@ -333,7 +333,7 @@ func main() { ) if activeUser == nil { - activeUser = cmder.TryLogin() + activeUser = command.TryLogin() } if activeUser != nil && activeUser.Nickname != "" {