🐝 reformat code
This commit is contained in:
@ -11,68 +11,68 @@ import (
|
||||
// use token login
|
||||
func TokenLogin() (*TokenLoginResp, error) {
|
||||
log.Infof("尝试使用token登录...")
|
||||
url:="https://auth.aliyundrive.com/v2/oauth/token_login"
|
||||
req:=TokenLoginReq{Token:conf.Conf.AliDrive.LoginToken}
|
||||
log.Debugf("token_login_req:%+v",req)
|
||||
url := "https://auth.aliyundrive.com/v2/oauth/token_login"
|
||||
req := TokenLoginReq{Token: conf.Conf.AliDrive.LoginToken}
|
||||
log.Debugf("token_login_req:%+v", req)
|
||||
var tokenLogin TokenLoginResp
|
||||
if body, err := DoPost(url, req,false); err != nil {
|
||||
log.Errorf("tokenLogin-doPost出错:%s",err.Error())
|
||||
return nil,err
|
||||
}else {
|
||||
if err = json.Unmarshal(body,&tokenLogin);err!=nil {
|
||||
log.Errorf("解析json[%s]出错:%s",string(body),err.Error())
|
||||
return nil,err
|
||||
if body, err := DoPost(url, req, false); err != nil {
|
||||
log.Errorf("tokenLogin-doPost出错:%s", err.Error())
|
||||
return nil, err
|
||||
} else {
|
||||
if err = json.Unmarshal(body, &tokenLogin); err != nil {
|
||||
log.Errorf("解析json[%s]出错:%s", string(body), err.Error())
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
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
|
||||
func GetToken(tokenLogin *TokenLoginResp) (*TokenResp,error) {
|
||||
func GetToken(tokenLogin *TokenLoginResp) (*TokenResp, error) {
|
||||
log.Infof("获取API token...")
|
||||
url:="https://websv.aliyundrive.com/token/get"
|
||||
code:=utils.GetCode(tokenLogin.Goto)
|
||||
url := "https://websv.aliyundrive.com/token/get"
|
||||
code := utils.GetCode(tokenLogin.Goto)
|
||||
if code == "" {
|
||||
return nil,fmt.Errorf("获取code出错")
|
||||
return nil, fmt.Errorf("获取code出错")
|
||||
}
|
||||
req:=GetTokenReq{Code:code}
|
||||
req := GetTokenReq{Code: code}
|
||||
var token TokenResp
|
||||
if body, err := DoPost(url, req,false); err != nil {
|
||||
log.Errorf("tokenLogin-doPost出错:%s",err.Error())
|
||||
return nil,err
|
||||
}else {
|
||||
if err = json.Unmarshal(body,&token);err!=nil {
|
||||
log.Errorf("解析json[%s]出错:%s",string(body),err.Error())
|
||||
if body, err := DoPost(url, req, false); err != nil {
|
||||
log.Errorf("tokenLogin-doPost出错:%s", err.Error())
|
||||
return nil, err
|
||||
} else {
|
||||
if err = json.Unmarshal(body, &token); err != nil {
|
||||
log.Errorf("解析json[%s]出错:%s", string(body), err.Error())
|
||||
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
|
||||
func RefreshToken() bool {
|
||||
log.Infof("刷新token...")
|
||||
url:="https://websv.aliyundrive.com/token/refresh"
|
||||
req:=RefreshTokenReq{RefreshToken:conf.Conf.AliDrive.RefreshToken}
|
||||
url := "https://websv.aliyundrive.com/token/refresh"
|
||||
req := RefreshTokenReq{RefreshToken: conf.Conf.AliDrive.RefreshToken}
|
||||
var token TokenResp
|
||||
if body, err := DoPost(url, req,false); err != nil {
|
||||
log.Errorf("tokenLogin-doPost出错:%s",err.Error())
|
||||
if body, err := DoPost(url, req, false); err != nil {
|
||||
log.Errorf("tokenLogin-doPost出错:%s", err.Error())
|
||||
return false
|
||||
}else {
|
||||
if err = json.Unmarshal(body,&token);err!=nil {
|
||||
log.Errorf("解析json[%s]出错:%s",string(body),err.Error())
|
||||
} else {
|
||||
if err = json.Unmarshal(body, &token); err != nil {
|
||||
log.Errorf("解析json[%s]出错:%s", string(body), err.Error())
|
||||
log.Errorf("此处json解析失败应该是refresh_token失效")
|
||||
return false
|
||||
}
|
||||
}
|
||||
//刷新成功 更新token并写入文件
|
||||
conf.Conf.AliDrive.AccessToken=token.AccessToken
|
||||
conf.Conf.AliDrive.RefreshToken=token.RefreshToken
|
||||
conf.Authorization=token.TokenType+"\t"+token.AccessToken
|
||||
utils.WriteToYml(conf.Con,conf.Conf)
|
||||
conf.Conf.AliDrive.AccessToken = token.AccessToken
|
||||
conf.Conf.AliDrive.RefreshToken = token.RefreshToken
|
||||
conf.Authorization = token.TokenType + "\t" + token.AccessToken
|
||||
utils.WriteToYml(conf.Con, conf.Conf)
|
||||
return true
|
||||
}
|
||||
|
@ -1,5 +1,5 @@
|
||||
package alidrive
|
||||
|
||||
var (
|
||||
User *UserInfo
|
||||
User *UserInfo
|
||||
)
|
||||
|
@ -24,10 +24,10 @@ type GetReq struct {
|
||||
|
||||
// download request bean
|
||||
type DownloadReq struct {
|
||||
DriveId string `json:"drive_id"`
|
||||
FileId string `json:"file_id"`
|
||||
ExpireSec int `json:"expire_sec"`
|
||||
FileName string `json:"file_name"`
|
||||
DriveId string `json:"drive_id"`
|
||||
FileId string `json:"file_id"`
|
||||
ExpireSec int `json:"expire_sec"`
|
||||
FileName string `json:"file_name"`
|
||||
}
|
||||
|
||||
// search request bean
|
||||
|
@ -14,64 +14,64 @@ import (
|
||||
|
||||
// get file
|
||||
func GetFile(fileId string) (*File, error) {
|
||||
url:=conf.Conf.AliDrive.ApiUrl+"/file/get"
|
||||
req:=GetReq{
|
||||
url := conf.Conf.AliDrive.ApiUrl + "/file/get"
|
||||
req := GetReq{
|
||||
DriveId: User.DefaultDriveId,
|
||||
FileId: fileId,
|
||||
ImageThumbnailProcess: conf.ImageThumbnailProcess,
|
||||
VideoThumbnailProcess: conf.VideoThumbnailProcess,
|
||||
}
|
||||
var resp File
|
||||
if err := BodyToJson(url, req, &resp, true); err!=nil {
|
||||
return nil,err
|
||||
if err := BodyToJson(url, req, &resp, true); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &resp,nil
|
||||
return &resp, nil
|
||||
}
|
||||
|
||||
// get download_url
|
||||
func GetDownLoadUrl(fileId string) (*DownloadResp, error) {
|
||||
url:=conf.Conf.AliDrive.ApiUrl+"/file/get_download_url"
|
||||
req:=DownloadReq{
|
||||
DriveId: User.DefaultDriveId,
|
||||
FileId: fileId,
|
||||
ExpireSec: 14400,
|
||||
url := conf.Conf.AliDrive.ApiUrl + "/file/get_download_url"
|
||||
req := DownloadReq{
|
||||
DriveId: User.DefaultDriveId,
|
||||
FileId: fileId,
|
||||
ExpireSec: 14400,
|
||||
}
|
||||
var resp DownloadResp
|
||||
if err := BodyToJson(url, req, &resp, true); err!=nil {
|
||||
return nil,err
|
||||
if err := BodyToJson(url, req, &resp, true); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &resp,nil
|
||||
return &resp, nil
|
||||
}
|
||||
|
||||
// search by keyword
|
||||
func Search(key string,limit int, marker string) (*Files, error) {
|
||||
url:=conf.Conf.AliDrive.ApiUrl+"/file/search"
|
||||
req:=SearchReq{
|
||||
func Search(key string, limit int, marker string) (*Files, error) {
|
||||
url := conf.Conf.AliDrive.ApiUrl + "/file/search"
|
||||
req := SearchReq{
|
||||
DriveId: User.DefaultDriveId,
|
||||
ImageThumbnailProcess: conf.ImageThumbnailProcess,
|
||||
ImageUrlProcess: conf.ImageUrlProcess,
|
||||
Limit: limit,
|
||||
Marker: marker,
|
||||
OrderBy: conf.OrderSearch,
|
||||
Query: fmt.Sprintf("name match '%s'",key),
|
||||
Query: fmt.Sprintf("name match '%s'", key),
|
||||
VideoThumbnailProcess: conf.VideoThumbnailProcess,
|
||||
}
|
||||
var resp Files
|
||||
if err := BodyToJson(url, req, &resp, true); err!=nil {
|
||||
return nil,err
|
||||
if err := BodyToJson(url, req, &resp, true); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &resp,nil
|
||||
return &resp, nil
|
||||
}
|
||||
|
||||
// get root folder
|
||||
func GetRoot(limit int,marker string,orderBy string,orderDirection string) (*Files,error) {
|
||||
return GetList(conf.Conf.AliDrive.RootFolder,limit,marker,orderBy,orderDirection)
|
||||
func GetRoot(limit int, marker string, orderBy string, orderDirection string) (*Files, error) {
|
||||
return GetList(conf.Conf.AliDrive.RootFolder, limit, marker, orderBy, orderDirection)
|
||||
}
|
||||
|
||||
// get folder list by file_id
|
||||
func GetList(parent string,limit int,marker string,orderBy string,orderDirection string) (*Files,error) {
|
||||
url:=conf.Conf.AliDrive.ApiUrl+"/file/list"
|
||||
req:=ListReq{
|
||||
func GetList(parent string, limit int, marker string, orderBy string, orderDirection string) (*Files, error) {
|
||||
url := conf.Conf.AliDrive.ApiUrl + "/file/list"
|
||||
req := ListReq{
|
||||
DriveId: User.DefaultDriveId,
|
||||
Fields: "*",
|
||||
ImageThumbnailProcess: conf.ImageThumbnailProcess,
|
||||
@ -84,45 +84,45 @@ func GetList(parent string,limit int,marker string,orderBy string,orderDirection
|
||||
VideoThumbnailProcess: conf.VideoThumbnailProcess,
|
||||
}
|
||||
var resp Files
|
||||
if err := BodyToJson(url, req, &resp, true); err!=nil {
|
||||
return nil,err
|
||||
if err := BodyToJson(url, req, &resp, true); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &resp,nil
|
||||
return &resp, nil
|
||||
}
|
||||
|
||||
// get user info
|
||||
func GetUserInfo() (*UserInfo,error) {
|
||||
url:=conf.Conf.AliDrive.ApiUrl+"/user/get"
|
||||
func GetUserInfo() (*UserInfo, error) {
|
||||
url := conf.Conf.AliDrive.ApiUrl + "/user/get"
|
||||
var resp UserInfo
|
||||
if err := BodyToJson(url, map[string]interface{}{}, &resp, true); err!=nil {
|
||||
return nil,err
|
||||
if err := BodyToJson(url, map[string]interface{}{}, &resp, true); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &resp,nil
|
||||
return &resp, nil
|
||||
}
|
||||
|
||||
// get office preview url and token
|
||||
func GetOfficePreviewUrl(fileId string) (*OfficePreviewUrlResp,error) {
|
||||
url:=conf.Conf.AliDrive.ApiUrl+"/file/get_office_preview_url"
|
||||
req:=OfficePreviewUrlReq{
|
||||
func GetOfficePreviewUrl(fileId string) (*OfficePreviewUrlResp, error) {
|
||||
url := conf.Conf.AliDrive.ApiUrl + "/file/get_office_preview_url"
|
||||
req := OfficePreviewUrlReq{
|
||||
AccessToken: conf.Conf.AliDrive.AccessToken,
|
||||
DriveId: User.DefaultDriveId,
|
||||
FileId: fileId,
|
||||
}
|
||||
var resp OfficePreviewUrlResp
|
||||
if err := BodyToJson(url, req, &resp, true); err!=nil {
|
||||
return nil,err
|
||||
if err := BodyToJson(url, req, &resp, true); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &resp,nil
|
||||
return &resp, nil
|
||||
}
|
||||
|
||||
// convert body to json
|
||||
func BodyToJson(url string, req interface{}, resp RespHandle,auth bool) error {
|
||||
if body,err := DoPost(url,req,auth);err!=nil {
|
||||
log.Errorf("doPost出错:%s",err.Error())
|
||||
func BodyToJson(url string, req interface{}, resp RespHandle, auth bool) error {
|
||||
if body, err := DoPost(url, req, auth); err != nil {
|
||||
log.Errorf("doPost出错:%s", err.Error())
|
||||
return err
|
||||
}else {
|
||||
if err = json.Unmarshal(body,&resp);err!=nil {
|
||||
log.Errorf("解析json[%s]出错:%s",string(body),err.Error())
|
||||
} else {
|
||||
if err = json.Unmarshal(body, &resp); err != nil {
|
||||
log.Errorf("解析json[%s]出错:%s", string(body), err.Error())
|
||||
return err
|
||||
}
|
||||
}
|
||||
@ -132,73 +132,73 @@ func BodyToJson(url string, req interface{}, resp RespHandle,auth bool) error {
|
||||
if resp.GetCode() == conf.AccessTokenInvalid {
|
||||
resp.SetCode("")
|
||||
if RefreshToken() {
|
||||
return BodyToJson(url,req,resp,auth)
|
||||
return BodyToJson(url, req, resp, auth)
|
||||
}
|
||||
}
|
||||
return fmt.Errorf(resp.GetMessage())
|
||||
}
|
||||
|
||||
// do post request
|
||||
func DoPost(url string,request interface{},auth bool) (body []byte, err error) {
|
||||
var(
|
||||
func DoPost(url string, request interface{}, auth bool) (body []byte, err error) {
|
||||
var (
|
||||
resp *http.Response
|
||||
)
|
||||
requestBody := new(bytes.Buffer)
|
||||
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 {
|
||||
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
|
||||
}
|
||||
if auth {
|
||||
req.Header.Set("authorization",conf.Authorization)
|
||||
req.Header.Set("authorization", conf.Authorization)
|
||||
}
|
||||
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("origin","https://aliyundrive.com")
|
||||
req.Header.Add("accept","*/*")
|
||||
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("origin", "https://aliyundrive.com")
|
||||
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("Connection", "keep-alive")
|
||||
|
||||
for retryCount := 3; retryCount >= 0; retryCount-- {
|
||||
if resp,err=conf.Client.Do(req);err!=nil&&strings.Contains(err.Error(),"timeout") {
|
||||
<- time.After(time.Second)
|
||||
}else {
|
||||
if resp, err = conf.Client.Do(req); err != nil && strings.Contains(err.Error(), "timeout") {
|
||||
<-time.After(time.Second)
|
||||
} else {
|
||||
break
|
||||
}
|
||||
}
|
||||
if err!=nil {
|
||||
log.Errorf("请求阿里云盘api时出错:%s",err.Error())
|
||||
if err != nil {
|
||||
log.Errorf("请求阿里云盘api时出错:%s", err.Error())
|
||||
return
|
||||
}
|
||||
if body, err = ioutil.ReadAll(resp.Body); err != nil {
|
||||
log.Errorf("读取api返回内容失败")
|
||||
}
|
||||
log.Debugf("请求返回信息:%s",string(body))
|
||||
log.Debugf("请求返回信息:%s", string(body))
|
||||
return
|
||||
}
|
||||
|
||||
func GetPaths(fileId string) (*[]Path,error) {
|
||||
paths:=make([]Path,0)
|
||||
func GetPaths(fileId string) (*[]Path, error) {
|
||||
paths := make([]Path, 0)
|
||||
for fileId != conf.Conf.AliDrive.RootFolder && fileId != "root" {
|
||||
file,err:=GetFile(fileId)
|
||||
if err !=nil {
|
||||
log.Errorf("获取path出错:%s",err.Error())
|
||||
return nil,err
|
||||
file, err := GetFile(fileId)
|
||||
if err != nil {
|
||||
log.Errorf("获取path出错:%s", err.Error())
|
||||
return nil, err
|
||||
}
|
||||
paths=append(paths,Path{
|
||||
paths = append(paths, Path{
|
||||
Name: file.Name,
|
||||
FileId: file.FileId,
|
||||
})
|
||||
fileId=file.ParentFileId
|
||||
fileId = file.ParentFileId
|
||||
}
|
||||
paths=append(paths, Path{
|
||||
paths = append(paths, Path{
|
||||
Name: "Root",
|
||||
FileId: "root",
|
||||
})
|
||||
return &paths,nil
|
||||
return &paths, nil
|
||||
}
|
||||
|
@ -11,27 +11,27 @@ func InitAliDrive() bool {
|
||||
log.Infof("初始化阿里云盘...")
|
||||
//首先token_login
|
||||
if conf.Conf.AliDrive.RefreshToken == "" {
|
||||
tokenLogin,err:=alidrive.TokenLogin()
|
||||
if err!=nil {
|
||||
log.Errorf("登录失败:%s",err.Error())
|
||||
tokenLogin, err := alidrive.TokenLogin()
|
||||
if err != nil {
|
||||
log.Errorf("登录失败:%s", err.Error())
|
||||
return false
|
||||
}
|
||||
//然后get_token
|
||||
token,err:=alidrive.GetToken(tokenLogin)
|
||||
if err!=nil {
|
||||
token, err := alidrive.GetToken(tokenLogin)
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
conf.Authorization=token.TokenType+"\t"+token.AccessToken
|
||||
}else {
|
||||
conf.Authorization=conf.Bearer+conf.Conf.AliDrive.AccessToken
|
||||
conf.Authorization = token.TokenType + "\t" + token.AccessToken
|
||||
} else {
|
||||
conf.Authorization = conf.Bearer + conf.Conf.AliDrive.AccessToken
|
||||
}
|
||||
log.Debugf("token:%s",conf.Authorization)
|
||||
user,err:=alidrive.GetUserInfo()
|
||||
log.Debugf("token:%s", conf.Authorization)
|
||||
user, err := alidrive.GetUserInfo()
|
||||
if err != nil {
|
||||
log.Errorf("初始化用户失败:%s",err.Error())
|
||||
log.Errorf("初始化用户失败:%s", err.Error())
|
||||
return false
|
||||
}
|
||||
log.Infof("当前用户信息:%+v",user)
|
||||
alidrive.User=user
|
||||
log.Infof("当前用户信息:%+v", user)
|
||||
alidrive.User = user
|
||||
return true
|
||||
}
|
||||
|
@ -11,6 +11,6 @@ import (
|
||||
func InitCache() {
|
||||
if conf.Conf.Cache.Enable {
|
||||
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)
|
||||
}
|
||||
}
|
||||
|
@ -7,7 +7,7 @@ import (
|
||||
)
|
||||
|
||||
// init request client
|
||||
func InitClient() {
|
||||
func InitClient() {
|
||||
log.Infof("初始化client...")
|
||||
conf.Client=&http.Client{}
|
||||
}
|
||||
conf.Client = &http.Client{}
|
||||
}
|
||||
|
@ -10,29 +10,29 @@ import (
|
||||
)
|
||||
|
||||
func init() {
|
||||
flag.BoolVar(&conf.Debug,"debug",false,"use debug mode")
|
||||
flag.BoolVar(&conf.Help,"help",false,"show usage help")
|
||||
flag.BoolVar(&conf.Version,"version",false,"show version info")
|
||||
flag.StringVar(&conf.Con,"conf","conf.yml","config file")
|
||||
flag.BoolVar(&conf.SkipUpdate,"skip-update",false,"skip update")
|
||||
flag.BoolVar(&conf.Debug, "debug", false, "use debug mode")
|
||||
flag.BoolVar(&conf.Help, "help", false, "show usage help")
|
||||
flag.BoolVar(&conf.Version, "version", false, "show version info")
|
||||
flag.StringVar(&conf.Con, "conf", "conf.yml", "config file")
|
||||
flag.BoolVar(&conf.SkipUpdate, "skip-update", false, "skip update")
|
||||
}
|
||||
|
||||
// bootstrap run
|
||||
func Run() {
|
||||
func Run() {
|
||||
flag.Parse()
|
||||
if conf.Help {
|
||||
flag.Usage()
|
||||
return
|
||||
}
|
||||
if conf.Version {
|
||||
fmt.Println("Current version:"+conf.VERSION)
|
||||
fmt.Println("Current version:" + conf.VERSION)
|
||||
return
|
||||
}
|
||||
start()
|
||||
}
|
||||
|
||||
// print asc
|
||||
func printASC() {
|
||||
func printASC() {
|
||||
log.Info(`
|
||||
________ ___ ___ ________ _________
|
||||
|\ __ \|\ \ |\ \|\ ____\|\___ ___\
|
||||
@ -72,12 +72,12 @@ func start() {
|
||||
|
||||
// start http server
|
||||
func server() {
|
||||
baseServer:="0.0.0.0:"+conf.Conf.Server.Port
|
||||
r:=gin.Default()
|
||||
baseServer := "0.0.0.0:" + conf.Conf.Server.Port
|
||||
r := gin.Default()
|
||||
serv.InitRouter(r)
|
||||
log.Infof("Starting server @ %s",baseServer)
|
||||
err:=r.Run(baseServer)
|
||||
if err!=nil {
|
||||
log.Errorf("Server failed start:%s",err.Error())
|
||||
log.Infof("Starting server @ %s", baseServer)
|
||||
err := r.Run(baseServer)
|
||||
if err != nil {
|
||||
log.Errorf("Server failed start:%s", err.Error())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -13,20 +13,20 @@ import (
|
||||
func ReadConf(config string) bool {
|
||||
log.Infof("读取配置文件...")
|
||||
if !utils.Exists(config) {
|
||||
log.Infof("找不到配置文件:%s",config)
|
||||
log.Infof("找不到配置文件:%s", config)
|
||||
return false
|
||||
}
|
||||
confFile,err:=ioutil.ReadFile(config)
|
||||
if err !=nil {
|
||||
log.Errorf("读取配置文件时发生错误:%s",err.Error())
|
||||
confFile, err := ioutil.ReadFile(config)
|
||||
if err != nil {
|
||||
log.Errorf("读取配置文件时发生错误:%s", err.Error())
|
||||
return false
|
||||
}
|
||||
err = yaml.Unmarshal(confFile, conf.Conf)
|
||||
if err !=nil {
|
||||
log.Errorf("加载配置文件时发生错误:%s",err.Error())
|
||||
if err != nil {
|
||||
log.Errorf("加载配置文件时发生错误:%s", err.Error())
|
||||
return false
|
||||
}
|
||||
log.Debugf("config:%+v",conf.Conf)
|
||||
conf.Origins = strings.Split(conf.Conf.Server.SiteUrl,",")
|
||||
log.Debugf("config:%+v", conf.Conf)
|
||||
conf.Origins = strings.Split(conf.Conf.Server.SiteUrl, ",")
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
@ -9,17 +9,17 @@ import (
|
||||
var Cron *cron.Cron
|
||||
|
||||
// refresh token func for cron
|
||||
func refreshToken() {
|
||||
func refreshToken() {
|
||||
alidrive.RefreshToken()
|
||||
}
|
||||
|
||||
// init cron jobs
|
||||
func InitCron() {
|
||||
log.Infof("初始化定时任务:刷新token")
|
||||
Cron=cron.New()
|
||||
_,err:=Cron.AddFunc("@every 2h",refreshToken)
|
||||
if err!=nil {
|
||||
log.Errorf("添加启动任务失败:%s",err.Error())
|
||||
Cron = cron.New()
|
||||
_, err := Cron.AddFunc("@every 2h", refreshToken)
|
||||
if err != nil {
|
||||
log.Errorf("添加启动任务失败:%s", err.Error())
|
||||
}
|
||||
Cron.Start()
|
||||
}
|
||||
}
|
||||
|
@ -10,13 +10,13 @@ import (
|
||||
func InitLog() {
|
||||
if conf.Debug {
|
||||
log.SetLevel(log.DebugLevel)
|
||||
}else {
|
||||
} else {
|
||||
gin.SetMode(gin.ReleaseMode)
|
||||
}
|
||||
log.SetFormatter(&log.TextFormatter{
|
||||
ForceColors:true,
|
||||
EnvironmentOverrideColors:true,
|
||||
TimestampFormat:"2006-01-02 15:04:05",
|
||||
FullTimestamp:true,
|
||||
ForceColors: true,
|
||||
EnvironmentOverrideColors: true,
|
||||
TimestampFormat: "2006-01-02 15:04:05",
|
||||
FullTimestamp: true,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
@ -11,37 +11,37 @@ import (
|
||||
|
||||
// github release response bean
|
||||
type GithubRelease struct {
|
||||
TagName string `json:"tag_name"`
|
||||
HtmlUrl string `json:"html_url"`
|
||||
Body string `json:"body"`
|
||||
TagName string `json:"tag_name"`
|
||||
HtmlUrl string `json:"html_url"`
|
||||
Body string `json:"body"`
|
||||
}
|
||||
|
||||
// check update
|
||||
func CheckUpdate() {
|
||||
log.Infof("检查更新...")
|
||||
url:="https://api.github.com/repos/Xhofe/alist/releases/latest"
|
||||
resp,err:=http.Get(url)
|
||||
if err!=nil {
|
||||
log.Warnf("检查更新失败:%s",err.Error())
|
||||
url := "https://api.github.com/repos/Xhofe/alist/releases/latest"
|
||||
resp, err := http.Get(url)
|
||||
if err != nil {
|
||||
log.Warnf("检查更新失败:%s", err.Error())
|
||||
return
|
||||
}
|
||||
body,err:=ioutil.ReadAll(resp.Body)
|
||||
if err!=nil {
|
||||
log.Warnf("读取更新内容失败:%s",err.Error())
|
||||
body, err := ioutil.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
log.Warnf("读取更新内容失败:%s", err.Error())
|
||||
return
|
||||
}
|
||||
var release GithubRelease
|
||||
err = json.Unmarshal(body,&release)
|
||||
if err!=nil {
|
||||
log.Warnf("解析更新失败:%s",err.Error())
|
||||
err = json.Unmarshal(body, &release)
|
||||
if err != nil {
|
||||
log.Warnf("解析更新失败:%s", err.Error())
|
||||
return
|
||||
}
|
||||
lasted:=release.TagName[1:]
|
||||
now:=conf.VERSION[1:]
|
||||
if utils.VersionCompare(lasted,now) != 1 {
|
||||
log.Infof("当前已是最新版本:%s",conf.VERSION)
|
||||
}else {
|
||||
log.Infof("发现新版本:%s",release.TagName)
|
||||
log.Infof("请至'%s'获取更新.",release.HtmlUrl)
|
||||
lasted := release.TagName[1:]
|
||||
now := conf.VERSION[1:]
|
||||
if utils.VersionCompare(lasted, now) != 1 {
|
||||
log.Infof("当前已是最新版本:%s", conf.VERSION)
|
||||
} else {
|
||||
log.Infof("发现新版本:%s", release.TagName)
|
||||
log.Infof("请至'%s'获取更新.", release.HtmlUrl)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -2,52 +2,52 @@ package conf
|
||||
|
||||
// config struct
|
||||
type Config struct {
|
||||
Info struct{
|
||||
Title string `yaml:"title" json:"title"`
|
||||
Logo string `yaml:"logo" json:"logo"`
|
||||
FooterText string `yaml:"footer_text" json:"footer_text"`
|
||||
FooterUrl string `yaml:"footer_url" json:"footer_url"`
|
||||
MusicImg string `yaml:"music_img" json:"music_img"`
|
||||
CheckUpdate bool `yaml:"check_update" json:"check_update"`
|
||||
Script string `yaml:"script" json:"script"`
|
||||
Autoplay bool `yaml:"autoplay" json:"autoplay"`
|
||||
Preview struct{
|
||||
Url string `yaml:"url" json:"url"`
|
||||
PreProcess []string `yaml:"pre_process" json:"pre_process"`
|
||||
Extensions []string `yaml:"extensions" json:"extensions"`
|
||||
Text []string `yaml:"text" json:"text"`
|
||||
MaxSize int `yaml:"max_size" json:"max_size"`
|
||||
} `yaml:"preview" json:"preview"`
|
||||
} `yaml:"info"`
|
||||
Server struct{
|
||||
Port string `yaml:"port"`//端口
|
||||
Search bool `yaml:"search" json:"search"`//允许搜索
|
||||
Static string `yaml:"static"`
|
||||
SiteUrl string `yaml:"site_url" json:"site_url"`//网站url
|
||||
} `yaml:"server"`
|
||||
Cache struct{
|
||||
Enable bool `yaml:"enable"`
|
||||
Expiration int `yaml:"expiration"`
|
||||
CleanupInterval int `yaml:"cleanup_interval"`
|
||||
RefreshPassword string `yaml:"refresh_password"`
|
||||
Info struct {
|
||||
Title string `yaml:"title" json:"title"`
|
||||
Logo string `yaml:"logo" json:"logo"`
|
||||
FooterText string `yaml:"footer_text" json:"footer_text"`
|
||||
FooterUrl string `yaml:"footer_url" json:"footer_url"`
|
||||
MusicImg string `yaml:"music_img" json:"music_img"`
|
||||
CheckUpdate bool `yaml:"check_update" json:"check_update"`
|
||||
Script string `yaml:"script" json:"script"`
|
||||
Autoplay bool `yaml:"autoplay" json:"autoplay"`
|
||||
Preview struct {
|
||||
Url string `yaml:"url" json:"url"`
|
||||
PreProcess []string `yaml:"pre_process" json:"pre_process"`
|
||||
Extensions []string `yaml:"extensions" json:"extensions"`
|
||||
Text []string `yaml:"text" json:"text"`
|
||||
MaxSize int `yaml:"max_size" json:"max_size"`
|
||||
} `yaml:"preview" json:"preview"`
|
||||
} `yaml:"info"`
|
||||
Server struct {
|
||||
Port string `yaml:"port"` //端口
|
||||
Search bool `yaml:"search" json:"search"` //允许搜索
|
||||
Static string `yaml:"static"`
|
||||
SiteUrl string `yaml:"site_url" json:"site_url"` //网站url
|
||||
} `yaml:"server"`
|
||||
Cache struct {
|
||||
Enable bool `yaml:"enable"`
|
||||
Expiration int `yaml:"expiration"`
|
||||
CleanupInterval int `yaml:"cleanup_interval"`
|
||||
RefreshPassword string `yaml:"refresh_password"`
|
||||
}
|
||||
AliDrive struct{
|
||||
ApiUrl string `yaml:"api_url"`//阿里云盘api
|
||||
RootFolder string `yaml:"root_folder"`//根目录id
|
||||
AliDrive struct {
|
||||
ApiUrl string `yaml:"api_url"` //阿里云盘api
|
||||
RootFolder string `yaml:"root_folder"` //根目录id
|
||||
//Authorization string `yaml:"authorization"`//授权token
|
||||
LoginToken string `yaml:"login_token"`
|
||||
AccessToken string `yaml:"access_token"`
|
||||
RefreshToken string `yaml:"refresh_token"`
|
||||
MaxFilesCount int `yaml:"max_files_count"`
|
||||
} `yaml:"ali_drive"`
|
||||
Database struct{
|
||||
Type string `yaml:"type"`
|
||||
User string `yaml:"user"`
|
||||
Password string `yaml:"password"`
|
||||
Host string `yaml:"host"`
|
||||
Port int `yaml:"port"`
|
||||
Name string `yaml:"name"`
|
||||
TablePrefix string `yaml:"tablePrefix"`
|
||||
DBFile string `yaml:"dBFile"`
|
||||
} `yaml:"database"`
|
||||
}
|
||||
LoginToken string `yaml:"login_token"`
|
||||
AccessToken string `yaml:"access_token"`
|
||||
RefreshToken string `yaml:"refresh_token"`
|
||||
MaxFilesCount int `yaml:"max_files_count"`
|
||||
} `yaml:"ali_drive"`
|
||||
Database struct {
|
||||
Type string `yaml:"type"`
|
||||
User string `yaml:"user"`
|
||||
Password string `yaml:"password"`
|
||||
Host string `yaml:"host"`
|
||||
Port int `yaml:"port"`
|
||||
Name string `yaml:"name"`
|
||||
TablePrefix string `yaml:"tablePrefix"`
|
||||
DBFile string `yaml:"dBFile"`
|
||||
} `yaml:"database"`
|
||||
}
|
||||
|
@ -6,15 +6,15 @@ import (
|
||||
"net/http"
|
||||
)
|
||||
|
||||
var(
|
||||
Debug bool // is debug command
|
||||
Help bool // is help command
|
||||
Version bool // is print version command
|
||||
Con string // config file
|
||||
SkipUpdate bool // skip update
|
||||
var (
|
||||
Debug bool // is debug command
|
||||
Help bool // is help command
|
||||
Version bool // is print version command
|
||||
Con string // config file
|
||||
SkipUpdate bool // skip update
|
||||
|
||||
Client *http.Client // request client
|
||||
Authorization string // authorization string
|
||||
Client *http.Client // request client
|
||||
Authorization string // authorization string
|
||||
|
||||
Cache *cache.Cache // cache
|
||||
|
||||
@ -26,18 +26,18 @@ var(
|
||||
var Conf = new(Config)
|
||||
|
||||
const (
|
||||
VERSION="v0.1.7"
|
||||
VERSION = "v0.1.7"
|
||||
|
||||
ImageThumbnailProcess="image/resize,w_50"
|
||||
VideoThumbnailProcess="video/snapshot,t_0,f_jpg,w_50"
|
||||
ImageUrlProcess="image/resize,w_1920/format,jpeg"
|
||||
ASC="ASC"
|
||||
DESC="DESC"
|
||||
OrderUpdatedAt="updated_at"
|
||||
OrderCreatedAt="created_at"
|
||||
OrderSize="size"
|
||||
OrderName="name"
|
||||
OrderSearch="type ASC,updated_at DESC"
|
||||
AccessTokenInvalid="AccessTokenInvalid"
|
||||
Bearer="Bearer\t"
|
||||
)
|
||||
ImageThumbnailProcess = "image/resize,w_50"
|
||||
VideoThumbnailProcess = "video/snapshot,t_0,f_jpg,w_50"
|
||||
ImageUrlProcess = "image/resize,w_1920/format,jpeg"
|
||||
ASC = "ASC"
|
||||
DESC = "DESC"
|
||||
OrderUpdatedAt = "updated_at"
|
||||
OrderCreatedAt = "created_at"
|
||||
OrderSize = "size"
|
||||
OrderName = "name"
|
||||
OrderSearch = "type ASC,updated_at DESC"
|
||||
AccessTokenInvalid = "AccessTokenInvalid"
|
||||
Bearer = "Bearer\t"
|
||||
)
|
||||
|
@ -5,9 +5,9 @@ import "github.com/gin-gonic/gin"
|
||||
// common meta response
|
||||
func MetaResponse(code int, msg string) gin.H {
|
||||
return gin.H{
|
||||
"meta":gin.H{
|
||||
"code":code,
|
||||
"msg":msg,
|
||||
"meta": gin.H{
|
||||
"code": code,
|
||||
"msg": msg,
|
||||
},
|
||||
}
|
||||
}
|
||||
@ -15,10 +15,10 @@ func MetaResponse(code int, msg string) gin.H {
|
||||
// common data response
|
||||
func DataResponse(data interface{}) gin.H {
|
||||
return gin.H{
|
||||
"meta":gin.H{
|
||||
"code":200,
|
||||
"msg":"success",
|
||||
"meta": gin.H{
|
||||
"code": 200,
|
||||
"msg": "success",
|
||||
},
|
||||
"data":data,
|
||||
"data": data,
|
||||
}
|
||||
}
|
||||
|
@ -13,30 +13,30 @@ func Info(c *gin.Context) {
|
||||
|
||||
// handle refresh_cache request
|
||||
func RefreshCache(c *gin.Context) {
|
||||
password:=c.Param("password")
|
||||
password := c.Param("password")
|
||||
if conf.Conf.Cache.Enable {
|
||||
if password == conf.Conf.Cache.RefreshPassword {
|
||||
conf.Cache.Flush()
|
||||
c.JSON(200, MetaResponse(200,"flush success."))
|
||||
c.JSON(200, MetaResponse(200, "flush success."))
|
||||
return
|
||||
}
|
||||
c.JSON(200, MetaResponse(401,"wrong password."))
|
||||
c.JSON(200, MetaResponse(401, "wrong password."))
|
||||
return
|
||||
}
|
||||
c.JSON(200, MetaResponse(400,"disabled cache."))
|
||||
c.JSON(200, MetaResponse(400, "disabled cache."))
|
||||
return
|
||||
}
|
||||
|
||||
// rebuild tree
|
||||
func RebuildTree(c *gin.Context) {
|
||||
if err:=models.Clear();err!=nil{
|
||||
c.JSON(200,MetaResponse(500,err.Error()))
|
||||
if err := models.Clear(); err != nil {
|
||||
c.JSON(200, MetaResponse(500, err.Error()))
|
||||
return
|
||||
}
|
||||
if err:=models.BuildTree();err!=nil {
|
||||
c.JSON(200,MetaResponse(500,err.Error()))
|
||||
if err := models.BuildTree(); err != nil {
|
||||
c.JSON(200, MetaResponse(500, err.Error()))
|
||||
return
|
||||
}
|
||||
c.JSON(200,MetaResponse(200,"success."))
|
||||
c.JSON(200, MetaResponse(200, "success."))
|
||||
return
|
||||
}
|
||||
}
|
||||
|
@ -13,10 +13,10 @@ import (
|
||||
func Get(c *gin.Context) {
|
||||
var get alidrive.GetReq
|
||||
if err := c.ShouldBindJSON(&get); err != nil {
|
||||
c.JSON(200, controllers.MetaResponse(400,"Bad Request"))
|
||||
c.JSON(200, controllers.MetaResponse(400, "Bad Request"))
|
||||
return
|
||||
}
|
||||
log.Debugf("get:%+v",get)
|
||||
log.Debugf("get:%+v", get)
|
||||
// cache
|
||||
//cacheKey:=fmt.Sprintf("%s-%s","g",get.FileId)
|
||||
//if conf.Conf.Cache.Enable {
|
||||
@ -27,23 +27,23 @@ func Get(c *gin.Context) {
|
||||
// return
|
||||
// }
|
||||
//}
|
||||
file,err:=alidrive.GetFile(get.FileId)
|
||||
if err !=nil {
|
||||
c.JSON(200, controllers.MetaResponse(500,err.Error()))
|
||||
file, err := alidrive.GetFile(get.FileId)
|
||||
if err != nil {
|
||||
c.JSON(200, controllers.MetaResponse(500, err.Error()))
|
||||
return
|
||||
}
|
||||
paths,err:=alidrive.GetPaths(get.FileId)
|
||||
if err!=nil {
|
||||
c.JSON(200, controllers.MetaResponse(500,err.Error()))
|
||||
paths, err := alidrive.GetPaths(get.FileId)
|
||||
if err != nil {
|
||||
c.JSON(200, controllers.MetaResponse(500, err.Error()))
|
||||
return
|
||||
}
|
||||
file.Paths=*paths
|
||||
download,err:=alidrive.GetDownLoadUrl(get.FileId)
|
||||
if err!=nil {
|
||||
c.JSON(200, controllers.MetaResponse(500,err.Error()))
|
||||
file.Paths = *paths
|
||||
download, err := alidrive.GetDownLoadUrl(get.FileId)
|
||||
if err != nil {
|
||||
c.JSON(200, controllers.MetaResponse(500, err.Error()))
|
||||
return
|
||||
}
|
||||
file.DownloadUrl=download.Url
|
||||
file.DownloadUrl = download.Url
|
||||
//if conf.Conf.Cache.Enable {
|
||||
// conf.Cache.Set(cacheKey,file,cache.DefaultExpiration)
|
||||
//}
|
||||
@ -51,9 +51,9 @@ func Get(c *gin.Context) {
|
||||
}
|
||||
|
||||
func Down(c *gin.Context) {
|
||||
fileIdParam:=c.Param("file_id")
|
||||
log.Debugf("down:%s",fileIdParam)
|
||||
fileId:=strings.Split(fileIdParam,"/")[1]
|
||||
fileIdParam := c.Param("file_id")
|
||||
log.Debugf("down:%s", fileIdParam)
|
||||
fileId := strings.Split(fileIdParam, "/")[1]
|
||||
//cacheKey:=fmt.Sprintf("%s-%s","d",fileId)
|
||||
//if conf.Conf.Cache.Enable {
|
||||
// downloadUrl,exist:=conf.Cache.Get(cacheKey)
|
||||
@ -63,14 +63,14 @@ func Down(c *gin.Context) {
|
||||
// return
|
||||
// }
|
||||
//}
|
||||
file,err:=alidrive.GetDownLoadUrl(fileId)
|
||||
file, err := alidrive.GetDownLoadUrl(fileId)
|
||||
if err != nil {
|
||||
c.JSON(200, controllers.MetaResponse(500,err.Error()))
|
||||
c.JSON(200, controllers.MetaResponse(500, err.Error()))
|
||||
return
|
||||
}
|
||||
//if conf.Conf.Cache.Enable {
|
||||
// conf.Cache.Set(cacheKey,file.DownloadUrl,cache.DefaultExpiration)
|
||||
//}
|
||||
c.Redirect(301,file.Url)
|
||||
c.Redirect(301, file.Url)
|
||||
return
|
||||
}
|
||||
|
@ -12,65 +12,65 @@ import (
|
||||
|
||||
// list request bean
|
||||
type ListReq struct {
|
||||
Password string `json:"password"`
|
||||
Password string `json:"password"`
|
||||
alidrive.ListReq
|
||||
}
|
||||
|
||||
// handle list request
|
||||
func List(c *gin.Context) {
|
||||
var list ListReq
|
||||
if err := c.ShouldBindJSON(&list);err!=nil {
|
||||
c.JSON(200, controllers.MetaResponse(400,"Bad Request"))
|
||||
if err := c.ShouldBindJSON(&list); err != nil {
|
||||
c.JSON(200, controllers.MetaResponse(400, "Bad Request"))
|
||||
return
|
||||
}
|
||||
log.Debugf("list:%+v",list)
|
||||
log.Debugf("list:%+v", list)
|
||||
// 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 {
|
||||
files,exist:=conf.Cache.Get(cacheKey)
|
||||
files, exist := conf.Cache.Get(cacheKey)
|
||||
if exist {
|
||||
log.Debugf("使用了缓存:%s",cacheKey)
|
||||
log.Debugf("使用了缓存:%s", cacheKey)
|
||||
c.JSON(200, controllers.DataResponse(files))
|
||||
return
|
||||
}
|
||||
}
|
||||
var (
|
||||
files *alidrive.Files
|
||||
err error
|
||||
err error
|
||||
)
|
||||
if list.Limit == 0 {
|
||||
list.Limit=50
|
||||
list.Limit = 50
|
||||
}
|
||||
if conf.Conf.AliDrive.MaxFilesCount!=0 {
|
||||
list.Limit=conf.Conf.AliDrive.MaxFilesCount
|
||||
if conf.Conf.AliDrive.MaxFilesCount != 0 {
|
||||
list.Limit = conf.Conf.AliDrive.MaxFilesCount
|
||||
}
|
||||
if list.ParentFileId == "root" {
|
||||
files,err=alidrive.GetRoot(list.Limit,list.Marker,list.OrderBy,list.OrderDirection)
|
||||
}else {
|
||||
files,err=alidrive.GetList(list.ParentFileId,list.Limit,list.Marker,list.OrderBy,list.OrderDirection)
|
||||
files, err = alidrive.GetRoot(list.Limit, list.Marker, list.OrderBy, list.OrderDirection)
|
||||
} else {
|
||||
files, err = alidrive.GetList(list.ParentFileId, list.Limit, list.Marker, list.OrderBy, list.OrderDirection)
|
||||
}
|
||||
if err!=nil {
|
||||
c.JSON(200, controllers.MetaResponse(500,err.Error()))
|
||||
if err != nil {
|
||||
c.JSON(200, controllers.MetaResponse(500, err.Error()))
|
||||
return
|
||||
}
|
||||
password:=alidrive.HasPassword(files)
|
||||
if password!="" && password!=list.Password {
|
||||
if list.Password=="" {
|
||||
c.JSON(200, controllers.MetaResponse(401,"need password."))
|
||||
password := alidrive.HasPassword(files)
|
||||
if password != "" && password != list.Password {
|
||||
if list.Password == "" {
|
||||
c.JSON(200, controllers.MetaResponse(401, "need password."))
|
||||
return
|
||||
}
|
||||
c.JSON(200, controllers.MetaResponse(401,"wrong password."))
|
||||
c.JSON(200, controllers.MetaResponse(401, "wrong password."))
|
||||
return
|
||||
}
|
||||
paths,err:=alidrive.GetPaths(list.ParentFileId)
|
||||
if err!=nil {
|
||||
c.JSON(200, controllers.MetaResponse(500,err.Error()))
|
||||
paths, err := alidrive.GetPaths(list.ParentFileId)
|
||||
if err != nil {
|
||||
c.JSON(200, controllers.MetaResponse(500, err.Error()))
|
||||
return
|
||||
}
|
||||
files.Paths=*paths
|
||||
files.Paths = *paths
|
||||
//files.Readme=alidrive.HasReadme(files)
|
||||
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))
|
||||
}
|
||||
}
|
||||
|
@ -11,14 +11,14 @@ import (
|
||||
func OfficePreview(c *gin.Context) {
|
||||
var req alidrive.OfficePreviewUrlReq
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
c.JSON(200, controllers.MetaResponse(400,"Bad Request"))
|
||||
c.JSON(200, controllers.MetaResponse(400, "Bad Request"))
|
||||
return
|
||||
}
|
||||
log.Debugf("preview_req:%+v",req)
|
||||
preview,err:=alidrive.GetOfficePreviewUrl(req.FileId)
|
||||
if err!=nil {
|
||||
c.JSON(200, controllers.MetaResponse(500,err.Error()))
|
||||
log.Debugf("preview_req:%+v", req)
|
||||
preview, err := alidrive.GetOfficePreviewUrl(req.FileId)
|
||||
if err != nil {
|
||||
c.JSON(200, controllers.MetaResponse(500, err.Error()))
|
||||
return
|
||||
}
|
||||
c.JSON(200, controllers.DataResponse(preview))
|
||||
}
|
||||
}
|
||||
|
@ -13,39 +13,39 @@ import (
|
||||
// handle search request
|
||||
func Search(c *gin.Context) {
|
||||
if !conf.Conf.Server.Search {
|
||||
c.JSON(200, controllers.MetaResponse(403,"Not allow search."))
|
||||
c.JSON(200, controllers.MetaResponse(403, "Not allow search."))
|
||||
return
|
||||
}
|
||||
var search alidrive.SearchReq
|
||||
if err := c.ShouldBindJSON(&search); err != nil {
|
||||
c.JSON(200, controllers.MetaResponse(400,"Bad Request"))
|
||||
c.JSON(200, controllers.MetaResponse(400, "Bad Request"))
|
||||
return
|
||||
}
|
||||
log.Debugf("search:%+v",search)
|
||||
log.Debugf("search:%+v", search)
|
||||
// cache
|
||||
cacheKey:=fmt.Sprintf("%s-%s","s",search.Query)
|
||||
cacheKey := fmt.Sprintf("%s-%s", "s", search.Query)
|
||||
if conf.Conf.Cache.Enable {
|
||||
files,exist:=conf.Cache.Get(cacheKey)
|
||||
files, exist := conf.Cache.Get(cacheKey)
|
||||
if exist {
|
||||
log.Debugf("使用了缓存:%s",cacheKey)
|
||||
log.Debugf("使用了缓存:%s", cacheKey)
|
||||
c.JSON(200, controllers.DataResponse(files))
|
||||
return
|
||||
}
|
||||
}
|
||||
if search.Limit == 0 {
|
||||
search.Limit=50
|
||||
search.Limit = 50
|
||||
}
|
||||
// Search只支持0-100
|
||||
//if conf.Conf.AliDrive.MaxFilesCount!=0 {
|
||||
// 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 {
|
||||
c.JSON(200, controllers.MetaResponse(500,err.Error()))
|
||||
c.JSON(200, controllers.MetaResponse(500, err.Error()))
|
||||
return
|
||||
}
|
||||
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))
|
||||
}
|
||||
}
|
||||
|
@ -23,8 +23,8 @@ func Get(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
log.Debugf("list:%+v", get)
|
||||
path,name:=filepath.Split(get.File)
|
||||
file, err := models.GetFileByParentPathAndName(path,name)
|
||||
dir, name := filepath.Split(get.File)
|
||||
file, err := models.GetFileByParentPathAndName(dir, name)
|
||||
if err != nil {
|
||||
c.JSON(200, controllers.MetaResponse(500, err.Error()))
|
||||
return
|
||||
@ -34,19 +34,19 @@ func Get(c *gin.Context) {
|
||||
|
||||
// handle download request
|
||||
func Down(c *gin.Context) {
|
||||
filePath:=c.Param("file")
|
||||
log.Debugf("down:%s",filePath)
|
||||
path,name:=filepath.Split(filePath)
|
||||
fileModel, err := models.GetFileByParentPathAndName(path,name)
|
||||
filePath := c.Param("file")
|
||||
log.Debugf("down:%s", filePath)
|
||||
dir, name := filepath.Split(filePath)
|
||||
fileModel, err := models.GetFileByParentPathAndName(dir, name)
|
||||
if err != nil {
|
||||
c.JSON(200, controllers.MetaResponse(500, err.Error()))
|
||||
return
|
||||
}
|
||||
file,err:=alidrive.GetDownLoadUrl(fileModel.FileId)
|
||||
file, err := alidrive.GetDownLoadUrl(fileModel.FileId)
|
||||
if err != nil {
|
||||
c.JSON(200, controllers.MetaResponse(500,err.Error()))
|
||||
c.JSON(200, controllers.MetaResponse(500, err.Error()))
|
||||
return
|
||||
}
|
||||
c.Redirect(301,file.Url)
|
||||
c.Redirect(301, file.Url)
|
||||
return
|
||||
}
|
||||
|
@ -10,7 +10,7 @@ import (
|
||||
// handle cors request
|
||||
func CorsHandler() gin.HandlerFunc {
|
||||
return func(context *gin.Context) {
|
||||
origin:=context.GetHeader("Origin")
|
||||
origin := context.GetHeader("Origin")
|
||||
// 同源
|
||||
if origin == "" {
|
||||
context.Next()
|
||||
@ -18,14 +18,14 @@ func CorsHandler() gin.HandlerFunc {
|
||||
}
|
||||
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-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-Max-Age", "172800")
|
||||
// 信任域名
|
||||
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."))
|
||||
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.Abort()
|
||||
}
|
||||
if method == "OPTIONS" {
|
||||
@ -34,4 +34,4 @@ func CorsHandler() gin.HandlerFunc {
|
||||
//处理请求
|
||||
context.Next()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -14,30 +14,30 @@ import (
|
||||
func InitRouter(engine *gin.Engine) {
|
||||
log.Infof("初始化路由...")
|
||||
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) {
|
||||
c.File(conf.Conf.Server.Static+"/index.html")
|
||||
c.File(conf.Conf.Server.Static + "/index.html")
|
||||
})
|
||||
InitApiRouter(engine)
|
||||
}
|
||||
|
||||
// init api router
|
||||
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("/list", v1.List)
|
||||
apiV1.POST("/search", v1.Search)
|
||||
apiV1.POST("/office_preview", v1.OfficePreview)
|
||||
apiV1.GET("/d/*file_id", v1.Down)
|
||||
}
|
||||
apiV2:=engine.Group("/api")
|
||||
apiV2 := engine.Group("/api")
|
||||
{
|
||||
apiV2.POST("/list",v2.List)
|
||||
apiV2.POST("/get",v2.Get)
|
||||
apiV2.POST("/list", v2.List)
|
||||
apiV2.POST("/get", v2.Get)
|
||||
}
|
||||
engine.GET("/d/*file",v2.Down)
|
||||
engine.GET("/cache/:password",controllers.RefreshCache)
|
||||
engine.GET("/rebuild",controllers.RebuildTree)
|
||||
}
|
||||
engine.GET("/d/*file", v2.Down)
|
||||
engine.GET("/cache/:password", controllers.RefreshCache)
|
||||
engine.GET("/rebuild", controllers.RebuildTree)
|
||||
}
|
||||
|
@ -17,31 +17,31 @@ func setup() {
|
||||
}
|
||||
|
||||
func TestGetUserInfo(t *testing.T) {
|
||||
user,err:= alidrive.GetUserInfo()
|
||||
user, err := alidrive.GetUserInfo()
|
||||
fmt.Println(err)
|
||||
fmt.Println(user)
|
||||
}
|
||||
|
||||
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(files)
|
||||
}
|
||||
|
||||
func TestSearch(t *testing.T) {
|
||||
files,err:=alidrive.Search("测试文件",50,"")
|
||||
files, err := alidrive.Search("测试文件", 50, "")
|
||||
fmt.Println(err)
|
||||
fmt.Println(files)
|
||||
}
|
||||
|
||||
func TestGet(t *testing.T) {
|
||||
file,err:=alidrive.GetFile("5fb7c80e85e4f335cd344008be1b1b5349f74414")
|
||||
file, err := alidrive.GetFile("5fb7c80e85e4f335cd344008be1b1b5349f74414")
|
||||
fmt.Println(err)
|
||||
fmt.Println(file)
|
||||
}
|
||||
|
||||
func TestMain(m *testing.M) {
|
||||
setup()
|
||||
code:=m.Run()
|
||||
code := m.Run()
|
||||
os.Exit(code)
|
||||
}
|
||||
}
|
||||
|
@ -7,7 +7,7 @@ import (
|
||||
)
|
||||
|
||||
func TestSplit(t *testing.T) {
|
||||
drive_id:="/123/456"
|
||||
strs:=strings.Split(drive_id,"/")
|
||||
drive_id := "/123/456"
|
||||
strs := strings.Split(drive_id, "/")
|
||||
fmt.Println(strs)
|
||||
}
|
||||
}
|
||||
|
@ -14,5 +14,5 @@ func TestStr(t *testing.T) {
|
||||
|
||||
func TestWriteYml(t *testing.T) {
|
||||
alidrive.RefreshToken()
|
||||
utils.WriteToYml("../conf.yml",conf.Conf)
|
||||
}
|
||||
utils.WriteToYml("../conf.yml", conf.Conf)
|
||||
}
|
||||
|
@ -9,12 +9,12 @@ import (
|
||||
|
||||
// get code from url
|
||||
func GetCode(rawUrl string) string {
|
||||
u,err:=url.Parse(rawUrl)
|
||||
if err!=nil {
|
||||
log.Errorf("解析url出错:%s",err.Error())
|
||||
u, err := url.Parse(rawUrl)
|
||||
if err != nil {
|
||||
log.Errorf("解析url出错:%s", err.Error())
|
||||
return ""
|
||||
}
|
||||
code:=u.Query().Get("code")
|
||||
code := u.Query().Get("code")
|
||||
return code
|
||||
}
|
||||
|
||||
@ -48,11 +48,11 @@ func VersionCompare(version1, version2 string) int {
|
||||
return 1 * flag
|
||||
}
|
||||
}
|
||||
for _, v:= range b[len(a):] {
|
||||
for _, v := range b[len(a):] {
|
||||
y, _ := strconv.Atoi(v)
|
||||
if y > 0 {
|
||||
return -1 * flag
|
||||
}
|
||||
}
|
||||
return 0
|
||||
}
|
||||
}
|
||||
|
@ -32,13 +32,13 @@ func CreatNestedFile(path string) (*os.File, error) {
|
||||
}
|
||||
|
||||
// write struct to yaml file
|
||||
func WriteToYml(src string,conf interface{}){
|
||||
data,err := yaml.Marshal(conf)
|
||||
if err!=nil {
|
||||
log.Errorf("Conf转[]byte失败:%s",err.Error())
|
||||
func WriteToYml(src string, conf interface{}) {
|
||||
data, err := yaml.Marshal(conf)
|
||||
if err != nil {
|
||||
log.Errorf("Conf转[]byte失败:%s", err.Error())
|
||||
}
|
||||
err = ioutil.WriteFile(src,data,0777)
|
||||
if err!=nil {
|
||||
log.Errorf("写yml文件失败",err.Error())
|
||||
err = ioutil.WriteFile(src, data, 0777)
|
||||
if err != nil {
|
||||
log.Errorf("写yml文件失败", err.Error())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
Reference in New Issue
Block a user