Compare commits

...

15 Commits

Author SHA1 Message Date
6d19b49a8d 🔖 release v1.0.0 2021-03-13 20:25:18 +08:00
4fa11879f2 🐛 目录名 2021-03-12 22:03:50 +08:00
abe9d9237a 🚧 获取链接 2021-03-12 18:12:56 +08:00
e4d206d59c 🔹 删除list与get接口 2021-03-08 20:28:44 +08:00
8636014397 🚧 合并get与list 2021-03-08 20:26:02 +08:00
c0f50ffeff 🚧 参数校验 2021-03-07 21:51:26 +08:00
b677d6ad21 去除缓存 2021-03-07 21:02:56 +08:00
443067b80f 🚧 密码逻辑 2021-03-06 23:19:16 +08:00
3138e031f5 🐝 reformat code 2021-03-05 21:25:44 +08:00
d137ef8759 🚧 构建目录树 2021-03-05 21:07:45 +08:00
389226662c 🚧 添加model 2021-03-04 23:50:51 +08:00
9cb548d4f7 跳过检查更新 2021-02-27 20:06:09 +08:00
0e7083a713 Merge pull request #27 from 122cygf/main
 下载链接有效期延长到四小时
2021-02-26 13:14:55 +08:00
46f09836f3 下载链接有效期延长到四小时 2021-02-26 12:37:44 +08:00
e146054679 📝 add notes 2021-02-04 10:02:34 +08:00
38 changed files with 898 additions and 507 deletions

View File

@ -2,12 +2,12 @@
<img src="https://img.oez.cc/2020/12/24/1fb16bc25a4f6.png" alt="AList Logo" width=200/>
</p>
<p align="center">
<a href="https://github.com/Xhofe/alist/releases"><img src="https://img.shields.io/github/release/Xhofe/alist" alt="Release version"></a>
<a href="https://github.com/Xhofe/alist/actions?query=workflow%3ABuild"><img src="https://github.com/Xhofe/alist/workflows/build/badge.svg" alt="Build status"></a>
<a href="https://github.com/Xhofe/alist/releases"><img src="https://img.shields.io/github/downloads/Xhofe/alist/latest/total" alt="Downloads"></a>
<a href="https://github.com/Xhofe/alist/blob/main/LICENSE"><img src="https://img.shields.io/github/license/Xhofe/alist" alt="License"></a>
<a href="https://github.com/Xhofe/alist/releases"><img src="https://img.shields.io/github/release/Xhofe/alist?style=flat-square" alt="Release version"></a>
<a href="https://github.com/Xhofe/alist/actions?query=workflow%3ABuild"><img src="https://img.shields.io/github/workflow/status/Xhofe/alist/build?style=flat-square" alt="Build status"></a>
<a href="https://github.com/Xhofe/alist/releases"><img src="https://img.shields.io/github/downloads/Xhofe/alist/total?style=flat-square" alt="Downloads"></a>
<a href="https://github.com/Xhofe/alist/blob/main/LICENSE"><img src="https://img.shields.io/github/license/Xhofe/alist?style=flat-square" alt="License"></a>
<a href="https://pay.xhofe.top">
<img src="https://img.shields.io/badge/%24-donate-ff69b4.svg" alt="donate">
<img src="https://img.shields.io/badge/%24-donate-ff69b4.svg?style=flat-square" alt="donate">
</a>
</p>
@ -23,7 +23,9 @@
### 演示地址
- https://alist.nn.ci
- https://alist.nn.ci (稳定版本)
- https://alist.now.sh (开发版本)
- https://alist-plyr.now.sh (plyr分支版本)
### 预览

View File

@ -8,68 +8,71 @@ import (
log "github.com/sirupsen/logrus"
)
// 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)
}
func GetToken(tokenLogin *TokenLoginResp) (*TokenResp,error) {
// get access token
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
}

View File

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

View File

@ -1,5 +1,6 @@
package alidrive
// list request bean
type ListReq struct {
DriveId string `json:"drive_id"`
Fields string `json:"fields"`
@ -13,6 +14,7 @@ type ListReq struct {
VideoThumbnailProcess string `json:"video_thumbnail_process"`
}
// get request bean
type GetReq struct {
DriveId string `json:"drive_id"`
FileId string `json:"file_id"`
@ -20,6 +22,15 @@ type GetReq struct {
VideoThumbnailProcess string `json:"video_thumbnail_process"`
}
// 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"`
}
// search request bean
type SearchReq struct {
DriveId string `json:"drive_id"`
ImageThumbnailProcess string `json:"image_thumbnail_process"`
@ -33,18 +44,22 @@ type SearchReq struct {
VideoThumbnailProcess string `json:"video_thumbnail_process"`
}
// token_login request bean
type TokenLoginReq struct {
Token string `json:"token"`
}
// get_token request bean
type GetTokenReq struct {
Code string `json:"code"`
}
// refresh_token request bean
type RefreshTokenReq struct {
RefreshToken string `json:"refresh_token"`
}
// office_preview_url request bean
type OfficePreviewUrlReq struct {
AccessToken string `json:"access_token"`
DriveId string `json:"drive_id"`

View File

@ -12,47 +12,66 @@ import (
"time"
)
// 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
}
func Search(key string,limit int, marker string) (*Files, error) {
url:=conf.Conf.AliDrive.ApiUrl+"/file/search"
req:=SearchReq{
// 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,
}
var resp DownloadResp
if err := BodyToJson(url, req, &resp, true); err != nil {
return nil, err
}
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{
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
}
func GetRoot(limit int,marker string,orderBy string,orderDirection string) (*Files,error) {
return GetList(conf.Conf.AliDrive.RootFolder,limit,marker,orderBy,orderDirection)
// 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 GetList(parent string,limit int,marker string,orderBy string,orderDirection string) (*Files,error) {
url:=conf.Conf.AliDrive.ApiUrl+"/file/list"
req:=ListReq{
// 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{
DriveId: User.DefaultDriveId,
Fields: "*",
ImageThumbnailProcess: conf.ImageThumbnailProcess,
@ -65,42 +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
}
func GetUserInfo() (*UserInfo,error) {
url:=conf.Conf.AliDrive.ApiUrl+"/user/get"
// get user info
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
}
func GetOfficePreviewUrl(fileId string) (*OfficePreviewUrlResp,error) {
url:=conf.Conf.AliDrive.ApiUrl+"/file/get_office_preview_url"
req:=OfficePreviewUrlReq{
// get office preview url and token
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
}
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())
// 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())
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
}
}
@ -110,72 +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())
}
func DoPost(url string,request interface{},auth bool) (body []byte, err error) {
var(
// do post request
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
}

View File

@ -8,13 +8,15 @@ import (
"time"
)
// response bean methods
type RespHandle interface {
IsAvailable() bool
GetCode() string
GetMessage() string
SetCode(code string)
IsAvailable() bool // check available
GetCode() string // get err code
GetMessage() string // get err message
SetCode(code string) // set err code
}
// common response bean
type RespError struct {
Code string `json:"code"`
Message string `json:"message"`
@ -24,18 +26,19 @@ func (resp *RespError) IsAvailable() bool {
return resp.Code == ""
}
func (resp *RespError)GetCode() string {
func (resp *RespError) GetCode() string {
return resp.Code
}
func (resp *RespError)GetMessage() string {
func (resp *RespError) GetMessage() string {
return resp.Message
}
func (resp *RespError)SetCode(code string) {
resp.Code=code
func (resp *RespError) SetCode(code string) {
resp.Code = code
}
// user_info response bean
type UserInfo struct {
RespError
DomainId string `json:"domain_id"`
@ -54,19 +57,22 @@ type UserInfo struct {
UserData map[string]interface{} `json:"user_data"`
}
// folder files response bean
type Files struct {
RespError
Items []File `json:"items"`
NextMarker string `json:"next_marker"`
Readme string `json:"readme"`
Readme string `json:"readme"` // Deprecated
Paths []Path `json:"paths"`
}
// path bean
type Path struct {
Name string `json:"name"`
FileId string `json:"file_id"`
}
// file response bean
type File struct {
RespError
DriveId string `json:"drive_id"`
@ -98,11 +104,25 @@ type File struct {
Paths []Path `json:"paths"`
}
type DownloadResp struct {
RespError
Expiration string `json:"expiration"`
Method string `json:"method"`
Size int64 `json:"size"`
Url string `json:"url"`
//RateLimit struct{
// PartSize int `json:"part_size"`
// PartSpeed int `json:"part_speed"`
//} `json:"rate_limit"`//rate limit
}
// token_login response bean
type TokenLoginResp struct {
RespError
Goto string `json:"goto"`
}
// token response bean
type TokenResp struct {
RespError
AccessToken string `json:"access_token"`
@ -123,12 +143,14 @@ type TokenResp struct {
DeviceId string `json:"device_id"`
}
// office_preview_url response bean
type OfficePreviewUrlResp struct {
RespError
PreviewUrl string `json:"preview_url"`
AccessToken string `json:"access_token"`
}
// check password
func HasPassword(files *Files) string {
fileList := files.Items
for i, file := range fileList {
@ -140,6 +162,7 @@ func HasPassword(files *Files) string {
return ""
}
// Deprecated: check readme, implemented by the front end now
func HasReadme(files *Files) string {
fileList := files.Items
for _, file := range fileList {

View File

@ -2,6 +2,7 @@ package main
import "github.com/Xhofe/alist/bootstrap"
// main function
func main() {
bootstrap.Run()
}

View File

@ -6,31 +6,32 @@ import (
log "github.com/sirupsen/logrus"
)
// init aliyun drive
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
}

View File

@ -1,15 +0,0 @@
package bootstrap
import (
"github.com/Xhofe/alist/conf"
"github.com/patrickmn/go-cache"
log "github.com/sirupsen/logrus"
"time"
)
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)
}
}

View File

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

View File

@ -10,26 +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.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")
}
func Run() {
// bootstrap 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()
}
func printASC() {
// print asc
func printASC() {
log.Info(`
________ ___ ___ ________ _________
|\ __ \|\ \ |\ \|\ ____\|\___ ___\
@ -42,10 +45,13 @@ func printASC() {
`)
}
// start server
func start() {
InitLog()
printASC()
CheckUpdate()
if !conf.SkipUpdate {
CheckUpdate()
}
if !ReadConf(conf.Con) {
log.Errorf("读取配置文件时出现错误,启动失败.")
return
@ -55,18 +61,22 @@ func start() {
log.Errorf("初始化阿里云盘出现错误,启动失败.")
return
}
InitCache()
if !InitModel() {
log.Errorf("初始化数据库出现错误,启动失败.")
return
}
InitCron()
server()
}
// 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())
}
}
}

View File

@ -9,23 +9,24 @@ import (
"strings"
)
// read config file
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
}
}

View File

@ -8,16 +8,18 @@ import (
var Cron *cron.Cron
func refreshToken() {
// refresh token func for cron
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()
}
}

View File

@ -6,16 +6,17 @@ import (
log "github.com/sirupsen/logrus"
)
// init logrus
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,
})
}
}

46
bootstrap/model.go Normal file
View File

@ -0,0 +1,46 @@
package bootstrap
import (
"github.com/Xhofe/alist/conf"
"github.com/Xhofe/alist/server/models"
"github.com/Xhofe/alist/utils"
log "github.com/sirupsen/logrus"
"gorm.io/driver/sqlite"
"gorm.io/gorm"
"strings"
)
func InitModel() bool {
log.Infof("初始化数据库...")
switch conf.Conf.Database.Type {
case "sqlite3":
{
if !(strings.HasSuffix(conf.Conf.Database.DBFile, ".db") && len(conf.Conf.Database.DBFile) > 3) {
log.Errorf("db名称不正确.")
return false
}
needMigrate := !utils.Exists(conf.Conf.Database.DBFile)
db, err := gorm.Open(sqlite.Open(conf.Conf.Database.DBFile), &gorm.Config{})
if err != nil {
log.Errorf("连接数据库出现错误:%s", err.Error())
return false
}
conf.DB = db
if needMigrate {
log.Infof("迁移数据库...")
err = conf.DB.AutoMigrate(&models.File{})
if err != nil {
log.Errorf("数据库迁移失败:%s", err.Error())
return false
}
if err := models.BuildTree(); err != nil {
log.Errorf("构建目录树失败:%s", err.Error())
}
}
return true
}
default:
log.Errorf("不支持的数据库类型:%s", conf.Conf.Database.Type)
return false
}
}

View File

@ -9,37 +9,39 @@ import (
"net/http"
)
// 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)
}
}
}

View File

@ -1,42 +1,48 @@
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"`
}
AliDrive struct{
ApiUrl string `yaml:"api_url"`//阿里云盘api
RootFolder string `yaml:"root_folder"`//根目录id
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"` //允许搜索
Static string `yaml:"static"`
SiteUrl string `yaml:"site_url"` //网站url
Password string `yaml:"password"`
} `yaml:"server"`
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"`
}
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"`
}

View File

@ -1,38 +1,40 @@
package conf
import (
"github.com/patrickmn/go-cache"
"gorm.io/gorm"
"net/http"
)
var(
Debug bool
Help bool
Version bool
Con string
Client *http.Client
Authorization string
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
Cache *cache.Cache
Client *http.Client // request client
Authorization string // authorization string
Origins []string
DB *gorm.DB
Origins []string // allow origins
)
var Conf = new(Config)
const (
VERSION="v0.1.6"
VERSION = "v1.0.0"
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"
)

4
go.mod
View File

@ -9,9 +9,9 @@ require (
github.com/golang/protobuf v1.4.3 // indirect
github.com/json-iterator/go v1.1.10 // indirect
github.com/leodido/go-urn v1.2.1 // indirect
github.com/mattn/go-sqlite3 v1.14.6 // indirect
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect
github.com/modern-go/reflect2 v1.0.1 // indirect
github.com/patrickmn/go-cache v2.1.0+incompatible
github.com/robfig/cron/v3 v3.0.0
github.com/sirupsen/logrus v1.7.0
github.com/ugorji/go v1.2.2 // indirect
@ -19,4 +19,6 @@ require (
golang.org/x/sys v0.0.0-20201218084310-7d0127a74742 // indirect
google.golang.org/protobuf v1.25.0 // indirect
gopkg.in/yaml.v2 v2.4.0
gorm.io/driver/sqlite v1.1.4
gorm.io/gorm v1.21.1
)

24
go.sum
View File

@ -3,6 +3,7 @@ github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03
github.com/census-instrumentation/opencensus-proto v0.2.1/go.mod h1:f6KPmirojxKA12rnyqOA5BBL4O983OfeGPqjHWSTneU=
github.com/client9/misspell v0.3.4/go.mod h1:qj6jICC3Q7zFZvVWo7KLAzC3yx5G7kyvSDkc90ppPyw=
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/elazarl/go-bindata-assetfs v1.0.0/go.mod h1:v+YaWX3bdea5J/mo8dSETolEo7R71Vk1u8bnjau5yw4=
github.com/envoyproxy/go-control-plane v0.9.1-0.20191026205805-5f8ba28d4473/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymFceY/DCBVvsKhRF0iEA4=
@ -14,6 +15,7 @@ github.com/gin-contrib/static v0.0.0-20200916080430-d45d9a37d28e/go.mod h1:VhW/C
github.com/gin-gonic/gin v1.5.0/go.mod h1:Nd6IXA8m5kNZdNEHMBd93KT+mdY3+bewLgRvmCsR2Do=
github.com/gin-gonic/gin v1.6.3 h1:ahKqKTFpO5KTPHxWZjEdPScmYaGtLo8Y4DMHoEsnp14=
github.com/gin-gonic/gin v1.6.3/go.mod h1:75u5sXoLsGZoRN5Sgbi1eraJ4GU3++wFwWzhwvtwp4M=
github.com/go-playground/assert/v2 v2.0.1 h1:MsBgLAaY856+nPRTKrp3/OZK38U/wa0CcBYNjji3q3A=
github.com/go-playground/assert/v2 v2.0.1/go.mod h1:VDjEfimB/XKnb+ZQfWdccd7VUvScMdVu0Titje2rxJ4=
github.com/go-playground/locales v0.12.1/go.mod h1:IUMDtCfWo/w/mtMfIE/IG2K+Ey3ygWanZIBtBW0W2TM=
github.com/go-playground/locales v0.13.0 h1:HyWk6mgj5qFqCT5fjGBuRArbVDfE4hi8+e8ceBS/t7Q=
@ -43,8 +45,13 @@ github.com/google/go-cmp v0.2.0/go.mod h1:oXzfMopK8JAjlY9xF4vHSVASa0yLyX7SntLO5a
github.com/google/go-cmp v0.3.0/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU=
github.com/google/go-cmp v0.3.1/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU=
github.com/google/go-cmp v0.4.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
github.com/google/go-cmp v0.5.0 h1:/QaMHBdZ26BB3SSst0Iwl10Epc+xhTquomWX0oZEB6w=
github.com/google/go-cmp v0.5.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=
github.com/jinzhu/inflection v1.0.0 h1:K317FqzuhWc8YvSVlFMCCUb36O/S9MCKRDI7QkRKD/E=
github.com/jinzhu/inflection v1.0.0/go.mod h1:h+uFLlag+Qp1Va5pdKtLDYj+kHp5pxUVkryuEj+Srlc=
github.com/jinzhu/now v1.1.1 h1:g39TucaRWyV3dwDO++eEc6qf8TVIQ/Da48WmqjZ3i7E=
github.com/jinzhu/now v1.1.1/go.mod h1:d3SSVoowX0Lcu0IBviAWJpolVfI5UJVZZ7cO71lE/z8=
github.com/json-iterator/go v1.1.7/go.mod h1:KdQUCv79m/52Kvf8AW2vK1V8akMuk1QjK/uOdHXbAo4=
github.com/json-iterator/go v1.1.9 h1:9yzud/Ht36ygwatGx56VwCZtlI/2AD15T1X2sjSuGns=
github.com/json-iterator/go v1.1.9/go.mod h1:KdQUCv79m/52Kvf8AW2vK1V8akMuk1QjK/uOdHXbAo4=
@ -58,6 +65,10 @@ github.com/leodido/go-urn v1.2.1/go.mod h1:zt4jvISO2HfUBqxjfIshjdMTYS56ZS/qv49ic
github.com/mattn/go-isatty v0.0.9/go.mod h1:YNRxwqDuOph6SZLI9vUUz6OYw3QyUt7WiY2yME+cCiQ=
github.com/mattn/go-isatty v0.0.12 h1:wuysRhFDzyxgEmMf5xjvJ2M9dZoWAXNNr5LSBS7uHXY=
github.com/mattn/go-isatty v0.0.12/go.mod h1:cbi8OIDigv2wuxKPP5vlRcQ1OAZbq2CE4Kysco4FUpU=
github.com/mattn/go-sqlite3 v1.14.5 h1:1IdxlwTNazvbKJQSxoJ5/9ECbEeaTTyeU7sEAZ5KKTQ=
github.com/mattn/go-sqlite3 v1.14.5/go.mod h1:WVKg1VTActs4Qso6iwGbiFih2UIHo0ENGwNd0Lj+XmI=
github.com/mattn/go-sqlite3 v1.14.6 h1:dNPt6NO46WmLVt2DLNpwczCmdV5boIZ6g/tlDrlRUbg=
github.com/mattn/go-sqlite3 v1.14.6/go.mod h1:NyWgC/yNuGj7Q9rpYnZvas74GogHl5/Z4A/KQRfk6bU=
github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421 h1:ZqeYNhU3OHLH3mGKHDcjJRFFRrJa6eAM5H+CtDdOsPc=
github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg=
@ -66,9 +77,7 @@ github.com/modern-go/reflect2 v0.0.0-20180701023420-4b7aa43c6742 h1:Esafd1046DLD
github.com/modern-go/reflect2 v0.0.0-20180701023420-4b7aa43c6742/go.mod h1:bx2lNnkwVCuqBIxFjflWJWanXIb3RllmbCylyMrvgv0=
github.com/modern-go/reflect2 v1.0.1 h1:9f412s+6RmYXLWZSEzVVgPGK7C2PphHj5RJrvfx9AWI=
github.com/modern-go/reflect2 v1.0.1/go.mod h1:bx2lNnkwVCuqBIxFjflWJWanXIb3RllmbCylyMrvgv0=
github.com/patrickmn/go-cache v1.0.0 h1:3gD5McaYs9CxjyK5AXGcq8gdeCARtd/9gJDUvVeaZ0Y=
github.com/patrickmn/go-cache v2.1.0+incompatible h1:HRMgzkcYKYpi3C8ajMPV8OFXaaRUnok+kx1WdO15EQc=
github.com/patrickmn/go-cache v2.1.0+incompatible/go.mod h1:3Qf8kWWT7OJRJbdiICTKqZju1ZixQ/KpMGzzAfe6+WQ=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/prometheus/client_model v0.0.0-20190812154241-14fe0d1b01d4/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA=
github.com/robfig/cron/v3 v3.0.0 h1:kQ6Cb7aHOHTSzNVNEhmp8EcWKLb4CbiMW9h9VyIhO4E=
@ -79,6 +88,7 @@ github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+
github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs=
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4=
github.com/stretchr/testify v1.6.1 h1:hDPOHmpOpP40lSULcqw7IrRb/u7w6RpDC9399XyoNd0=
github.com/stretchr/testify v1.6.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/ugorji/go v1.1.7 h1:/68gy2h+1mWMrwZFeD1kQialdSzAb432dtpeJ42ovdo=
github.com/ugorji/go v1.1.7/go.mod h1:kZn38zHttfInRq0xu/PH0az30d+z6vm202qpg1oXVMw=
@ -124,6 +134,7 @@ golang.org/x/tools v0.0.0-20190114222345-bf090417da8b/go.mod h1:n7NCudcB/nEzxVGm
golang.org/x/tools v0.0.0-20190226205152-f727befe758c/go.mod h1:9Yl7xja0Znq3iFh3HoIrodX9oNMXvdceNzlUR8zjMvY=
golang.org/x/tools v0.0.0-20190311212946-11955173bddd/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs=
golang.org/x/tools v0.0.0-20190524140312-2c0ae7006135/go.mod h1:RgjU9mgBXZiqYHBnxXauZ1Gv1EHHAz9KjViQ78xBX0Q=
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543 h1:E7g+9GITq07hpfrRu66IVDexMakfv52eLZ2CXBWiKr4=
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
google.golang.org/appengine v1.1.0/go.mod h1:EbEs0AVv82hx2wNQdGPgUI5lhzA/G0D9YwlJXL52JkM=
google.golang.org/appengine v1.4.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4=
@ -144,6 +155,7 @@ google.golang.org/protobuf v1.23.0/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2
google.golang.org/protobuf v1.23.1-0.20200526195155-81db48ad09cc/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU=
google.golang.org/protobuf v1.25.0 h1:Ejskq+SyPohKW+1uil0JJMtmHCgJPJ/qWTxr8qp+R4c=
google.golang.org/protobuf v1.25.0/go.mod h1:9JNX74DMeImyA3h4bdi1ymwjUzf21/xIlbajtzgsN7c=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/go-playground/assert.v1 v1.2.1/go.mod h1:9RXL0bg/zibRAgZUYszZSwO/z8Y/a8bDuhia5mkpMnE=
gopkg.in/go-playground/validator.v9 v9.29.1/go.mod h1:+c9/zcJMFNgbLvly1L1V+PpxWdVbfP1avr/N00E2vyQ=
@ -152,6 +164,12 @@ gopkg.in/yaml.v2 v2.2.8 h1:obN1ZagJSUGI0Ek/LBmuj4SNLPfIny3KsKFopxRdj10=
gopkg.in/yaml.v2 v2.2.8/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
gopkg.in/yaml.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY=
gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ=
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c h1:dUUwHk2QECo/6vqA44rthZ8ie2QXMNeKRTHCNY2nXvo=
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
gorm.io/driver/sqlite v1.1.4 h1:PDzwYE+sI6De2+mxAneV9Xs11+ZyKV6oxD3wDGkaNvM=
gorm.io/driver/sqlite v1.1.4/go.mod h1:mJCeTFr7+crvS+TRnWc5Z3UvwxUN1BGBLMrf5LA9DYw=
gorm.io/gorm v1.20.7/go.mod h1:0HFTzE/SqkGTzK6TlDPPQbAYCluiVvhzoA1+aVyzenw=
gorm.io/gorm v1.21.1 h1:ACwUZ+jzH8eG8zxgqTnMIdgWd+lGfCKZTUxL/uQ1ZQo=
gorm.io/gorm v1.21.1/go.mod h1:0HFTzE/SqkGTzK6TlDPPQbAYCluiVvhzoA1+aVyzenw=
honnef.co/go/tools v0.0.0-20190102054323-c2f93a96b099/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4=
honnef.co/go/tools v0.0.0-20190523083050-ea95bdfd59fc/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4=

View File

@ -2,21 +2,23 @@ package controllers
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,
},
}
}
// 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,
}
}

View File

@ -0,0 +1,53 @@
package controllers
import (
"github.com/Xhofe/alist/alidrive"
"github.com/Xhofe/alist/server/models"
"github.com/gin-gonic/gin"
log "github.com/sirupsen/logrus"
"path/filepath"
)
type DownReq struct {
Password string `form:"pw"`
}
// handle download request
func Down(c *gin.Context) {
filePath := c.Param("path")[1:]
var down DownReq
if err := c.ShouldBindQuery(&down); err != nil {
c.JSON(200, MetaResponse(400, "Bad Request."))
return
}
log.Debugf("down:%s", filePath)
dir, name := filepath.Split(filePath)
fileModel, err := models.GetFileByDirAndName(dir, name)
if err != nil {
if fileModel == nil {
c.JSON(200, MetaResponse(404, "Path not found."))
return
}
c.JSON(200, MetaResponse(500, err.Error()))
return
}
if fileModel.Password != "" && fileModel.Password != down.Password {
if down.Password == "" {
c.JSON(200, MetaResponse(401, "need password."))
} else {
c.JSON(200, MetaResponse(401, "wrong password."))
}
return
}
if fileModel.Type == "folder" {
c.JSON(200, MetaResponse(406, "无法下载目录."))
return
}
file, err := alidrive.GetDownLoadUrl(fileModel.FileId)
if err != nil {
c.JSON(200, MetaResponse(500, err.Error()))
return
}
c.Redirect(301, file.Url)
return
}

View File

@ -2,68 +2,48 @@ package controllers
import (
"github.com/Xhofe/alist/alidrive"
"github.com/Xhofe/alist/server/models"
"github.com/gin-gonic/gin"
log "github.com/sirupsen/logrus"
"strings"
"path/filepath"
)
// 因为下载地址有时效,所以去掉了文件请求和直链的缓存
func Get(c *gin.Context) {
var get alidrive.GetReq
if err := c.ShouldBindJSON(&get); err != nil {
c.JSON(200, MetaResponse(400,"Bad Request"))
return
}
log.Debugf("get:%+v",get)
// cache
//cacheKey:=fmt.Sprintf("%s-%s","g",get.FileId)
//if conf.Conf.Cache.Enable {
// file,exist:=conf.Cache.Get(cacheKey)
// if exist {
// log.Debugf("使用了缓存:%s",cacheKey)
// c.JSON(200,DataResponse(file))
// return
// }
//}
file,err:=alidrive.GetFile(get.FileId)
if err !=nil {
c.JSON(200, MetaResponse(500,err.Error()))
return
}
paths,err:=alidrive.GetPaths(get.FileId)
if err!=nil {
c.JSON(200, MetaResponse(500,err.Error()))
return
}
file.Paths=*paths
//if conf.Conf.Cache.Enable {
// conf.Cache.Set(cacheKey,file,cache.DefaultExpiration)
//}
c.JSON(200, DataResponse(file))
// get request bean
type GetReq struct {
Path string `json:"path" binding:"required"`
Password string `json:"password"`
}
func Down(c *gin.Context) {
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)
// if exist {
// log.Debugf("使用了缓存:%s",cacheKey)
// c.Redirect(301,downloadUrl.(string))
// return
// }
//}
file,err:=alidrive.GetFile(fileId)
if err != nil {
c.JSON(200, MetaResponse(500,err.Error()))
// handle get request
func Get(c *gin.Context) {
var get GetReq
if err := c.ShouldBindJSON(&get); err != nil {
c.JSON(200, MetaResponse(400, "Bad Request:"+err.Error()))
return
}
//if conf.Conf.Cache.Enable {
// conf.Cache.Set(cacheKey,file.DownloadUrl,cache.DefaultExpiration)
//}
c.Redirect(301,file.DownloadUrl)
return
}
log.Debugf("list:%+v", get)
dir, name := filepath.Split(get.Path)
file, err := models.GetFileByDirAndName(dir, name)
if err != nil {
if file == nil {
c.JSON(200, MetaResponse(404, "Path not found."))
return
}
c.JSON(200, MetaResponse(500, err.Error()))
return
}
if file.Password != "" && file.Password != get.Password {
if get.Password == "" {
c.JSON(200, MetaResponse(401, "need password."))
} else {
c.JSON(200, MetaResponse(401, "wrong password."))
}
return
}
down, err := alidrive.GetDownLoadUrl(file.FileId)
if err != nil {
c.JSON(200, MetaResponse(500, err.Error()))
return
}
c.JSON(200, DataResponse(down))
}

View File

@ -1,73 +0,0 @@
package controllers
import (
"fmt"
"github.com/Xhofe/alist/alidrive"
"github.com/Xhofe/alist/conf"
"github.com/gin-gonic/gin"
"github.com/patrickmn/go-cache"
log "github.com/sirupsen/logrus"
)
type ListReq struct {
Password string `json:"password"`
alidrive.ListReq
}
func List(c *gin.Context) {
var list ListReq
if err := c.ShouldBindJSON(&list);err!=nil {
c.JSON(200, MetaResponse(400,"Bad Request"))
return
}
log.Debugf("list:%+v",list)
// cache
cacheKey:=fmt.Sprintf("%s-%s-%s","l",list.ParentFileId,list.Password)
if conf.Conf.Cache.Enable {
files,exist:=conf.Cache.Get(cacheKey)
if exist {
log.Debugf("使用了缓存:%s",cacheKey)
c.JSON(200, DataResponse(files))
return
}
}
var (
files *alidrive.Files
err error
)
if list.Limit == 0 {
list.Limit=50
}
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)
}
if err!=nil {
c.JSON(200, MetaResponse(500,err.Error()))
return
}
password:=alidrive.HasPassword(files)
if password!="" && password!=list.Password {
if list.Password=="" {
c.JSON(200, MetaResponse(401,"need password."))
return
}
c.JSON(200, MetaResponse(401,"wrong password."))
return
}
paths,err:=alidrive.GetPaths(list.ParentFileId)
if err!=nil {
c.JSON(200, MetaResponse(500,err.Error()))
return
}
files.Paths=*paths
files.Readme=alidrive.HasReadme(files)
if conf.Conf.Cache.Enable {
conf.Cache.Set(cacheKey,files,cache.DefaultExpiration)
}
c.JSON(200, DataResponse(files))
}

View File

@ -6,17 +6,22 @@ import (
log "github.com/sirupsen/logrus"
)
type OfficePreviewReq struct {
FileId string `json:"file_id" binding:"required"`
}
// handle office_preview request
func OfficePreview(c *gin.Context) {
var req alidrive.OfficePreviewUrlReq
var req OfficePreviewReq
if err := c.ShouldBindJSON(&req); err != nil {
c.JSON(200, MetaResponse(400,"Bad Request"))
c.JSON(200, MetaResponse(400, "Bad Request:"+err.Error()))
return
}
log.Debugf("preview_req:%+v",req)
preview,err:=alidrive.GetOfficePreviewUrl(req.FileId)
if err!=nil {
c.JSON(200, MetaResponse(500,err.Error()))
log.Debugf("preview_req:%+v", req)
preview, err := alidrive.GetOfficePreviewUrl(req.FileId)
if err != nil {
c.JSON(200, MetaResponse(500, err.Error()))
return
}
c.JSON(200, DataResponse(preview))
}
}

View File

@ -0,0 +1,61 @@
package controllers
import (
"github.com/Xhofe/alist/server/models"
"github.com/gin-gonic/gin"
log "github.com/sirupsen/logrus"
"path/filepath"
)
// path request bean
type PathReq struct {
Path string `json:"path" binding:"required"`
Password string `json:"password"`
}
// handle path request
func Path(c *gin.Context) {
var req PathReq
if err := c.ShouldBindJSON(&req); err != nil {
c.JSON(200, MetaResponse(400, "Bad Request:"+err.Error()))
return
}
log.Debugf("path:%+v", req)
// find model
dir, name := filepath.Split(req.Path)
file, err := models.GetFileByDirAndName(dir, name)
if err != nil {
// folder model not exist
if file == nil {
c.JSON(200, MetaResponse(404, "path not found."))
return
}
c.JSON(200, MetaResponse(500, err.Error()))
return
}
// check password
if file.Password != "" && file.Password != req.Password {
if req.Password == "" {
c.JSON(200, MetaResponse(401, "need password."))
} else {
c.JSON(200, MetaResponse(401, "wrong password."))
}
return
}
// file
if file.Type == "file" {
c.JSON(200, DataResponse(file))
return
}
// folder
files, err := models.GetFilesByDir(req.Path + "/")
if err != nil {
c.JSON(200, MetaResponse(500, err.Error()))
return
}
// delete password
for i, _ := range *files {
(*files)[i].Password = ""
}
c.JSON(200, DataResponse(files))
}

View File

@ -1,49 +1,35 @@
package controllers
import (
"fmt"
"github.com/Xhofe/alist/alidrive"
"github.com/Xhofe/alist/conf"
"github.com/Xhofe/alist/server/models"
"github.com/gin-gonic/gin"
"github.com/patrickmn/go-cache"
log "github.com/sirupsen/logrus"
)
func Search(c *gin.Context) {
if !conf.Conf.Server.Search {
c.JSON(200, MetaResponse(403,"Not allow search."))
type SearchReq struct {
Keyword string `json:"keyword" binding:"required"`
Dir string `json:"dir" binding:"required"`
}
func LocalSearch(c *gin.Context) {
var req SearchReq
if err := c.ShouldBindJSON(&req); err != nil {
c.JSON(200, MetaResponse(400, "Bad Request:"+err.Error()))
return
}
var search alidrive.SearchReq
if err := c.ShouldBindJSON(&search); err != nil {
c.JSON(200, MetaResponse(400,"Bad Request"))
return
}
log.Debugf("search:%+v",search)
// cache
cacheKey:=fmt.Sprintf("%s-%s","s",search.Query)
if conf.Conf.Cache.Enable {
files,exist:=conf.Cache.Get(cacheKey)
if exist {
log.Debugf("使用了缓存:%s",cacheKey)
c.JSON(200, DataResponse(files))
log.Debugf("list:%+v", req)
files, err := models.SearchByNameInDir(req.Keyword, req.Dir)
if err != nil {
if files == nil {
c.JSON(200, MetaResponse(404, "Path not found."))
return
}
}
if search.Limit == 0 {
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)
if err != nil {
c.JSON(200, MetaResponse(500,err.Error()))
c.JSON(200, MetaResponse(500, err.Error()))
return
}
if conf.Conf.Cache.Enable {
conf.Cache.Set(cacheKey,files,cache.DefaultExpiration)
}
c.JSON(200, DataResponse(files))
}
}
func GlobalSearch(c *gin.Context) {
}

View File

@ -2,24 +2,34 @@ package controllers
import (
"github.com/Xhofe/alist/conf"
"github.com/Xhofe/alist/server/models"
"github.com/gin-gonic/gin"
)
// handle info request
func Info(c *gin.Context) {
c.JSON(200, DataResponse(conf.Conf.Info))
}
func RefreshCache(c *gin.Context) {
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."))
// rebuild tree
func RebuildTree(c *gin.Context) {
password := c.Param("password")[1:]
if password != conf.Conf.Server.Password {
if password == "" {
c.JSON(200, MetaResponse(401, "need password."))
return
}
c.JSON(200, MetaResponse(401,"wrong password."))
c.JSON(200, MetaResponse(401, "wrong password."))
return
}
c.JSON(200, MetaResponse(400,"disabled cache."))
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()))
return
}
c.JSON(200, MetaResponse(200, "success."))
return
}
}

View File

@ -7,9 +7,10 @@ import (
"github.com/gin-gonic/gin"
)
func CrosHandler() gin.HandlerFunc {
// handle cors request
func CorsHandler() gin.HandlerFunc {
return func(context *gin.Context) {
origin:=context.GetHeader("Origin")
origin := context.GetHeader("Origin")
// 同源
if origin == "" {
context.Next()
@ -17,14 +18,14 @@ func CrosHandler() 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" {
@ -33,4 +34,4 @@ func CrosHandler() gin.HandlerFunc {
//处理请求
context.Next()
}
}
}

80
server/models/create.go Normal file
View File

@ -0,0 +1,80 @@
package models
import (
"fmt"
"github.com/Xhofe/alist/alidrive"
"github.com/Xhofe/alist/conf"
log "github.com/sirupsen/logrus"
"gorm.io/gorm"
"strings"
)
// build tree
func BuildTree() error {
log.Infof("开始构建目录树...")
tx := conf.DB.Begin()
defer func() {
if r := recover(); r != nil {
tx.Rollback()
}
}()
if err := tx.Error; err != nil {
return err
}
rootFile := File{
Dir: "",
FileId: conf.Conf.AliDrive.RootFolder,
Name: "root",
Type: "folder",
}
if err := tx.Create(&rootFile).Error; err != nil {
tx.Rollback()
return err
}
if err := BuildOne(conf.Conf.AliDrive.RootFolder, "root/", tx, ""); err != nil {
tx.Rollback()
return err
}
return tx.Commit().Error
}
func BuildOne(parent string, path string, tx *gorm.DB, parentPassword string) error {
files, err := alidrive.GetList(parent, conf.Conf.AliDrive.MaxFilesCount, "", "", "")
if err != nil {
return err
}
for _, file := range files.Items {
name := file.Name
if strings.HasSuffix(name, ".hide") {
continue
}
password := parentPassword
if strings.Contains(name, ".password-") {
index := strings.Index(name, ".password-")
name = file.Name[:index]
password = file.Name[index+10:]
}
newFile := File{
Dir: path,
FileExtension: file.FileExtension,
FileId: file.FileId,
Name: name,
Type: file.Type,
UpdatedAt: file.UpdatedAt,
Category: file.Category,
ContentType: file.ContentType,
Size: file.Size,
Password: password,
}
log.Debugf("插入file:%+v", newFile)
if err := tx.Create(&newFile).Error; err != nil {
return err
}
if file.Type == "folder" {
if err := BuildOne(file.FileId, fmt.Sprintf("%s%s/", path, name), tx, password); err != nil {
return err
}
}
}
return nil
}

61
server/models/file.go Normal file
View File

@ -0,0 +1,61 @@
package models
import (
"fmt"
"github.com/Xhofe/alist/conf"
"time"
)
type File struct {
Dir string `json:"dir" gorm:"index"`
FileExtension string `json:"file_extension"`
FileId string `json:"file_id"`
Name string `json:"name" gorm:"index"`
Type string `json:"type"`
UpdatedAt *time.Time `json:"updated_at"`
Category string `json:"category"`
ContentType string `json:"content_type"`
Size int64 `json:"size"`
Password string `json:"password"`
Url string `json:"url" gorm:"-"`
}
func (file *File) Create() error {
return conf.DB.Create(file).Error
}
func Clear() error {
return conf.DB.Where("1 = 1").Delete(&File{}).Error
}
func GetFileByDirAndName(dir, name string) (*File, error) {
var file File
if err := conf.DB.Where("dir = ? AND name = ?", dir, name).First(&file).Error; err != nil {
return nil, err
}
return &file, nil
}
func GetFilesByDir(dir string) (*[]File, error) {
var files []File
if err := conf.DB.Where("dir = ?", dir).Find(&files).Error; err != nil {
return nil, err
}
return &files, nil
}
func SearchByNameGlobal(keyword string) (*[]File, error) {
var files []File
if err := conf.DB.Where("name LIKE ? AND password = ''", fmt.Sprintf("%%%s%%", keyword)).Find(&files).Error; err != nil {
return nil, err
}
return &files, nil
}
func SearchByNameInDir(keyword string, dir string) (*[]File, error) {
var files []File
if err := conf.DB.Where("dir LIKE ? AND name LIKE ? AND password = ''", fmt.Sprintf("%s%%", dir), fmt.Sprintf("%%%s%%", keyword)).Find(&files).Error; err != nil {
return nil, err
}
return &files, nil
}

View File

@ -8,25 +8,28 @@ import (
log "github.com/sirupsen/logrus"
)
// init router
func InitRouter(engine *gin.Engine) {
log.Infof("初始化路由...")
engine.Use(CrosHandler())
engine.Use(CorsHandler())
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")
})
InitApiRouter(engine)
}
// init api router
func InitApiRouter(engine *gin.Engine) {
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")
})
v2:=engine.Group("/api")
apiV2 := engine.Group("/api")
{
v2.GET("/info",controllers.Info)
v2.POST("/get",controllers.Get)
v2.POST("/list",controllers.List)
v2.POST("/search",controllers.Search)
v2.POST("/office_preview",controllers.OfficePreview)
apiV2.GET("/info", controllers.Info)
apiV2.POST("/get", controllers.Get)
apiV2.POST("/path", controllers.Path)
apiV2.POST("/office_preview", controllers.OfficePreview)
apiV2.POST("/local_search", controllers.LocalSearch)
apiV2.POST("/global_search", controllers.GlobalSearch)
apiV2.GET("/rebuild/*password", controllers.RebuildTree)
}
engine.GET("/d/*file_id",controllers.Down)
engine.GET("/cache/:password",controllers.RefreshCache)
}
engine.GET("/d/*path", controllers.Down)
}

View File

@ -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)
}
}

View File

@ -2,12 +2,26 @@ package test
import (
"fmt"
"path/filepath"
"strings"
"testing"
)
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)
}
func TestPassword(t *testing.T) {
fullName:="hello.password-xhf"
index:=strings.Index(fullName,".password-")
name:=fullName[:index]
password:=fullName[index+10:]
fmt.Printf("name:%s, password:%s\n",name,password)
}
func TestDir(t *testing.T) {
dir,file:=filepath.Split("root")
fmt.Printf("dir:%s\nfile:%s\n",dir,file)
}

View File

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

View File

@ -7,16 +7,18 @@ import (
"strings"
)
// 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
}
// determine whether to include
func ContainsString(array []string, val string) (index int) {
index = -1
for i := 0; i < len(array); i++ {
@ -28,6 +30,7 @@ func ContainsString(array []string, val string) (index int) {
return
}
// compare version
func VersionCompare(version1, version2 string) int {
a := strings.Split(version1, ".")
b := strings.Split(version2, ".")
@ -45,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
}
}

57
utils/common.go Normal file
View File

@ -0,0 +1,57 @@
package utils
import (
"errors"
"fmt"
"reflect"
)
// copy interface val
func SimpleCopyProperties(dst, src interface{}) (err error) {
// 防止意外panic
defer func() {
if e := recover(); e != nil {
err = fmt.Errorf("%v", e)
}
}()
dstType, dstValue := reflect.TypeOf(dst), reflect.ValueOf(dst)
srcType, srcValue := reflect.TypeOf(src), reflect.ValueOf(src)
// dst必须结构体指针类型
if dstType.Kind() != reflect.Ptr || dstType.Elem().Kind() != reflect.Struct {
return errors.New("dst type should be a struct pointer")
}
// src必须为结构体或者结构体指针.Elem()类似于*ptr的操作返回指针指向的地址反射类型
if srcType.Kind() == reflect.Ptr {
srcType, srcValue = srcType.Elem(), srcValue.Elem()
}
if srcType.Kind() != reflect.Struct {
return errors.New("src type should be a struct or a struct pointer")
}
// 取具体内容
dstType, dstValue = dstType.Elem(), dstValue.Elem()
// 属性个数
propertyNums := dstType.NumField()
for i := 0; i < propertyNums; i++ {
// 属性
property := dstType.Field(i)
// 待填充属性值
propertyValue := srcValue.FieldByName(property.Name)
// 无效说明src没有这个属性 || 属性同名但类型不同
if !propertyValue.IsValid() || property.Type != propertyValue.Type() {
continue
}
if dstValue.Field(i).CanSet() {
dstValue.Field(i).Set(propertyValue)
}
}
return nil
}

View File

@ -8,6 +8,7 @@ import (
"path/filepath"
)
// determine whether the file exists
func Exists(name string) bool {
if _, err := os.Stat(name); err != nil {
if os.IsNotExist(err) {
@ -17,6 +18,7 @@ func Exists(name string) bool {
return true
}
// 嵌套创建文件
func CreatNestedFile(path string) (*os.File, error) {
basePath := filepath.Dir(path)
if !Exists(basePath) {
@ -29,13 +31,14 @@ func CreatNestedFile(path string) (*os.File, error) {
return os.Create(path)
}
func WriteToYml(src string,conf interface{}){
data,err := yaml.Marshal(conf)
if err!=nil {
log.Errorf("Conf转[]byte失败:%s",err.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())
}
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())
}
}
}