🎇 支持mysql

This commit is contained in:
微凉
2021-03-16 23:15:37 +08:00
parent 4d0d892ce7
commit a5b2f998ab
15 changed files with 85 additions and 89 deletions

View File

@ -155,7 +155,7 @@ func DoPost(url string, request interface{}, auth string) (body []byte, err erro
return return
} }
if auth != "" { if auth != "" {
req.Header.Set("authorization", conf.Bearer + auth) req.Header.Set("authorization", conf.Bearer+auth)
} }
req.Header.Add("content-type", "application/json") 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("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")

View File

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

View File

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

View File

@ -12,7 +12,7 @@ var (
ConfigFile string // config file ConfigFile string // config file
SkipUpdate bool // skip update SkipUpdate bool // skip update
Client *http.Client // request client Client *http.Client // request client
DB *gorm.DB DB *gorm.DB

3
go.mod
View File

@ -19,6 +19,7 @@ require (
golang.org/x/sys v0.0.0-20201218084310-7d0127a74742 // indirect golang.org/x/sys v0.0.0-20201218084310-7d0127a74742 // indirect
google.golang.org/protobuf v1.25.0 // indirect google.golang.org/protobuf v1.25.0 // indirect
gopkg.in/yaml.v2 v2.4.0 gopkg.in/yaml.v2 v2.4.0
gorm.io/driver/mysql v1.0.5
gorm.io/driver/sqlite v1.1.4 gorm.io/driver/sqlite v1.1.4
gorm.io/gorm v1.21.1 gorm.io/gorm v1.21.3
) )

6
go.sum
View File

@ -27,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.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 h1:pH2c5ADXtd66mxoE0Zm9SUhxE20r7aM3F26W0hOn+GE=
github.com/go-playground/validator/v10 v10.4.1/go.mod h1:nlOn6nFhuKACm19sB/8EGNn9GlaMV7XkbRSipzJ0Ii4= 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/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/mock v1.1.1/go.mod h1:oTYuIxOrZwtPieC+H1uAHpcLFnEyAGVDL/k47Jfbm0A=
github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U=
@ -166,10 +168,14 @@ 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.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 h1:dUUwHk2QECo/6vqA44rthZ8ie2QXMNeKRTHCNY2nXvo=
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= 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 h1:PDzwYE+sI6De2+mxAneV9Xs11+ZyKV6oxD3wDGkaNvM=
gorm.io/driver/sqlite v1.1.4/go.mod h1:mJCeTFr7+crvS+TRnWc5Z3UvwxUN1BGBLMrf5LA9DYw= 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.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 h1:ACwUZ+jzH8eG8zxgqTnMIdgWd+lGfCKZTUxL/uQ1ZQo=
gorm.io/gorm v1.21.1/go.mod h1:0HFTzE/SqkGTzK6TlDPPQbAYCluiVvhzoA1+aVyzenw= 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-20190102054323-c2f93a96b099/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4=
honnef.co/go/tools v0.0.0-20190523083050-ea95bdfd59fc/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= honnef.co/go/tools v0.0.0-20190523083050-ea95bdfd59fc/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4=

View File

@ -45,7 +45,7 @@ func Down(c *gin.Context) {
c.JSON(200, MetaResponse(406, "无法下载目录.")) c.JSON(200, MetaResponse(406, "无法下载目录."))
return return
} }
drive := utils.GetDriveByName(strings.Split(dir,"/")[0]) drive := utils.GetDriveByName(strings.Split(dir, "/")[0])
if drive == nil { if drive == nil {
c.JSON(200, MetaResponse(500, "找不到drive.")) c.JSON(200, MetaResponse(500, "找不到drive."))
return return

View File

@ -42,7 +42,7 @@ func Get(c *gin.Context) {
} }
return return
} }
drive := utils.GetDriveByName(strings.Split(dir,"/")[0]) drive := utils.GetDriveByName(strings.Split(dir, "/")[0])
if drive == nil { if drive == nil {
c.JSON(200, MetaResponse(500, "找不到drive.")) c.JSON(200, MetaResponse(500, "找不到drive."))
return return

View File

@ -44,6 +44,11 @@ func Path(c *gin.Context) {
} }
// file // file
if file.Type == "file" { if file.Type == "file" {
if file.Password == "" {
file.Password = "n"
} else {
file.Password = "y"
}
c.JSON(200, DataResponse(file)) c.JSON(200, DataResponse(file))
return return
} }
@ -57,7 +62,7 @@ func Path(c *gin.Context) {
for i, _ := range *files { for i, _ := range *files {
if (*files)[i].Password == "" { if (*files)[i].Password == "" {
(*files)[i].Password = "n" (*files)[i].Password = "n"
}else { } else {
(*files)[i].Password = "y" (*files)[i].Password = "y"
} }
} }

View File

@ -13,7 +13,7 @@ func BuildTreeAll() {
for i, _ := range conf.Conf.AliDrive.Drives { for i, _ := range conf.Conf.AliDrive.Drives {
if err := BuildTree(&conf.Conf.AliDrive.Drives[i]); err != nil { if err := BuildTree(&conf.Conf.AliDrive.Drives[i]); err != nil {
log.Errorf("盘[%s]构建目录树失败:%s", err.Error()) log.Errorf("盘[%s]构建目录树失败:%s", err.Error())
}else { } else {
log.Infof("盘[%s]构建目录树成功") log.Infof("盘[%s]构建目录树成功")
} }
} }

View File

@ -1,47 +0,0 @@
package test
import (
"fmt"
"github.com/Xhofe/alist/alidrive"
"github.com/Xhofe/alist/bootstrap"
"github.com/Xhofe/alist/conf"
"os"
"testing"
)
func setup() {
bootstrap.InitLog()
bootstrap.ReadConf("../conf.yml")
bootstrap.InitClient()
bootstrap.InitAliDrive()
}
func TestGetUserInfo(t *testing.T) {
user, err := alidrive.GetUserInfo()
fmt.Println(err)
fmt.Println(user)
}
func TestGetRoot(t *testing.T) {
files, err := alidrive.GetRoot(50, "", conf.OrderUpdatedAt, conf.DESC)
fmt.Println(err)
fmt.Println(files)
}
func TestSearch(t *testing.T) {
files, err := alidrive.Search("测试文件", 50, "")
fmt.Println(err)
fmt.Println(files)
}
func TestGet(t *testing.T) {
file, err := alidrive.GetFile("5fb7c80e85e4f335cd344008be1b1b5349f74414")
fmt.Println(err)
fmt.Println(file)
}
func TestMain(m *testing.M) {
setup()
code := m.Run()
os.Exit(code)
}

View File

@ -15,16 +15,16 @@ func TestSplit(t *testing.T) {
} }
func TestPassword(t *testing.T) { func TestPassword(t *testing.T) {
fullName:="hello.password-xhf" fullName := "hello.password-xhf"
index:=strings.Index(fullName,".password-") index := strings.Index(fullName, ".password-")
name:=fullName[:index] name := fullName[:index]
password:=fullName[index+10:] password := fullName[index+10:]
fmt.Printf("name:%s, password:%s\n",name,password) fmt.Printf("name:%s, password:%s\n", name, password)
} }
func TestDir(t *testing.T) { func TestDir(t *testing.T) {
dir,file:=filepath.Split("root") dir, file := filepath.Split("root")
fmt.Printf("dir:%s\nfile:%s\n",dir,file) fmt.Printf("dir:%s\nfile:%s\n", dir, file)
} }
func TestMD5(t *testing.T) { func TestMD5(t *testing.T) {

View File

@ -2,7 +2,6 @@ package test
import ( import (
"fmt" "fmt"
"github.com/Xhofe/alist/alidrive"
"github.com/Xhofe/alist/conf" "github.com/Xhofe/alist/conf"
"github.com/Xhofe/alist/utils" "github.com/Xhofe/alist/utils"
"testing" "testing"
@ -13,7 +12,5 @@ func TestStr(t *testing.T) {
} }
func TestWriteYml(t *testing.T) { func TestWriteYml(t *testing.T) {
alidrive.RefreshToken()
utils.WriteToYml("../conf.yml", conf.Conf) utils.WriteToYml("../conf.yml", conf.Conf)
} }

View File

@ -13,6 +13,6 @@ func GetMD5Encode(data string) string {
} }
//返回一个16位md5加密后的字符串 //返回一个16位md5加密后的字符串
func Get16MD5Encode(data string) string{ func Get16MD5Encode(data string) string {
return GetMD5Encode(data)[8:24] return GetMD5Encode(data)[8:24]
} }