Compare commits
71 Commits
Author | SHA1 | Date | |
---|---|---|---|
f31fc9155a | |||
d3db012dd0 | |||
74b86ef5e5 | |||
6be90429ad | |||
a6bbff2199 | |||
3827d3ed67 | |||
e242867f41 | |||
e09a75a87c | |||
e0a80b1477 | |||
d693e27ec0 | |||
b20f0717fe | |||
427244d8d5 | |||
b613598c2b | |||
f0013320a6 | |||
974caf74d9 | |||
0bb02664c7 | |||
6c5a0cba6e | |||
7e21e12e11 | |||
11489d8856 | |||
6d824a4ee9 | |||
8d74d070d4 | |||
77aae6660e | |||
76081a81a6 | |||
8760ab283d | |||
61ab27398c | |||
2e64df7e3d | |||
9561f0c951 | |||
03f5a54764 | |||
9952c3e90b | |||
d94e319df3 | |||
b51b2deea1 | |||
7dda701f1e | |||
3b93445648 | |||
a353081126 | |||
a5b2f998ab | |||
4d0d892ce7 | |||
8e9ddcf81e | |||
5c6344cac0 | |||
7076efb6be | |||
6d19b49a8d | |||
4fa11879f2 | |||
abe9d9237a | |||
e4d206d59c | |||
8636014397 | |||
c0f50ffeff | |||
b677d6ad21 | |||
443067b80f | |||
3138e031f5 | |||
d137ef8759 | |||
389226662c | |||
9cb548d4f7 | |||
0e7083a713 | |||
46f09836f3 | |||
e146054679 | |||
3b2a729dc6 | |||
d18a752732 | |||
b9676182c9 | |||
434eb25408 | |||
858291876b | |||
dcebf5257f | |||
0cd4624a36 | |||
fcd9c59089 | |||
b394711859 | |||
495c3f25e9 | |||
d5e3527bfb | |||
ba7c33a2bb | |||
bf3f741b22 | |||
02e665ae37 | |||
bacbf7bc1b | |||
4af469efed | |||
52cddc431a |
82
.github/workflows/build.yml
vendored
Normal file
82
.github/workflows/build.yml
vendored
Normal file
@ -0,0 +1,82 @@
|
||||
name: build
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [ main ]
|
||||
pull_request:
|
||||
branches: [ main ]
|
||||
|
||||
jobs:
|
||||
|
||||
build:
|
||||
strategy:
|
||||
matrix:
|
||||
platform: [ubuntu-16.04]
|
||||
go-version: [1.15]
|
||||
name: Build
|
||||
runs-on: ${{ matrix.platform }}
|
||||
steps:
|
||||
|
||||
- name: Set up Go
|
||||
uses: actions/setup-go@v2
|
||||
with:
|
||||
go-version: ${{ matrix.go-version }}
|
||||
|
||||
- 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 alist_linux_amd64 alist.go
|
||||
CC=aarch64-linux-gnu-gcc CGO_ENABLED=1 GOOS=linux GOARCH=arm64 go build -o alist_linux_arm64 alist.go
|
||||
CC=arm-linux-gnueabihf-gcc CGO_ENABLED=1 GOOS=linux GOARCH=arm go build -o alist_linux_arm alist.go
|
||||
|
||||
- name: Build windows
|
||||
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:
|
||||
name: alist_linux_amd64
|
||||
path: alist_linux_amd64
|
||||
|
||||
- name: Upload artifacts linux_arm64
|
||||
uses: actions/upload-artifact@v2
|
||||
with:
|
||||
name: alist_linux_arm64
|
||||
path: alist_linux_arm64
|
||||
|
||||
- name: Upload artifacts linux_arm
|
||||
uses: actions/upload-artifact@v2
|
||||
with:
|
||||
name: alist_linux_arm
|
||||
path: alist_linux_arm
|
||||
|
||||
- name: Upload artifacts windows_amd64
|
||||
uses: actions/upload-artifact@v2
|
||||
with:
|
||||
name: alist_windows_amd64
|
||||
path: alist_windows_amd64.exe
|
||||
|
||||
- name: Upload artifacts linux_386
|
||||
uses: actions/upload-artifact@v2
|
||||
with:
|
||||
name: alist_linux_386
|
||||
path: alist_linux_386
|
140
.github/workflows/release.yml
vendored
140
.github/workflows/release.yml
vendored
@ -1,28 +1,134 @@
|
||||
name: Release
|
||||
name: release
|
||||
on:
|
||||
push:
|
||||
tags:
|
||||
- '*'
|
||||
|
||||
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
|
27
README.md
27
README.md
@ -1,15 +1,16 @@
|
||||
<p align="center">
|
||||
<img src="https://img.oez.cc/2020/12/24/1fb16bc25a4f6.png" alt="RenewalManage Logo" width=200/>
|
||||
<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%3ARelease"><img src="https://github.com/Xhofe/alist/workflows/Release/badge.svg" alt="Release status"></a>
|
||||
<a href="https://github.com/Xhofe/RenewalManage/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>
|
||||
|
||||
---
|
||||
|
||||
### 这是什么?
|
||||
@ -22,7 +23,9 @@
|
||||
|
||||
### 演示地址
|
||||
|
||||
- https://alist.nn.ci
|
||||
- https://alist.nn.ci (稳定版本)
|
||||
- https://alist.now.sh (开发版本)
|
||||
- https://alist-plyr.now.sh (plyr分支版本)
|
||||
|
||||
### 预览
|
||||
|
||||
@ -35,26 +38,26 @@
|
||||
- 目录加密
|
||||
- `Readme`渲染
|
||||
- 自定义根目录
|
||||
- 文件直链下载
|
||||
- …
|
||||
|
||||
#### TODO
|
||||
|
||||
- [x] 排序
|
||||
- [ ] 文件预览
|
||||
- [x] 文件预览
|
||||
- [x] 图片
|
||||
- [x] 视频
|
||||
- [x] 音频
|
||||
- [ ] 文档
|
||||
- [x] `Readme`渲染
|
||||
- [x] 密码加密
|
||||
- [ ] 搜索与翻页
|
||||
- [ ] 文件直链
|
||||
- [x] 文件直链
|
||||
- [ ] 路径优化
|
||||
- [ ] 缓存
|
||||
- [x] 缓存
|
||||
|
||||
### 如何使用
|
||||
|
||||
正在写……
|
||||
- https://www.nn.ci/archives/alist.html
|
||||
|
||||
### License
|
||||
|
||||
|
@ -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 ""
|
||||
}
|
||||
|
@ -1,5 +0,0 @@
|
||||
package alidrive
|
||||
|
||||
var (
|
||||
User *UserInfo
|
||||
)
|
80
alidrive/post_json.go
Normal file
80
alidrive/post_json.go
Normal 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
|
||||
}
|
@ -1,5 +1,6 @@
|
||||
package alidrive
|
||||
|
||||
// ListReq 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"`
|
||||
}
|
||||
|
||||
// GetReq get request bean
|
||||
type GetReq struct {
|
||||
DriveId string `json:"drive_id"`
|
||||
FileId string `json:"file_id"`
|
||||
@ -20,27 +22,54 @@ type GetReq struct {
|
||||
VideoThumbnailProcess string `json:"video_thumbnail_process"`
|
||||
}
|
||||
|
||||
// DownloadReq 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"`
|
||||
}
|
||||
|
||||
// SearchReq 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"
|
||||
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"`
|
||||
}
|
||||
|
||||
// TokenLoginReq token_login request bean
|
||||
type TokenLoginReq struct {
|
||||
Token string `json:"token"`
|
||||
}
|
||||
|
||||
// GetTokenReq get_token request bean
|
||||
type GetTokenReq struct {
|
||||
Code string `json:"code"`
|
||||
}
|
||||
|
||||
// RefreshTokenReq refresh_token request bean
|
||||
type RefreshTokenReq struct {
|
||||
RefreshToken string `json:"refresh_token"`
|
||||
GrantType string `json:"grant_type"`
|
||||
}
|
||||
|
||||
// OfficePreviewUrlReq office_preview_url request bean
|
||||
type OfficePreviewUrlReq struct {
|
||||
AccessToken string `json:"access_token"`
|
||||
DriveId string `json:"drive_id"`
|
||||
FileId string `json:"file_id"`
|
||||
}
|
||||
|
||||
// VideoPreviewUrlReq video preview url request bean
|
||||
type VideoPreviewUrlReq struct {
|
||||
DriveId string `json:"drive_id"`
|
||||
FileId string `json:"file_id"`
|
||||
ExpireSec int `json:"expire_sec"`
|
||||
}
|
@ -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,109 +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返回内容失败")
|
||||
}
|
||||
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
|
||||
// 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: file.Name,
|
||||
FileId: file.FileId,
|
||||
})
|
||||
fileId=file.ParentFileId
|
||||
var resp VideoPreviewUrlResp
|
||||
if err := BodyToJson(url, req, &resp, drive); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
paths=append(paths, Path{
|
||||
Name: "Root",
|
||||
FileId: "root",
|
||||
})
|
||||
return &paths,nil
|
||||
return &resp, nil
|
||||
}
|
@ -1,25 +1,47 @@
|
||||
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"`
|
||||
UserId string `json:"user_id"`
|
||||
Avatar string `json:"avatar"`
|
||||
CreatedAt int `json:"created_at"`
|
||||
UpdatedAt int `json:"updated_at"`
|
||||
CreatedAt int64 `json:"created_at"`
|
||||
UpdatedAt int64 `json:"updated_at"`
|
||||
Email string `json:"email"`
|
||||
NickName string `json:"nick_name"`
|
||||
Phone string `json:"phone"`
|
||||
@ -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"`
|
||||
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"`
|
||||
@ -66,8 +99,8 @@ type File struct {
|
||||
ContentType string `json:"content_type"`
|
||||
Crc64Hash string `json:"crc_64_hash"`
|
||||
DownloadUrl string `json:"download_url"`
|
||||
PunishFlag int `json:"punish_flag"`
|
||||
Size int `json:"size"`
|
||||
PunishFlag int64 `json:"punish_flag"`
|
||||
Size int64 `json:"size"`
|
||||
Thumbnail string `json:"thumbnail"`
|
||||
Url string `json:"url"`
|
||||
ImageMediaMetadata map[string]interface{} `json:"image_media_metadata"`
|
||||
@ -75,15 +108,25 @@ type File struct {
|
||||
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,32 +147,18 @@ type TokenResp struct {
|
||||
DeviceId string `json:"device_id"`
|
||||
}
|
||||
|
||||
func HasPassword(files *Files) string {
|
||||
fileList := files.Items
|
||||
for _, file := range fileList {
|
||||
if strings.HasPrefix(file.Name, ".password-") {
|
||||
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
41
alidrive/utils.go
Normal 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 ""
|
||||
}
|
1
alist.go
1
alist.go
@ -2,6 +2,7 @@ package main
|
||||
|
||||
import "github.com/Xhofe/alist/bootstrap"
|
||||
|
||||
// main function
|
||||
func main() {
|
||||
bootstrap.Run()
|
||||
}
|
@ -6,29 +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
|
||||
res := alidrive.RefreshTokenAll()
|
||||
if res != "" {
|
||||
log.Errorf("盘[%s]refresh_token失效,请检查", res)
|
||||
}
|
||||
//然后get_token
|
||||
token,err:=alidrive.GetToken(tokenLogin)
|
||||
if err!=nil {
|
||||
return false
|
||||
log.Debugf("config:%+v", conf.Conf)
|
||||
for i, _ := range conf.Conf.AliDrive.Drives {
|
||||
InitDriveId(&conf.Conf.AliDrive.Drives[i])
|
||||
}
|
||||
conf.Authorization=token.TokenType+" "+token.AccessToken
|
||||
}
|
||||
conf.Authorization=conf.Bearer+conf.Conf.AliDrive.AccessToken
|
||||
log.Infof("token:%s",conf.Authorization)
|
||||
user,err:=alidrive.GetUserInfo()
|
||||
if err != nil {
|
||||
log.Errorf("初始化用户失败:%s",err.Error())
|
||||
return false
|
||||
}
|
||||
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
|
||||
}
|
||||
|
@ -1,10 +1,17 @@
|
||||
package bootstrap
|
||||
|
||||
import (
|
||||
"crypto/tls"
|
||||
"github.com/Xhofe/alist/conf"
|
||||
log "github.com/sirupsen/logrus"
|
||||
"net/http"
|
||||
)
|
||||
|
||||
// init request client
|
||||
func InitClient() {
|
||||
conf.Client=&http.Client{}
|
||||
log.Infof("初始化client...")
|
||||
tr := &http.Transport{
|
||||
TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
|
||||
}
|
||||
conf.Client = &http.Client{Transport: tr}
|
||||
}
|
@ -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,20 +11,28 @@ 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")
|
||||
}
|
||||
|
||||
// bootstrap run
|
||||
func Run() {
|
||||
flag.Parse()
|
||||
if conf.Help {
|
||||
flag.Usage()
|
||||
return
|
||||
}
|
||||
if conf.Version {
|
||||
fmt.Println("Current version:" + conf.VERSION)
|
||||
return
|
||||
}
|
||||
start()
|
||||
}
|
||||
|
||||
// print asc
|
||||
func printASC() {
|
||||
log.Info(`
|
||||
________ ___ ___ ________ _________
|
||||
@ -36,29 +46,38 @@ func printASC() {
|
||||
`)
|
||||
}
|
||||
|
||||
// start server
|
||||
func start() {
|
||||
InitLog()
|
||||
printASC()
|
||||
InitClient()
|
||||
if !ReadConf(conf.Con) {
|
||||
if !conf.SkipUpdate {
|
||||
CheckUpdate()
|
||||
}
|
||||
if !ReadConf(conf.ConfigFile) {
|
||||
log.Errorf("读取配置文件时出现错误,启动失败.")
|
||||
return
|
||||
}
|
||||
InitClient()
|
||||
if !InitAliDrive() {
|
||||
log.Errorf("初始化阿里云盘出现错误,启动失败.")
|
||||
return
|
||||
}
|
||||
if !InitModel() {
|
||||
log.Errorf("初始化数据库出现错误,启动失败.")
|
||||
return
|
||||
}
|
||||
InitCron()
|
||||
server()
|
||||
}
|
||||
|
||||
// start http server
|
||||
func server() {
|
||||
baseServer:="0.0.0.0:"+conf.Conf.Server.Port
|
||||
log.Infof("Starting server @ %s",baseServer)
|
||||
r:=gin.Default()
|
||||
baseServer := conf.Conf.Server.Address + ":" + conf.Conf.Server.Port
|
||||
r := gin.Default()
|
||||
serv.InitRouter(r)
|
||||
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())
|
||||
}
|
||||
}
|
@ -6,23 +6,79 @@ import (
|
||||
log "github.com/sirupsen/logrus"
|
||||
"gopkg.in/yaml.v2"
|
||||
"io/ioutil"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// read config file
|
||||
func ReadConf(config string) bool {
|
||||
log.Infof("读取配置文件...")
|
||||
if !utils.Exists(config) {
|
||||
log.Infof("找不到配置文件:%s",config)
|
||||
log.Infof("找不到配置文件:%s", config)
|
||||
if !Write(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.Conf.Info.Roots = utils.GetNames()
|
||||
conf.Origins = strings.Split(conf.Conf.Server.SiteUrl, ",")
|
||||
return true
|
||||
}
|
||||
func Write(path string) bool {
|
||||
log.Infof("创建默认配置文件")
|
||||
file, err := utils.CreatNestedFile(path)
|
||||
if err != nil {
|
||||
log.Errorf("无法创建配置文件, %s", err)
|
||||
return false
|
||||
}
|
||||
defer func() {
|
||||
_ = file.Close()
|
||||
}()
|
||||
str := `
|
||||
info:
|
||||
title: AList #标题
|
||||
logo: "" #网站logo 如果填写,则会替换掉默认的
|
||||
footer_text: Xhofe's Blog #网页底部文字
|
||||
footer_url: https://www.nn.ci #网页底部文字链接
|
||||
music_img: https://img.xhofe.top/2020/12/19/0f8b57866bdb5.gif #预览音乐文件时的图片
|
||||
check_update: true #前端是否显示更新
|
||||
script: #自定义脚本,可以是脚本的链接,也可以直接是脚本内容
|
||||
autoplay: true #视频是否自动播放
|
||||
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:
|
||||
address: "0.0.0.0"
|
||||
port: "5244"
|
||||
search: true
|
||||
static: dist
|
||||
site_url: '*'
|
||||
password: password #用于重建目录
|
||||
ali_drive:
|
||||
api_url: https://api.aliyundrive.com/v2
|
||||
max_files_count: 100
|
||||
drives:
|
||||
- refresh_token: xxx #refresh_token
|
||||
root_folder: root #根目录的file_id
|
||||
name: drive0 #盘名,多个盘不可重复,这里只是示例,不是一定要叫这个名字,可随意修改
|
||||
password: pass #该盘密码,空('')则不设密码,修改需要重建生效
|
||||
hide: false #是否在主页隐藏该盘,不可全部隐藏,至少暴露一个
|
||||
database:
|
||||
type: sqlite3
|
||||
dBFile: alist.db
|
||||
`
|
||||
_, err = file.WriteString(str)
|
||||
if err != nil {
|
||||
log.Errorf("无法写入配置文件, %s", err)
|
||||
return false
|
||||
}
|
||||
log.Debugf("config:%v",conf.Conf)
|
||||
return true
|
||||
}
|
@ -8,16 +8,18 @@ import (
|
||||
|
||||
var Cron *cron.Cron
|
||||
|
||||
// refresh token func for cron
|
||||
func refreshToken() {
|
||||
alidrive.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()
|
||||
}
|
@ -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
74
bootstrap/model.go
Normal 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
|
||||
}
|
||||
}
|
47
bootstrap/update.go
Normal file
47
bootstrap/update.go
Normal file
@ -0,0 +1,47 @@
|
||||
package bootstrap
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"github.com/Xhofe/alist/conf"
|
||||
"github.com/Xhofe/alist/utils"
|
||||
log "github.com/sirupsen/logrus"
|
||||
"io/ioutil"
|
||||
"net/http"
|
||||
)
|
||||
|
||||
// github release response bean
|
||||
type GithubRelease struct {
|
||||
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())
|
||||
return
|
||||
}
|
||||
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())
|
||||
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)
|
||||
}
|
||||
}
|
@ -1,15 +1,35 @@
|
||||
info:
|
||||
title: AList
|
||||
site_url: http://localhost
|
||||
logo:
|
||||
title: AList #标题
|
||||
logo: "" #网站logo 如果填写,则会替换掉默认的
|
||||
footer_text: Xhofe's Blog #网页底部文字
|
||||
footer_url: https://www.nn.ci #网页底部文字链接
|
||||
music_img: https://img.oez.cc/2020/12/19/0f8b57866bdb5.gif #预览音乐文件时的图片
|
||||
check_update: true #前端是否显示更新
|
||||
script: #自定义脚本,可以是脚本的链接,也可以直接是脚本内容,如document.querySelector('body').style="background-image:url('https://api.mtyqx.cn/api/random.php');background-attachment:fixed"
|
||||
autoplay: true #视频是否自动播放
|
||||
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:
|
||||
address: "0.0.0.0"
|
||||
port: "5244"
|
||||
search: true
|
||||
static: dist
|
||||
site_url: '*'
|
||||
password: password #用于重建目录
|
||||
ali_drive:
|
||||
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
|
||||
token:
|
||||
access_token:
|
||||
refresh_token: need
|
||||
max_files_count: 3000
|
||||
name: drive1
|
||||
password: pass
|
||||
hide: false
|
||||
database:
|
||||
type: sqlite3
|
||||
dBFile: alist.db
|
||||
|
@ -1,23 +1,56 @@
|
||||
package conf
|
||||
|
||||
type Config struct {
|
||||
Info struct{
|
||||
Title string `yaml:"title" json:"title"`
|
||||
SiteUrl string `yaml:"site_url" json:"site_url"`//网站url
|
||||
Logo string `yaml:"logo" json:"logo"`
|
||||
} `yaml:"info"`
|
||||
Server struct{
|
||||
Port string `yaml:"port"`//端口
|
||||
Search bool `yaml:"search" json:"search"`//允许搜索
|
||||
Static string `yaml:"static"`
|
||||
} `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"`
|
||||
type Drive struct {
|
||||
AccessToken string `yaml:"-"`
|
||||
RefreshToken string `yaml:"refresh_token"`
|
||||
MaxFilesCount int `yaml:"max_files_count"`
|
||||
} `yaml:"ali_drive"`
|
||||
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"`
|
||||
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"`
|
||||
}
|
@ -1,32 +1,39 @@
|
||||
package conf
|
||||
|
||||
import (
|
||||
"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
|
||||
|
||||
Client *http.Client // request client
|
||||
|
||||
DB *gorm.DB
|
||||
|
||||
Origins []string // allow origins
|
||||
)
|
||||
|
||||
var Conf = new(Config)
|
||||
|
||||
const (
|
||||
VERSION="0.1.0"
|
||||
VERSION = "v1.0.5"
|
||||
|
||||
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
4
go.mod
@ -9,6 +9,7 @@ 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/robfig/cron/v3 v3.0.0
|
||||
@ -18,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
|
||||
)
|
||||
|
27
go.sum
27
go.sum
@ -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,6 +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/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=
|
||||
@ -76,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=
|
||||
@ -121,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=
|
||||
@ -141,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=
|
||||
@ -149,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=
|
||||
|
@ -1,22 +0,0 @@
|
||||
package server
|
||||
|
||||
import "github.com/gin-gonic/gin"
|
||||
|
||||
func metaResponse(code int, msg string) gin.H {
|
||||
return gin.H{
|
||||
"meta":gin.H{
|
||||
"code":code,
|
||||
"msg":msg,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
func dataResponse(data interface{}) gin.H {
|
||||
return gin.H{
|
||||
"meta":gin.H{
|
||||
"code":200,
|
||||
"msg":"success",
|
||||
},
|
||||
"data":data,
|
||||
}
|
||||
}
|
@ -1,104 +0,0 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"github.com/Xhofe/alist/alidrive"
|
||||
"github.com/Xhofe/alist/conf"
|
||||
"github.com/gin-gonic/gin"
|
||||
log "github.com/sirupsen/logrus"
|
||||
)
|
||||
|
||||
func Info(c *gin.Context) {
|
||||
c.JSON(200,dataResponse(conf.Conf.Info))
|
||||
}
|
||||
|
||||
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)
|
||||
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
|
||||
c.JSON(200,dataResponse(file))
|
||||
}
|
||||
|
||||
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)
|
||||
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)
|
||||
c.JSON(200,dataResponse(files))
|
||||
}
|
||||
|
||||
func Search(c *gin.Context) {
|
||||
if !conf.Conf.Server.Search {
|
||||
c.JSON(200,metaResponse(403,"Not allow search."))
|
||||
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)
|
||||
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()))
|
||||
return
|
||||
}
|
||||
c.JSON(200,dataResponse(files))
|
||||
}
|
25
server/controllers/common.go
Normal file
25
server/controllers/common.go
Normal file
@ -0,0 +1,25 @@
|
||||
package controllers
|
||||
|
||||
type Response struct {
|
||||
Code int `json:"code"`
|
||||
Data interface{} `json:"data"`
|
||||
Message string `json:"message"`
|
||||
}
|
||||
|
||||
// MetaResponse common meta response
|
||||
func MetaResponse(code int, msg string) Response {
|
||||
return Response{
|
||||
Code: code,
|
||||
Data: nil,
|
||||
Message: msg,
|
||||
}
|
||||
}
|
||||
|
||||
// DataResponse common data response
|
||||
func DataResponse(data interface{}) Response {
|
||||
return Response{
|
||||
Code: 200,
|
||||
Data: data,
|
||||
Message: "ok",
|
||||
}
|
||||
}
|
60
server/controllers/down.go
Normal file
60
server/controllers/down.go
Normal 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
|
||||
}
|
56
server/controllers/get.go
Normal file
56
server/controllers/get.go
Normal file
@ -0,0 +1,56 @@
|
||||
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"
|
||||
)
|
||||
|
||||
// get request bean
|
||||
type GetReq struct {
|
||||
Path string `json:"path" binding:"required"`
|
||||
Password string `json:"password"`
|
||||
}
|
||||
|
||||
// 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
|
||||
}
|
||||
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))
|
||||
}
|
34
server/controllers/offie_preview.go
Normal file
34
server/controllers/offie_preview.go
Normal 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))
|
||||
}
|
||||
|
70
server/controllers/path.go
Normal file
70
server/controllers/path.go
Normal 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))
|
||||
}
|
35
server/controllers/search.go
Normal file
35
server/controllers/search.go
Normal file
@ -0,0 +1,35 @@
|
||||
package controllers
|
||||
|
||||
import (
|
||||
"github.com/Xhofe/alist/server/models"
|
||||
"github.com/gin-gonic/gin"
|
||||
log "github.com/sirupsen/logrus"
|
||||
)
|
||||
|
||||
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
|
||||
}
|
||||
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
|
||||
}
|
||||
c.JSON(200, MetaResponse(500, err.Error()))
|
||||
return
|
||||
}
|
||||
c.JSON(200, DataResponse(files))
|
||||
}
|
||||
|
||||
func GlobalSearch(c *gin.Context) {
|
||||
|
||||
}
|
44
server/controllers/utils.go
Normal file
44
server/controllers/utils.go
Normal file
@ -0,0 +1,44 @@
|
||||
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))
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
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
|
||||
}
|
33
server/controllers/video_preview.go
Normal file
33
server/controllers/video_preview.go
Normal 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))
|
||||
}
|
@ -2,26 +2,35 @@ package server
|
||||
|
||||
import (
|
||||
"github.com/Xhofe/alist/conf"
|
||||
"github.com/Xhofe/alist/server/controllers"
|
||||
"github.com/Xhofe/alist/utils"
|
||||
"github.com/gin-gonic/gin"
|
||||
"net/http"
|
||||
)
|
||||
|
||||
func CrosHandler() gin.HandlerFunc {
|
||||
// handle cors request
|
||||
func CorsHandler() gin.HandlerFunc {
|
||||
return func(context *gin.Context) {
|
||||
method := context.Request.Method
|
||||
context.Writer.Header().Set("Access-Control-Allow-Origin", "*")
|
||||
context.Header("Access-Control-Allow-Origin", conf.Conf.Info.SiteUrl) // 设置允许访问所有域
|
||||
context.Header("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE,UPDATE")
|
||||
context.Header("Access-Control-Allow-Headers", "Authorization, Content-Length, X-CSRF-Token, Token,session,X_Requested_With,Accept, Origin, Host, Connection, Accept-Encoding, Accept-Language,DNT, X-CustomHeader, Keep-Alive, User-Agent, X-Requested-With, If-Modified-Since, Cache-Control, Content-Type, Pragma,token,openid,opentoken")
|
||||
context.Header("Access-Control-Expose-Headers", "Content-Length, Access-Control-Allow-Origin, Access-Control-Allow-Headers,Cache-Control,Content-Language,Content-Type,Expires,Last-Modified,Pragma,FooBar")
|
||||
context.Header("Access-Control-Max-Age", "172800")
|
||||
context.Header("Access-Control-Allow-Credentials", "true")
|
||||
//context.Set("content-type", "application/json") //设置返回格式是json
|
||||
|
||||
if method == "OPTIONS" {
|
||||
context.JSON(http.StatusOK, metaResponse(200,"Options Request!"))
|
||||
origin := context.GetHeader("Origin")
|
||||
// 同源
|
||||
if origin == "" {
|
||||
context.Next()
|
||||
return
|
||||
}
|
||||
method := context.Request.Method
|
||||
// 设置跨域
|
||||
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."))
|
||||
context.Abort()
|
||||
}
|
||||
if method == "OPTIONS" {
|
||||
context.AbortWithStatus(204)
|
||||
}
|
||||
|
||||
//处理请求
|
||||
context.Next()
|
||||
}
|
||||
|
205
server/models/create.go
Normal file
205
server/models/create.go
Normal file
@ -0,0 +1,205 @@
|
||||
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
|
||||
password := parentPassword
|
||||
if strings.HasSuffix(name, ".hide") {
|
||||
continue
|
||||
}
|
||||
if strings.Contains(name, ".ln-") {
|
||||
index := strings.Index(name, ".ln-")
|
||||
name = file.Name[:index]
|
||||
fileId := file.Name[index+4:]
|
||||
newFile := File{
|
||||
Dir: path,
|
||||
FileExtension: "",
|
||||
FileId: fileId,
|
||||
Name: name,
|
||||
Type: "folder",
|
||||
UpdatedAt: file.UpdatedAt,
|
||||
Category: "",
|
||||
ContentType: "",
|
||||
Size: 0,
|
||||
Password: password,
|
||||
}
|
||||
log.Debugf("插入file:%+v", newFile)
|
||||
if err = tx.Create(&newFile).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
if err = BuildOne(fileId, fmt.Sprintf("%s%s/", path, name), tx, password, drive, depth-1); err != nil {
|
||||
return err
|
||||
}
|
||||
continue
|
||||
}
|
||||
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
69
server/models/file.go
Normal 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
|
||||
}
|
@ -1,8 +0,0 @@
|
||||
package server
|
||||
|
||||
import "github.com/Xhofe/alist/alidrive"
|
||||
|
||||
type ListReq struct {
|
||||
Password string `json:"password"`
|
||||
alidrive.ListReq
|
||||
}
|
@ -2,25 +2,35 @@ package server
|
||||
|
||||
import (
|
||||
"github.com/Xhofe/alist/conf"
|
||||
"github.com/Xhofe/alist/server/controllers"
|
||||
"github.com/gin-contrib/static"
|
||||
"github.com/gin-gonic/gin"
|
||||
log "github.com/sirupsen/logrus"
|
||||
)
|
||||
|
||||
// init router
|
||||
func InitRouter(engine *gin.Engine) {
|
||||
engine.Use(CrosHandler())
|
||||
log.Infof("初始化路由...")
|
||||
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",Info)
|
||||
v2.POST("/get",Get)
|
||||
v2.POST("/list",List)
|
||||
v2.POST("/search",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/*path", controllers.Down)
|
||||
}
|
@ -1,40 +0,0 @@
|
||||
package test
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"github.com/Xhofe/alist/alidrive"
|
||||
"github.com/Xhofe/alist/bootstrap"
|
||||
"github.com/Xhofe/alist/conf"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func init() {
|
||||
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)
|
||||
}
|
32
test/string_test.go
Normal file
32
test/string_test.go
Normal file
@ -0,0 +1,32 @@
|
||||
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, "/")
|
||||
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"))
|
||||
}
|
@ -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)
|
||||
}
|
@ -3,14 +3,56 @@ package utils
|
||||
import (
|
||||
log "github.com/sirupsen/logrus"
|
||||
"net/url"
|
||||
"strconv"
|
||||
"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++ {
|
||||
if array[i] == val {
|
||||
index = i
|
||||
return
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// compare version
|
||||
func VersionCompare(version1, version2 string) int {
|
||||
a := strings.Split(version1, ".")
|
||||
b := strings.Split(version2, ".")
|
||||
flag := 1
|
||||
if len(a) > len(b) {
|
||||
a, b = b, a
|
||||
flag = -1
|
||||
}
|
||||
for i := range a {
|
||||
x, _ := strconv.Atoi(a[i])
|
||||
y, _ := strconv.Atoi(b[i])
|
||||
if x < y {
|
||||
return -1 * flag
|
||||
} else if x > y {
|
||||
return 1 * flag
|
||||
}
|
||||
}
|
||||
for _, v := range b[len(a):] {
|
||||
y, _ := strconv.Atoi(v)
|
||||
if y > 0 {
|
||||
return -1 * flag
|
||||
}
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
57
utils/common.go
Normal file
57
utils/common.go
Normal 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
22
utils/config.go
Normal 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
|
||||
}
|
@ -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
18
utils/md5.go
Normal 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]
|
||||
}
|
Reference in New Issue
Block a user