Compare commits

...

48 Commits

Author SHA1 Message Date
d693e27ec0 🔖 release 1.0.4 2021-05-01 20:42:00 +08:00
b20f0717fe 🐛 fix: #101 分次请求文件 2021-04-30 19:01:40 +08:00
427244d8d5 🎇 指定路径与深度rebuild 2021-04-14 13:34:14 +08:00
b613598c2b 在线预览视频时间延长到4小时 (#96)
* Update request.go

* Update req_bean.go
2021-04-13 23:37:20 +08:00
f0013320a6 🔖 release v1.0.3 2021-04-09 10:45:16 +08:00
974caf74d9 🔥 只初始化一次client 2021-04-09 10:38:57 +08:00
0bb02664c7 🐛 fix: #85 修复 x509: certificate signed by unknown authority (#86)
* 修复 x509: certificate signed by unknown authority

* 添加忽略证书验证
2021-04-09 10:30:03 +08:00
6c5a0cba6e 🐛 修复refresh_token失效时无限刷新的bug 2021-03-31 11:05:39 +08:00
7e21e12e11 👷 release增加Linux386 2021-03-31 09:08:06 +08:00
11489d8856 Merge pull request #68 from 122cygf/main
修复了因为Referer导致不能下载的问题
2021-03-31 08:04:51 +08:00
lzz
6d824a4ee9 Update auth.go 2021-03-31 00:23:51 +08:00
lzz
8d74d070d4 Update req_bean.go 2021-03-31 00:21:49 +08:00
77aae6660e 增加视频接口 2021-03-30 10:22:07 +08:00
76081a81a6 💚 linux_386构建出错 2021-03-21 10:31:53 +08:00
8760ab283d 💚 linux_386构建出错 2021-03-21 10:23:00 +08:00
61ab27398c 👷 添加linux386测试 2021-03-21 10:14:59 +08:00
2e64df7e3d Merge pull request #48 from phoon/main
自定义监听地址配置
2021-03-19 18:45:53 +08:00
9561f0c951 update conf.yml.example 2021-03-17 18:25:20 +08:00
03f5a54764 allow to set address in configuration file 2021-03-17 18:08:22 +08:00
9952c3e90b 💚 版本号 2021-03-17 13:01:02 +08:00
d94e319df3 🔖 release v1.0.1 2021-03-17 12:56:47 +08:00
b51b2deea1 💚 错误的文件名 2021-03-17 11:46:53 +08:00
7dda701f1e 💚 CI重复ID 2021-03-17 11:40:45 +08:00
3b93445648 👷 release ci surpoort cgo 2021-03-17 11:34:24 +08:00
a353081126 🐛 重建时删除不完全 2021-03-16 23:52:41 +08:00
a5b2f998ab 🎇 支持mysql 2021-03-16 23:15:37 +08:00
4d0d892ce7 🎇 多盘支持 2021-03-16 21:25:16 +08:00
8e9ddcf81e 🐛 fix: #43 直链密码错误 2021-03-16 16:25:02 +08:00
5c6344cac0 🎇 直链url密码哈希 2021-03-14 19:13:09 +08:00
7076efb6be 💚 降低构建系统版本 2021-03-13 23:04:13 +08:00
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
3b2a729dc6 🔧 修改配置文件 2021-01-22 14:27:03 +08:00
d18a752732 添加了office接口 2021-01-19 17:20:14 +08:00
b9676182c9 🌿 优化了一些代码 2021-01-19 17:19:48 +08:00
46 changed files with 1524 additions and 755 deletions

View File

@ -11,7 +11,7 @@ jobs:
build:
strategy:
matrix:
platform: [ubuntu-latest]
platform: [ubuntu-16.04]
go-version: [1.15]
name: Build
runs-on: ${{ matrix.platform }}
@ -46,6 +46,11 @@ jobs:
run: |
CC=x86_64-w64-mingw32-gcc CGO_ENABLED=1 GOOS=windows GOARCH=amd64 go build -o alist_windows_amd64.exe alist.go
- name: Build linux_386
run: |
sudo apt-get -y install libc6-dev-i386
CC=gcc CGO_ENABLED=1 GOOS=linux GOARCH=386 go build -o alist_linux_386 alist.go
- name: Upload artifacts linux_amd64
uses: actions/upload-artifact@v2
with:
@ -68,4 +73,10 @@ jobs:
uses: actions/upload-artifact@v2
with:
name: alist_windows_amd64
path: alist_windows_amd64.exe
path: alist_windows_amd64.exe
- name: Upload artifacts linux_386
uses: actions/upload-artifact@v2
with:
name: alist_linux_386
path: alist_linux_386

View File

@ -5,24 +5,130 @@ on:
- '*'
jobs:
goreleaser:
runs-on: ubuntu-latest
release:
strategy:
matrix:
platform: [ ubuntu-16.04 ]
go-version: [ 1.15 ]
name: Build
runs-on: ${{ matrix.platform }}
steps:
-
name: Checkout
uses: actions/checkout@v2
with:
fetch-depth: 0
-
name: Set up Go
- name: Set up Go
uses: actions/setup-go@v2
with:
go-version: 1.15
-
name: Run GoReleaser
uses: goreleaser/goreleaser-action@v2
with:
version: latest
args: release --rm-dist
go-version: ${{ matrix.go-version }}
- name: Get version
id: get_version
run: echo ::set-output name=VERSION::${GITHUB_REF/refs\/tags\//}
- name: Check out code into the Go module directory
uses: actions/checkout@v2
- name: Get dependencies
run: |
sudo apt-get update
sudo apt-get -y install gcc-mingw-w64-x86-64
sudo apt-get -y install gcc-arm-linux-gnueabihf libc6-dev-armhf-cross
sudo apt-get -y install gcc-aarch64-linux-gnu libc6-dev-arm64-cross
go get -v -t -d ./...
if [ -f Gopkg.toml ]; then
curl https://raw.githubusercontent.com/golang/dep/master/install.sh | sh
dep ensure
fi
- name: Build linux
run: |
CC=gcc CGO_ENABLED=1 GOOS=linux GOARCH=amd64 go build -o linux_amd64/alist alist.go
CC=aarch64-linux-gnu-gcc CGO_ENABLED=1 GOOS=linux GOARCH=arm64 go build -o linux_arm64/alist alist.go
CC=arm-linux-gnueabihf-gcc CGO_ENABLED=1 GOOS=linux GOARCH=arm go build -o linux_arm/alist alist.go
- name: Build windows
run: |
CC=x86_64-w64-mingw32-gcc CGO_ENABLED=1 GOOS=windows GOARCH=amd64 go build -o windows_amd64/alist.exe alist.go
- name: Build linux_386
run: |
sudo apt-get -y install libc6-dev-i386
CC=gcc CGO_ENABLED=1 GOOS=linux GOARCH=386 go build -o linux_386/alist alist.go
- name: compress
run: |
tar -czvf alist_linux_amd64.tar.gz linux_amd64/alist conf.yml.example
tar -czvf alist_linux_arm64.tar.gz linux_arm64/alist conf.yml.example
tar -czvf alist_linux_arm.tar.gz linux_arm/alist conf.yml.example
tar -czvf alist_linux_386.tar.gz linux_386/alist conf.yml.example
zip alist_windows_amd64.zip windows_amd64/alist.exe conf.yml.example
- name: Build Changelog
id: github_release
uses: mikepenz/release-changelog-builder-action@main
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
- name: Create Release
id: create_release
uses: actions/create-release@v1
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
with:
tag_name: ${{ github.ref }}
release_name: Release ${{ github.ref }}
body: ${{steps.github_release.outputs.changelog}}
draft: false
prerelease: false
- name: Upload alist_linux_amd64
id: upload-release-linux-amd64
uses: actions/upload-release-asset@v1
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
with:
upload_url: ${{ steps.create_release.outputs.upload_url }}
asset_path: alist_linux_amd64.tar.gz
asset_name: alist_${{ steps.get_version.outputs.VERSION }}_linux_amd64.tar.gz
asset_content_type: application/gzip
- name: Upload alist_linux_arm64
id: upload-release-linux-arm64
uses: actions/upload-release-asset@v1
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
with:
upload_url: ${{ steps.create_release.outputs.upload_url }}
asset_path: alist_linux_arm64.tar.gz
asset_name: alist_${{ steps.get_version.outputs.VERSION }}_linux_arm64.tar.gz
asset_content_type: application/gzip
- name: Upload alist_linux_arm
id: upload-release-linux-arm
uses: actions/upload-release-asset@v1
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
with:
upload_url: ${{ steps.create_release.outputs.upload_url }}
asset_path: alist_linux_arm.tar.gz
asset_name: alist_${{ steps.get_version.outputs.VERSION }}_linux_arm.tar.gz
asset_content_type: application/gzip
- name: Upload alist_linux_386
id: upload-release-linux-386
uses: actions/upload-release-asset@v1
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
with:
upload_url: ${{ steps.create_release.outputs.upload_url }}
asset_path: alist_linux_386.tar.gz
asset_name: alist_${{ steps.get_version.outputs.VERSION }}_linux_386.tar.gz
asset_content_type: application/gzip
- name: Upload alist_windows_amd64
id: upload-release-windows-amd64
uses: actions/upload-release-asset@v1
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
with:
upload_url: ${{ steps.create_release.outputs.upload_url }}
asset_path: alist_windows_amd64.zip
asset_name: alist_${{ steps.get_version.outputs.VERSION }}_windows_amd64.zip
asset_content_type: application/zip

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

@ -2,74 +2,48 @@ package alidrive
import (
"encoding/json"
"fmt"
"github.com/Xhofe/alist/conf"
"github.com/Xhofe/alist/utils"
log "github.com/sirupsen/logrus"
)
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)
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 tokenLogin.IsAvailable() {
return &tokenLogin,nil
}
return nil,fmt.Errorf("登录token失效,请更换:%s",tokenLogin.Message)
}
func GetToken(tokenLogin *TokenLoginResp) (*TokenResp,error) {
log.Infof("获取API token...")
url:="https://websv.aliyundrive.com/token/get"
code:=utils.GetCode(tokenLogin.Goto)
if code == "" {
return nil,fmt.Errorf("获取code出错")
}
req:=GetTokenReq{Code:code}
// refresh access_token token by refresh_token
func RefreshToken(drive *conf.Drive) bool {
log.Infof("刷新[%s]token...", drive.Name)
url := "https://auth.aliyundrive.com/v2/account/token"
req := RefreshTokenReq{RefreshToken: drive.RefreshToken , GrantType: "refresh_token"}
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())
log.Errorf("此处json解析失败应该是code失效")
return nil,fmt.Errorf("code失效")
}
}
return &token,nil
}
func RefreshToken() bool {
log.Infof("刷新token...")
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, ""); 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())
log.Errorf("此处json解析失败应该是refresh_token失效")
} else {
if err = json.Unmarshal(body, &token); err != nil {
log.Errorf("解析json[%s]出错:%s", string(body), err.Error())
log.Errorf("此处json解析失败应该是[%s]refresh_token失效", drive.Name)
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)
if token.Code != "" {
log.Errorf("盘[%s]刷新token出错%s", drive.Name, token.Message)
return false
}
//刷新成功 更新token
drive.AccessToken = token.AccessToken
drive.RefreshToken = token.RefreshToken
return true
}
func RefreshTokenAll() string {
log.Infof("刷新所有token...")
res := ""
for i, drive := range conf.Conf.AliDrive.Drives {
if !RefreshToken(&conf.Conf.AliDrive.Drives[i]) {
res = res + drive.Name + ","
}
}
utils.WriteToYml(conf.ConfigFile, conf.Conf)
if res != "" {
return res[:len(res)-1]
}
return ""
}

View File

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

80
alidrive/post_json.go Normal file
View File

@ -0,0 +1,80 @@
package alidrive
import (
"bytes"
"encoding/json"
"fmt"
"github.com/Xhofe/alist/conf"
log "github.com/sirupsen/logrus"
"io/ioutil"
"net/http"
"strings"
"time"
)
// convert body to json
func BodyToJson(url string, req interface{}, resp RespHandle, drive *conf.Drive) error {
if body, err := DoPost(url, req, drive.AccessToken); 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())
return err
}
}
if resp.IsAvailable() {
return nil
}
if resp.GetCode() == conf.AccessTokenInvalid {
resp.SetCode("")
if RefreshToken(drive) {
return BodyToJson(url, req, resp, drive)
}
}
return fmt.Errorf(resp.GetMessage())
}
// do post request
func DoPost(url string, request interface{}, auth string) (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())
return
}
if auth != "" {
req.Header.Set("authorization", conf.Bearer+auth)
}
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 {
break
}
}
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))
return
}

View File

@ -1,46 +1,75 @@
package alidrive
// list request bean
type ListReq struct {
DriveId string `json:"drive_id"`
Fields string `json:"fields"`
ImageThumbnailProcess string `json:"image_thumbnail_process"`
ImageUrlProcess string `json:"image_url_process"`
Limit int `json:"limit"`
Marker string `json:"marker"`
OrderBy string `json:"order_by"`
OrderDirection string `json:"order_direction"`
ParentFileId string `json:"parent_file_id"`
VideoThumbnailProcess string `json:"video_thumbnail_process"`
DriveId string `json:"drive_id"`
Fields string `json:"fields"`
ImageThumbnailProcess string `json:"image_thumbnail_process"`
ImageUrlProcess string `json:"image_url_process"`
Limit int `json:"limit"`
Marker string `json:"marker"`
OrderBy string `json:"order_by"`
OrderDirection string `json:"order_direction"`
ParentFileId string `json:"parent_file_id"`
VideoThumbnailProcess string `json:"video_thumbnail_process"`
}
// get request bean
type GetReq struct {
DriveId string `json:"drive_id"`
FileId string `json:"file_id"`
ImageThumbnailProcess string `json:"image_thumbnail_process"`
VideoThumbnailProcess string `json:"video_thumbnail_process"`
DriveId string `json:"drive_id"`
FileId string `json:"file_id"`
ImageThumbnailProcess string `json:"image_thumbnail_process"`
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"`
ImageUrlProcess string `json:"image_url_process"`
Limit int `json:"limit"`
Marker string `json:"marker"`
OrderBy string `json:"order_by"`//"type ASC,updated_at DESC"
DriveId string `json:"drive_id"`
ImageThumbnailProcess string `json:"image_thumbnail_process"`
ImageUrlProcess string `json:"image_url_process"`
Limit int `json:"limit"`
Marker string `json:"marker"`
OrderBy string `json:"order_by"` //"type ASC,updated_at DESC"
Query string `json:"query"`// "name match '测试文件'"
Query string `json:"query"` // "name match '测试文件'"
VideoThumbnailProcess string `json:"video_thumbnail_process"`
VideoThumbnailProcess string `json:"video_thumbnail_process"`
}
// token_login request bean
type TokenLoginReq struct {
Token string `json:"token"`
Token string `json:"token"`
}
// get_token request bean
type GetTokenReq struct {
Code string `json:"code"`
Code string `json:"code"`
}
// refresh_token request bean
type RefreshTokenReq struct {
RefreshToken string `json:"refresh_token"`
}
RefreshToken string `json:"refresh_token"`
GrantType string `json:"grant_type"`
}
// office_preview_url request bean
type OfficePreviewUrlReq struct {
AccessToken string `json:"access_token"`
DriveId string `json:"drive_id"`
FileId string `json:"file_id"`
}
// video preview url request bean
type VideoPreviewUrlReq struct {
DriveId string `json:"drive_id"`
FileId string `json:"file_id"`
ExpireSec int `json:"expire_sec"`
}

View File

@ -1,87 +1,71 @@
package alidrive
import (
"bytes"
"encoding/json"
"fmt"
"github.com/Xhofe/alist/conf"
log "github.com/sirupsen/logrus"
"io/ioutil"
"net/http"
"strings"
"time"
)
func GetFile(fileId string) (*File, error) {
url:=conf.Conf.AliDrive.ApiUrl+"/file/get"
req:=GetReq{
DriveId: User.DefaultDriveId,
// get file
func GetFile(fileId string, drive *conf.Drive) (*File, error) {
url := conf.Conf.AliDrive.ApiUrl + "/file/get"
req := GetReq{
DriveId: drive.DefaultDriveId,
FileId: fileId,
ImageThumbnailProcess: conf.ImageThumbnailProcess,
VideoThumbnailProcess: conf.VideoThumbnailProcess,
}
var file File
if body, err := DoPost(url, req,true); err != nil {
log.Errorf("doPost出错:%s",err.Error())
return nil,err
}else {
if err = json.Unmarshal(body,&file);err !=nil {
log.Errorf("解析json[%s]出错:%s",string(body),err.Error())
return nil,err
}
var resp File
if err := BodyToJson(url, req, &resp, drive); err != nil {
return nil, err
}
if file.IsAvailable() {
return &file,nil
}
if file.Code==conf.AccessTokenInvalid {
if RefreshToken() {
return GetFile(fileId)
}
}
return nil,fmt.Errorf(file.Message)
return &resp, nil
}
func Search(key string,limit int, marker string) (*Files, error) {
url:=conf.Conf.AliDrive.ApiUrl+"/file/search"
req:=SearchReq{
DriveId: User.DefaultDriveId,
// get download_url
func GetDownLoadUrl(fileId string, drive *conf.Drive) (*DownloadResp, error) {
url := conf.Conf.AliDrive.ApiUrl + "/file/get_download_url"
req := DownloadReq{
DriveId: drive.DefaultDriveId,
FileId: fileId,
ExpireSec: 14400,
}
var resp DownloadResp
if err := BodyToJson(url, req, &resp, drive); err != nil {
return nil, err
}
return &resp, nil
}
// search by keyword
func Search(key string, limit int, marker string, drive *conf.Drive) (*Files, error) {
url := conf.Conf.AliDrive.ApiUrl + "/file/search"
req := SearchReq{
DriveId: drive.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 files Files
if body, err := DoPost(url, req,true); err != nil {
log.Errorf("doPost出错:%s",err.Error())
return nil,err
}else {
if err = json.Unmarshal(body,&files);err !=nil {
log.Errorf("解析json[%s]出错:%s",string(body),err.Error())
return nil,err
}
var resp Files
if err := BodyToJson(url, req, &resp, drive); err != nil {
return nil, err
}
if files.IsAvailable() {
return &files,nil
}
if files.Code==conf.AccessTokenInvalid {
if RefreshToken() {
return Search(key,limit,marker)
}
}
return nil,fmt.Errorf(files.Message)
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, drive *conf.Drive) (*Files, error) {
return GetList(drive.RootFolder, limit, marker, orderBy, orderDirection, drive)
}
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,
// get folder list by file_id
func GetList(parent string, limit int, marker string, orderBy string, orderDirection string, drive *conf.Drive) (*Files, error) {
url := conf.Conf.AliDrive.ApiUrl + "/file/list"
req := ListReq{
DriveId: drive.DefaultDriveId,
Fields: "*",
ImageThumbnailProcess: conf.ImageThumbnailProcess,
ImageUrlProcess: conf.ImageUrlProcess,
@ -92,110 +76,49 @@ func GetList(parent string,limit int,marker string,orderBy string,orderDirection
ParentFileId: parent,
VideoThumbnailProcess: conf.VideoThumbnailProcess,
}
var files Files
if body, err := DoPost(url, req,true); err != nil {
log.Errorf("doPost出错:%s",err.Error())
return nil,err
}else {
if err = json.Unmarshal(body,&files);err !=nil {
log.Errorf("解析json[%s]出错:%s",string(body),err.Error())
return nil,err
}
var resp Files
if err := BodyToJson(url, req, &resp, drive); err != nil {
return nil, err
}
if files.IsAvailable() {
return &files,nil
}
if files.Code==conf.AccessTokenInvalid {
if RefreshToken() {
return GetRoot(limit,marker,orderBy,orderDirection)
}
}
return nil,fmt.Errorf(files.Message)
return &resp, nil
}
func GetUserInfo() (*UserInfo,error) {
url:=conf.Conf.AliDrive.ApiUrl+"/user/get"
var user UserInfo
if body, err := DoPost(url, map[string]interface{}{},true); err != nil {
log.Errorf("doPost出错:%s",err.Error())
return nil,err
}else {
if err = json.Unmarshal(body,&user);err !=nil {
log.Errorf("解析json[%s]出错:%s",string(body),err.Error())
return nil,err
}
// get user info
func GetUserInfo(drive *conf.Drive) (*UserInfo, error) {
url := conf.Conf.AliDrive.ApiUrl + "/user/get"
var resp UserInfo
if err := BodyToJson(url, map[string]interface{}{}, &resp, drive); err != nil {
return nil, err
}
if user.IsAvailable() {
return &user,nil
}
if user.Code==conf.AccessTokenInvalid {
if RefreshToken() {
return GetUserInfo()
}
}
return nil,fmt.Errorf(user.Message)
return &resp, nil
}
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())
// get office preview url and token
func GetOfficePreviewUrl(fileId string, drive *conf.Drive) (*OfficePreviewUrlResp, error) {
url := conf.Conf.AliDrive.ApiUrl + "/file/get_office_preview_url"
req := OfficePreviewUrlReq{
AccessToken: drive.AccessToken,
DriveId: drive.DefaultDriveId,
FileId: fileId,
}
req,err:=http.NewRequest("POST",url,requestBody)
log.Debugf("do_post_req:%+v",req)
if err != nil {
log.Errorf("创建request出错:%s",err.Error())
return
var resp OfficePreviewUrlResp
if err := BodyToJson(url, req, &resp, drive); err != nil {
return nil, err
}
if auth {
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("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 {
break
}
}
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))
return
return &resp, nil
}
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
}
paths=append(paths,Path{
Name: file.Name,
FileId: file.FileId,
})
fileId=file.ParentFileId
// get video preview url
func GetVideoPreviewUrl(fileId string, drive *conf.Drive) (*VideoPreviewUrlResp, error) {
url := conf.Conf.AliDrive.ApiUrl + "/databox/get_video_play_info"
req := VideoPreviewUrlReq{
DriveId: drive.DefaultDriveId,
FileId: fileId,
ExpireSec: 14400,
}
paths=append(paths, Path{
Name: "Root",
FileId: "root",
})
return &paths,nil
}
var resp VideoPreviewUrlResp
if err := BodyToJson(url, req, &resp, drive); err != nil {
return nil, err
}
return &resp, nil
}

View File

@ -1,18 +1,40 @@
package alidrive
import (
log "github.com/sirupsen/logrus"
"io/ioutil"
"net/http"
"strings"
"time"
)
// response bean methods
type RespHandle interface {
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"`
}
func (resp *RespError) IsAvailable() bool {
return resp.Code == ""
}
func (resp *RespError) GetCode() string {
return resp.Code
}
func (resp *RespError) GetMessage() string {
return resp.Message
}
func (resp *RespError) SetCode(code string) {
resp.Code = code
}
// user_info response bean
type UserInfo struct {
RespError
DomainId string `json:"domain_id"`
@ -31,19 +53,30 @@ 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"`
Paths []Path `json:"paths"`
Readme string `json:"readme"` // Deprecated
Paths []Path `json:"paths"`
}
// path bean
type Path struct {
Name string `json:"name"`
FileId string `json:"file_id"`
}
/** 秒传
{
"name":"mikuclub.mp4",
"content_hash":"C733AC50D1F964C0398D0E403F3A30C37EFC2ADD",
"size":1141068377,
"content_type":"video/mp4"
}
*/
// file response bean
type File struct {
RespError
DriveId string `json:"drive_id"`
@ -72,18 +105,28 @@ type File struct {
Url string `json:"url"`
ImageMediaMetadata map[string]interface{} `json:"image_media_metadata"`
Paths []Path `json:"paths"`
Paths []Path `json:"paths"`
}
func (resp *RespError) IsAvailable() bool {
return resp.Code == ""
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"`
@ -104,33 +147,18 @@ type TokenResp struct {
DeviceId string `json:"device_id"`
}
func HasPassword(files *Files) string {
fileList := files.Items
for i, file := range fileList {
if strings.HasPrefix(file.Name, ".password-") {
files.Items=fileList[:i+copy(fileList[i:],fileList[i+1:])]
return file.Name[10:]
}
}
return ""
// office_preview_url response bean
type OfficePreviewUrlResp struct {
RespError
PreviewUrl string `json:"preview_url"`
AccessToken string `json:"access_token"`
}
func HasReadme(files *Files) string {
fileList := files.Items
for _, file := range fileList {
if file.Name == "Readme.md" {
resp, err := http.Get(file.Url)
if err != nil {
log.Errorf("Get Readme出错:%s", err.Error())
return ""
}
data, err := ioutil.ReadAll(resp.Body)
if err != nil {
log.Errorf("读取 Readme出错:%s", err.Error())
return ""
}
return string(data)
}
}
return ""
type VideoPreviewUrlResp struct {
RespError
TemplateList []struct {
TemplateId string `json:"template_id"`
Status string `json:"status"`
Url string `json:"url"`
} `json:"template_list"`
}

41
alidrive/utils.go Normal file
View File

@ -0,0 +1,41 @@
package alidrive
import (
log "github.com/sirupsen/logrus"
"io/ioutil"
"net/http"
"strings"
)
// check password
func HasPassword(files *Files) string {
fileList := files.Items
for i, file := range fileList {
if strings.HasPrefix(file.Name, ".password-") {
files.Items = fileList[:i+copy(fileList[i:], fileList[i+1:])]
return file.Name[10:]
}
}
return ""
}
// Deprecated: check readme, implemented by the front end now
func HasReadme(files *Files) string {
fileList := files.Items
for _, file := range fileList {
if file.Name == "Readme.md" {
resp, err := http.Get(file.Url)
if err != nil {
log.Errorf("Get Readme出错:%s", err.Error())
return ""
}
data, err := ioutil.ReadAll(resp.Body)
if err != nil {
log.Errorf("读取 Readme出错:%s", err.Error())
return ""
}
return string(data)
}
}
return ""
}

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,28 @@ 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())
return false
}
//然后get_token
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
res := alidrive.RefreshTokenAll()
if res != "" {
log.Errorf("盘[%s]refresh_token失效,请检查", res)
}
log.Debugf("token:%s",conf.Authorization)
user,err:=alidrive.GetUserInfo()
if err != nil {
log.Errorf("初始化用户失败:%s",err.Error())
return false
log.Debugf("config:%+v", conf.Conf)
for i, _ := range conf.Conf.AliDrive.Drives {
InitDriveId(&conf.Conf.AliDrive.Drives[i])
}
log.Infof("当前用户信息:%+v",user)
alidrive.User=user
return true
}
func InitDriveId(drive *conf.Drive) bool {
user, err := alidrive.GetUserInfo(drive)
if err != nil {
log.Errorf("初始化盘[%s]失败:%s", drive.Name, err.Error())
return false
}
drive.DefaultDriveId = user.DefaultDriveId
log.Infof("初始化盘[%s]成功:%+v", drive.Name, 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

@ -1,12 +1,17 @@
package bootstrap
import (
"crypto/tls"
"github.com/Xhofe/alist/conf"
log "github.com/sirupsen/logrus"
"net/http"
)
func InitClient() {
// init request client
func InitClient() {
log.Infof("初始化client...")
conf.Client=&http.Client{}
}
tr := &http.Transport{
TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
}
conf.Client = &http.Client{Transport: tr}
}

View File

@ -2,6 +2,8 @@ package bootstrap
import (
"flag"
"fmt"
"github.com/Xhofe/alist/conf"
serv "github.com/Xhofe/alist/server"
"github.com/gin-gonic/gin"
@ -9,21 +11,29 @@ import (
)
func init() {
flag.BoolVar(&conf.Debug,"debug",false,"use debug mode")
flag.BoolVar(&conf.Help,"help",false,"show usage help")
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.ConfigFile, "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)
return
}
start()
}
func printASC() {
// print asc
func printASC() {
log.Info(`
________ ___ ___ ________ _________
|\ __ \|\ \ |\ \|\ ____\|\___ ___\
@ -36,11 +46,14 @@ func printASC() {
`)
}
// start server
func start() {
InitLog()
printASC()
CheckUpdate()
if !ReadConf(conf.Con) {
if !conf.SkipUpdate {
CheckUpdate()
}
if !ReadConf(conf.ConfigFile) {
log.Errorf("读取配置文件时出现错误,启动失败.")
return
}
@ -49,18 +62,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 := conf.Conf.Server.Address + ":" + 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,25 @@ 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.Conf.Info.Roots = utils.GetNames()
conf.Origins = strings.Split(conf.Conf.Server.SiteUrl, ",")
return true
}
}

View File

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

74
bootstrap/model.go Normal file
View File

@ -0,0 +1,74 @@
package bootstrap
import (
"fmt"
"github.com/Xhofe/alist/conf"
"github.com/Xhofe/alist/server/models"
"github.com/Xhofe/alist/utils"
log "github.com/sirupsen/logrus"
"gorm.io/driver/mysql"
"gorm.io/driver/sqlite"
"gorm.io/gorm"
"gorm.io/gorm/schema"
"strings"
)
func InitModel() bool {
log.Infof("初始化数据库...")
dbConfig := conf.Conf.Database
switch dbConfig.Type {
case "sqlite3":
{
if !(strings.HasSuffix(dbConfig.DBFile, ".db") && len(dbConfig.DBFile) > 3) {
log.Errorf("db名称不正确.")
return false
}
needMigrate := !utils.Exists(dbConfig.DBFile)
db, err := gorm.Open(sqlite.Open(dbConfig.DBFile), &gorm.Config{
NamingStrategy: schema.NamingStrategy{
TablePrefix: dbConfig.TablePrefix,
},
})
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
}
//models.BuildTreeAll()
}
return true
}
case "mysql":
{
dsn := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=utf8mb4&parseTime=True&loc=Local",
dbConfig.User, dbConfig.Password, dbConfig.Host, dbConfig.Port, dbConfig.Name)
db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{
NamingStrategy: schema.NamingStrategy{
TablePrefix: dbConfig.TablePrefix,
},
})
if err != nil {
log.Errorf("连接数据库出现错误:%s", err.Error())
return false
}
conf.DB = db
log.Infof("迁移数据库...")
err = conf.DB.AutoMigrate(&models.File{})
if err != nil {
log.Errorf("数据库迁移失败:%s", err.Error())
return false
}
return true
}
default:
log.Errorf("不支持的数据库类型:%s", dbConfig.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

@ -7,24 +7,29 @@ info:
check_update: true #前端是否显示更新
script: #自定义脚本,可以是脚本的链接,也可以直接是脚本内容,如document.querySelector('body').style="background-image:url('https://api.mtyqx.cn/api/random.php');background-attachment:fixed"
autoplay: true #视频是否自动播放
preview:
url: https://view.alist.nn.ci/onlinePreview?url= #extensions中包含的后缀名预览的地址默认使用了kkFileView,可以自行搭建
pre_process: [base64,encodeURIComponent] #对地址的处理支持base64,encodeURIComponent,encodeURI
extensions: [doc,docx,ppt,pptx,xls,xlsx,pdf] #使用上面的url预览的文件后缀
text: [txt,htm,html,xml,java,properties,sql,js,md,json,conf,ini,vue,php,py,bat,gitignore,yml,go,sh,c,cpp,h,hpp] #要预览的文本文件的后缀,可以自行添加
max_size: 5242880
preview:
text: [txt,htm,html,xml,java,properties,sql,js,md,json,conf,ini,vue,php,py,bat,gitignore,yml,go,sh,c,cpp,h,hpp] #要预览的文本文件的后缀,可以自行添加
server:
port: "5244" #程序监听端口
search: true #是否开启搜索接口,开启搜索之后密码和根目录都会失效,所以前端暂时不做搜索
static: dist #前端文件目录
site_url: '*' #建议直接填*,若有信任域名要求,可填写其他,逗号分割
cache:
enable: true #是否开启缓存
expiration: 60 #缓存失效时间(单位:分钟)
cleanup_interval: 120 #清理失效缓存间隔
refresh_password: password #手动清理缓存密码
address: "0.0.0.0"
port: "5244"
search: true
static: dist
site_url: '*'
password: password #用于重建目录
ali_drive:
api_url: https://api.aliyundrive.com/v2 #阿里云盘api,无需修改
root_folder: root #根目录
refresh_token: need
max_files_count: 3000
api_url: https://api.aliyundrive.com/v2
max_files_count: 50 #重建目录时每次请求的文件
drives:
- refresh_token: xxx #refresh_token
root_folder: root #根目录的file_id
name: drive0 #盘名,多个盘不可重复
password: pass #该盘密码,空则不设密码,修改需要重建生效
hide: false #是否在主页隐藏该盘,不可全部隐藏,至少暴露一个
- refresh_token: xxx
root_folder: root
name: drive1
password: pass
hide: false
database:
type: sqlite3
dBFile: alist.db

View File

@ -1,42 +1,56 @@
package conf
type Drive struct {
AccessToken string `yaml:"-"`
RefreshToken string `yaml:"refresh_token"`
RootFolder string `yaml:"root_folder"` //根目录id
Name string `yaml:"name"`
Password string `yaml:"password"`
Hide bool `yaml:"hide"`
DefaultDriveId string `yaml:"-"`
}
// 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
//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"`
}
Info struct {
Title string `yaml:"title" json:"title"`
Roots []string `yaml:"-" json:"roots"`
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 {
Address string `yaml:"address"`
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
MaxFilesCount int `yaml:"max_files_count"`
Drives []Drive `yaml:"drives"`
} `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,37 +1,39 @@
package conf
import (
"github.com/patrickmn/go-cache"
"gorm.io/gorm"
"net/http"
)
var(
Debug bool
Help 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
ConfigFile string // config file
SkipUpdate bool // skip update
Cache *cache.Cache
Client *http.Client // request client
Origins []string
DB *gorm.DB
Origins []string // allow origins
)
var Conf = new(Config)
const (
VERSION="v0.1.5"
VERSION = "v1.0.4"
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
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,7 @@ 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/mysql v1.0.5
gorm.io/driver/sqlite v1.1.4
gorm.io/gorm v1.21.3
)

30
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=
@ -25,6 +27,8 @@ github.com/go-playground/validator/v10 v10.2.0 h1:KgJ0snyC2R9VXYN2rneOtQcw5aHQB1
github.com/go-playground/validator/v10 v10.2.0/go.mod h1:uOYAAleCW8F/7oMFd6aG0GOhaH6EGOAJShg8Id5JGkI=
github.com/go-playground/validator/v10 v10.4.1 h1:pH2c5ADXtd66mxoE0Zm9SUhxE20r7aM3F26W0hOn+GE=
github.com/go-playground/validator/v10 v10.4.1/go.mod h1:nlOn6nFhuKACm19sB/8EGNn9GlaMV7XkbRSipzJ0Ii4=
github.com/go-sql-driver/mysql v1.5.0 h1:ozyZYNQW3x3HtqT1jira07DN2PArx2v7/mN66gGcHOs=
github.com/go-sql-driver/mysql v1.5.0/go.mod h1:DCzpHaOWr8IXmIStZouvnhqoel9Qv2LBy8hT2VhHyBg=
github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b/go.mod h1:SBH7ygxi8pfUlaOkMMuAQtPIUF8ecWP5IEl/CR7VP2Q=
github.com/golang/mock v1.1.1/go.mod h1:oTYuIxOrZwtPieC+H1uAHpcLFnEyAGVDL/k47Jfbm0A=
github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U=
@ -43,8 +47,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 +67,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 +79,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 +90,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 +136,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 +157,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 +166,16 @@ 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/mysql v1.0.5 h1:WAAmvLK2rG0tCOqrf5XcLi2QUwugd4rcVJ/W3aoon9o=
gorm.io/driver/mysql v1.0.5/go.mod h1:N1OIhHAIhx5SunkMGqWbGFVeh4yTNWKmMo1GOAsohLI=
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=
gorm.io/gorm v1.21.3 h1:qDFi55ZOsjZTwk5eN+uhAmHi8GysJ/qCTichM/yO7ME=
gorm.io/gorm v1.21.3/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,60 @@
package controllers
import (
"github.com/Xhofe/alist/alidrive"
"github.com/Xhofe/alist/server/models"
"github.com/Xhofe/alist/utils"
"github.com/gin-gonic/gin"
log "github.com/sirupsen/logrus"
"path/filepath"
"strings"
)
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 != "" && down.Password != utils.Get16MD5Encode(fileModel.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
}
drive := utils.GetDriveByName(strings.Split(filePath, "/")[0])
if drive == nil {
c.JSON(200, MetaResponse(500, "找不到drive."))
return
}
file, err := alidrive.GetDownLoadUrl(fileModel.FileId, drive)
if err != nil {
c.JSON(200, MetaResponse(500, err.Error()))
return
}
c.Redirect(301, file.Url)
return
}

View File

@ -2,68 +2,55 @@ package controllers
import (
"github.com/Xhofe/alist/alidrive"
"github.com/Xhofe/alist/server/models"
"github.com/Xhofe/alist/utils"
"github.com/gin-gonic/gin"
log "github.com/sirupsen/logrus"
"path/filepath"
"strings"
)
// 因为下载地址有时效,所以去掉了文件请求和直链的缓存
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
}
drive := utils.GetDriveByName(strings.Split(get.Path, "/")[0])
if drive == nil {
c.JSON(200, MetaResponse(500, "找不到drive."))
return
}
down, err := alidrive.GetDownLoadUrl(file.FileId, drive)
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

@ -0,0 +1,34 @@
package controllers
import (
"github.com/Xhofe/alist/alidrive"
"github.com/Xhofe/alist/utils"
"github.com/gin-gonic/gin"
log "github.com/sirupsen/logrus"
)
type OfficePreviewReq struct {
FileId string `json:"file_id" binding:"required"`
}
// handle office_preview request
func OfficePreview(c *gin.Context) {
drive := utils.GetDriveByName(c.Param("drive"))
if drive == nil {
c.JSON(200, MetaResponse(400, "drive isn't exist."))
return
}
var req OfficePreviewReq
if err := c.ShouldBindJSON(&req); err != nil {
c.JSON(200, MetaResponse(400, "Bad Request:"+err.Error()))
return
}
log.Debugf("preview_req:%+v", req)
preview, err := alidrive.GetOfficePreviewUrl(req.FileId, drive)
if err != nil {
c.JSON(200, MetaResponse(500, err.Error()))
return
}
c.JSON(200, DataResponse(preview))
}

View File

@ -0,0 +1,70 @@
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.(第一次请先点击网页底部rebuild)"))
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" {
if file.Password == "" {
file.Password = "n"
} else {
file.Password = "y"
}
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 {
if (*files)[i].Password == "" {
(*files)[i].Password = "n"
} else {
(*files)[i].Password = "y"
}
}
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,43 @@ package controllers
import (
"github.com/Xhofe/alist/conf"
"github.com/Xhofe/alist/server/models"
"github.com/gin-gonic/gin"
log "github.com/sirupsen/logrus"
)
// 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."))
return
}
c.JSON(200, MetaResponse(401,"wrong password."))
type RebuildReq struct {
Path string `json:"path" binding:"required"`
Password string `json:"password"`
Depth int `json:"depth"`
}
// rebuild tree
func RebuildTree(c *gin.Context) {
var req RebuildReq
if err := c.ShouldBindJSON(&req); err != nil {
c.JSON(200, MetaResponse(400, "Bad Request:"+err.Error()))
return
}
c.JSON(200, MetaResponse(400,"disabled cache."))
log.Debugf("rebuild:%+v", req)
password := req.Password
if password != conf.Conf.Server.Password {
if password == "" {
c.JSON(200, MetaResponse(401, "need password."))
return
}
c.JSON(200, MetaResponse(401, "wrong password."))
return
}
if err := models.BuildTreeWithPath(req.Path, req.Depth); err != nil {
c.JSON(200, MetaResponse(500, err.Error()))
return
}
c.JSON(200, MetaResponse(200, "success."))
return
}
}

View File

@ -0,0 +1,33 @@
package controllers
import (
"github.com/Xhofe/alist/alidrive"
"github.com/Xhofe/alist/utils"
"github.com/gin-gonic/gin"
log "github.com/sirupsen/logrus"
)
type VideoPreviewReq struct {
FileId string `json:"file_id" binding:"required"`
}
// handle video_preview request
func VideoPreview(c *gin.Context) {
drive := utils.GetDriveByName(c.Param("drive"))
if drive == nil {
c.JSON(200, MetaResponse(400, "drive isn't exist."))
return
}
var req VideoPreviewReq
if err := c.ShouldBindJSON(&req); err != nil {
c.JSON(200, MetaResponse(400, "Bad Request:"+err.Error()))
return
}
log.Debugf("preview_req:%+v", req)
preview, err := alidrive.GetVideoPreviewUrl(req.FileId, drive)
if err != nil {
c.JSON(200, MetaResponse(500, err.Error()))
return
}
c.JSON(200, DataResponse(preview))
}

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

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

@ -0,0 +1,180 @@
package models
import (
"fmt"
"github.com/Xhofe/alist/alidrive"
"github.com/Xhofe/alist/conf"
"github.com/Xhofe/alist/utils"
log "github.com/sirupsen/logrus"
"gorm.io/gorm"
"path/filepath"
"strings"
)
func BuildTreeAll(depth int) {
for i, _ := range conf.Conf.AliDrive.Drives {
if err := BuildTree(&conf.Conf.AliDrive.Drives[i], depth); err != nil {
log.Errorf("盘[%s]构建目录树失败:%s", conf.Conf.AliDrive.Drives[i].Name, err.Error())
} else {
log.Infof("盘[%s]构建目录树成功", conf.Conf.AliDrive.Drives[i].Name)
}
}
}
// build tree
func BuildTree(drive *conf.Drive, depth int) 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: drive.RootFolder,
Name: drive.Name,
Type: "folder",
Password: drive.Password,
}
if err := tx.Create(&rootFile).Error; err != nil {
tx.Rollback()
return err
}
if err := BuildOne(drive.RootFolder, drive.Name+"/", tx, drive.Password, drive, depth); err != nil {
tx.Rollback()
return err
}
return tx.Commit().Error
}
/*
递归构建目录树,插入指定目录下的所有文件
parent 父目录的file_id
path 指定的目录
parentPassword 父目录所携带的密码
drive 要构建的盘
*/
func BuildOne(parent string, path string, tx *gorm.DB, parentPassword string, drive *conf.Drive, depth int) error {
if depth == 0 {
return nil
}
marker := "first"
for marker != "" {
if marker == "first" {
marker = ""
}
files, err := alidrive.GetList(parent, conf.Conf.AliDrive.MaxFilesCount, marker, "", "", drive)
if err != nil {
return err
}
marker = files.NextMarker
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,
ContentHash: file.ContentHash,
}
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, drive, depth-1); err != nil {
return err
}
}
}
}
return nil
}
//重建指定路径与深度的目录树: 先删除该目录与该目录下所有文件的model再重新插入
func BuildTreeWithPath(path string, depth int) error {
dir, name := filepath.Split(path)
driveName := strings.Split(path, "/")[0]
drive := utils.GetDriveByName(driveName)
if drive == nil {
return fmt.Errorf("找不到drive[%s]", driveName)
}
file := &File{
Dir: "",
FileId: drive.RootFolder,
Name: drive.Name,
Type: "folder",
Password: drive.Password,
}
var err error
if dir != "" {
file, err = GetFileByDirAndName(dir, name)
if err != nil {
if file == nil {
return fmt.Errorf("path not found")
}
return err
}
}
tx := conf.DB.Begin()
defer func() {
if r := recover(); r != nil {
tx.Rollback()
}
}()
if err = tx.Error; err != nil {
tx.Rollback()
return err
}
if err = tx.Where("dir = ? AND name = ?", file.Dir, file.Name).Delete(file).Error; err != nil{
tx.Rollback()
return err
}
if err = tx.Where("dir like ?", fmt.Sprintf("%s%%", path)).Delete(&File{}).Error; err != nil{
tx.Rollback()
return err
}
//if dir != "" {
// aliFile, err := alidrive.GetFile(file.FileId, drive)
// if err != nil {
// tx.Rollback()
// return err
// }
// aliName := aliFile.Name
// if strings.HasSuffix(aliName, ".hide") {
// return nil
// }
// if strings.Contains(aliName, ".password-") {
// index := strings.Index(name, ".password-")
// file.Name = aliName[:index]
// file.Password = aliName[index+10:]
// }
//}
if err = tx.Create(&file).Error; err != nil {
return err
}
if err = BuildOne(file.FileId, path+"/", tx, file.Password, drive, depth); err != nil {
tx.Rollback()
return err
}
return tx.Commit().Error
}

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

@ -0,0 +1,69 @@
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:"-"`
ContentHash string `json:"content_hash"`
}
func (file *File) Create() error {
return conf.DB.Create(file).Error
}
func Clear(drive *conf.Drive) error {
if err := conf.DB.Where("dir = '' AND name = ?", drive.Name).Delete(&File{}).Error; err != nil {
return err
}
return conf.DB.Where("dir like ?", fmt.Sprintf("%s%%", drive.Name)).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
}
func DeleteWithDir(dir string) error {
return conf.DB.Where("dir like ?", fmt.Sprintf("%s%%", dir)).Delete(&File{}).Error
}

View File

@ -8,24 +8,29 @@ 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)
apiV2.GET("/info", controllers.Info)
apiV2.POST("/get", controllers.Get)
apiV2.POST("/path", controllers.Path)
apiV2.POST("/office_preview/:drive", controllers.OfficePreview)
apiV2.POST("/video_preview/:drive", controllers.VideoPreview)
apiV2.POST("/local_search", controllers.LocalSearch)
apiV2.POST("/global_search", controllers.GlobalSearch)
apiV2.POST("/rebuild", controllers.RebuildTree)
}
engine.GET("/d/*file_id",controllers.Down)
engine.GET("/cache/:password",controllers.RefreshCache)
}
engine.GET("/d/*path", controllers.Down)
}

View File

@ -1,47 +0,0 @@
package test
import (
"fmt"
"github.com/Xhofe/alist/alidrive"
"github.com/Xhofe/alist/bootstrap"
"github.com/Xhofe/alist/conf"
"os"
"testing"
)
func setup() {
bootstrap.InitLog()
bootstrap.ReadConf("../conf.yml")
bootstrap.InitClient()
bootstrap.InitAliDrive()
}
func TestGetUserInfo(t *testing.T) {
user,err:= alidrive.GetUserInfo()
fmt.Println(err)
fmt.Println(user)
}
func TestGetRoot(t *testing.T) {
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,"")
fmt.Println(err)
fmt.Println(files)
}
func TestGet(t *testing.T) {
file,err:=alidrive.GetFile("5fb7c80e85e4f335cd344008be1b1b5349f74414")
fmt.Println(err)
fmt.Println(file)
}
func TestMain(m *testing.M) {
setup()
code:=m.Run()
os.Exit(code)
}

View File

@ -2,12 +2,31 @@ package test
import (
"fmt"
"github.com/Xhofe/alist/utils"
"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)
}
func TestMD5(t *testing.T) {
fmt.Printf("%s\n", utils.Get16MD5Encode("123456"))
}

View File

@ -2,7 +2,6 @@ package test
import (
"fmt"
"github.com/Xhofe/alist/alidrive"
"github.com/Xhofe/alist/conf"
"github.com/Xhofe/alist/utils"
"testing"
@ -13,6 +12,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)
}

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
}

22
utils/config.go Normal file
View File

@ -0,0 +1,22 @@
package utils
import "github.com/Xhofe/alist/conf"
func GetDriveByName(name string) *conf.Drive {
for i, drive := range conf.Conf.AliDrive.Drives{
if drive.Name == name {
return &conf.Conf.AliDrive.Drives[i]
}
}
return nil
}
func GetNames() []string {
res := make([]string, 0)
for _, drive := range conf.Conf.AliDrive.Drives{
if !drive.Hide {
res = append(res, drive.Name)
}
}
return res
}

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

18
utils/md5.go Normal file
View File

@ -0,0 +1,18 @@
package utils
import (
"crypto/md5"
"encoding/hex"
)
//返回一个32位md5加密后的字符串
func GetMD5Encode(data string) string {
h := md5.New()
h.Write([]byte(data))
return hex.EncodeToString(h.Sum(nil))
}
//返回一个16位md5加密后的字符串
func Get16MD5Encode(data string) string {
return GetMD5Encode(data)[8:24]
}