Finish the install procedure.

This commit is contained in:
zicla
2018-12-06 19:26:11 +08:00
parent b7e8a3c1a1
commit 5e84721435
17 changed files with 242 additions and 448 deletions

View File

@ -1,162 +0,0 @@
CREATE TABLE `tank20_dashboard`
(
`uuid` char(36) NOT NULL,
`invoke_num` bigint(20) NOT NULL DEFAULT '0' COMMENT '当日访问量',
`total_invoke_num` bigint(20) NOT NULL DEFAULT '0' COMMENT '截至目前总访问量',
`uv` bigint(20) NOT NULL DEFAULT '0' COMMENT '当日UV',
`total_uv` bigint(20) NOT NULL DEFAULT '0' COMMENT '截至目前总UV',
`matter_num` bigint(20) NOT NULL DEFAULT '0' COMMENT '文件数量',
`total_matter_num` bigint(20) NOT NULL DEFAULT '0' COMMENT '截至目前文件数量',
`file_size` bigint(20) NOT NULL DEFAULT '0' COMMENT '当日文件大小',
`total_file_size` bigint(20) NOT NULL DEFAULT '0' COMMENT '截至目前文件总大小',
`avg_cost` bigint(20) NOT NULL DEFAULT '0' COMMENT '请求平均耗时 ms',
`dt` varchar(45) NOT NULL COMMENT '日期',
`sort` bigint(20) NOT NULL DEFAULT '0',
`update_time` timestamp NULL DEFAULT NULL,
`create_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`uuid`),
UNIQUE KEY `uq_dt` (`dt`),
KEY `idx_dt` (`dt`),
KEY `idx_ct` (`create_time`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='汇总表,离线统计';
CREATE TABLE `tank20_download_token`
(
`uuid` char(36) NOT NULL,
`user_uuid` char(36) DEFAULT NULL COMMENT '用户uuid',
`matter_uuid` char(36) DEFAULT NULL COMMENT '文件标识',
`expire_time` timestamp NULL DEFAULT NULL COMMENT '授权访问的次数',
`ip` varchar(45) DEFAULT NULL COMMENT '消费者的ip',
`sort` bigint(20) DEFAULT NULL,
`update_time` timestamp NULL DEFAULT NULL,
`create_time` timestamp NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
PRIMARY KEY (`uuid`),
UNIQUE KEY `id_UNIQUE` (`uuid`),
KEY `id_mu` (`matter_uuid`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='下载的token表';
CREATE TABLE `tank20_footprint`
(
`uuid` char(36) NOT NULL,
`user_uuid` char(36) DEFAULT NULL,
`ip` varchar(45) DEFAULT NULL,
`host` varchar(45) DEFAULT NULL,
`uri` varchar(255) DEFAULT NULL,
`params` text,
`cost` int(11) DEFAULT '0' COMMENT '耗时 ms',
`success` tinyint(1) DEFAULT '1',
`sort` bigint(20) NOT NULL DEFAULT '0',
`update_time` timestamp NULL DEFAULT NULL,
`create_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`uuid`),
KEY `idx_ct` (`create_time`),
KEY `dix_ip` (`ip`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='访问记录表';
CREATE TABLE `tank20_image_cache`
(
`uuid` char(36) NOT NULL,
`user_uuid` char(36) DEFAULT NULL COMMENT '上传的用户id',
`matter_uuid` char(36) DEFAULT NULL,
`mode` varchar(512) DEFAULT NULL COMMENT '请求的uri',
`md5` varchar(45) DEFAULT NULL COMMENT '文件的md5值',
`size` bigint(20) DEFAULT '0' COMMENT '文件大小',
`path` varchar(255) DEFAULT NULL,
`sort` bigint(20) DEFAULT NULL,
`update_time` timestamp NULL DEFAULT NULL,
`create_time` timestamp NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
PRIMARY KEY (`uuid`),
UNIQUE KEY `id_UNIQUE` (`uuid`),
KEY `idx_mu` (`matter_uuid`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='图片缓存表';
CREATE TABLE `tank20_matter`
(
`uuid` char(36) NOT NULL,
`puuid` varchar(45) DEFAULT NULL COMMENT '上一级的uuid',
`user_uuid` char(36) DEFAULT NULL COMMENT '上传的用户id',
`dir` tinyint(1) DEFAULT '0' COMMENT '是否是文件夹',
`alien` tinyint(1) DEFAULT '0',
`name` varchar(255) DEFAULT NULL COMMENT '文件名称',
`md5` varchar(45) DEFAULT NULL COMMENT '文件的md5值',
`size` bigint(20) DEFAULT '0' COMMENT '文件大小',
`privacy` tinyint(1) DEFAULT '0' COMMENT '文件是否是公有的',
`path` varchar(255) DEFAULT NULL,
`times` bigint(20) DEFAULT '0' COMMENT '下载次数',
`sort` bigint(20) DEFAULT NULL,
`update_time` timestamp NULL DEFAULT NULL,
`create_time` timestamp NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
PRIMARY KEY (`uuid`),
UNIQUE KEY `id_UNIQUE` (`uuid`),
KEY `idx_uu` (`user_uuid`),
KEY `idx_ct` (`create_time`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='file表';
CREATE TABLE `tank20_preference`
(
`uuid` char(36) NOT NULL,
`name` varchar(45) DEFAULT NULL COMMENT '网站名称',
`logo_url` varchar(255) DEFAULT NULL,
`favicon_url` varchar(255) DEFAULT NULL,
`footer_line1` varchar(1024) DEFAULT NULL,
`footer_line2` varchar(1024) DEFAULT NULL,
`version` varchar(45) DEFAULT NULL,
`sort` bigint(20) DEFAULT NULL,
`update_time` timestamp NULL DEFAULT NULL,
`create_time` timestamp NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
PRIMARY KEY (`uuid`),
UNIQUE KEY `id_UNIQUE` (`uuid`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='网站偏好设置表';
CREATE TABLE `tank20_session`
(
`uuid` char(36) NOT NULL,
`user_uuid` char(36) DEFAULT NULL COMMENT '用户uuid',
`ip` varchar(45) DEFAULT NULL COMMENT '用户的ip地址',
`expire_time` timestamp NULL DEFAULT NULL,
`sort` bigint(20) DEFAULT NULL,
`update_time` timestamp NULL DEFAULT NULL,
`create_time` timestamp NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
PRIMARY KEY (`uuid`),
UNIQUE KEY `id_UNIQUE` (`uuid`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='session表';
CREATE TABLE `tank20_upload_token`
(
`uuid` char(36) NOT NULL,
`user_uuid` char(36) DEFAULT NULL COMMENT '用户uuid',
`folder_uuid` char(36) DEFAULT NULL,
`matter_uuid` char(36) DEFAULT NULL,
`filename` varchar(255) DEFAULT NULL COMMENT '文件后缀名的过滤,可以只允许用户上传特定格式的文件。',
`privacy` tinyint(1) DEFAULT '1',
`size` bigint(20) DEFAULT '0',
`expire_time` timestamp NULL DEFAULT NULL,
`ip` varchar(45) DEFAULT NULL COMMENT '消费者的ip',
`sort` bigint(20) DEFAULT NULL,
`update_time` timestamp NULL DEFAULT NULL,
`create_time` timestamp NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
PRIMARY KEY (`uuid`),
UNIQUE KEY `id_UNIQUE` (`uuid`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='上传的token表';
CREATE TABLE `tank20_user`
(
`uuid` char(36) NOT NULL,
`role` varchar(45) DEFAULT 'USER',
`username` varchar(255) DEFAULT NULL COMMENT '昵称',
`password` varchar(255) DEFAULT NULL COMMENT '密码',
`email` varchar(45) DEFAULT NULL COMMENT '邮箱',
`phone` varchar(45) DEFAULT NULL COMMENT '电话',
`gender` varchar(45) DEFAULT 'UNKNOWN' COMMENT '性别,默认未知',
`city` varchar(45) DEFAULT NULL COMMENT '城市',
`avatar_url` varchar(255) DEFAULT NULL COMMENT '头像链接',
`last_time` datetime DEFAULT NULL COMMENT '上次登录使劲按',
`last_ip` varchar(45) DEFAULT NULL,
`size_limit` int(11) DEFAULT '-1' COMMENT '该账号上传文件的大小限制单位byte。<0 表示不设限制',
`status` varchar(45) DEFAULT 'OK',
`sort` bigint(20) DEFAULT NULL,
`update_time` timestamp NULL DEFAULT NULL,
`create_time` timestamp NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
PRIMARY KEY (`uuid`),
UNIQUE KEY `id_UNIQUE` (`uuid`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='用户表描述';

View File

@ -1,21 +0,0 @@
CREATE TABLE `tank20_dashboard`
(
`uuid` char(36) NOT NULL,
`invoke_num` bigint(20) NOT NULL DEFAULT '0' COMMENT '当日访问量',
`total_invoke_num` bigint(20) NOT NULL DEFAULT '0' COMMENT '截至目前总访问量',
`uv` bigint(20) NOT NULL DEFAULT '0' COMMENT '当日UV',
`total_uv` bigint(20) NOT NULL DEFAULT '0' COMMENT '截至目前总UV',
`matter_num` bigint(20) NOT NULL DEFAULT '0' COMMENT '文件数量',
`total_matter_num` bigint(20) NOT NULL DEFAULT '0' COMMENT '截至目前文件数量',
`file_size` bigint(20) NOT NULL DEFAULT '0' COMMENT '当日文件大小',
`total_file_size` bigint(20) NOT NULL DEFAULT '0' COMMENT '截至目前文件总大小',
`avg_cost` bigint(20) NOT NULL DEFAULT '0' COMMENT '请求平均耗时 ms',
`dt` varchar(45) NOT NULL COMMENT '日期',
`sort` bigint(20) NOT NULL DEFAULT '0',
`update_time` timestamp NULL DEFAULT NULL,
`create_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`uuid`),
UNIQUE KEY `uq_dt` (`dt`),
KEY `idx_dt` (`dt`),
KEY `idx_ct` (`create_time`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='汇总表,离线统计';

View File

@ -1,14 +0,0 @@
CREATE TABLE `tank20_download_token`
(
`uuid` char(36) NOT NULL,
`user_uuid` char(36) DEFAULT NULL COMMENT '用户uuid',
`matter_uuid` char(36) DEFAULT NULL COMMENT '文件标识',
`expire_time` timestamp NULL DEFAULT NULL COMMENT '授权访问的次数',
`ip` varchar(45) DEFAULT NULL COMMENT '消费者的ip',
`sort` bigint(20) DEFAULT NULL,
`update_time` timestamp NULL DEFAULT NULL,
`create_time` timestamp NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
PRIMARY KEY (`uuid`),
UNIQUE KEY `id_UNIQUE` (`uuid`),
KEY `id_mu` (`matter_uuid`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='下载的token表';

View File

@ -1,17 +0,0 @@
CREATE TABLE `tank20_footprint`
(
`uuid` char(36) NOT NULL,
`user_uuid` char(36) DEFAULT NULL,
`ip` varchar(45) DEFAULT NULL,
`host` varchar(45) DEFAULT NULL,
`uri` varchar(255) DEFAULT NULL,
`params` text,
`cost` int(11) DEFAULT '0' COMMENT '耗时 ms',
`success` tinyint(1) DEFAULT '1',
`sort` bigint(20) NOT NULL DEFAULT '0',
`update_time` timestamp NULL DEFAULT NULL,
`create_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`uuid`),
KEY `idx_ct` (`create_time`),
KEY `dix_ip` (`ip`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='访问记录表';

View File

@ -1,16 +0,0 @@
CREATE TABLE `tank20_image_cache`
(
`uuid` char(36) NOT NULL,
`user_uuid` char(36) DEFAULT NULL COMMENT '上传的用户id',
`matter_uuid` char(36) DEFAULT NULL,
`mode` varchar(512) DEFAULT NULL COMMENT '请求的uri',
`md5` varchar(45) DEFAULT NULL COMMENT '文件的md5值',
`size` bigint(20) DEFAULT '0' COMMENT '文件大小',
`path` varchar(255) DEFAULT NULL,
`sort` bigint(20) DEFAULT NULL,
`update_time` timestamp NULL DEFAULT NULL,
`create_time` timestamp NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
PRIMARY KEY (`uuid`),
UNIQUE KEY `id_UNIQUE` (`uuid`),
KEY `idx_mu` (`matter_uuid`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='图片缓存表';

View File

@ -1,21 +0,0 @@
CREATE TABLE `tank20_matter`
(
`uuid` char(36) NOT NULL,
`puuid` varchar(45) DEFAULT NULL COMMENT '上一级的uuid',
`user_uuid` char(36) DEFAULT NULL COMMENT '上传的用户id',
`dir` tinyint(1) DEFAULT '0' COMMENT '是否是文件夹',
`alien` tinyint(1) DEFAULT '0',
`name` varchar(255) DEFAULT NULL COMMENT '文件名称',
`md5` varchar(45) DEFAULT NULL COMMENT '文件的md5值',
`size` bigint(20) DEFAULT '0' COMMENT '文件大小',
`privacy` tinyint(1) DEFAULT '0' COMMENT '文件是否是公有的',
`path` varchar(255) DEFAULT NULL,
`times` bigint(20) DEFAULT '0' COMMENT '下载次数',
`sort` bigint(20) DEFAULT NULL,
`update_time` timestamp NULL DEFAULT NULL,
`create_time` timestamp NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
PRIMARY KEY (`uuid`),
UNIQUE KEY `id_UNIQUE` (`uuid`),
KEY `idx_uu` (`user_uuid`),
KEY `idx_ct` (`create_time`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='file表';

View File

@ -1,15 +0,0 @@
CREATE TABLE `tank20_preference`
(
`uuid` char(36) NOT NULL,
`name` varchar(45) DEFAULT NULL COMMENT '网站名称',
`logo_url` varchar(255) DEFAULT NULL,
`favicon_url` varchar(255) DEFAULT NULL,
`footer_line1` varchar(1024) DEFAULT NULL,
`footer_line2` varchar(1024) DEFAULT NULL,
`version` varchar(45) DEFAULT NULL,
`sort` bigint(20) DEFAULT NULL,
`update_time` timestamp NULL DEFAULT NULL,
`create_time` timestamp NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
PRIMARY KEY (`uuid`),
UNIQUE KEY `id_UNIQUE` (`uuid`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='网站偏好设置表';

View File

@ -1,12 +0,0 @@
CREATE TABLE `tank20_session`
(
`uuid` char(36) NOT NULL,
`user_uuid` char(36) DEFAULT NULL COMMENT '用户uuid',
`ip` varchar(45) DEFAULT NULL COMMENT '用户的ip地址',
`expire_time` timestamp NULL DEFAULT NULL,
`sort` bigint(20) DEFAULT NULL,
`update_time` timestamp NULL DEFAULT NULL,
`create_time` timestamp NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
PRIMARY KEY (`uuid`),
UNIQUE KEY `id_UNIQUE` (`uuid`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='session表';

View File

@ -1,17 +0,0 @@
CREATE TABLE `tank20_upload_token`
(
`uuid` char(36) NOT NULL,
`user_uuid` char(36) DEFAULT NULL COMMENT '用户uuid',
`folder_uuid` char(36) DEFAULT NULL,
`matter_uuid` char(36) DEFAULT NULL,
`filename` varchar(255) DEFAULT NULL COMMENT '文件后缀名的过滤,可以只允许用户上传特定格式的文件。',
`privacy` tinyint(1) DEFAULT '1',
`size` bigint(20) DEFAULT '0',
`expire_time` timestamp NULL DEFAULT NULL,
`ip` varchar(45) DEFAULT NULL COMMENT '消费者的ip',
`sort` bigint(20) DEFAULT NULL,
`update_time` timestamp NULL DEFAULT NULL,
`create_time` timestamp NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
PRIMARY KEY (`uuid`),
UNIQUE KEY `id_UNIQUE` (`uuid`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='上传的token表';

View File

@ -1,21 +0,0 @@
CREATE TABLE `tank20_user`
(
`uuid` char(36) NOT NULL,
`role` varchar(45) DEFAULT 'USER',
`username` varchar(255) DEFAULT NULL COMMENT '昵称',
`password` varchar(255) DEFAULT NULL COMMENT '密码',
`email` varchar(45) DEFAULT NULL COMMENT '邮箱',
`phone` varchar(45) DEFAULT NULL COMMENT '电话',
`gender` varchar(45) DEFAULT 'UNKNOWN' COMMENT '性别,默认未知',
`city` varchar(45) DEFAULT NULL COMMENT '城市',
`avatar_url` varchar(255) DEFAULT NULL COMMENT '头像链接',
`last_time` datetime DEFAULT NULL COMMENT '上次登录使劲按',
`last_ip` varchar(45) DEFAULT NULL,
`size_limit` int(11) DEFAULT '-1' COMMENT '该账号上传文件的大小限制单位byte。<0 表示不设限制',
`status` varchar(45) DEFAULT 'OK',
`sort` bigint(20) DEFAULT NULL,
`update_time` timestamp NULL DEFAULT NULL,
`create_time` timestamp NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
PRIMARY KEY (`uuid`),
UNIQUE KEY `id_UNIQUE` (`uuid`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='用户表描述';

View File

@ -14,16 +14,13 @@ func main() {
rest.LOGGER.Init() rest.LOGGER.Init()
defer rest.LOGGER.Destroy() defer rest.LOGGER.Destroy()
//装载配置文件,这个决定了是否需要执行安装过程 //装载配置文件,这个决定了是否需要执行安装过程
rest.CONFIG.Init() rest.CONFIG.Init()
//全局运行的上下文 //全局运行的上下文
rest.CONTEXT.Init() rest.CONTEXT.Init()
defer rest.CONTEXT.Destroy() defer rest.CONTEXT.Destroy()
http.Handle("/", rest.CONTEXT.Router) http.Handle("/", rest.CONTEXT.Router)
rest.LOGGER.Info("App started at http://localhost:%v", rest.CONFIG.ServerPort) rest.LOGGER.Info("App started at http://localhost:%v", rest.CONFIG.ServerPort)

View File

@ -1,7 +1,6 @@
package rest package rest
import ( import (
"encoding/json"
"github.com/json-iterator/go" "github.com/json-iterator/go"
"io/ioutil" "io/ioutil"
"time" "time"
@ -31,8 +30,8 @@ var CONFIG = &Config{}
type Config struct { type Config struct {
//默认监听端口号 //默认监听端口号
ServerPort int ServerPort int
//数据库是否配置完备 //网站是否已经完成安装
DBConfigured bool Installed bool
//上传的文件路径,要求不以/结尾。如果没有指定默认在根目录下的matter文件夹中。eg: /var/www/matter //上传的文件路径,要求不以/结尾。如果没有指定默认在根目录下的matter文件夹中。eg: /var/www/matter
MatterPath string MatterPath string
//数据库连接信息。 //数据库连接信息。
@ -118,37 +117,61 @@ func (this *Config) Init() {
}, nil) }, nil)
//默认从6010端口启动 //默认从6010端口启动
CONFIG.ServerPort = 6010 this.ServerPort = 6010
this.ReadFromConfigFile()
}
//系统如果安装好了就调用这个方法。
func (this *Config) ReadFromConfigFile() {
//读取配置文件 //读取配置文件
filePath := GetConfPath() + "/tank.json" filePath := GetConfPath() + "/tank.json"
content, err := ioutil.ReadFile(filePath) content, err := ioutil.ReadFile(filePath)
if err != nil { if err != nil {
LOGGER.Warn("即将进入安装过程,无法找到配置文件:%s", filePath) LOGGER.Warn("无法找到配置文件:%s 即将进入安装过程!", filePath)
this.DBConfigured = false this.Installed = false
} else { } else {
// 用 json.Unmarshal this.Item = &ConfigItem{}
err := json.Unmarshal(content, this.Item) err := jsoniter.ConfigCompatibleWithStandardLibrary.Unmarshal(content, this.Item)
if err != nil { if err != nil {
LOGGER.Error("配置文件格式错误!") LOGGER.Error("配置文件格式错误!")
this.DBConfigured = false this.Installed = false
return return
} }
//验证项是否齐全 //验证项是否齐全
itemValidate := this.Item.validate() itemValidate := this.Item.validate()
if !itemValidate { if !itemValidate {
this.DBConfigured = false LOGGER.Error("配置文件信息不齐全!")
this.Installed = false
return return
} }
//使用配置项中的文件路径
if this.Item.MatterPath == "" { if this.Item.MatterPath == "" {
CONFIG.MatterPath = GetHomePath() + "/matter" this.MatterPath = GetHomePath() + "/matter"
} else {
this.MatterPath = this.Item.MatterPath
} }
MakeDirAll(CONFIG.MatterPath) MakeDirAll(CONFIG.MatterPath)
this.MysqlUrl = GetMysqlUrl(this.Item.MysqlPort, this.Item.MysqlHost, this.Item.MysqlSchema, this.Item.MysqlUsername, this.Item.MysqlPassword) //使用配置项中的端口
this.DBConfigured = true if this.Item.ServerPort != 0 {
this.ServerPort = this.Item.ServerPort
} }
this.MysqlUrl = GetMysqlUrl(this.Item.MysqlPort, this.Item.MysqlHost, this.Item.MysqlSchema, this.Item.MysqlUsername, this.Item.MysqlPassword)
this.Installed = true
LOGGER.Info("使用配置文件:%s", filePath)
LOGGER.Info("上传文件存放路径:%s", this.MatterPath)
}
}
//系统如果安装好了就调用这个方法。
func (this *Config) InstallOk() {
this.ReadFromConfigFile()
} }

View File

@ -43,10 +43,7 @@ func (this *Context) Init() {
this.Router = NewRouter() this.Router = NewRouter()
//如果数据库信息配置好了,就直接打开数据库连接 同时执行Bean的ConfigPost方法 //如果数据库信息配置好了,就直接打开数据库连接 同时执行Bean的ConfigPost方法
if CONFIG.DBConfigured { this.InstallOk()
this.OpenDb()
this.configPostBeans()
}
} }
@ -173,14 +170,20 @@ func (this *Context) initBeans() {
} }
} }
//所有配置项完备后执行的方法
func (this *Context) configPostBeans() { //系统如果安装好了就调用这个方法。
func (this *Context) InstallOk() {
if CONFIG.Installed {
this.OpenDb()
for _, bean := range this.BeanMap { for _, bean := range this.BeanMap {
bean.ConfigPost() bean.ConfigPost()
} }
} }
}
//销毁的方法 //销毁的方法
func (this *Context) Destroy() { func (this *Context) Destroy() {
this.CloseDb() this.CloseDb()

View File

@ -73,7 +73,7 @@ func (this *FootprintService) Trace(writer http.ResponseWriter, request *http.Re
} }
//有可能DB尚且没有配置 直接打印出内容,并且退出 //有可能DB尚且没有配置 直接打印出内容,并且退出
if CONFIG.DBConfigured { if CONFIG.Installed {
user := this.findUser(writer, request) user := this.findUser(writer, request)
userUuid := "" userUuid := ""
if user != nil { if user != nil {

View File

@ -1,87 +0,0 @@
package rest
import (
"fmt"
"github.com/jinzhu/gorm"
)
//首次运行的时候,将自动安装数据库等内容。
func InstallDatabase() {
db, err := gorm.Open("mysql", CONFIG.MysqlUrl)
if err != nil {
LOGGER.Panic(fmt.Sprintf("无法打开%s", CONFIG.MysqlUrl))
}
if db != nil {
defer db.Close()
}
//这个方法只会简单查看表是否存在,不会去比照每个字段的。因此如果用户自己修改表结构将会出现不可预测的错误。
var hasTable = true
downloadToken := &DownloadToken{}
hasTable = db.HasTable(downloadToken)
if !hasTable {
createDownloadToken := "CREATE TABLE `tank20_download_token` (`uuid` char(36) NOT NULL,`user_uuid` char(36) DEFAULT NULL COMMENT '用户uuid',`matter_uuid` char(36) DEFAULT NULL COMMENT '文件标识',`expire_time` timestamp NULL DEFAULT NULL COMMENT '授权访问的次数',`ip` varchar(45) DEFAULT NULL COMMENT '消费者的ip',`sort` bigint(20) DEFAULT NULL,`modify_time` timestamp NULL DEFAULT NULL,`create_time` timestamp NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',PRIMARY KEY (`uuid`),UNIQUE KEY `id_UNIQUE` (`uuid`)) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='下载的token表';"
db = db.Exec(createDownloadToken)
if db.Error != nil {
LOGGER.Panic(db.Error.Error())
}
LOGGER.Info("创建DownloadToken表")
}
matter := &Matter{}
hasTable = db.HasTable(matter)
if !hasTable {
createMatter := "CREATE TABLE `tank20_matter` (`uuid` char(36) NOT NULL,`puuid` varchar(45) DEFAULT NULL COMMENT '上一级的uuid',`user_uuid` char(36) DEFAULT NULL COMMENT '上传的用户id',`dir` tinyint(1) DEFAULT '0' COMMENT '是否是文件夹',`alien` tinyint(1) DEFAULT '0',`name` varchar(255) DEFAULT NULL COMMENT '文件名称',`md5` varchar(45) DEFAULT NULL COMMENT '文件的md5值',`size` bigint(20) DEFAULT '0' COMMENT '文件大小',`privacy` tinyint(1) DEFAULT '0' COMMENT '文件是否是公有的',`path` varchar(255) DEFAULT NULL,`sort` bigint(20) DEFAULT NULL,`modify_time` timestamp NULL DEFAULT NULL,`create_time` timestamp NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',PRIMARY KEY (`uuid`),UNIQUE KEY `id_UNIQUE` (`uuid`)) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='file表';"
db = db.Exec(createMatter)
if db.Error != nil {
LOGGER.Panic(db.Error.Error())
}
LOGGER.Info("创建Matter表")
}
preference := &Preference{}
hasTable = db.HasTable(preference)
if !hasTable {
createPreference := "CREATE TABLE `tank20_preference` (`uuid` char(36) NOT NULL,`name` varchar(45) DEFAULT NULL COMMENT '网站名称',`logo_url` varchar(255) DEFAULT NULL,`favicon_url` varchar(255) DEFAULT NULL,`footer_line1` varchar(1024) DEFAULT NULL,`footer_line2` varchar(1024) DEFAULT NULL,`version` varchar(45) DEFAULT NULL,`sort` bigint(20) DEFAULT NULL,`modify_time` timestamp NULL DEFAULT NULL,`create_time` timestamp NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',PRIMARY KEY (`uuid`),UNIQUE KEY `id_UNIQUE` (`uuid`)) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='网站偏好设置表';"
db = db.Exec(createPreference)
if db.Error != nil {
LOGGER.Panic(db.Error.Error())
}
LOGGER.Info("创建Preference表")
}
session := &Session{}
hasTable = db.HasTable(session)
if !hasTable {
createSession := "CREATE TABLE `tank20_session` (`uuid` char(36) NOT NULL,`authentication` char(36) DEFAULT NULL COMMENT '认证身份存放在cookie中',`user_uuid` char(36) DEFAULT NULL COMMENT '用户uuid',`ip` varchar(45) DEFAULT NULL COMMENT '用户的ip地址',`expire_time` timestamp NULL DEFAULT NULL,`sort` bigint(20) DEFAULT NULL,`modify_time` timestamp NULL DEFAULT NULL,`create_time` timestamp NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',PRIMARY KEY (`uuid`),UNIQUE KEY `id_UNIQUE` (`uuid`)) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='session表';"
db = db.Exec(createSession)
if db.Error != nil {
LOGGER.Panic(db.Error.Error())
}
LOGGER.Info("创建Session表")
}
uploadToken := &UploadToken{}
hasTable = db.HasTable(uploadToken)
if !hasTable {
createUploadToken := "CREATE TABLE `tank20_upload_token` (`uuid` char(36) NOT NULL,`user_uuid` char(36) DEFAULT NULL COMMENT '用户uuid',`folder_uuid` char(36) DEFAULT NULL,`matter_uuid` char(36) DEFAULT NULL,`filename` varchar(255) DEFAULT NULL COMMENT '文件后缀名的过滤,可以只允许用户上传特定格式的文件。',`privacy` tinyint(1) DEFAULT '1',`size` bigint(20) DEFAULT '0',`expire_time` timestamp NULL DEFAULT NULL,`ip` varchar(45) DEFAULT NULL COMMENT '消费者的ip',`sort` bigint(20) DEFAULT NULL,`modify_time` timestamp NULL DEFAULT NULL,`create_time` timestamp NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',PRIMARY KEY (`uuid`),UNIQUE KEY `id_UNIQUE` (`uuid`)) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='上传的token表';"
db = db.Exec(createUploadToken)
if db.Error != nil {
LOGGER.Panic(db.Error.Error())
}
LOGGER.Info("创建UploadToken表")
}
user := &User{}
hasTable = db.HasTable(user)
if !hasTable {
}
}

View File

@ -3,10 +3,12 @@ package rest
import ( import (
"fmt" "fmt"
"github.com/jinzhu/gorm" "github.com/jinzhu/gorm"
"github.com/json-iterator/go"
"github.com/nu7hatch/gouuid" "github.com/nu7hatch/gouuid"
"go/build" "go/build"
"io/ioutil" "io/ioutil"
"net/http" "net/http"
"os"
"regexp" "regexp"
"strconv" "strconv"
"time" "time"
@ -69,7 +71,10 @@ func (this *InstallController) RegisterRoutes() map[string]func(writer http.Resp
routeMap["/api/install/verify"] = this.Wrap(this.Verify, USER_ROLE_GUEST) routeMap["/api/install/verify"] = this.Wrap(this.Verify, USER_ROLE_GUEST)
routeMap["/api/install/table/info/list"] = this.Wrap(this.TableInfoList, USER_ROLE_GUEST) routeMap["/api/install/table/info/list"] = this.Wrap(this.TableInfoList, USER_ROLE_GUEST)
routeMap["/api/install/create/table"] = this.Wrap(this.CreateTable, USER_ROLE_GUEST) routeMap["/api/install/create/table"] = this.Wrap(this.CreateTable, USER_ROLE_GUEST)
routeMap["/api/install/admin/list"] = this.Wrap(this.AdminList, USER_ROLE_GUEST)
routeMap["/api/install/create/admin"] = this.Wrap(this.CreateAdmin, USER_ROLE_GUEST) routeMap["/api/install/create/admin"] = this.Wrap(this.CreateAdmin, USER_ROLE_GUEST)
routeMap["/api/install/validate/admin"] = this.Wrap(this.ValidateAdmin, USER_ROLE_GUEST)
routeMap["/api/install/finish"] = this.Wrap(this.Finish, USER_ROLE_GUEST)
return routeMap return routeMap
} }
@ -97,6 +102,8 @@ func (this *InstallController) openDbConnection(writer http.ResponseWriter, requ
db, err := gorm.Open("mysql", mysqlUrl) db, err := gorm.Open("mysql", mysqlUrl)
this.PanicError(err) this.PanicError(err)
db.LogMode(true)
return db return db
} }
@ -178,6 +185,46 @@ func (this *InstallController) getTableMeta(gormDb *gorm.DB, entity IBase) (bool
} }
//根据表名获取建表SQL语句
func (this *InstallController) getTableMetaList(db *gorm.DB) []*InstallTableInfo {
var tableNames = []IBase{&Dashboard{}, &DownloadToken{}, &Footprint{}, &ImageCache{}, &Matter{}, &Preference{}, &Session{}, UploadToken{}, &User{}}
var installTableInfos []*InstallTableInfo
for _, iBase := range tableNames {
exist, allFields, missingFields := this.getTableMeta(db, iBase)
installTableInfos = append(installTableInfos, &InstallTableInfo{
Name: iBase.TableName(),
TableExist: exist,
AllFields: allFields,
MissingFields: missingFields,
})
}
return installTableInfos
}
//验证表结构是否完整。会直接抛出异常
func (this *InstallController) validateTableMetaList(tableInfoList []*InstallTableInfo) {
for _, tableInfo := range tableInfoList {
if tableInfo.TableExist {
if len(tableInfo.MissingFields) != 0 {
var strs []string
for _, v := range tableInfo.MissingFields {
strs = append(strs, v.DBName)
}
this.PanicBadRequest(fmt.Sprintf("%s 表的以下字段缺失:%v", tableInfo.Name, strs))
}
} else {
this.PanicBadRequest(tableInfo.Name + "表不存在")
}
}
}
//验证数据库连接 //验证数据库连接
func (this *InstallController) Verify(writer http.ResponseWriter, request *http.Request) *WebResult { func (this *InstallController) Verify(writer http.ResponseWriter, request *http.Request) *WebResult {
@ -194,26 +241,10 @@ func (this *InstallController) Verify(writer http.ResponseWriter, request *http.
//获取需要安装的数据库表 //获取需要安装的数据库表
func (this *InstallController) TableInfoList(writer http.ResponseWriter, request *http.Request) *WebResult { func (this *InstallController) TableInfoList(writer http.ResponseWriter, request *http.Request) *WebResult {
var tableNames = []IBase{&Dashboard{}, &DownloadToken{}, &Footprint{}, &ImageCache{}, &Matter{}, &Preference{}, &Session{}, UploadToken{}, &User{}}
var installTableInfos []*InstallTableInfo
db := this.openDbConnection(writer, request) db := this.openDbConnection(writer, request)
defer this.closeDbConnection(db) defer this.closeDbConnection(db)
for _, iBase := range tableNames { return this.Success(this.getTableMetaList(db))
exist, allFields, missingFields := this.getTableMeta(db, iBase)
installTableInfos = append(installTableInfos, &InstallTableInfo{
Name: iBase.TableName(),
TableExist: exist,
AllFields: allFields,
MissingFields: missingFields,
})
}
return this.Success(installTableInfos)
} }
//创建缺失数据库和表 //创建缺失数据库和表
@ -245,6 +276,27 @@ func (this *InstallController) CreateTable(writer http.ResponseWriter, request *
} }
//获取管理员列表(10条记录)
func (this *InstallController) AdminList(writer http.ResponseWriter, request *http.Request) *WebResult {
db := this.openDbConnection(writer, request)
defer this.closeDbConnection(db)
var wp = &WherePair{}
wp = wp.And(&WherePair{Query: "role = ?", Args: []interface{}{USER_ROLE_ADMINISTRATOR}})
count := 0
db = db.Model(&User{}).Where(wp.Query, wp.Args...).Count(&count)
this.PanicError(db.Error)
var users []*User
db = db.Where(wp.Query, wp.Args...).Offset(0).Limit(10).Find(&users)
this.PanicError(db.Error)
return this.Success(users)
}
//创建管理员 //创建管理员
func (this *InstallController) CreateAdmin(writer http.ResponseWriter, request *http.Request) *WebResult { func (this *InstallController) CreateAdmin(writer http.ResponseWriter, request *http.Request) *WebResult {
@ -269,6 +321,21 @@ func (this *InstallController) CreateAdmin(writer http.ResponseWriter, request *
this.PanicBadRequest(`超级管理员邮箱必填`) this.PanicBadRequest(`超级管理员邮箱必填`)
} }
//检查是否有重复。
var count1 int64
db1 := db.Model(&User{}).Where("email = ?", adminEmail).Count(&count1)
this.PanicError(db1.Error)
if count1 > 0 {
this.PanicBadRequest(`该邮箱已存在`)
}
var count2 int64
db2 := db.Model(&User{}).Where("username = ?", adminUsername).Count(&count2)
this.PanicError(db2.Error)
if count2 > 0 {
this.PanicBadRequest(`该用户名已存在`)
}
user := &User{} user := &User{}
timeUUID, _ := uuid.NewV4() timeUUID, _ := uuid.NewV4()
user.Uuid = string(timeUUID.String()) user.Uuid = string(timeUUID.String())
@ -285,8 +352,115 @@ func (this *InstallController) CreateAdmin(writer http.ResponseWriter, request *
user.SizeLimit = -1 user.SizeLimit = -1
user.Status = USER_STATUS_OK user.Status = USER_STATUS_OK
db.Create(user) db3 := db.Create(user)
this.PanicError(db3.Error)
return this.Success("OK") return this.Success("OK")
} }
//(如果数据库中本身存在管理员了)验证管理员
func (this *InstallController) ValidateAdmin(writer http.ResponseWriter, request *http.Request) *WebResult {
db := this.openDbConnection(writer, request)
defer this.closeDbConnection(db)
adminEmail := request.FormValue("adminEmail")
adminPassword := request.FormValue("adminPassword")
//验证超级管理员的信息
if adminEmail == "" {
this.PanicBadRequest(`超级管理员邮箱必填`)
}
if len(adminPassword) < 6 {
this.PanicBadRequest(`超级管理员密码长度至少为6位`)
}
var existEmailUser = &User{}
db = db.Where(&User{Email: adminEmail}).First(existEmailUser)
if db.Error != nil {
this.PanicBadRequest(fmt.Sprintf("%s对应的用户不存在", adminEmail))
}
if !MatchBcrypt(adminPassword, existEmailUser.Password) {
this.PanicBadRequest("邮箱或密码错误")
}
if existEmailUser.Role != USER_ROLE_ADMINISTRATOR {
this.PanicBadRequest("该账号不是管理员")
}
return this.Success("OK")
}
//完成系统安装
func (this *InstallController) Finish(writer http.ResponseWriter, request *http.Request) *WebResult {
mysqlPortStr := request.FormValue("mysqlPort")
mysqlHost := request.FormValue("mysqlHost")
mysqlSchema := request.FormValue("mysqlSchema")
mysqlUsername := request.FormValue("mysqlUsername")
mysqlPassword := request.FormValue("mysqlPassword")
var mysqlPort int
if mysqlPortStr != "" {
tmp, err := strconv.Atoi(mysqlPortStr)
this.PanicError(err)
mysqlPort = tmp
}
//要求数据库连接通畅
db := this.openDbConnection(writer, request)
defer this.closeDbConnection(db)
//要求数据库完整。
tableMetaList := this.getTableMetaList(db)
this.validateTableMetaList(tableMetaList)
//要求至少有一名管理员。
var count1 int64
db1 := db.Model(&User{}).Where("role = ?", USER_ROLE_ADMINISTRATOR).Count(&count1)
this.PanicError(db1.Error)
if count1 == 0 {
this.PanicBadRequest(`请至少配置一名管理员`)
}
var configItem = &ConfigItem{
//默认监听端口号
ServerPort: CONFIG.ServerPort,
//上传的文件路径,要求不以/结尾。如果没有指定默认在根目录下的matter文件夹中。eg: /var/www/matter
MatterPath: CONFIG.MatterPath,
//mysql相关配置。
//数据库端口
MysqlPort: mysqlPort,
//数据库Host
MysqlHost: mysqlHost,
//数据库名字
MysqlSchema: mysqlSchema,
//用户名
MysqlUsername: mysqlUsername,
//密码
MysqlPassword: mysqlPassword,
}
//用json的方式输出返回值。
jsonStr, _ := jsoniter.ConfigCompatibleWithStandardLibrary.Marshal(configItem)
//写入到配置文件中
filePath := GetConfPath() + "/tank.json"
f, err := os.OpenFile(filePath, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0777)
this.PanicError(err)
_, err = f.Write(jsonStr)
this.PanicError(err)
err = f.Close()
this.PanicError(err)
//通知配置文件安装完毕。
CONFIG.InstallOk()
//通知全局上下文,说系统安装好了
CONTEXT.InstallOk()
return this.Success("OK")
}

View File

@ -122,7 +122,7 @@ func (this *Router) ServeHTTP(writer http.ResponseWriter, request *http.Request)
path := request.URL.Path path := request.URL.Path
if strings.HasPrefix(path, "/api") { if strings.HasPrefix(path, "/api") {
if CONFIG.DBConfigured { if CONFIG.Installed {
//已安装的模式 //已安装的模式
//统一处理用户的身份信息。 //统一处理用户的身份信息。