🐝 reformat code

This commit is contained in:
微凉
2021-03-05 21:25:44 +08:00
parent d137ef8759
commit 3138e031f5
28 changed files with 389 additions and 389 deletions

View File

@ -11,68 +11,68 @@ import (
// use token login // use token login
func TokenLogin() (*TokenLoginResp, error) { func TokenLogin() (*TokenLoginResp, error) {
log.Infof("尝试使用token登录...") log.Infof("尝试使用token登录...")
url:="https://auth.aliyundrive.com/v2/oauth/token_login" url := "https://auth.aliyundrive.com/v2/oauth/token_login"
req:=TokenLoginReq{Token:conf.Conf.AliDrive.LoginToken} req := TokenLoginReq{Token: conf.Conf.AliDrive.LoginToken}
log.Debugf("token_login_req:%+v",req) log.Debugf("token_login_req:%+v", req)
var tokenLogin TokenLoginResp var tokenLogin TokenLoginResp
if body, err := DoPost(url, req,false); err != nil { if body, err := DoPost(url, req, false); err != nil {
log.Errorf("tokenLogin-doPost出错:%s",err.Error()) log.Errorf("tokenLogin-doPost出错:%s", err.Error())
return nil,err return nil, err
}else { } else {
if err = json.Unmarshal(body,&tokenLogin);err!=nil { if err = json.Unmarshal(body, &tokenLogin); err != nil {
log.Errorf("解析json[%s]出错:%s",string(body),err.Error()) log.Errorf("解析json[%s]出错:%s", string(body), err.Error())
return nil,err return nil, err
} }
} }
if tokenLogin.IsAvailable() { if tokenLogin.IsAvailable() {
return &tokenLogin,nil return &tokenLogin, nil
} }
return nil,fmt.Errorf("登录token失效,请更换:%s",tokenLogin.Message) return nil, fmt.Errorf("登录token失效,请更换:%s", tokenLogin.Message)
} }
// get access token // get access token
func GetToken(tokenLogin *TokenLoginResp) (*TokenResp,error) { func GetToken(tokenLogin *TokenLoginResp) (*TokenResp, error) {
log.Infof("获取API token...") log.Infof("获取API token...")
url:="https://websv.aliyundrive.com/token/get" url := "https://websv.aliyundrive.com/token/get"
code:=utils.GetCode(tokenLogin.Goto) code := utils.GetCode(tokenLogin.Goto)
if code == "" { if code == "" {
return nil,fmt.Errorf("获取code出错") return nil, fmt.Errorf("获取code出错")
} }
req:=GetTokenReq{Code:code} req := GetTokenReq{Code: code}
var token TokenResp var token TokenResp
if body, err := DoPost(url, req,false); err != nil { if body, err := DoPost(url, req, false); err != nil {
log.Errorf("tokenLogin-doPost出错:%s",err.Error()) log.Errorf("tokenLogin-doPost出错:%s", err.Error())
return nil,err return nil, err
}else { } else {
if err = json.Unmarshal(body,&token);err!=nil { if err = json.Unmarshal(body, &token); err != nil {
log.Errorf("解析json[%s]出错:%s",string(body),err.Error()) log.Errorf("解析json[%s]出错:%s", string(body), err.Error())
log.Errorf("此处json解析失败应该是code失效") log.Errorf("此处json解析失败应该是code失效")
return nil,fmt.Errorf("code失效") return nil, fmt.Errorf("code失效")
} }
} }
return &token,nil return &token, nil
} }
// refresh access_token token by refresh_token // refresh access_token token by refresh_token
func RefreshToken() bool { func RefreshToken() bool {
log.Infof("刷新token...") log.Infof("刷新token...")
url:="https://websv.aliyundrive.com/token/refresh" url := "https://websv.aliyundrive.com/token/refresh"
req:=RefreshTokenReq{RefreshToken:conf.Conf.AliDrive.RefreshToken} req := RefreshTokenReq{RefreshToken: conf.Conf.AliDrive.RefreshToken}
var token TokenResp var token TokenResp
if body, err := DoPost(url, req,false); err != nil { if body, err := DoPost(url, req, false); err != nil {
log.Errorf("tokenLogin-doPost出错:%s",err.Error()) log.Errorf("tokenLogin-doPost出错:%s", err.Error())
return false return false
}else { } else {
if err = json.Unmarshal(body,&token);err!=nil { if err = json.Unmarshal(body, &token); err != nil {
log.Errorf("解析json[%s]出错:%s",string(body),err.Error()) log.Errorf("解析json[%s]出错:%s", string(body), err.Error())
log.Errorf("此处json解析失败应该是refresh_token失效") log.Errorf("此处json解析失败应该是refresh_token失效")
return false return false
} }
} }
//刷新成功 更新token并写入文件 //刷新成功 更新token并写入文件
conf.Conf.AliDrive.AccessToken=token.AccessToken conf.Conf.AliDrive.AccessToken = token.AccessToken
conf.Conf.AliDrive.RefreshToken=token.RefreshToken conf.Conf.AliDrive.RefreshToken = token.RefreshToken
conf.Authorization=token.TokenType+"\t"+token.AccessToken conf.Authorization = token.TokenType + "\t" + token.AccessToken
utils.WriteToYml(conf.Con,conf.Conf) utils.WriteToYml(conf.Con, conf.Conf)
return true return true
} }

View File

@ -1,5 +1,5 @@
package alidrive package alidrive
var ( var (
User *UserInfo User *UserInfo
) )

View File

@ -24,10 +24,10 @@ type GetReq struct {
// download request bean // download request bean
type DownloadReq struct { type DownloadReq struct {
DriveId string `json:"drive_id"` DriveId string `json:"drive_id"`
FileId string `json:"file_id"` FileId string `json:"file_id"`
ExpireSec int `json:"expire_sec"` ExpireSec int `json:"expire_sec"`
FileName string `json:"file_name"` FileName string `json:"file_name"`
} }
// search request bean // search request bean

View File

@ -14,64 +14,64 @@ import (
// get file // get file
func GetFile(fileId string) (*File, error) { func GetFile(fileId string) (*File, error) {
url:=conf.Conf.AliDrive.ApiUrl+"/file/get" url := conf.Conf.AliDrive.ApiUrl + "/file/get"
req:=GetReq{ req := GetReq{
DriveId: User.DefaultDriveId, DriveId: User.DefaultDriveId,
FileId: fileId, FileId: fileId,
ImageThumbnailProcess: conf.ImageThumbnailProcess, ImageThumbnailProcess: conf.ImageThumbnailProcess,
VideoThumbnailProcess: conf.VideoThumbnailProcess, VideoThumbnailProcess: conf.VideoThumbnailProcess,
} }
var resp File var resp File
if err := BodyToJson(url, req, &resp, true); err!=nil { if err := BodyToJson(url, req, &resp, true); err != nil {
return nil,err return nil, err
} }
return &resp,nil return &resp, nil
} }
// get download_url // get download_url
func GetDownLoadUrl(fileId string) (*DownloadResp, error) { func GetDownLoadUrl(fileId string) (*DownloadResp, error) {
url:=conf.Conf.AliDrive.ApiUrl+"/file/get_download_url" url := conf.Conf.AliDrive.ApiUrl + "/file/get_download_url"
req:=DownloadReq{ req := DownloadReq{
DriveId: User.DefaultDriveId, DriveId: User.DefaultDriveId,
FileId: fileId, FileId: fileId,
ExpireSec: 14400, ExpireSec: 14400,
} }
var resp DownloadResp var resp DownloadResp
if err := BodyToJson(url, req, &resp, true); err!=nil { if err := BodyToJson(url, req, &resp, true); err != nil {
return nil,err return nil, err
} }
return &resp,nil return &resp, nil
} }
// search by keyword // search by keyword
func Search(key string,limit int, marker string) (*Files, error) { func Search(key string, limit int, marker string) (*Files, error) {
url:=conf.Conf.AliDrive.ApiUrl+"/file/search" url := conf.Conf.AliDrive.ApiUrl + "/file/search"
req:=SearchReq{ req := SearchReq{
DriveId: User.DefaultDriveId, DriveId: User.DefaultDriveId,
ImageThumbnailProcess: conf.ImageThumbnailProcess, ImageThumbnailProcess: conf.ImageThumbnailProcess,
ImageUrlProcess: conf.ImageUrlProcess, ImageUrlProcess: conf.ImageUrlProcess,
Limit: limit, Limit: limit,
Marker: marker, Marker: marker,
OrderBy: conf.OrderSearch, OrderBy: conf.OrderSearch,
Query: fmt.Sprintf("name match '%s'",key), Query: fmt.Sprintf("name match '%s'", key),
VideoThumbnailProcess: conf.VideoThumbnailProcess, VideoThumbnailProcess: conf.VideoThumbnailProcess,
} }
var resp Files var resp Files
if err := BodyToJson(url, req, &resp, true); err!=nil { if err := BodyToJson(url, req, &resp, true); err != nil {
return nil,err return nil, err
} }
return &resp,nil return &resp, nil
} }
// get root folder // get root folder
func GetRoot(limit int,marker string,orderBy string,orderDirection string) (*Files,error) { func GetRoot(limit int, marker string, orderBy string, orderDirection string) (*Files, error) {
return GetList(conf.Conf.AliDrive.RootFolder,limit,marker,orderBy,orderDirection) return GetList(conf.Conf.AliDrive.RootFolder, limit, marker, orderBy, orderDirection)
} }
// get folder list by file_id // get folder list by file_id
func GetList(parent string,limit int,marker string,orderBy string,orderDirection string) (*Files,error) { func GetList(parent string, limit int, marker string, orderBy string, orderDirection string) (*Files, error) {
url:=conf.Conf.AliDrive.ApiUrl+"/file/list" url := conf.Conf.AliDrive.ApiUrl + "/file/list"
req:=ListReq{ req := ListReq{
DriveId: User.DefaultDriveId, DriveId: User.DefaultDriveId,
Fields: "*", Fields: "*",
ImageThumbnailProcess: conf.ImageThumbnailProcess, ImageThumbnailProcess: conf.ImageThumbnailProcess,
@ -84,45 +84,45 @@ func GetList(parent string,limit int,marker string,orderBy string,orderDirection
VideoThumbnailProcess: conf.VideoThumbnailProcess, VideoThumbnailProcess: conf.VideoThumbnailProcess,
} }
var resp Files var resp Files
if err := BodyToJson(url, req, &resp, true); err!=nil { if err := BodyToJson(url, req, &resp, true); err != nil {
return nil,err return nil, err
} }
return &resp,nil return &resp, nil
} }
// get user info // get user info
func GetUserInfo() (*UserInfo,error) { func GetUserInfo() (*UserInfo, error) {
url:=conf.Conf.AliDrive.ApiUrl+"/user/get" url := conf.Conf.AliDrive.ApiUrl + "/user/get"
var resp UserInfo var resp UserInfo
if err := BodyToJson(url, map[string]interface{}{}, &resp, true); err!=nil { if err := BodyToJson(url, map[string]interface{}{}, &resp, true); err != nil {
return nil,err return nil, err
} }
return &resp,nil return &resp, nil
} }
// get office preview url and token // get office preview url and token
func GetOfficePreviewUrl(fileId string) (*OfficePreviewUrlResp,error) { func GetOfficePreviewUrl(fileId string) (*OfficePreviewUrlResp, error) {
url:=conf.Conf.AliDrive.ApiUrl+"/file/get_office_preview_url" url := conf.Conf.AliDrive.ApiUrl + "/file/get_office_preview_url"
req:=OfficePreviewUrlReq{ req := OfficePreviewUrlReq{
AccessToken: conf.Conf.AliDrive.AccessToken, AccessToken: conf.Conf.AliDrive.AccessToken,
DriveId: User.DefaultDriveId, DriveId: User.DefaultDriveId,
FileId: fileId, FileId: fileId,
} }
var resp OfficePreviewUrlResp var resp OfficePreviewUrlResp
if err := BodyToJson(url, req, &resp, true); err!=nil { if err := BodyToJson(url, req, &resp, true); err != nil {
return nil,err return nil, err
} }
return &resp,nil return &resp, nil
} }
// convert body to json // convert body to json
func BodyToJson(url string, req interface{}, resp RespHandle,auth bool) error { func BodyToJson(url string, req interface{}, resp RespHandle, auth bool) error {
if body,err := DoPost(url,req,auth);err!=nil { if body, err := DoPost(url, req, auth); err != nil {
log.Errorf("doPost出错:%s",err.Error()) log.Errorf("doPost出错:%s", err.Error())
return err return err
}else { } else {
if err = json.Unmarshal(body,&resp);err!=nil { if err = json.Unmarshal(body, &resp); err != nil {
log.Errorf("解析json[%s]出错:%s",string(body),err.Error()) log.Errorf("解析json[%s]出错:%s", string(body), err.Error())
return err return err
} }
} }
@ -132,73 +132,73 @@ func BodyToJson(url string, req interface{}, resp RespHandle,auth bool) error {
if resp.GetCode() == conf.AccessTokenInvalid { if resp.GetCode() == conf.AccessTokenInvalid {
resp.SetCode("") resp.SetCode("")
if RefreshToken() { if RefreshToken() {
return BodyToJson(url,req,resp,auth) return BodyToJson(url, req, resp, auth)
} }
} }
return fmt.Errorf(resp.GetMessage()) return fmt.Errorf(resp.GetMessage())
} }
// do post request // do post request
func DoPost(url string,request interface{},auth bool) (body []byte, err error) { func DoPost(url string, request interface{}, auth bool) (body []byte, err error) {
var( var (
resp *http.Response resp *http.Response
) )
requestBody := new(bytes.Buffer) requestBody := new(bytes.Buffer)
err = json.NewEncoder(requestBody).Encode(request) err = json.NewEncoder(requestBody).Encode(request)
if err !=nil {
log.Errorf("创建requestBody出错:%s",err.Error())
}
req,err:=http.NewRequest("POST",url,requestBody)
log.Debugf("do_post_req:%+v",req)
if err != nil { if err != nil {
log.Errorf("创建request出错:%s",err.Error()) log.Errorf("创建requestBody出错:%s", err.Error())
}
req, err := http.NewRequest("POST", url, requestBody)
log.Debugf("do_post_req:%+v", req)
if err != nil {
log.Errorf("创建request出错:%s", err.Error())
return return
} }
if auth { if auth {
req.Header.Set("authorization",conf.Authorization) req.Header.Set("authorization", conf.Authorization)
} }
req.Header.Add("content-type","application/json") req.Header.Add("content-type", "application/json")
req.Header.Add("user-agent","Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36") req.Header.Add("user-agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36")
req.Header.Add("origin","https://aliyundrive.com") req.Header.Add("origin", "https://aliyundrive.com")
req.Header.Add("accept","*/*") req.Header.Add("accept", "*/*")
req.Header.Add("Accept-Language", "zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3") req.Header.Add("Accept-Language", "zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3")
req.Header.Add("Connection", "keep-alive") req.Header.Add("Connection", "keep-alive")
for retryCount := 3; retryCount >= 0; retryCount-- { for retryCount := 3; retryCount >= 0; retryCount-- {
if resp,err=conf.Client.Do(req);err!=nil&&strings.Contains(err.Error(),"timeout") { if resp, err = conf.Client.Do(req); err != nil && strings.Contains(err.Error(), "timeout") {
<- time.After(time.Second) <-time.After(time.Second)
}else { } else {
break break
} }
} }
if err!=nil { if err != nil {
log.Errorf("请求阿里云盘api时出错:%s",err.Error()) log.Errorf("请求阿里云盘api时出错:%s", err.Error())
return return
} }
if body, err = ioutil.ReadAll(resp.Body); err != nil { if body, err = ioutil.ReadAll(resp.Body); err != nil {
log.Errorf("读取api返回内容失败") log.Errorf("读取api返回内容失败")
} }
log.Debugf("请求返回信息:%s",string(body)) log.Debugf("请求返回信息:%s", string(body))
return return
} }
func GetPaths(fileId string) (*[]Path,error) { func GetPaths(fileId string) (*[]Path, error) {
paths:=make([]Path,0) paths := make([]Path, 0)
for fileId != conf.Conf.AliDrive.RootFolder && fileId != "root" { for fileId != conf.Conf.AliDrive.RootFolder && fileId != "root" {
file,err:=GetFile(fileId) file, err := GetFile(fileId)
if err !=nil { if err != nil {
log.Errorf("获取path出错:%s",err.Error()) log.Errorf("获取path出错:%s", err.Error())
return nil,err return nil, err
} }
paths=append(paths,Path{ paths = append(paths, Path{
Name: file.Name, Name: file.Name,
FileId: file.FileId, FileId: file.FileId,
}) })
fileId=file.ParentFileId fileId = file.ParentFileId
} }
paths=append(paths, Path{ paths = append(paths, Path{
Name: "Root", Name: "Root",
FileId: "root", FileId: "root",
}) })
return &paths,nil return &paths, nil
} }

View File

@ -11,27 +11,27 @@ func InitAliDrive() bool {
log.Infof("初始化阿里云盘...") log.Infof("初始化阿里云盘...")
//首先token_login //首先token_login
if conf.Conf.AliDrive.RefreshToken == "" { if conf.Conf.AliDrive.RefreshToken == "" {
tokenLogin,err:=alidrive.TokenLogin() tokenLogin, err := alidrive.TokenLogin()
if err!=nil { if err != nil {
log.Errorf("登录失败:%s",err.Error()) log.Errorf("登录失败:%s", err.Error())
return false return false
} }
//然后get_token //然后get_token
token,err:=alidrive.GetToken(tokenLogin) token, err := alidrive.GetToken(tokenLogin)
if err!=nil { if err != nil {
return false return false
} }
conf.Authorization=token.TokenType+"\t"+token.AccessToken conf.Authorization = token.TokenType + "\t" + token.AccessToken
}else { } else {
conf.Authorization=conf.Bearer+conf.Conf.AliDrive.AccessToken conf.Authorization = conf.Bearer + conf.Conf.AliDrive.AccessToken
} }
log.Debugf("token:%s",conf.Authorization) log.Debugf("token:%s", conf.Authorization)
user,err:=alidrive.GetUserInfo() user, err := alidrive.GetUserInfo()
if err != nil { if err != nil {
log.Errorf("初始化用户失败:%s",err.Error()) log.Errorf("初始化用户失败:%s", err.Error())
return false return false
} }
log.Infof("当前用户信息:%+v",user) log.Infof("当前用户信息:%+v", user)
alidrive.User=user alidrive.User = user
return true return true
} }

View File

@ -11,6 +11,6 @@ import (
func InitCache() { func InitCache() {
if conf.Conf.Cache.Enable { if conf.Conf.Cache.Enable {
log.Infof("初始化缓存...") log.Infof("初始化缓存...")
conf.Cache=cache.New(time.Duration(conf.Conf.Cache.Expiration)*time.Minute,time.Duration(conf.Conf.Cache.CleanupInterval)*time.Minute) conf.Cache = cache.New(time.Duration(conf.Conf.Cache.Expiration)*time.Minute, time.Duration(conf.Conf.Cache.CleanupInterval)*time.Minute)
} }
} }

View File

@ -7,7 +7,7 @@ import (
) )
// init request client // init request client
func InitClient() { func InitClient() {
log.Infof("初始化client...") log.Infof("初始化client...")
conf.Client=&http.Client{} conf.Client = &http.Client{}
} }

View File

@ -10,29 +10,29 @@ import (
) )
func init() { func init() {
flag.BoolVar(&conf.Debug,"debug",false,"use debug mode") flag.BoolVar(&conf.Debug, "debug", false, "use debug mode")
flag.BoolVar(&conf.Help,"help",false,"show usage help") flag.BoolVar(&conf.Help, "help", false, "show usage help")
flag.BoolVar(&conf.Version,"version",false,"show version info") flag.BoolVar(&conf.Version, "version", false, "show version info")
flag.StringVar(&conf.Con,"conf","conf.yml","config file") flag.StringVar(&conf.Con, "conf", "conf.yml", "config file")
flag.BoolVar(&conf.SkipUpdate,"skip-update",false,"skip update") flag.BoolVar(&conf.SkipUpdate, "skip-update", false, "skip update")
} }
// bootstrap run // bootstrap run
func Run() { func Run() {
flag.Parse() flag.Parse()
if conf.Help { if conf.Help {
flag.Usage() flag.Usage()
return return
} }
if conf.Version { if conf.Version {
fmt.Println("Current version:"+conf.VERSION) fmt.Println("Current version:" + conf.VERSION)
return return
} }
start() start()
} }
// print asc // print asc
func printASC() { func printASC() {
log.Info(` log.Info(`
________ ___ ___ ________ _________ ________ ___ ___ ________ _________
|\ __ \|\ \ |\ \|\ ____\|\___ ___\ |\ __ \|\ \ |\ \|\ ____\|\___ ___\
@ -72,12 +72,12 @@ func start() {
// start http server // start http server
func server() { func server() {
baseServer:="0.0.0.0:"+conf.Conf.Server.Port baseServer := "0.0.0.0:" + conf.Conf.Server.Port
r:=gin.Default() r := gin.Default()
serv.InitRouter(r) serv.InitRouter(r)
log.Infof("Starting server @ %s",baseServer) log.Infof("Starting server @ %s", baseServer)
err:=r.Run(baseServer) err := r.Run(baseServer)
if err!=nil { if err != nil {
log.Errorf("Server failed start:%s",err.Error()) log.Errorf("Server failed start:%s", err.Error())
} }
} }

View File

@ -13,20 +13,20 @@ import (
func ReadConf(config string) bool { func ReadConf(config string) bool {
log.Infof("读取配置文件...") log.Infof("读取配置文件...")
if !utils.Exists(config) { if !utils.Exists(config) {
log.Infof("找不到配置文件:%s",config) log.Infof("找不到配置文件:%s", config)
return false return false
} }
confFile,err:=ioutil.ReadFile(config) confFile, err := ioutil.ReadFile(config)
if err !=nil { if err != nil {
log.Errorf("读取配置文件时发生错误:%s",err.Error()) log.Errorf("读取配置文件时发生错误:%s", err.Error())
return false return false
} }
err = yaml.Unmarshal(confFile, conf.Conf) err = yaml.Unmarshal(confFile, conf.Conf)
if err !=nil { if err != nil {
log.Errorf("加载配置文件时发生错误:%s",err.Error()) log.Errorf("加载配置文件时发生错误:%s", err.Error())
return false return false
} }
log.Debugf("config:%+v",conf.Conf) log.Debugf("config:%+v", conf.Conf)
conf.Origins = strings.Split(conf.Conf.Server.SiteUrl,",") conf.Origins = strings.Split(conf.Conf.Server.SiteUrl, ",")
return true return true
} }

View File

@ -9,17 +9,17 @@ import (
var Cron *cron.Cron var Cron *cron.Cron
// refresh token func for cron // refresh token func for cron
func refreshToken() { func refreshToken() {
alidrive.RefreshToken() alidrive.RefreshToken()
} }
// init cron jobs // init cron jobs
func InitCron() { func InitCron() {
log.Infof("初始化定时任务:刷新token") log.Infof("初始化定时任务:刷新token")
Cron=cron.New() Cron = cron.New()
_,err:=Cron.AddFunc("@every 2h",refreshToken) _, err := Cron.AddFunc("@every 2h", refreshToken)
if err!=nil { if err != nil {
log.Errorf("添加启动任务失败:%s",err.Error()) log.Errorf("添加启动任务失败:%s", err.Error())
} }
Cron.Start() Cron.Start()
} }

View File

@ -10,13 +10,13 @@ import (
func InitLog() { func InitLog() {
if conf.Debug { if conf.Debug {
log.SetLevel(log.DebugLevel) log.SetLevel(log.DebugLevel)
}else { } else {
gin.SetMode(gin.ReleaseMode) gin.SetMode(gin.ReleaseMode)
} }
log.SetFormatter(&log.TextFormatter{ log.SetFormatter(&log.TextFormatter{
ForceColors:true, ForceColors: true,
EnvironmentOverrideColors:true, EnvironmentOverrideColors: true,
TimestampFormat:"2006-01-02 15:04:05", TimestampFormat: "2006-01-02 15:04:05",
FullTimestamp:true, FullTimestamp: true,
}) })
} }

View File

@ -11,37 +11,37 @@ import (
// github release response bean // github release response bean
type GithubRelease struct { type GithubRelease struct {
TagName string `json:"tag_name"` TagName string `json:"tag_name"`
HtmlUrl string `json:"html_url"` HtmlUrl string `json:"html_url"`
Body string `json:"body"` Body string `json:"body"`
} }
// check update // check update
func CheckUpdate() { func CheckUpdate() {
log.Infof("检查更新...") log.Infof("检查更新...")
url:="https://api.github.com/repos/Xhofe/alist/releases/latest" url := "https://api.github.com/repos/Xhofe/alist/releases/latest"
resp,err:=http.Get(url) resp, err := http.Get(url)
if err!=nil { if err != nil {
log.Warnf("检查更新失败:%s",err.Error()) log.Warnf("检查更新失败:%s", err.Error())
return return
} }
body,err:=ioutil.ReadAll(resp.Body) body, err := ioutil.ReadAll(resp.Body)
if err!=nil { if err != nil {
log.Warnf("读取更新内容失败:%s",err.Error()) log.Warnf("读取更新内容失败:%s", err.Error())
return return
} }
var release GithubRelease var release GithubRelease
err = json.Unmarshal(body,&release) err = json.Unmarshal(body, &release)
if err!=nil { if err != nil {
log.Warnf("解析更新失败:%s",err.Error()) log.Warnf("解析更新失败:%s", err.Error())
return return
} }
lasted:=release.TagName[1:] lasted := release.TagName[1:]
now:=conf.VERSION[1:] now := conf.VERSION[1:]
if utils.VersionCompare(lasted,now) != 1 { if utils.VersionCompare(lasted, now) != 1 {
log.Infof("当前已是最新版本:%s",conf.VERSION) log.Infof("当前已是最新版本:%s", conf.VERSION)
}else { } else {
log.Infof("发现新版本:%s",release.TagName) log.Infof("发现新版本:%s", release.TagName)
log.Infof("请至'%s'获取更新.",release.HtmlUrl) log.Infof("请至'%s'获取更新.", release.HtmlUrl)
} }
} }

View File

@ -2,52 +2,52 @@ package conf
// config struct // config struct
type Config struct { type Config struct {
Info struct{ Info struct {
Title string `yaml:"title" json:"title"` Title string `yaml:"title" json:"title"`
Logo string `yaml:"logo" json:"logo"` Logo string `yaml:"logo" json:"logo"`
FooterText string `yaml:"footer_text" json:"footer_text"` FooterText string `yaml:"footer_text" json:"footer_text"`
FooterUrl string `yaml:"footer_url" json:"footer_url"` FooterUrl string `yaml:"footer_url" json:"footer_url"`
MusicImg string `yaml:"music_img" json:"music_img"` MusicImg string `yaml:"music_img" json:"music_img"`
CheckUpdate bool `yaml:"check_update" json:"check_update"` CheckUpdate bool `yaml:"check_update" json:"check_update"`
Script string `yaml:"script" json:"script"` Script string `yaml:"script" json:"script"`
Autoplay bool `yaml:"autoplay" json:"autoplay"` Autoplay bool `yaml:"autoplay" json:"autoplay"`
Preview struct{ Preview struct {
Url string `yaml:"url" json:"url"` Url string `yaml:"url" json:"url"`
PreProcess []string `yaml:"pre_process" json:"pre_process"` PreProcess []string `yaml:"pre_process" json:"pre_process"`
Extensions []string `yaml:"extensions" json:"extensions"` Extensions []string `yaml:"extensions" json:"extensions"`
Text []string `yaml:"text" json:"text"` Text []string `yaml:"text" json:"text"`
MaxSize int `yaml:"max_size" json:"max_size"` MaxSize int `yaml:"max_size" json:"max_size"`
} `yaml:"preview" json:"preview"` } `yaml:"preview" json:"preview"`
} `yaml:"info"` } `yaml:"info"`
Server struct{ Server struct {
Port string `yaml:"port"`//端口 Port string `yaml:"port"` //端口
Search bool `yaml:"search" json:"search"`//允许搜索 Search bool `yaml:"search" json:"search"` //允许搜索
Static string `yaml:"static"` Static string `yaml:"static"`
SiteUrl string `yaml:"site_url" json:"site_url"`//网站url SiteUrl string `yaml:"site_url" json:"site_url"` //网站url
} `yaml:"server"` } `yaml:"server"`
Cache struct{ Cache struct {
Enable bool `yaml:"enable"` Enable bool `yaml:"enable"`
Expiration int `yaml:"expiration"` Expiration int `yaml:"expiration"`
CleanupInterval int `yaml:"cleanup_interval"` CleanupInterval int `yaml:"cleanup_interval"`
RefreshPassword string `yaml:"refresh_password"` RefreshPassword string `yaml:"refresh_password"`
} }
AliDrive struct{ AliDrive struct {
ApiUrl string `yaml:"api_url"`//阿里云盘api ApiUrl string `yaml:"api_url"` //阿里云盘api
RootFolder string `yaml:"root_folder"`//根目录id RootFolder string `yaml:"root_folder"` //根目录id
//Authorization string `yaml:"authorization"`//授权token //Authorization string `yaml:"authorization"`//授权token
LoginToken string `yaml:"login_token"` LoginToken string `yaml:"login_token"`
AccessToken string `yaml:"access_token"` AccessToken string `yaml:"access_token"`
RefreshToken string `yaml:"refresh_token"` RefreshToken string `yaml:"refresh_token"`
MaxFilesCount int `yaml:"max_files_count"` MaxFilesCount int `yaml:"max_files_count"`
} `yaml:"ali_drive"` } `yaml:"ali_drive"`
Database struct{ Database struct {
Type string `yaml:"type"` Type string `yaml:"type"`
User string `yaml:"user"` User string `yaml:"user"`
Password string `yaml:"password"` Password string `yaml:"password"`
Host string `yaml:"host"` Host string `yaml:"host"`
Port int `yaml:"port"` Port int `yaml:"port"`
Name string `yaml:"name"` Name string `yaml:"name"`
TablePrefix string `yaml:"tablePrefix"` TablePrefix string `yaml:"tablePrefix"`
DBFile string `yaml:"dBFile"` DBFile string `yaml:"dBFile"`
} `yaml:"database"` } `yaml:"database"`
} }

View File

@ -6,15 +6,15 @@ import (
"net/http" "net/http"
) )
var( var (
Debug bool // is debug command Debug bool // is debug command
Help bool // is help command Help bool // is help command
Version bool // is print version command Version bool // is print version command
Con string // config file Con string // config file
SkipUpdate bool // skip update SkipUpdate bool // skip update
Client *http.Client // request client Client *http.Client // request client
Authorization string // authorization string Authorization string // authorization string
Cache *cache.Cache // cache Cache *cache.Cache // cache
@ -26,18 +26,18 @@ var(
var Conf = new(Config) var Conf = new(Config)
const ( const (
VERSION="v0.1.7" VERSION = "v0.1.7"
ImageThumbnailProcess="image/resize,w_50" ImageThumbnailProcess = "image/resize,w_50"
VideoThumbnailProcess="video/snapshot,t_0,f_jpg,w_50" VideoThumbnailProcess = "video/snapshot,t_0,f_jpg,w_50"
ImageUrlProcess="image/resize,w_1920/format,jpeg" ImageUrlProcess = "image/resize,w_1920/format,jpeg"
ASC="ASC" ASC = "ASC"
DESC="DESC" DESC = "DESC"
OrderUpdatedAt="updated_at" OrderUpdatedAt = "updated_at"
OrderCreatedAt="created_at" OrderCreatedAt = "created_at"
OrderSize="size" OrderSize = "size"
OrderName="name" OrderName = "name"
OrderSearch="type ASC,updated_at DESC" OrderSearch = "type ASC,updated_at DESC"
AccessTokenInvalid="AccessTokenInvalid" AccessTokenInvalid = "AccessTokenInvalid"
Bearer="Bearer\t" Bearer = "Bearer\t"
) )

View File

@ -5,9 +5,9 @@ import "github.com/gin-gonic/gin"
// common meta response // common meta response
func MetaResponse(code int, msg string) gin.H { func MetaResponse(code int, msg string) gin.H {
return gin.H{ return gin.H{
"meta":gin.H{ "meta": gin.H{
"code":code, "code": code,
"msg":msg, "msg": msg,
}, },
} }
} }
@ -15,10 +15,10 @@ func MetaResponse(code int, msg string) gin.H {
// common data response // common data response
func DataResponse(data interface{}) gin.H { func DataResponse(data interface{}) gin.H {
return gin.H{ return gin.H{
"meta":gin.H{ "meta": gin.H{
"code":200, "code": 200,
"msg":"success", "msg": "success",
}, },
"data":data, "data": data,
} }
} }

View File

@ -13,30 +13,30 @@ func Info(c *gin.Context) {
// handle refresh_cache request // handle refresh_cache request
func RefreshCache(c *gin.Context) { func RefreshCache(c *gin.Context) {
password:=c.Param("password") password := c.Param("password")
if conf.Conf.Cache.Enable { if conf.Conf.Cache.Enable {
if password == conf.Conf.Cache.RefreshPassword { if password == conf.Conf.Cache.RefreshPassword {
conf.Cache.Flush() conf.Cache.Flush()
c.JSON(200, MetaResponse(200,"flush success.")) c.JSON(200, MetaResponse(200, "flush success."))
return return
} }
c.JSON(200, MetaResponse(401,"wrong password.")) c.JSON(200, MetaResponse(401, "wrong password."))
return return
} }
c.JSON(200, MetaResponse(400,"disabled cache.")) c.JSON(200, MetaResponse(400, "disabled cache."))
return return
} }
// rebuild tree // rebuild tree
func RebuildTree(c *gin.Context) { func RebuildTree(c *gin.Context) {
if err:=models.Clear();err!=nil{ if err := models.Clear(); err != nil {
c.JSON(200,MetaResponse(500,err.Error())) c.JSON(200, MetaResponse(500, err.Error()))
return return
} }
if err:=models.BuildTree();err!=nil { if err := models.BuildTree(); err != nil {
c.JSON(200,MetaResponse(500,err.Error())) c.JSON(200, MetaResponse(500, err.Error()))
return return
} }
c.JSON(200,MetaResponse(200,"success.")) c.JSON(200, MetaResponse(200, "success."))
return return
} }

View File

@ -13,10 +13,10 @@ import (
func Get(c *gin.Context) { func Get(c *gin.Context) {
var get alidrive.GetReq var get alidrive.GetReq
if err := c.ShouldBindJSON(&get); err != nil { if err := c.ShouldBindJSON(&get); err != nil {
c.JSON(200, controllers.MetaResponse(400,"Bad Request")) c.JSON(200, controllers.MetaResponse(400, "Bad Request"))
return return
} }
log.Debugf("get:%+v",get) log.Debugf("get:%+v", get)
// cache // cache
//cacheKey:=fmt.Sprintf("%s-%s","g",get.FileId) //cacheKey:=fmt.Sprintf("%s-%s","g",get.FileId)
//if conf.Conf.Cache.Enable { //if conf.Conf.Cache.Enable {
@ -27,23 +27,23 @@ func Get(c *gin.Context) {
// return // return
// } // }
//} //}
file,err:=alidrive.GetFile(get.FileId) file, err := alidrive.GetFile(get.FileId)
if err !=nil { if err != nil {
c.JSON(200, controllers.MetaResponse(500,err.Error())) c.JSON(200, controllers.MetaResponse(500, err.Error()))
return return
} }
paths,err:=alidrive.GetPaths(get.FileId) paths, err := alidrive.GetPaths(get.FileId)
if err!=nil { if err != nil {
c.JSON(200, controllers.MetaResponse(500,err.Error())) c.JSON(200, controllers.MetaResponse(500, err.Error()))
return return
} }
file.Paths=*paths file.Paths = *paths
download,err:=alidrive.GetDownLoadUrl(get.FileId) download, err := alidrive.GetDownLoadUrl(get.FileId)
if err!=nil { if err != nil {
c.JSON(200, controllers.MetaResponse(500,err.Error())) c.JSON(200, controllers.MetaResponse(500, err.Error()))
return return
} }
file.DownloadUrl=download.Url file.DownloadUrl = download.Url
//if conf.Conf.Cache.Enable { //if conf.Conf.Cache.Enable {
// conf.Cache.Set(cacheKey,file,cache.DefaultExpiration) // conf.Cache.Set(cacheKey,file,cache.DefaultExpiration)
//} //}
@ -51,9 +51,9 @@ func Get(c *gin.Context) {
} }
func Down(c *gin.Context) { func Down(c *gin.Context) {
fileIdParam:=c.Param("file_id") fileIdParam := c.Param("file_id")
log.Debugf("down:%s",fileIdParam) log.Debugf("down:%s", fileIdParam)
fileId:=strings.Split(fileIdParam,"/")[1] fileId := strings.Split(fileIdParam, "/")[1]
//cacheKey:=fmt.Sprintf("%s-%s","d",fileId) //cacheKey:=fmt.Sprintf("%s-%s","d",fileId)
//if conf.Conf.Cache.Enable { //if conf.Conf.Cache.Enable {
// downloadUrl,exist:=conf.Cache.Get(cacheKey) // downloadUrl,exist:=conf.Cache.Get(cacheKey)
@ -63,14 +63,14 @@ func Down(c *gin.Context) {
// return // return
// } // }
//} //}
file,err:=alidrive.GetDownLoadUrl(fileId) file, err := alidrive.GetDownLoadUrl(fileId)
if err != nil { if err != nil {
c.JSON(200, controllers.MetaResponse(500,err.Error())) c.JSON(200, controllers.MetaResponse(500, err.Error()))
return return
} }
//if conf.Conf.Cache.Enable { //if conf.Conf.Cache.Enable {
// conf.Cache.Set(cacheKey,file.DownloadUrl,cache.DefaultExpiration) // conf.Cache.Set(cacheKey,file.DownloadUrl,cache.DefaultExpiration)
//} //}
c.Redirect(301,file.Url) c.Redirect(301, file.Url)
return return
} }

View File

@ -12,65 +12,65 @@ import (
// list request bean // list request bean
type ListReq struct { type ListReq struct {
Password string `json:"password"` Password string `json:"password"`
alidrive.ListReq alidrive.ListReq
} }
// handle list request // handle list request
func List(c *gin.Context) { func List(c *gin.Context) {
var list ListReq var list ListReq
if err := c.ShouldBindJSON(&list);err!=nil { if err := c.ShouldBindJSON(&list); err != nil {
c.JSON(200, controllers.MetaResponse(400,"Bad Request")) c.JSON(200, controllers.MetaResponse(400, "Bad Request"))
return return
} }
log.Debugf("list:%+v",list) log.Debugf("list:%+v", list)
// cache // cache
cacheKey:=fmt.Sprintf("%s-%s-%s","l",list.ParentFileId,list.Password) cacheKey := fmt.Sprintf("%s-%s-%s", "l", list.ParentFileId, list.Password)
if conf.Conf.Cache.Enable { if conf.Conf.Cache.Enable {
files,exist:=conf.Cache.Get(cacheKey) files, exist := conf.Cache.Get(cacheKey)
if exist { if exist {
log.Debugf("使用了缓存:%s",cacheKey) log.Debugf("使用了缓存:%s", cacheKey)
c.JSON(200, controllers.DataResponse(files)) c.JSON(200, controllers.DataResponse(files))
return return
} }
} }
var ( var (
files *alidrive.Files files *alidrive.Files
err error err error
) )
if list.Limit == 0 { if list.Limit == 0 {
list.Limit=50 list.Limit = 50
} }
if conf.Conf.AliDrive.MaxFilesCount!=0 { if conf.Conf.AliDrive.MaxFilesCount != 0 {
list.Limit=conf.Conf.AliDrive.MaxFilesCount list.Limit = conf.Conf.AliDrive.MaxFilesCount
} }
if list.ParentFileId == "root" { if list.ParentFileId == "root" {
files,err=alidrive.GetRoot(list.Limit,list.Marker,list.OrderBy,list.OrderDirection) files, err = alidrive.GetRoot(list.Limit, list.Marker, list.OrderBy, list.OrderDirection)
}else { } else {
files,err=alidrive.GetList(list.ParentFileId,list.Limit,list.Marker,list.OrderBy,list.OrderDirection) files, err = alidrive.GetList(list.ParentFileId, list.Limit, list.Marker, list.OrderBy, list.OrderDirection)
} }
if err!=nil { if err != nil {
c.JSON(200, controllers.MetaResponse(500,err.Error())) c.JSON(200, controllers.MetaResponse(500, err.Error()))
return return
} }
password:=alidrive.HasPassword(files) password := alidrive.HasPassword(files)
if password!="" && password!=list.Password { if password != "" && password != list.Password {
if list.Password=="" { if list.Password == "" {
c.JSON(200, controllers.MetaResponse(401,"need password.")) c.JSON(200, controllers.MetaResponse(401, "need password."))
return return
} }
c.JSON(200, controllers.MetaResponse(401,"wrong password.")) c.JSON(200, controllers.MetaResponse(401, "wrong password."))
return return
} }
paths,err:=alidrive.GetPaths(list.ParentFileId) paths, err := alidrive.GetPaths(list.ParentFileId)
if err!=nil { if err != nil {
c.JSON(200, controllers.MetaResponse(500,err.Error())) c.JSON(200, controllers.MetaResponse(500, err.Error()))
return return
} }
files.Paths=*paths files.Paths = *paths
//files.Readme=alidrive.HasReadme(files) //files.Readme=alidrive.HasReadme(files)
if conf.Conf.Cache.Enable { if conf.Conf.Cache.Enable {
conf.Cache.Set(cacheKey,files,cache.DefaultExpiration) conf.Cache.Set(cacheKey, files, cache.DefaultExpiration)
} }
c.JSON(200, controllers.DataResponse(files)) c.JSON(200, controllers.DataResponse(files))
} }

View File

@ -11,14 +11,14 @@ import (
func OfficePreview(c *gin.Context) { func OfficePreview(c *gin.Context) {
var req alidrive.OfficePreviewUrlReq var req alidrive.OfficePreviewUrlReq
if err := c.ShouldBindJSON(&req); err != nil { if err := c.ShouldBindJSON(&req); err != nil {
c.JSON(200, controllers.MetaResponse(400,"Bad Request")) c.JSON(200, controllers.MetaResponse(400, "Bad Request"))
return return
} }
log.Debugf("preview_req:%+v",req) log.Debugf("preview_req:%+v", req)
preview,err:=alidrive.GetOfficePreviewUrl(req.FileId) preview, err := alidrive.GetOfficePreviewUrl(req.FileId)
if err!=nil { if err != nil {
c.JSON(200, controllers.MetaResponse(500,err.Error())) c.JSON(200, controllers.MetaResponse(500, err.Error()))
return return
} }
c.JSON(200, controllers.DataResponse(preview)) c.JSON(200, controllers.DataResponse(preview))
} }

View File

@ -13,39 +13,39 @@ import (
// handle search request // handle search request
func Search(c *gin.Context) { func Search(c *gin.Context) {
if !conf.Conf.Server.Search { if !conf.Conf.Server.Search {
c.JSON(200, controllers.MetaResponse(403,"Not allow search.")) c.JSON(200, controllers.MetaResponse(403, "Not allow search."))
return return
} }
var search alidrive.SearchReq var search alidrive.SearchReq
if err := c.ShouldBindJSON(&search); err != nil { if err := c.ShouldBindJSON(&search); err != nil {
c.JSON(200, controllers.MetaResponse(400,"Bad Request")) c.JSON(200, controllers.MetaResponse(400, "Bad Request"))
return return
} }
log.Debugf("search:%+v",search) log.Debugf("search:%+v", search)
// cache // cache
cacheKey:=fmt.Sprintf("%s-%s","s",search.Query) cacheKey := fmt.Sprintf("%s-%s", "s", search.Query)
if conf.Conf.Cache.Enable { if conf.Conf.Cache.Enable {
files,exist:=conf.Cache.Get(cacheKey) files, exist := conf.Cache.Get(cacheKey)
if exist { if exist {
log.Debugf("使用了缓存:%s",cacheKey) log.Debugf("使用了缓存:%s", cacheKey)
c.JSON(200, controllers.DataResponse(files)) c.JSON(200, controllers.DataResponse(files))
return return
} }
} }
if search.Limit == 0 { if search.Limit == 0 {
search.Limit=50 search.Limit = 50
} }
// Search只支持0-100 // Search只支持0-100
//if conf.Conf.AliDrive.MaxFilesCount!=0 { //if conf.Conf.AliDrive.MaxFilesCount!=0 {
// search.Limit=conf.Conf.AliDrive.MaxFilesCount // search.Limit=conf.Conf.AliDrive.MaxFilesCount
//} //}
files,err:=alidrive.Search(search.Query,search.Limit,search.OrderBy) files, err := alidrive.Search(search.Query, search.Limit, search.OrderBy)
if err != nil { if err != nil {
c.JSON(200, controllers.MetaResponse(500,err.Error())) c.JSON(200, controllers.MetaResponse(500, err.Error()))
return return
} }
if conf.Conf.Cache.Enable { if conf.Conf.Cache.Enable {
conf.Cache.Set(cacheKey,files,cache.DefaultExpiration) conf.Cache.Set(cacheKey, files, cache.DefaultExpiration)
} }
c.JSON(200, controllers.DataResponse(files)) c.JSON(200, controllers.DataResponse(files))
} }

View File

@ -23,8 +23,8 @@ func Get(c *gin.Context) {
return return
} }
log.Debugf("list:%+v", get) log.Debugf("list:%+v", get)
path,name:=filepath.Split(get.File) dir, name := filepath.Split(get.File)
file, err := models.GetFileByParentPathAndName(path,name) file, err := models.GetFileByParentPathAndName(dir, name)
if err != nil { if err != nil {
c.JSON(200, controllers.MetaResponse(500, err.Error())) c.JSON(200, controllers.MetaResponse(500, err.Error()))
return return
@ -34,19 +34,19 @@ func Get(c *gin.Context) {
// handle download request // handle download request
func Down(c *gin.Context) { func Down(c *gin.Context) {
filePath:=c.Param("file") filePath := c.Param("file")
log.Debugf("down:%s",filePath) log.Debugf("down:%s", filePath)
path,name:=filepath.Split(filePath) dir, name := filepath.Split(filePath)
fileModel, err := models.GetFileByParentPathAndName(path,name) fileModel, err := models.GetFileByParentPathAndName(dir, name)
if err != nil { if err != nil {
c.JSON(200, controllers.MetaResponse(500, err.Error())) c.JSON(200, controllers.MetaResponse(500, err.Error()))
return return
} }
file,err:=alidrive.GetDownLoadUrl(fileModel.FileId) file, err := alidrive.GetDownLoadUrl(fileModel.FileId)
if err != nil { if err != nil {
c.JSON(200, controllers.MetaResponse(500,err.Error())) c.JSON(200, controllers.MetaResponse(500, err.Error()))
return return
} }
c.Redirect(301,file.Url) c.Redirect(301, file.Url)
return return
} }

View File

@ -10,7 +10,7 @@ import (
// handle cors request // handle cors request
func CorsHandler() gin.HandlerFunc { func CorsHandler() gin.HandlerFunc {
return func(context *gin.Context) { return func(context *gin.Context) {
origin:=context.GetHeader("Origin") origin := context.GetHeader("Origin")
// 同源 // 同源
if origin == "" { if origin == "" {
context.Next() context.Next()
@ -18,14 +18,14 @@ func CorsHandler() gin.HandlerFunc {
} }
method := context.Request.Method method := context.Request.Method
// 设置跨域 // 设置跨域
context.Header("Access-Control-Allow-Origin",origin) context.Header("Access-Control-Allow-Origin", origin)
context.Header("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE,UPDATE") context.Header("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE,UPDATE")
context.Header("Access-Control-Allow-Headers", "Content-Length,session,Accept, Origin, Host, Connection, Accept-Encoding, Accept-Language, Keep-Alive, User-Agent, Cache-Control, Content-Type") context.Header("Access-Control-Allow-Headers", "Content-Length,session,Accept, Origin, Host, Connection, Accept-Encoding, Accept-Language, Keep-Alive, User-Agent, Cache-Control, Content-Type")
context.Header("Access-Control-Expose-Headers", "Content-Length,Cache-Control,Content-Language,Content-Type,Expires,Last-Modified") context.Header("Access-Control-Expose-Headers", "Content-Length,Cache-Control,Content-Language,Content-Type,Expires,Last-Modified")
context.Header("Access-Control-Max-Age", "172800") context.Header("Access-Control-Max-Age", "172800")
// 信任域名 // 信任域名
if conf.Conf.Server.SiteUrl!="*"&&utils.ContainsString(conf.Origins,context.GetHeader("Origin"))==-1 { if conf.Conf.Server.SiteUrl != "*" && utils.ContainsString(conf.Origins, context.GetHeader("Origin")) == -1 {
context.JSON(200,controllers.MetaResponse(413,"The origin is not in the site_url list, please configure it correctly.")) context.JSON(200, controllers.MetaResponse(413, "The origin is not in the site_url list, please configure it correctly."))
context.Abort() context.Abort()
} }
if method == "OPTIONS" { if method == "OPTIONS" {
@ -34,4 +34,4 @@ func CorsHandler() gin.HandlerFunc {
//处理请求 //处理请求
context.Next() context.Next()
} }
} }

View File

@ -14,30 +14,30 @@ import (
func InitRouter(engine *gin.Engine) { func InitRouter(engine *gin.Engine) {
log.Infof("初始化路由...") log.Infof("初始化路由...")
engine.Use(CorsHandler()) engine.Use(CorsHandler())
engine.Use(static.Serve("/",static.LocalFile(conf.Conf.Server.Static,false))) engine.Use(static.Serve("/", static.LocalFile(conf.Conf.Server.Static, false)))
engine.NoRoute(func(c *gin.Context) { engine.NoRoute(func(c *gin.Context) {
c.File(conf.Conf.Server.Static+"/index.html") c.File(conf.Conf.Server.Static + "/index.html")
}) })
InitApiRouter(engine) InitApiRouter(engine)
} }
// init api router // init api router
func InitApiRouter(engine *gin.Engine) { func InitApiRouter(engine *gin.Engine) {
apiV1 :=engine.Group("/api/v1") apiV1 := engine.Group("/api/v1")
{ {
apiV1.GET("/info",controllers.Info) apiV1.GET("/info", controllers.Info)
apiV1.POST("/get", v1.Get) apiV1.POST("/get", v1.Get)
apiV1.POST("/list", v1.List) apiV1.POST("/list", v1.List)
apiV1.POST("/search", v1.Search) apiV1.POST("/search", v1.Search)
apiV1.POST("/office_preview", v1.OfficePreview) apiV1.POST("/office_preview", v1.OfficePreview)
apiV1.GET("/d/*file_id", v1.Down) apiV1.GET("/d/*file_id", v1.Down)
} }
apiV2:=engine.Group("/api") apiV2 := engine.Group("/api")
{ {
apiV2.POST("/list",v2.List) apiV2.POST("/list", v2.List)
apiV2.POST("/get",v2.Get) apiV2.POST("/get", v2.Get)
} }
engine.GET("/d/*file",v2.Down) engine.GET("/d/*file", v2.Down)
engine.GET("/cache/:password",controllers.RefreshCache) engine.GET("/cache/:password", controllers.RefreshCache)
engine.GET("/rebuild",controllers.RebuildTree) engine.GET("/rebuild", controllers.RebuildTree)
} }

View File

@ -17,31 +17,31 @@ func setup() {
} }
func TestGetUserInfo(t *testing.T) { func TestGetUserInfo(t *testing.T) {
user,err:= alidrive.GetUserInfo() user, err := alidrive.GetUserInfo()
fmt.Println(err) fmt.Println(err)
fmt.Println(user) fmt.Println(user)
} }
func TestGetRoot(t *testing.T) { func TestGetRoot(t *testing.T) {
files,err:=alidrive.GetRoot(50,"",conf.OrderUpdatedAt,conf.DESC) files, err := alidrive.GetRoot(50, "", conf.OrderUpdatedAt, conf.DESC)
fmt.Println(err) fmt.Println(err)
fmt.Println(files) fmt.Println(files)
} }
func TestSearch(t *testing.T) { func TestSearch(t *testing.T) {
files,err:=alidrive.Search("测试文件",50,"") files, err := alidrive.Search("测试文件", 50, "")
fmt.Println(err) fmt.Println(err)
fmt.Println(files) fmt.Println(files)
} }
func TestGet(t *testing.T) { func TestGet(t *testing.T) {
file,err:=alidrive.GetFile("5fb7c80e85e4f335cd344008be1b1b5349f74414") file, err := alidrive.GetFile("5fb7c80e85e4f335cd344008be1b1b5349f74414")
fmt.Println(err) fmt.Println(err)
fmt.Println(file) fmt.Println(file)
} }
func TestMain(m *testing.M) { func TestMain(m *testing.M) {
setup() setup()
code:=m.Run() code := m.Run()
os.Exit(code) os.Exit(code)
} }

View File

@ -7,7 +7,7 @@ import (
) )
func TestSplit(t *testing.T) { func TestSplit(t *testing.T) {
drive_id:="/123/456" drive_id := "/123/456"
strs:=strings.Split(drive_id,"/") strs := strings.Split(drive_id, "/")
fmt.Println(strs) fmt.Println(strs)
} }

View File

@ -14,5 +14,5 @@ func TestStr(t *testing.T) {
func TestWriteYml(t *testing.T) { func TestWriteYml(t *testing.T) {
alidrive.RefreshToken() alidrive.RefreshToken()
utils.WriteToYml("../conf.yml",conf.Conf) utils.WriteToYml("../conf.yml", conf.Conf)
} }

View File

@ -9,12 +9,12 @@ import (
// get code from url // get code from url
func GetCode(rawUrl string) string { func GetCode(rawUrl string) string {
u,err:=url.Parse(rawUrl) u, err := url.Parse(rawUrl)
if err!=nil { if err != nil {
log.Errorf("解析url出错:%s",err.Error()) log.Errorf("解析url出错:%s", err.Error())
return "" return ""
} }
code:=u.Query().Get("code") code := u.Query().Get("code")
return code return code
} }
@ -48,11 +48,11 @@ func VersionCompare(version1, version2 string) int {
return 1 * flag return 1 * flag
} }
} }
for _, v:= range b[len(a):] { for _, v := range b[len(a):] {
y, _ := strconv.Atoi(v) y, _ := strconv.Atoi(v)
if y > 0 { if y > 0 {
return -1 * flag return -1 * flag
} }
} }
return 0 return 0
} }

View File

@ -32,13 +32,13 @@ func CreatNestedFile(path string) (*os.File, error) {
} }
// write struct to yaml file // write struct to yaml file
func WriteToYml(src string,conf interface{}){ func WriteToYml(src string, conf interface{}) {
data,err := yaml.Marshal(conf) data, err := yaml.Marshal(conf)
if err!=nil { if err != nil {
log.Errorf("Conf转[]byte失败:%s",err.Error()) log.Errorf("Conf转[]byte失败:%s", err.Error())
} }
err = ioutil.WriteFile(src,data,0777) err = ioutil.WriteFile(src, data, 0777)
if err!=nil { if err != nil {
log.Errorf("写yml文件失败",err.Error()) log.Errorf("写yml文件失败", err.Error())
} }
} }