Compare commits

...

11 Commits

Author SHA1 Message Date
0cd4624a36 🆕 新版本 2021-01-05 16:51:31 +08:00
fcd9c59089 🔧 fix: #8 增加了多个文件预览 2021-01-05 16:40:02 +08:00
b394711859 自定义脚本 2020-12-31 17:08:54 +08:00
495c3f25e9 🆕 检查更新 2020-12-31 16:15:15 +08:00
d5e3527bfb 🍃 去除文件缓存 2020-12-31 15:03:25 +08:00
ba7c33a2bb 🐛 配置名 2020-12-29 13:54:08 +08:00
bf3f741b22 🐎 加入缓存 2020-12-29 13:37:58 +08:00
02e665ae37 多个自定义内容 2020-12-28 11:22:54 +08:00
bacbf7bc1b 文件301直链与password文件隐藏 2020-12-28 10:23:54 +08:00
4af469efed 🐛 时间超出int范围 2020-12-26 18:11:17 +08:00
52cddc431a 📝 添加教程 2020-12-25 19:12:27 +08:00
27 changed files with 456 additions and 154 deletions

71
.github/workflows/build.yml vendored Normal file
View File

@ -0,0 +1,71 @@
name: Build
on:
push:
branches: [ main ]
pull_request:
branches: [ main ]
jobs:
build:
strategy:
matrix:
platform: [ubuntu-latest]
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: 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

View File

@ -1,15 +1,16 @@
<p align="center"> <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>
<p align="center"> <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/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/alist/actions?query=workflow%3ABuild"><img src="https://github.com/Xhofe/alist/workflows/Build/badge.svg" alt="Build status"></a>
<a href="https://github.com/Xhofe/RenewalManage/releases"><img src="https://img.shields.io/github/downloads/Xhofe/alist/latest/total" alt="Downloads"></a> <a href="https://github.com/Xhofe/alist/releases"><img src="https://img.shields.io/github/downloads/Xhofe/alist/latest/total" alt="Downloads"></a>
<a href="https://github.com/Xhofe/alist/blob/main/LICENSE"><img src="https://img.shields.io/github/license/Xhofe/alist" alt="License"></a> <a href="https://github.com/Xhofe/alist/blob/main/LICENSE"><img src="https://img.shields.io/github/license/Xhofe/alist" alt="License"></a>
<a href="https://pay.xhofe.top"> <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" alt="donate">
</a> </a>
</p> </p>
--- ---
### 这是什么? ### 这是什么?
@ -35,26 +36,26 @@
- 目录加密 - 目录加密
- `Readme`渲染 - `Readme`渲染
- 自定义根目录 - 自定义根目录
- 文件直链下载
- -
#### TODO #### TODO
- [x] 排序 - [x] 排序
- [ ] 文件预览 - [x] 文件预览
- [x] 图片 - [x] 图片
- [x] 视频 - [x] 视频
- [x] 音频 - [x] 音频
- [ ] 文档
- [x] `Readme`渲染 - [x] `Readme`渲染
- [x] 密码加密 - [x] 密码加密
- [ ] 搜索与翻页 - [ ] 搜索与翻页
- [ ] 文件直链 - [x] 文件直链
- [ ] 路径优化 - [ ] 路径优化
- [ ] 缓存 - [x] 缓存
### 如何使用 ### 如何使用
正在写…… - https://www.nn.ci/archives/alist.html
### License ### License

View File

@ -12,7 +12,7 @@ func TokenLogin() (*TokenLoginResp, error) {
log.Infof("尝试使用token登录...") log.Infof("尝试使用token登录...")
url:="https://auth.aliyundrive.com/v2/oauth/token_login" url:="https://auth.aliyundrive.com/v2/oauth/token_login"
req:=TokenLoginReq{Token:conf.Conf.AliDrive.LoginToken} req:=TokenLoginReq{Token:conf.Conf.AliDrive.LoginToken}
log.Debugf("token_login_req:%v",req) log.Debugf("token_login_req:%+v",req)
var tokenLogin TokenLoginResp var tokenLogin TokenLoginResp
if body, err := DoPost(url, req,false); err != nil { if body, err := DoPost(url, req,false); err != nil {
log.Errorf("tokenLogin-doPost出错:%s",err.Error()) log.Errorf("tokenLogin-doPost出错:%s",err.Error())

View File

@ -146,7 +146,7 @@ func DoPost(url string,request interface{},auth bool) (body []byte, err error) {
log.Errorf("创建requestBody出错:%s",err.Error()) log.Errorf("创建requestBody出错:%s",err.Error())
} }
req,err:=http.NewRequest("POST",url,requestBody) req,err:=http.NewRequest("POST",url,requestBody)
log.Debugf("do_post_req:%v",req) log.Debugf("do_post_req:%+v",req)
if err != nil { if err != nil {
log.Errorf("创建request出错:%s",err.Error()) log.Errorf("创建request出错:%s",err.Error())
return return
@ -175,6 +175,7 @@ func DoPost(url string,request interface{},auth bool) (body []byte, err error) {
if body, err = ioutil.ReadAll(resp.Body); err != nil { if body, err = ioutil.ReadAll(resp.Body); err != nil {
log.Errorf("读取api返回内容失败") log.Errorf("读取api返回内容失败")
} }
log.Debugf("请求返回信息:%s",string(body))
return return
} }

View File

@ -18,8 +18,8 @@ type UserInfo struct {
DomainId string `json:"domain_id"` DomainId string `json:"domain_id"`
UserId string `json:"user_id"` UserId string `json:"user_id"`
Avatar string `json:"avatar"` Avatar string `json:"avatar"`
CreatedAt int `json:"created_at"` CreatedAt int64 `json:"created_at"`
UpdatedAt int `json:"updated_at"` UpdatedAt int64 `json:"updated_at"`
Email string `json:"email"` Email string `json:"email"`
NickName string `json:"nick_name"` NickName string `json:"nick_name"`
Phone string `json:"phone"` Phone string `json:"phone"`
@ -66,8 +66,8 @@ type File struct {
ContentType string `json:"content_type"` ContentType string `json:"content_type"`
Crc64Hash string `json:"crc_64_hash"` Crc64Hash string `json:"crc_64_hash"`
DownloadUrl string `json:"download_url"` DownloadUrl string `json:"download_url"`
PunishFlag int `json:"punish_flag"` PunishFlag int64 `json:"punish_flag"`
Size int `json:"size"` Size int64 `json:"size"`
Thumbnail string `json:"thumbnail"` Thumbnail string `json:"thumbnail"`
Url string `json:"url"` Url string `json:"url"`
ImageMediaMetadata map[string]interface{} `json:"image_media_metadata"` ImageMediaMetadata map[string]interface{} `json:"image_media_metadata"`
@ -106,8 +106,9 @@ type TokenResp struct {
func HasPassword(files *Files) string { func HasPassword(files *Files) string {
fileList := files.Items fileList := files.Items
for _, file := range fileList { for i, file := range fileList {
if strings.HasPrefix(file.Name, ".password-") { if strings.HasPrefix(file.Name, ".password-") {
files.Items=fileList[:i+copy(fileList[i:],fileList[i+1:])]
return file.Name[10:] return file.Name[10:]
} }
} }

View File

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

15
bootstrap/cache.go Normal file
View File

@ -0,0 +1,15 @@
package bootstrap
import (
"github.com/Xhofe/alist/conf"
"github.com/patrickmn/go-cache"
log "github.com/sirupsen/logrus"
"time"
)
func InitCache() {
if conf.Conf.Cache.Enable {
log.Infof("初始化缓存...")
conf.Cache=cache.New(time.Duration(conf.Conf.Cache.Expiration)*time.Minute,time.Duration(conf.Conf.Cache.CleanupInterval)*time.Minute)
}
}

View File

@ -2,9 +2,11 @@ package bootstrap
import ( import (
"github.com/Xhofe/alist/conf" "github.com/Xhofe/alist/conf"
log "github.com/sirupsen/logrus"
"net/http" "net/http"
) )
func InitClient() { func InitClient() {
log.Infof("初始化client...")
conf.Client=&http.Client{} conf.Client=&http.Client{}
} }

View File

@ -39,24 +39,26 @@ func printASC() {
func start() { func start() {
InitLog() InitLog()
printASC() printASC()
InitClient() CheckUpdate()
if !ReadConf(conf.Con) { if !ReadConf(conf.Con) {
log.Errorf("读取配置文件时出现错误,启动失败.") log.Errorf("读取配置文件时出现错误,启动失败.")
return return
} }
InitClient()
if !InitAliDrive() { if !InitAliDrive() {
log.Errorf("初始化阿里云盘出现错误,启动失败.") log.Errorf("初始化阿里云盘出现错误,启动失败.")
return return
} }
InitCache()
InitCron() InitCron()
server() server()
} }
func server() { func server() {
baseServer:="0.0.0.0:"+conf.Conf.Server.Port baseServer:="0.0.0.0:"+conf.Conf.Server.Port
log.Infof("Starting server @ %s",baseServer)
r:=gin.Default() r:=gin.Default()
serv.InitRouter(r) serv.InitRouter(r)
log.Infof("Starting server @ %s",baseServer)
err:=r.Run(baseServer) err:=r.Run(baseServer)
if err!=nil { if err!=nil {
log.Errorf("Server failed start:%s",err.Error()) log.Errorf("Server failed start:%s",err.Error())

View File

@ -9,6 +9,7 @@ import (
) )
func ReadConf(config string) bool { func ReadConf(config string) bool {
log.Infof("读取配置文件...")
if !utils.Exists(config) { if !utils.Exists(config) {
log.Infof("找不到配置文件:%s",config) log.Infof("找不到配置文件:%s",config)
return false return false
@ -23,6 +24,6 @@ func ReadConf(config string) bool {
log.Errorf("加载配置文件时发生错误:%s",err.Error()) log.Errorf("加载配置文件时发生错误:%s",err.Error())
return false return false
} }
log.Debugf("config:%v",conf.Conf) log.Debugf("config:%+v",conf.Conf)
return true return true
} }

41
bootstrap/update.go Normal file
View File

@ -0,0 +1,41 @@
package bootstrap
import (
"encoding/json"
"github.com/Xhofe/alist/conf"
log "github.com/sirupsen/logrus"
"io/ioutil"
"net/http"
)
type GithubRelease struct {
TagName string `json:"tag_name"`
HtmlUrl string `json:"html_url"`
Body string `json:"body"`
}
func CheckUpdate() {
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
}
if conf.VERSION == release.TagName {
log.Infof("当前已是最新版本:%s",release.TagName)
}else {
log.Infof("发现新版本:%s",release.TagName)
log.Infof("请至'%s'获取更新.",release.HtmlUrl)
}
}

View File

@ -1,15 +1,24 @@
info: info:
title: AList title: AList #标题
site_url: http://localhost site_url: http://localhost:5277 #前端地址
logo: backend_url: http://localhost:5244 #后端地址
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"
server: server:
port: "5244" port: "5244" #程序监听端口
search: true search: true #是否开启搜索接口,开启搜索之后密码和根目录都会失效,所以前端暂时不做搜索
static: dist static: dist #前端文件目录
cache:
enable: true #是否开启缓存
expiration: 60 #缓存失效时间(单位:分钟)
cleanup_interval: 120 #清理失效缓存间隔
refresh_password: password #手动清理缓存密码
ali_drive: ali_drive:
api_url: https://api.aliyundrive.com/v2 api_url: https://api.aliyundrive.com/v2 #阿里云盘api,无需修改
root_folder: root root_folder: root #根目录
token:
access_token:
refresh_token: need refresh_token: need
max_files_count: 3000 max_files_count: 3000

View File

@ -4,13 +4,33 @@ type Config struct {
Info struct{ Info struct{
Title string `yaml:"title" json:"title"` Title string `yaml:"title" json:"title"`
SiteUrl string `yaml:"site_url" json:"site_url"`//网站url SiteUrl string `yaml:"site_url" json:"site_url"`//网站url
BackendUrl string `yaml:"backend_url" json:"backend_url"`//后端地址
Logo string `yaml:"logo" json:"logo"` 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"` } `yaml:"info"`
Server struct{ Server struct{
Port string `yaml:"port"`//端口 Port string `yaml:"port"`//端口
Search bool `yaml:"search" json:"search"`//允许搜索 Search bool `yaml:"search" json:"search"`//允许搜索
Static string `yaml:"static"` Static string `yaml:"static"`
} `yaml:"server"` } `yaml:"server"`
Cache struct{
Enable bool `yaml:"enable"`
Expiration int `yaml:"expiration"`
CleanupInterval int `yaml:"cleanup_interval"`
RefreshPassword string `yaml:"refresh_password"`
}
AliDrive struct{ AliDrive struct{
ApiUrl string `yaml:"api_url"`//阿里云盘api ApiUrl string `yaml:"api_url"`//阿里云盘api
RootFolder string `yaml:"root_folder"`//根目录id RootFolder string `yaml:"root_folder"`//根目录id

View File

@ -1,6 +1,7 @@
package conf package conf
import ( import (
"github.com/patrickmn/go-cache"
"net/http" "net/http"
) )
@ -10,12 +11,14 @@ var(
Con string Con string
Client *http.Client Client *http.Client
Authorization string Authorization string
Cache *cache.Cache
) )
var Conf = new(Config) var Conf = new(Config)
const ( const (
VERSION="0.1.0" VERSION="v0.1.4"
ImageThumbnailProcess="image/resize,w_50" ImageThumbnailProcess="image/resize,w_50"
VideoThumbnailProcess="video/snapshot,t_0,f_jpg,w_50" VideoThumbnailProcess="video/snapshot,t_0,f_jpg,w_50"

1
go.mod
View File

@ -11,6 +11,7 @@ require (
github.com/leodido/go-urn v1.2.1 // indirect github.com/leodido/go-urn v1.2.1 // indirect
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect
github.com/modern-go/reflect2 v1.0.1 // indirect github.com/modern-go/reflect2 v1.0.1 // indirect
github.com/patrickmn/go-cache v2.1.0+incompatible
github.com/robfig/cron/v3 v3.0.0 github.com/robfig/cron/v3 v3.0.0
github.com/sirupsen/logrus v1.7.0 github.com/sirupsen/logrus v1.7.0
github.com/ugorji/go v1.2.2 // indirect github.com/ugorji/go v1.2.2 // indirect

3
go.sum
View File

@ -66,6 +66,9 @@ 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 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 h1:9f412s+6RmYXLWZSEzVVgPGK7C2PphHj5RJrvfx9AWI=
github.com/modern-go/reflect2 v1.0.1/go.mod h1:bx2lNnkwVCuqBIxFjflWJWanXIb3RllmbCylyMrvgv0= github.com/modern-go/reflect2 v1.0.1/go.mod h1:bx2lNnkwVCuqBIxFjflWJWanXIb3RllmbCylyMrvgv0=
github.com/patrickmn/go-cache v1.0.0 h1:3gD5McaYs9CxjyK5AXGcq8gdeCARtd/9gJDUvVeaZ0Y=
github.com/patrickmn/go-cache v2.1.0+incompatible h1:HRMgzkcYKYpi3C8ajMPV8OFXaaRUnok+kx1WdO15EQc=
github.com/patrickmn/go-cache v2.1.0+incompatible/go.mod h1:3Qf8kWWT7OJRJbdiICTKqZju1ZixQ/KpMGzzAfe6+WQ=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= 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/prometheus/client_model v0.0.0-20190812154241-14fe0d1b01d4/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA=
github.com/robfig/cron/v3 v3.0.0 h1:kQ6Cb7aHOHTSzNVNEhmp8EcWKLb4CbiMW9h9VyIhO4E= github.com/robfig/cron/v3 v3.0.0 h1:kQ6Cb7aHOHTSzNVNEhmp8EcWKLb4CbiMW9h9VyIhO4E=

View File

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

View File

@ -1,4 +1,4 @@
package server package controllers
import "github.com/gin-gonic/gin" import "github.com/gin-gonic/gin"
@ -19,4 +19,4 @@ func dataResponse(data interface{}) gin.H {
}, },
"data":data, "data":data,
} }
} }

69
server/controllers/get.go Normal file
View File

@ -0,0 +1,69 @@
package controllers
import (
"github.com/Xhofe/alist/alidrive"
"github.com/gin-gonic/gin"
log "github.com/sirupsen/logrus"
"strings"
)
// 因为下载地址有时效,所以去掉了文件请求和直链的缓存
func Get(c *gin.Context) {
var get alidrive.GetReq
if err := c.ShouldBindJSON(&get); err != nil {
c.JSON(200,metaResponse(400,"Bad Request"))
return
}
log.Debugf("get:%+v",get)
// cache
//cacheKey:=fmt.Sprintf("%s-%s","g",get.FileId)
//if conf.Conf.Cache.Enable {
// file,exist:=conf.Cache.Get(cacheKey)
// if exist {
// log.Debugf("使用了缓存:%s",cacheKey)
// c.JSON(200,dataResponse(file))
// return
// }
//}
file,err:=alidrive.GetFile(get.FileId)
if err !=nil {
c.JSON(200,metaResponse(500,err.Error()))
return
}
paths,err:=alidrive.GetPaths(get.FileId)
if err!=nil {
c.JSON(200,metaResponse(500,err.Error()))
return
}
file.Paths=*paths
//if conf.Conf.Cache.Enable {
// conf.Cache.Set(cacheKey,file,cache.DefaultExpiration)
//}
c.JSON(200,dataResponse(file))
}
func Down(c *gin.Context) {
fileIdParam:=c.Param("file_id")
log.Debugf("down:%s",fileIdParam)
fileId:=strings.Split(fileIdParam,"/")[1]
//cacheKey:=fmt.Sprintf("%s-%s","d",fileId)
//if conf.Conf.Cache.Enable {
// downloadUrl,exist:=conf.Cache.Get(cacheKey)
// if exist {
// log.Debugf("使用了缓存:%s",cacheKey)
// c.Redirect(301,downloadUrl.(string))
// return
// }
//}
file,err:=alidrive.GetFile(fileId)
if err != nil {
c.JSON(200, metaResponse(500,err.Error()))
return
}
//if conf.Conf.Cache.Enable {
// conf.Cache.Set(cacheKey,file.DownloadUrl,cache.DefaultExpiration)
//}
c.Redirect(301,file.DownloadUrl)
return
}

View File

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

View File

@ -0,0 +1,49 @@
package controllers
import (
"fmt"
"github.com/Xhofe/alist/alidrive"
"github.com/Xhofe/alist/conf"
"github.com/gin-gonic/gin"
"github.com/patrickmn/go-cache"
log "github.com/sirupsen/logrus"
)
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)
// cache
cacheKey:=fmt.Sprintf("%s-%s","s",search.Query)
if conf.Conf.Cache.Enable {
files,exist:=conf.Cache.Get(cacheKey)
if exist {
log.Debugf("使用了缓存:%s",cacheKey)
c.JSON(200, dataResponse(files))
return
}
}
if search.Limit == 0 {
search.Limit=50
}
// Search只支持0-100
//if conf.Conf.AliDrive.MaxFilesCount!=0 {
// search.Limit=conf.Conf.AliDrive.MaxFilesCount
//}
files,err:=alidrive.Search(search.Query,search.Limit,search.OrderBy)
if err != nil {
c.JSON(200, metaResponse(500,err.Error()))
return
}
if conf.Conf.Cache.Enable {
conf.Cache.Set(cacheKey,files,cache.DefaultExpiration)
}
c.JSON(200, dataResponse(files))
}

View File

@ -0,0 +1,25 @@
package controllers
import (
"github.com/Xhofe/alist/conf"
"github.com/gin-gonic/gin"
)
func Info(c *gin.Context) {
c.JSON(200, dataResponse(conf.Conf.Info))
}
func RefreshCache(c *gin.Context) {
password:=c.Param("password")
if conf.Conf.Cache.Enable {
if password == conf.Conf.Cache.RefreshPassword {
conf.Cache.Flush()
c.JSON(200,metaResponse(200,"flush success."))
return
}
c.JSON(200,metaResponse(401,"wrong password."))
return
}
c.JSON(200,metaResponse(400,"disabled cache."))
return
}

View File

@ -19,7 +19,7 @@ func CrosHandler() gin.HandlerFunc {
//context.Set("content-type", "application/json") //设置返回格式是json //context.Set("content-type", "application/json") //设置返回格式是json
if method == "OPTIONS" { if method == "OPTIONS" {
context.JSON(http.StatusOK, metaResponse(200,"Options Request!")) context.JSON(http.StatusOK, gin.H{})
} }
//处理请求 //处理请求

View File

@ -1,8 +0,0 @@
package server
import "github.com/Xhofe/alist/alidrive"
type ListReq struct {
Password string `json:"password"`
alidrive.ListReq
}

View File

@ -2,11 +2,14 @@ package server
import ( import (
"github.com/Xhofe/alist/conf" "github.com/Xhofe/alist/conf"
"github.com/Xhofe/alist/server/controllers"
"github.com/gin-contrib/static" "github.com/gin-contrib/static"
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"
log "github.com/sirupsen/logrus"
) )
func InitRouter(engine *gin.Engine) { func InitRouter(engine *gin.Engine) {
log.Infof("初始化路由...")
engine.Use(CrosHandler()) engine.Use(CrosHandler())
InitApiRouter(engine) InitApiRouter(engine)
} }
@ -18,9 +21,11 @@ func InitApiRouter(engine *gin.Engine) {
}) })
v2:=engine.Group("/api") v2:=engine.Group("/api")
{ {
v2.GET("/info",Info) v2.GET("/info",controllers.Info)
v2.POST("/get",Get) v2.POST("/get",controllers.Get)
v2.POST("/list",List) v2.POST("/list",controllers.List)
v2.POST("/search",Search) v2.POST("/search",controllers.Search)
} }
engine.GET("/d/*file_id",controllers.Down)
engine.GET("/cache/:password",controllers.RefreshCache)
} }

View File

@ -5,10 +5,11 @@ import (
"github.com/Xhofe/alist/alidrive" "github.com/Xhofe/alist/alidrive"
"github.com/Xhofe/alist/bootstrap" "github.com/Xhofe/alist/bootstrap"
"github.com/Xhofe/alist/conf" "github.com/Xhofe/alist/conf"
"os"
"testing" "testing"
) )
func init() { func setup() {
bootstrap.InitLog() bootstrap.InitLog()
bootstrap.ReadConf("../conf.yml") bootstrap.ReadConf("../conf.yml")
bootstrap.InitClient() bootstrap.InitClient()
@ -37,4 +38,10 @@ func TestGet(t *testing.T) {
file,err:=alidrive.GetFile("5fb7c80e85e4f335cd344008be1b1b5349f74414") file,err:=alidrive.GetFile("5fb7c80e85e4f335cd344008be1b1b5349f74414")
fmt.Println(err) fmt.Println(err)
fmt.Println(file) fmt.Println(file)
}
func TestMain(m *testing.M) {
setup()
code:=m.Run()
os.Exit(code)
} }

13
test/string_test.go Normal file
View File

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