Merge pull request #1 from mindoc-org/master

consistant to mindoc
pull/681/head
LawyZheng 2021-04-25 10:20:30 +08:00 committed by GitHub
commit effc92694d
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
65 changed files with 1305 additions and 1110 deletions

2
.gitignore vendored
View File

@ -21,9 +21,11 @@ _testmain.go
*.exe *.exe
mindoc mindoc
database
*.test *.test
*.prof *.prof
.idea .idea
.vscode
/conf/app.conf /conf/app.conf
/vendor /vendor
/runtime /runtime

View File

@ -1,32 +1,46 @@
os: linux
dist: focal
language: go language: go
go: go:
- "1.12" - "1.13"
arch:
- amd64
env:
- GO111MODULE=on CGO_ENABLED=1
sudo: true
install: install:
- dep ensure - go mod tidy -v
before_install: before_install:
- curl https://raw.githubusercontent.com/golang/dep/master/install.sh | sh - whereis gcc
- go env
script: script:
- dep ensure && GO_ENABLED=1 go build -v -x -tags "pam" && go install - go build -o mindoc_linux_amd64 -ldflags "-w"
- cp conf/app.conf.example conf/app.conf
- ./mindoc_linux_amd64 version
- rm conf/app.conf
before_deploy: before_deploy:
- dep ensure -v && CGO_ENABLED=1 GOARCH=amd64 GOOS=linux go build -o mindoc_linux_amd64 -ldflags="-w -X github.com/mindoc-org/mindoc/conf.VERSION=$TRAVIS_TAG -X 'github.com/mindoc-org/mindoc/conf.BUILD_TIME=`date`' -X 'conf.GO_VERSION=`github.com/mindoc-org/mindoc/go version`'" - go mod tidy -v && GOARCH=amd64 GOOS=linux go build -o mindoc_linux_amd64 -ldflags="-w -X 'github.com/mindoc-org/mindoc/conf.VERSION=$TRAVIS_TAG' -X 'github.com/mindoc-org/mindoc/conf.BUILD_TIME=`date`' -X 'conf.GO_VERSION=`go version`'"
- rm -rf simsun.ttc start.sh commands controllers models modules data routers tasks vendor docs search utils graphics .git Godeps uploads/* .gitignore .travis.yml Dockerfile Gopkg.toml LICENSE main.go README.md conf/enumerate.go conf/mail.go install.lock *.md # remove files
- rm appveyor.yml docker-compose.yml Dockerfile .travis.yml .gitattributes .gitignore go.mod go.sum main.go README.md simsun.ttc start.sh
# remove dirs
- rm -rf cache commands controllers converter .git .github graphics mail models routers utils
- ls -alh
- cp conf/app.conf.example conf/app.conf - cp conf/app.conf.example conf/app.conf
- zip -r mindoc_linux_amd64.zip conf static uploads views lib mindoc_linux_amd64 - zip -r mindoc_linux_amd64.zip conf static uploads views lib mindoc_linux_amd64 favicon.ico LICENSE.md
deploy: deploy:
provider: releases provider: releases
api_key: $CI_USER_TOKEN token: $CI_USER_TOKEN
skip_cleanup: true cleanup: true
overwrite: true
file: file:
- mindoc_linux_amd64.zip - mindoc_linux_amd64.zip
on: on:
overwrite: true
tags: true tags: true
all_branches: true branch: master
go: "1.12"

View File

@ -1,29 +1,25 @@
# MinDoc 简介 # MinDoc 简介
[![Build Status](https://travis-ci.org/lifei6671/mindoc.svg?branch=master)](https://travis-ci.org/lifei6671/mindoc) [![Build Status](https://travis-ci.com/mindoc-org/mindoc.svg?branch=master)](https://travis-ci.com/mindoc-org/mindoc)
[![Build status](https://ci.appveyor.com/api/projects/status/ik70whjrioyvfy18/branch/master?svg=true)](https://ci.appveyor.com/project/lifei6671/godoc/branch/master) [![Build status](https://ci.appveyor.com/api/projects/status/o3lcfmf5iy2cp9m6?svg=true)](https://ci.appveyor.com/project/gsw945/mindoc)
MinDoc 是一款针对IT团队开发的简单好用的文档管理系统。 MinDoc 是一款针对IT团队开发的简单好用的文档管理系统。
MinDoc 的前身是 SmartWiki 文档系统。SmartWiki 是基于 PHP 框架 laravel 开发的一款文档管理系统。因 PHP 的部署对普通用户来说太复杂,所以改用 Golang 开发。可以方便用户部署和实用。 MinDoc 的前身是 [SmartWiki](https://github.com/lifei6671/SmartWiki) 文档系统。SmartWiki 是基于 PHP 框架 laravel 开发的一款文档管理系统。因 PHP 的部署对普通用户来说太复杂,所以改用 Golang 开发。可以方便用户部署和实用。
开发缘起是公司IT部门需要一款简单实用的项目接口文档管理和分享的系统。其功能和界面源于 kancloud 。 开发缘起是公司IT部门需要一款简单实用的项目接口文档管理和分享的系统。其功能和界面源于 kancloud 。
可以用来储存日常接口文档,数据库字典,手册说明等文档。内置项目管理,用户管理,权限管理等功能,能够满足大部分中小团队的文档管理需求。 可以用来储存日常接口文档,数据库字典,手册说明等文档。内置项目管理,用户管理,权限管理等功能,能够满足大部分中小团队的文档管理需求。
演示站点: [http://doc.iminho.me](http://doc.iminho.me) 演示站点: [https://www.iminho.me/wiki/](https://www.iminho.me/wiki/)
--- ---
<details> ### 开发&维护&使用 悉知
<summary>开发维护召集令</summary>
感谢作者 [lifei6671](https://github.com/lifei6671) 创造了MinDoc并持续维护了很久。 感谢作者 [lifei6671](https://github.com/lifei6671) 创造了MinDoc并持续维护了很久。
本人向公司推广了MinDoc反向很好。受益于开源便想回馈于开源。但看到MinDoc似乎停更了一年尝试和作者沟通后得知作者因工作等原因精力有限无法持续维护请求得到了GitHub仓库的部分维护权限。 作者因工作等原因精力有限无法花费足够的时间来持续维护mindoc已于北京时间2021年3月23日将mindoc交给社区(github组织[mindoc-org](https://github.com/mindoc-org))维护,期待热心开发者加入[mindoc-org](https://github.com/mindoc-org)一起来维护MinDoc。
本人技术能力有限,且业余时间并不充裕,处理 Issues 和 Pull Requests 的进度缓慢希望能和热心开发者一起持续维护MinDoc。
维护权限需要作者添加有意向者请添加下方QQ群或通过发送邮件(`gsw945#foxmail.com`, 请替换`#`为`@`),私聊我加入作者所在的微信群。
</details>
遇到问题请提 [Issues](https://github.com/mindoc-org/mindoc/issues )欢迎使用者和贡献者加入QQ群 `1051164153` 遇到问题请提 [Issues](https://github.com/mindoc-org/mindoc/issues )欢迎使用者和贡献者加入QQ群 `1051164153`
<a target="_blank" href="https://qm.qq.com/cgi-bin/qm/qr?k=bHFR7P3Qp1nsSPbsTw4KN_ZpFLUAblIU&jump_from=webapi"><img border="0" src="https://pub.idqqimg.com/wpa/images/group.png" alt="MinDoc使用&amp;开发交流群" title="MinDoc使用&amp;开发交流群"></a> <a target="_blank" href="https://qm.qq.com/cgi-bin/qm/qr?k=bHFR7P3Qp1nsSPbsTw4KN_ZpFLUAblIU&jump_from=webapi"><img border="0" src="https://pub.idqqimg.com/wpa/images/group.png" alt="MinDoc使用&amp;开发交流群" title="MinDoc使用&amp;开发交流群"></a>
@ -38,17 +34,18 @@ MinDoc 的前身是 SmartWiki 文档系统。SmartWiki 是基于 PHP 框架 lara
对于没有Golang使用经验的用户可以从 [https://github.com/mindoc-org/mindoc/releases](https://github.com/mindoc-org/mindoc/releases) 这里下载编译完的程序。 对于没有Golang使用经验的用户可以从 [https://github.com/mindoc-org/mindoc/releases](https://github.com/mindoc-org/mindoc/releases) 这里下载编译完的程序。
如果有Golang开发经验建议通过编译安装在此之前您需要先安装Golang官方包管理工具详见[Install dep](https://golang.github.io/dep/docs/installation.html)。 如果有Golang开发经验建议通过编译安装要求golang版本不小于1.13(需支持`CGO`和`go mod`)。
```bash ```bash
# 克隆源码
git clone https://github.com/mindoc-org/mindoc.git git clone https://github.com/mindoc-org/mindoc.git
# go包安装
dep ensure go mod tidy
# 编译(sqlite需要CGO支持)
go build -ldflags "-w" go build -ldflags "-w"
# 数据库初始化(此步骤执行之前,需配置`conf/app.conf`)
./mindoc install ./mindoc install
# 执行
./mindoc ./mindoc
``` ```
@ -64,7 +61,7 @@ MinDoc 如果使用MySQL储存数据则编码必须是`utf8mb4_general_ci`。
```bash ```bash
#邮件配置 #邮件配置-示例
#是否启用邮件 #是否启用邮件
enable_mail=true enable_mail=true
#smtp服务器的账号 #smtp服务器的账号
@ -100,6 +97,7 @@ HTTP_PORT 程序监听的端口号
举个栗子 举个栗子
```bash ```bash
# TODO: 新版docker镜像将使用阿里云配置中
docker run -p 8181:8181 --name mindoc -e DB_ADAPTER=mysql -e MYSQL_PORT_3306_TCP_ADDR=10.xxx.xxx.xxx -e MYSQL_PORT_3306_TCP_PORT=3306 -e MYSQL_INSTANCE_NAME=mindoc -e MYSQL_USERNAME=root -e MYSQL_PASSWORD=123456 -e httpport=8181 -d daocloud.io/lifei6671/mindoc:latest docker run -p 8181:8181 --name mindoc -e DB_ADAPTER=mysql -e MYSQL_PORT_3306_TCP_ADDR=10.xxx.xxx.xxx -e MYSQL_PORT_3306_TCP_PORT=3306 -e MYSQL_INSTANCE_NAME=mindoc -e MYSQL_USERNAME=root -e MYSQL_PASSWORD=123456 -e httpport=8181 -d daocloud.io/lifei6671/mindoc:latest
``` ```
### docker-compose 一键安装 ### docker-compose 一键安装
@ -130,7 +128,8 @@ docker run -p 8181:8181 --name mindoc -e DB_ADAPTER=mysql -e MYSQL_PORT_3306_TCP
> docker-compose down > docker-compose down
- 删除并重新创建 - 删除并重新创建
> docker-compose -f docker-compose.yml down && docker-compose up -d > docker-compose -f docker-compose.yml down && docker-compose up -d
更多 docker-compose 的使用相关的内容 请查看官网文档或百度 >
> 更多 docker-compose 的使用相关的内容 请查看官网文档或百度
# 项目截图 # 项目截图
@ -171,23 +170,24 @@ docker run -p 8181:8181 --name mindoc -e DB_ADAPTER=mysql -e MYSQL_PORT_3306_TCP
![超级管理员后台](https://raw.githubusercontent.com/lifei6671/mindoc/master/uploads/20170501204710.png) ![超级管理员后台](https://raw.githubusercontent.com/lifei6671/mindoc/master/uploads/20170501204710.png)
# 使用的技术 # 使用的技术(TODO: 最新技术栈整理中,使用的第三方库升级中)
- beego 1.10.0 - [Beego](https://github.com/beego/beego) ~~1.10.0~~
- mysql 5.6 - MySQL 5.6
- editor.md Markdown 编辑器 - [editor.md](https://github.com/pandao/editor.md) Markdown 编辑器
- bootstrap 3.2 - [Bootstrap](https://github.com/twbs/bootstrap) 3.2
- jquery 库 - jQuery(https://github.com/jquery/jquery) 库
- webuploader 文件上传框架 - [WebUploader](https://github.com/fex-team/webuploader) 文件上传框架
- Nprogress 库 - [NProgress](https://github.com/rstacruz/nprogress) 库
- jstree 树状结构库 - [jsTree](https://github.com/vakata/jstree) 树状结构库
- font awesome 字体库 - [Font Awesome](https://github.com/FortAwesome/Font-Awesome) 字体库
- cropper 图片剪裁库 - [Cropper](https://github.com/fengyuanchen/cropper) 图片剪裁库
- layer 弹出层框架 - [layer](https://github.com/sentsin/layer) 弹出层框架
- highlight 代码高亮库 - [highlight.js](https://github.com/highlightjs/highlight.js) 代码高亮库
- to-markdown HTML转Markdown库 - ~~to-markdown~~[Turndown](https://github.com/domchristie/turndown) HTML转Markdown库
- quill 富文本编辑器 - ~~quill 富文本编辑器~~
- vue 框架 - [wangEditor](https://github.com/wangeditor-team/wangEditor) 富文本编辑器
- [Vue.js](https://github.com/vuejs/vue) 框架
# 主要功能 # 主要功能
@ -206,7 +206,7 @@ docker run -p 8181:8181 --name mindoc -e DB_ADAPTER=mysql -e MYSQL_PORT_3306_TCP
如果您还不熟悉GitHub的Fork and Pull开发模式您可以阅读GitHub的文档https://help.github.com/articles/using-pull-requests 获得更多的信息。 如果您还不熟悉GitHub的Fork and Pull开发模式您可以阅读GitHub的文档https://help.github.com/articles/using-pull-requests 获得更多的信息。
# 关于作者 # 关于作者[lifei6671](https://github.com/lifei6671)
一个不纯粹的PHPer一个不自由的 gopher 。 一个不纯粹的PHPer一个不自由的 gopher 。

View File

@ -1,65 +1,42 @@
version: "{build}" version: 1.0.{build}
clone_folder: c:\gopath\src\github.com\lifei6671\mindoc branches:
only:
- master
image: Visual Studio 2015
clone_folder: c:\gopath\src\github.com\mindoc-org\mindoc
init:
- cmd: >-
if [%tbs_arch%]==[x86] SET PATH=C:\MinGW\bin;%PATH%
if [%tbs_arch%]==[x64] SET PATH=C:\mingw-w64\x86_64-7.2.0-posix-seh-rt_v5-rev1\mingw64;C:\mingw-w64\x86_64-7.2.0-posix-seh-rt_v5-rev1\mingw64\bin;%PATH%
SET PATH=%GOPATH%\bin;%GOBIN%;%PATH%
FOR /f "delims=" %%i IN ('go version') DO (SET GO_VERSION=%%i)
environment: environment:
GOPATH: c:\gopath GOPATH: c:\gopath
GOVERSION: "1.12" GOBIN: c:\gobin
GO111MODULE: on
CGO_ENABLED: 1
matrix: matrix:
- tbs_arch: "x86" - tbs_arch: x86
tbs_tools: "mingw" GOARCH: 386
tbs_static_runtime: 1 - tbs_arch: x64
GOARCH: 386 GOARCH: amd64
- tbs_arch: "x64"
tbs_tools: "mingw"
tbs_static_runtime: 1
GOARCH: amd64
install: install:
- ps: if($env:tbs_tools -eq 'mingw' -and $env:tbs_arch -eq 'x64') - cmd: >-
{ echo %PATH%
Start-FileDownload "http://libgd.blob.core.windows.net/mingw/x86_64-4.9.1-release-posix-seh-rt_v3-rev1.7z" -FileName mingw_x86_64.7z; echo %GO_VERSION%
7z x -oC:\ mingw_x86_64.7z | out-null; go env
} where gcc
- ps: if($env:tbs_tools -eq 'mingw' -and $env:tbs_arch -eq 'x86') where g++
{
Start-FileDownload "http://libgd.blob.core.windows.net/mingw/i686-4.9.1-release-posix-dwarf-rt_v3-rev1.7z" -FileName mingw_x86.7z;
7z x -oC:\ mingw_x86.7z | out-null;
}
- set PATH=%GOPATH%\bin;c:\go\bin;%PATH%
- echo %PATH%
- echo %GOPATH%
- go version
- go env
build_script: build_script:
- if [%tbs_tools%]==[mingw] if [%tbs_arch%]==[x86] SET PATH=C:\mingw32\bin;%PATH% - cmd: >-
- if [%tbs_tools%]==[mingw] if [%tbs_arch%]==[x64] SET PATH=C:\mingw64\bin;%PATH% cd c:\gopath\src\github.com\mindoc-org\mindoc
- set CGO_ENABLED=1 go mod tidy
- for /f "delims=" %%i in ('go version') do (set GO_VERSION=%%i) go build -ldflags "-w"
- cd c:\gopath\src\github.com\lifei6671\mindoc go build -v -o "mindoc_windows_%GOARCH%.exe" -ldflags="-w -X github.com/mindoc-org/mindoc/conf.VERSION=%APPVEYOR_REPO_TAG_NAME% -X 'github.com/mindoc-org/mindoc/conf.BUILD_TIME=%date% %time%' -X 'conf.GO_VERSION=%GO_VERSION%'"
- go mod tidy 7z a -t7z -r mindoc_windows_%GOARCH%.7z conf/*.conf* static/* mindoc_windows_%GOARCH%.exe views/* uploads/*
- go build -v -o "mindoc_windows_%GOARCH%.exe" -ldflags="-w -X github.com/mindoc-org/mindoc/conf.VERSION=%APPVEYOR_REPO_TAG_NAME% -X 'github.com/mindoc-org/mindoc/conf.BUILD_TIME=%date% %time%' -X 'conf.GO_VERSION=%GO_VERSION%'"
- 7z a -t7z -r mindoc_windows_%GOARCH%.7z conf/*.conf* static/* mindoc_windows_%GOARCH%.exe views/* uploads/*
test_script: test_script:
- mindoc_windows_%GOARCH%.exe version - cmd: >-
cd c:\gopath\src\github.com\mindoc-org\mindoc
notifications: xcopy conf\app.conf.example conf\app.conf /F /Y
- provider: Email mindoc_windows_%GOARCH%.exe version
to: deploy: off
- lifei6671@163.com
on_build_success: false
artifacts:
- path: mindoc_windows_%GOARCH%.7z
name: Releases
deploy:
- provider: GitHub
auth_token:
secure: "Qkhxloft5lBKti7O+vVS+Vrxh7CBAUVhlfdZ9ptBXjFtjt6jHXnaBA2uv2OYbISB"
draft: false
prerelease: false
artifact: mindoc_windows_%GOARCH%.7z
on:
appveyor_repo_tag: true

42
cache/cache.go vendored
View File

@ -1,20 +1,27 @@
package cache package cache
import ( import (
"github.com/astaxie/beego/cache"
"time"
"encoding/gob"
"bytes" "bytes"
"context"
"encoding/gob"
"errors" "errors"
"github.com/astaxie/beego" "time"
)
"github.com/beego/beego/v2/core/logs"
"github.com/beego/beego/v2/client/cache"
)
var bm cache.Cache var bm cache.Cache
var nilctx = context.TODO()
func Get(key string, e interface{}) error { func Get(key string, e interface{}) error {
val := bm.Get(key) val, err := bm.Get(nilctx, key)
if err != nil {
return errors.New("get cache error:" + err.Error())
}
if val == nil { if val == nil {
return errors.New("cache does not exist") return errors.New("cache does not exist")
@ -27,7 +34,7 @@ func Get(key string, e interface{}) error {
err := decoder.Decode(e) err := decoder.Decode(e)
if err != nil { if err != nil {
beego.Error("反序列化对象失败 ->", err) logs.Error("反序列化对象失败 ->", err)
} }
return err return err
} else if s, ok := val.(string); ok && s != "" { } else if s, ok := val.(string); ok && s != "" {
@ -39,14 +46,13 @@ func Get(key string, e interface{}) error {
err := decoder.Decode(e) err := decoder.Decode(e)
if err != nil { if err != nil {
beego.Error("反序列化对象失败 ->", err) logs.Error("反序列化对象失败 ->", err)
} }
return err return err
} }
return errors.New("value is not []byte or string") return errors.New("value is not []byte or string")
} }
func Put(key string, val interface{}, timeout time.Duration) error { func Put(key string, val interface{}, timeout time.Duration) error {
var buf bytes.Buffer var buf bytes.Buffer
@ -55,34 +61,34 @@ func Put(key string, val interface{}, timeout time.Duration) error {
err := encoder.Encode(val) err := encoder.Encode(val)
if err != nil { if err != nil {
beego.Error("序列化对象失败 ->", err) logs.Error("序列化对象失败 ->", err)
return err return err
} }
return bm.Put(key, buf.String(), timeout) return bm.Put(nilctx, key, buf.String(), timeout)
} }
func Delete(key string) error { func Delete(key string) error {
return bm.Delete(key) return bm.Delete(nilctx, key)
} }
func Incr(key string) error { func Incr(key string) error {
return bm.Incr(key) return bm.Incr(nilctx, key)
} }
func Decr(key string) error { func Decr(key string) error {
return bm.Decr(key) return bm.Decr(nilctx, key)
} }
func IsExist(key string) bool { func IsExist(key string) (bool, error) {
return bm.IsExist(key) return bm.IsExist(nilctx, key)
} }
func ClearAll() error { func ClearAll() error {
return bm.ClearAll() return bm.ClearAll(nilctx)
} }
func StartAndGC(config string) error { func StartAndGC(config string) error {
return bm.StartAndGC(config) return bm.StartAndGC(config)
} }
//初始化缓存 //Init will initialize cache
func Init(c cache.Cache) { func Init(c cache.Cache) {
bm = c bm = c
} }

27
cache/cache_null.go vendored
View File

@ -1,36 +1,39 @@
package cache package cache
import "time" import (
"context"
"time"
)
type NullCache struct { type NullCache struct {
} }
func (bm *NullCache) Get(key string) interface{} { func (bm *NullCache) Get(ctx context.Context, key string) (interface{}, error) {
return nil return nil, nil
} }
func (bm *NullCache)GetMulti(keys []string) []interface{} { func (bm *NullCache)GetMulti(ctx context.Context, keys []string) ([]interface{}, error) {
return nil return nil, nil
} }
func (bm *NullCache)Put(key string, val interface{}, timeout time.Duration) error { func (bm *NullCache)Put(ctx context.Context,key string, val interface{}, timeout time.Duration) error {
return nil return nil
} }
func (bm *NullCache)Delete(key string) error { func (bm *NullCache)Delete(ctx context.Context,key string) error {
return nil return nil
} }
func (bm *NullCache)Incr(key string) error { func (bm *NullCache)Incr(ctx context.Context,key string) error {
return nil return nil
} }
func (bm *NullCache)Decr(key string) error { func (bm *NullCache)Decr(ctx context.Context,key string) error {
return nil return nil
} }
func (bm *NullCache)IsExist(key string) bool { func (bm *NullCache)IsExist(ctx context.Context,key string) (bool, error) {
return false return false, nil
} }
func (bm *NullCache)ClearAll() error{ func (bm *NullCache)ClearAll(ctx context.Context) error{
return nil return nil
} }

View File

@ -15,14 +15,13 @@ import (
"encoding/json" "encoding/json"
"net/http" "net/http"
"github.com/astaxie/beego" beegoCache "github.com/beego/beego/v2/client/cache"
beegoCache "github.com/astaxie/beego/cache" _ "github.com/beego/beego/v2/client/cache/memcache"
_ "github.com/astaxie/beego/cache/memcache" "github.com/beego/beego/v2/client/cache/redis"
_ "github.com/beego/beego/v2/client/cache/redis"
"github.com/astaxie/beego/cache/redis" "github.com/beego/beego/v2/client/orm"
_ "github.com/astaxie/beego/cache/redis" "github.com/beego/beego/v2/core/logs"
"github.com/astaxie/beego/logs" "github.com/beego/beego/v2/server/web"
"github.com/astaxie/beego/orm"
"github.com/howeyc/fsnotify" "github.com/howeyc/fsnotify"
"github.com/lifei6671/gocaptcha" "github.com/lifei6671/gocaptcha"
"github.com/mindoc-org/mindoc/cache" "github.com/mindoc-org/mindoc/cache"
@ -33,37 +32,37 @@ import (
// RegisterDataBase 注册数据库 // RegisterDataBase 注册数据库
func RegisterDataBase() { func RegisterDataBase() {
beego.Info("正在初始化数据库配置.") logs.Info("正在初始化数据库配置.")
adapter := beego.AppConfig.String("db_adapter") dbadapter, _ := web.AppConfig.String("db_adapter")
orm.DefaultTimeLoc = time.Local orm.DefaultTimeLoc = time.Local
orm.DefaultRowsLimit = -1 orm.DefaultRowsLimit = -1
if strings.EqualFold(adapter, "mysql") { if strings.EqualFold(dbadapter, "mysql") {
host := beego.AppConfig.String("db_host") host, _ := web.AppConfig.String("db_host")
database := beego.AppConfig.String("db_database") database, _ := web.AppConfig.String("db_database")
username := beego.AppConfig.String("db_username") username, _ := web.AppConfig.String("db_username")
password := beego.AppConfig.String("db_password") password, _ := web.AppConfig.String("db_password")
timezone := beego.AppConfig.String("timezone") timezone, _ := web.AppConfig.String("timezone")
location, err := time.LoadLocation(timezone) location, err := time.LoadLocation(timezone)
if err == nil { if err == nil {
orm.DefaultTimeLoc = location orm.DefaultTimeLoc = location
} else { } else {
beego.Error("加载时区配置信息失败,请检查是否存在 ZONEINFO 环境变量->", err) logs.Error("加载时区配置信息失败,请检查是否存在 ZONEINFO 环境变量->", err)
} }
port := beego.AppConfig.String("db_port") port, _ := web.AppConfig.String("db_port")
dataSource := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8mb4&parseTime=true&loc=%s", username, password, host, port, database, url.QueryEscape(timezone)) dataSource := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8mb4&parseTime=true&loc=%s", username, password, host, port, database, url.QueryEscape(timezone))
if err := orm.RegisterDataBase("default", "mysql", dataSource); err != nil { if err := orm.RegisterDataBase("default", "mysql", dataSource); err != nil {
beego.Error("注册默认数据库失败->", err) logs.Error("注册默认数据库失败->", err)
os.Exit(1) os.Exit(1)
} }
} else if strings.EqualFold(adapter, "sqlite3") { } else if strings.EqualFold(dbadapter, "sqlite3") {
database := beego.AppConfig.String("db_database") database, _ := web.AppConfig.String("db_database")
if strings.HasPrefix(database, "./") { if strings.HasPrefix(database, "./") {
database = filepath.Join(conf.WorkingDirectory, string(database[1:])) database = filepath.Join(conf.WorkingDirectory, string(database[1:]))
} }
@ -80,13 +79,13 @@ func RegisterDataBase() {
err := orm.RegisterDataBase("default", "sqlite3", database) err := orm.RegisterDataBase("default", "sqlite3", database)
if err != nil { if err != nil {
beego.Error("注册默认数据库失败->", err) logs.Error("注册默认数据库失败->", err)
} }
} else { } else {
beego.Error("不支持的数据库类型.") logs.Error("不支持的数据库类型.")
os.Exit(1) os.Exit(1)
} }
beego.Info("数据库初始化完成.") logs.Info("数据库初始化完成.")
} }
// RegisterModel 注册Model // RegisterModel 注册Model
@ -123,11 +122,11 @@ func RegisterLogger(log string) {
_ = logs.SetLogger("console") _ = logs.SetLogger("console")
logs.EnableFuncCallDepth(true) logs.EnableFuncCallDepth(true)
if beego.AppConfig.DefaultBool("log_is_async", true) { if web.AppConfig.DefaultBool("log_is_async", true) {
logs.Async(1e3) logs.Async(1e3)
} }
if log == "" { if log == "" {
logPath, err := filepath.Abs(beego.AppConfig.DefaultString("log_path", conf.WorkingDir("runtime", "logs"))) logPath, err := filepath.Abs(web.AppConfig.DefaultString("log_path", conf.WorkingDir("runtime", "logs")))
if err == nil { if err == nil {
log = logPath log = logPath
} else { } else {
@ -147,55 +146,47 @@ func RegisterLogger(log string) {
config["perm"] = "0755" config["perm"] = "0755"
config["rotate"] = true config["rotate"] = true
if maxLines := beego.AppConfig.DefaultInt("log_maxlines", 1000000); maxLines > 0 { if maxLines := web.AppConfig.DefaultInt("log_maxlines", 1000000); maxLines > 0 {
config["maxLines"] = maxLines config["maxLines"] = maxLines
} }
if maxSize := beego.AppConfig.DefaultInt("log_maxsize", 1<<28); maxSize > 0 { if maxSize := web.AppConfig.DefaultInt("log_maxsize", 1<<28); maxSize > 0 {
config["maxsize"] = maxSize config["maxsize"] = maxSize
} }
if !beego.AppConfig.DefaultBool("log_daily", true) { if !web.AppConfig.DefaultBool("log_daily", true) {
config["daily"] = false config["daily"] = false
} }
if maxDays := beego.AppConfig.DefaultInt("log_maxdays", 7); maxDays > 0 { if maxDays := web.AppConfig.DefaultInt("log_maxdays", 7); maxDays > 0 {
config["maxdays"] = maxDays config["maxdays"] = maxDays
} }
if level := beego.AppConfig.DefaultString("log_level", "Trace"); level != "" { if level := web.AppConfig.DefaultString("log_level", "Trace"); level != "" {
switch level { switch level {
case "Emergency": case "Emergency":
config["level"] = beego.LevelEmergency config["level"] = logs.LevelEmergency
break
case "Alert": case "Alert":
config["level"] = beego.LevelAlert config["level"] = logs.LevelAlert
break
case "Critical": case "Critical":
config["level"] = beego.LevelCritical config["level"] = logs.LevelCritical
break
case "Error": case "Error":
config["level"] = beego.LevelError config["level"] = logs.LevelError
break
case "Warning": case "Warning":
config["level"] = beego.LevelWarning config["level"] = logs.LevelWarning
break
case "Notice": case "Notice":
config["level"] = beego.LevelNotice config["level"] = logs.LevelNotice
break
case "Informational": case "Informational":
config["level"] = beego.LevelInformational config["level"] = logs.LevelInformational
break
case "Debug": case "Debug":
config["level"] = beego.LevelDebug config["level"] = logs.LevelDebug
break
} }
} }
b, err := json.Marshal(config) b, err := json.Marshal(config)
if err != nil { if err != nil {
beego.Error("初始化文件日志时出错 ->", err) logs.Error("初始化文件日志时出错 ->", err)
_ = beego.SetLogger("file", `{"filename":"`+logPath+`"}`) _ = logs.SetLogger("file", `{"filename":"`+logPath+`"}`)
} else { } else {
_ = beego.SetLogger(logs.AdapterFile, string(b)) _ = logs.SetLogger(logs.AdapterFile, string(b))
} }
beego.SetLogFuncCall(true) logs.SetLogFuncCall(true)
} }
// RunCommand 注册orm命令行工具 // RunCommand 注册orm命令行工具
@ -213,20 +204,20 @@ func RegisterCommand() {
//注册模板函数 //注册模板函数
func RegisterFunction() { func RegisterFunction() {
err := beego.AddFuncMap("config", models.GetOptionValue) err := web.AddFuncMap("config", models.GetOptionValue)
if err != nil { if err != nil {
beego.Error("注册函数 config 出错 ->", err) logs.Error("注册函数 config 出错 ->", err)
os.Exit(-1) os.Exit(-1)
} }
err = beego.AddFuncMap("cdn", func(p string) string { err = web.AddFuncMap("cdn", func(p string) string {
cdn := beego.AppConfig.DefaultString("cdn", "") cdn := web.AppConfig.DefaultString("cdn", "")
if strings.HasPrefix(p, "http://") || strings.HasPrefix(p, "https://") { if strings.HasPrefix(p, "http://") || strings.HasPrefix(p, "https://") {
return p return p
} }
//如果没有设置cdn则使用baseURL拼接 //如果没有设置cdn则使用baseURL拼接
if cdn == "" { if cdn == "" {
baseUrl := beego.AppConfig.DefaultString("baseurl", "") baseUrl := web.AppConfig.DefaultString("baseurl", "")
if strings.HasPrefix(p, "/") && strings.HasSuffix(baseUrl, "/") { if strings.HasPrefix(p, "/") && strings.HasSuffix(baseUrl, "/") {
return baseUrl + p[1:] return baseUrl + p[1:]
@ -245,36 +236,36 @@ func RegisterFunction() {
return cdn + p return cdn + p
}) })
if err != nil { if err != nil {
beego.Error("注册函数 cdn 出错 ->", err) logs.Error("注册函数 cdn 出错 ->", err)
os.Exit(-1) os.Exit(-1)
} }
err = beego.AddFuncMap("cdnjs", conf.URLForWithCdnJs) err = web.AddFuncMap("cdnjs", conf.URLForWithCdnJs)
if err != nil { if err != nil {
beego.Error("注册函数 cdnjs 出错 ->", err) logs.Error("注册函数 cdnjs 出错 ->", err)
os.Exit(-1) os.Exit(-1)
} }
err = beego.AddFuncMap("cdncss", conf.URLForWithCdnCss) err = web.AddFuncMap("cdncss", conf.URLForWithCdnCss)
if err != nil { if err != nil {
beego.Error("注册函数 cdncss 出错 ->", err) logs.Error("注册函数 cdncss 出错 ->", err)
os.Exit(-1) os.Exit(-1)
} }
err = beego.AddFuncMap("cdnimg", conf.URLForWithCdnImage) err = web.AddFuncMap("cdnimg", conf.URLForWithCdnImage)
if err != nil { if err != nil {
beego.Error("注册函数 cdnimg 出错 ->", err) logs.Error("注册函数 cdnimg 出错 ->", err)
os.Exit(-1) os.Exit(-1)
} }
//重写url生成支持配置域名以及域名前缀 //重写url生成支持配置域名以及域名前缀
err = beego.AddFuncMap("urlfor", conf.URLFor) err = web.AddFuncMap("urlfor", conf.URLFor)
if err != nil { if err != nil {
beego.Error("注册函数 urlfor 出错 ->", err) logs.Error("注册函数 urlfor 出错 ->", err)
os.Exit(-1) os.Exit(-1)
} }
err = beego.AddFuncMap("date_format", func(t time.Time, format string) string { err = web.AddFuncMap("date_format", func(t time.Time, format string) string {
return t.Local().Format(format) return t.Local().Format(format)
}) })
if err != nil { if err != nil {
beego.Error("注册函数 date_format 出错 ->", err) logs.Error("注册函数 date_format 出错 ->", err)
os.Exit(-1) os.Exit(-1)
} }
} }
@ -307,11 +298,11 @@ func ResolveCommand(args []string) {
log.Fatal("读取字体文件时出错 -> ", err) log.Fatal("读取字体文件时出错 -> ", err)
} }
if err := beego.LoadAppConfig("ini", conf.ConfigurationFile); err != nil { if err := web.LoadAppConfig("ini", conf.ConfigurationFile); err != nil {
log.Fatal("An error occurred:", err) log.Fatal("An error occurred:", err)
} }
if conf.LogFile == "" { if conf.LogFile == "" {
logPath, err := filepath.Abs(beego.AppConfig.DefaultString("log_path", conf.WorkingDir("runtime", "logs"))) logPath, err := filepath.Abs(web.AppConfig.DefaultString("log_path", conf.WorkingDir("runtime", "logs")))
if err == nil { if err == nil {
conf.LogFile = logPath conf.LogFile = logPath
} else { } else {
@ -319,15 +310,15 @@ func ResolveCommand(args []string) {
} }
} }
conf.AutoLoadDelay = beego.AppConfig.DefaultInt("config_auto_delay", 0) conf.AutoLoadDelay = web.AppConfig.DefaultInt("config_auto_delay", 0)
uploads := conf.WorkingDir("uploads") uploads := conf.WorkingDir("uploads")
_ = os.MkdirAll(uploads, 0666) _ = os.MkdirAll(uploads, 0666)
beego.BConfig.WebConfig.StaticDir["/static"] = filepath.Join(conf.WorkingDirectory, "static") web.BConfig.WebConfig.StaticDir["/static"] = filepath.Join(conf.WorkingDirectory, "static")
beego.BConfig.WebConfig.StaticDir["/uploads"] = uploads web.BConfig.WebConfig.StaticDir["/uploads"] = uploads
beego.BConfig.WebConfig.ViewsPath = conf.WorkingDir("views") web.BConfig.WebConfig.ViewsPath = conf.WorkingDir("views")
beego.BConfig.WebConfig.Session.SessionCookieSameSite = http.SameSiteDefaultMode web.BConfig.WebConfig.Session.SessionCookieSameSite = http.SameSiteDefaultMode
fonts := conf.WorkingDir("static", "fonts") fonts := conf.WorkingDir("static", "fonts")
@ -349,15 +340,15 @@ func ResolveCommand(args []string) {
//注册缓存管道 //注册缓存管道
func RegisterCache() { func RegisterCache() {
isOpenCache := beego.AppConfig.DefaultBool("cache", false) isOpenCache := web.AppConfig.DefaultBool("cache", false)
if !isOpenCache { if !isOpenCache {
cache.Init(&cache.NullCache{}) cache.Init(&cache.NullCache{})
return return
} }
beego.Info("正常初始化缓存配置.") logs.Info("正常初始化缓存配置.")
cacheProvider := beego.AppConfig.String("cache_provider") cacheProvider, _ := web.AppConfig.String("cache_provider")
if cacheProvider == "file" { if cacheProvider == "file" {
cacheFilePath := beego.AppConfig.DefaultString("cache_file_path", "./runtime/cache/") cacheFilePath := web.AppConfig.DefaultString("cache_file_path", "./runtime/cache/")
if strings.HasPrefix(cacheFilePath, "./") { if strings.HasPrefix(cacheFilePath, "./") {
cacheFilePath = filepath.Join(conf.WorkingDirectory, string(cacheFilePath[1:])) cacheFilePath = filepath.Join(conf.WorkingDirectory, string(cacheFilePath[1:]))
} }
@ -366,13 +357,13 @@ func RegisterCache() {
fileConfig := make(map[string]string, 0) fileConfig := make(map[string]string, 0)
fileConfig["CachePath"] = cacheFilePath fileConfig["CachePath"] = cacheFilePath
fileConfig["DirectoryLevel"] = beego.AppConfig.DefaultString("cache_file_dir_level", "2") fileConfig["DirectoryLevel"] = web.AppConfig.DefaultString("cache_file_dir_level", "2")
fileConfig["EmbedExpiry"] = beego.AppConfig.DefaultString("cache_file_expiry", "120") fileConfig["EmbedExpiry"] = web.AppConfig.DefaultString("cache_file_expiry", "120")
fileConfig["FileSuffix"] = beego.AppConfig.DefaultString("cache_file_suffix", ".bin") fileConfig["FileSuffix"] = web.AppConfig.DefaultString("cache_file_suffix", ".bin")
bc, err := json.Marshal(&fileConfig) bc, err := json.Marshal(&fileConfig)
if err != nil { if err != nil {
beego.Error("初始化file缓存失败:", err) logs.Error("初始化file缓存失败:", err)
os.Exit(1) os.Exit(1)
} }
@ -381,13 +372,13 @@ func RegisterCache() {
cache.Init(fileCache) cache.Init(fileCache)
} else if cacheProvider == "memory" { } else if cacheProvider == "memory" {
cacheInterval := beego.AppConfig.DefaultInt("cache_memory_interval", 60) cacheInterval := web.AppConfig.DefaultInt("cache_memory_interval", 60)
memory := beegoCache.NewMemoryCache() memory := beegoCache.NewMemoryCache()
beegoCache.DefaultEvery = cacheInterval beegoCache.DefaultEvery = cacheInterval
cache.Init(memory) cache.Init(memory)
} else if cacheProvider == "redis" { } else if cacheProvider == "redis" {
//设置Redis前缀 //设置Redis前缀
if key := beego.AppConfig.DefaultString("cache_redis_prefix", ""); key != "" { if key := web.AppConfig.DefaultString("cache_redis_prefix", ""); key != "" {
redis.DefaultKey = key redis.DefaultKey = key
} }
var redisConfig struct { var redisConfig struct {
@ -396,23 +387,23 @@ func RegisterCache() {
DbNum int `json:"dbNum"` DbNum int `json:"dbNum"`
} }
redisConfig.DbNum = 0 redisConfig.DbNum = 0
redisConfig.Conn = beego.AppConfig.DefaultString("cache_redis_host", "") redisConfig.Conn = web.AppConfig.DefaultString("cache_redis_host", "")
if pwd := beego.AppConfig.DefaultString("cache_redis_password", ""); pwd != "" { if pwd := web.AppConfig.DefaultString("cache_redis_password", ""); pwd != "" {
redisConfig.Password = pwd redisConfig.Password = pwd
} }
if dbNum := beego.AppConfig.DefaultInt("cache_redis_db", 0); dbNum > 0 { if dbNum := web.AppConfig.DefaultInt("cache_redis_db", 0); dbNum > 0 {
redisConfig.DbNum = dbNum redisConfig.DbNum = dbNum
} }
bc, err := json.Marshal(&redisConfig) bc, err := json.Marshal(&redisConfig)
if err != nil { if err != nil {
beego.Error("初始化Redis缓存失败:", err) logs.Error("初始化Redis缓存失败:", err)
os.Exit(1) os.Exit(1)
} }
redisCache, err := beegoCache.NewCache("redis", string(bc)) redisCache, err := beegoCache.NewCache("redis", string(bc))
if err != nil { if err != nil {
beego.Error("初始化Redis缓存失败:", err) logs.Error("初始化Redis缓存失败:", err)
os.Exit(1) os.Exit(1)
} }
@ -422,17 +413,17 @@ func RegisterCache() {
var memcacheConfig struct { var memcacheConfig struct {
Conn string `json:"conn"` Conn string `json:"conn"`
} }
memcacheConfig.Conn = beego.AppConfig.DefaultString("cache_memcache_host", "") memcacheConfig.Conn = web.AppConfig.DefaultString("cache_memcache_host", "")
bc, err := json.Marshal(&memcacheConfig) bc, err := json.Marshal(&memcacheConfig)
if err != nil { if err != nil {
beego.Error("初始化 Memcache 缓存失败 ->", err) logs.Error("初始化 Memcache 缓存失败 ->", err)
os.Exit(1) os.Exit(1)
} }
memcache, err := beegoCache.NewCache("memcache", string(bc)) memcache, err := beegoCache.NewCache("memcache", string(bc))
if err != nil { if err != nil {
beego.Error("初始化 Memcache 缓存失败 ->", err) logs.Error("初始化 Memcache 缓存失败 ->", err)
os.Exit(1) os.Exit(1)
} }
@ -440,10 +431,10 @@ func RegisterCache() {
} else { } else {
cache.Init(&cache.NullCache{}) cache.Init(&cache.NullCache{})
beego.Warn("不支持的缓存管道,缓存将禁用 ->", cacheProvider) logs.Warn("不支持的缓存管道,缓存将禁用 ->", cacheProvider)
return return
} }
beego.Info("缓存初始化完成.") logs.Info("缓存初始化完成.")
} }
//自动加载配置文件.修改了监听端口号和数据库配置无法自动生效. //自动加载配置文件.修改了监听端口号和数据库配置无法自动生效.
@ -453,7 +444,7 @@ func RegisterAutoLoadConfig() {
watcher, err := fsnotify.NewWatcher() watcher, err := fsnotify.NewWatcher()
if err != nil { if err != nil {
beego.Error("创建配置文件监控器失败 ->", err) logs.Error("创建配置文件监控器失败 ->", err)
} }
go func() { go func() {
for { for {
@ -461,19 +452,19 @@ func RegisterAutoLoadConfig() {
case ev := <-watcher.Event: case ev := <-watcher.Event:
//如果是修改了配置文件 //如果是修改了配置文件
if ev.IsModify() { if ev.IsModify() {
if err := beego.LoadAppConfig("ini", conf.ConfigurationFile); err != nil { if err := web.LoadAppConfig("ini", conf.ConfigurationFile); err != nil {
beego.Error("An error occurred ->", err) logs.Error("An error occurred ->", err)
continue continue
} }
RegisterCache() RegisterCache()
RegisterLogger("") RegisterLogger("")
beego.Info("配置文件已加载 ->", conf.ConfigurationFile) logs.Info("配置文件已加载 ->", conf.ConfigurationFile)
} else if ev.IsRename() { } else if ev.IsRename() {
_ = watcher.WatchFlags(conf.ConfigurationFile, fsnotify.FSN_MODIFY|fsnotify.FSN_RENAME) _ = watcher.WatchFlags(conf.ConfigurationFile, fsnotify.FSN_MODIFY|fsnotify.FSN_RENAME)
} }
beego.Info(ev.String()) logs.Info(ev.String())
case err := <-watcher.Error: case err := <-watcher.Error:
beego.Error("配置文件监控器错误 ->", err) logs.Error("配置文件监控器错误 ->", err)
} }
} }
@ -482,34 +473,34 @@ func RegisterAutoLoadConfig() {
err = watcher.WatchFlags(conf.ConfigurationFile, fsnotify.FSN_MODIFY|fsnotify.FSN_RENAME) err = watcher.WatchFlags(conf.ConfigurationFile, fsnotify.FSN_MODIFY|fsnotify.FSN_RENAME)
if err != nil { if err != nil {
beego.Error("监控配置文件失败 ->", err) logs.Error("监控配置文件失败 ->", err)
} }
} }
} }
//注册错误处理方法. //注册错误处理方法.
func RegisterError() { func RegisterError() {
beego.ErrorHandler("404", func(writer http.ResponseWriter, request *http.Request) { web.ErrorHandler("404", func(writer http.ResponseWriter, request *http.Request) {
var buf bytes.Buffer var buf bytes.Buffer
data := make(map[string]interface{}) data := make(map[string]interface{})
data["ErrorCode"] = 404 data["ErrorCode"] = 404
data["ErrorMessage"] = "页面未找到或已删除" data["ErrorMessage"] = "页面未找到或已删除"
if err := beego.ExecuteViewPathTemplate(&buf, "errors/error.tpl", beego.BConfig.WebConfig.ViewsPath, data); err == nil { if err := web.ExecuteViewPathTemplate(&buf, "errors/error.tpl", web.BConfig.WebConfig.ViewsPath, data); err == nil {
_, _ = fmt.Fprint(writer, buf.String()) _, _ = fmt.Fprint(writer, buf.String())
} else { } else {
_, _ = fmt.Fprint(writer, data["ErrorMessage"]) _, _ = fmt.Fprint(writer, data["ErrorMessage"])
} }
}) })
beego.ErrorHandler("401", func(writer http.ResponseWriter, request *http.Request) { web.ErrorHandler("401", func(writer http.ResponseWriter, request *http.Request) {
var buf bytes.Buffer var buf bytes.Buffer
data := make(map[string]interface{}) data := make(map[string]interface{})
data["ErrorCode"] = 401 data["ErrorCode"] = 401
data["ErrorMessage"] = "请与 Web 服务器的管理员联系,以确认您是否具有访问所请求资源的权限。" data["ErrorMessage"] = "请与 Web 服务器的管理员联系,以确认您是否具有访问所请求资源的权限。"
if err := beego.ExecuteViewPathTemplate(&buf, "errors/error.tpl", beego.BConfig.WebConfig.ViewsPath, data); err == nil { if err := web.ExecuteViewPathTemplate(&buf, "errors/error.tpl", web.BConfig.WebConfig.ViewsPath, data); err == nil {
_, _ = fmt.Fprint(writer, buf.String()) _, _ = fmt.Fprint(writer, buf.String())
} else { } else {
_, _ = fmt.Fprint(writer, data["ErrorMessage"]) _, _ = fmt.Fprint(writer, data["ErrorMessage"])

View File

@ -6,7 +6,8 @@ import (
"path/filepath" "path/filepath"
"github.com/astaxie/beego" "github.com/beego/beego/v2/core/logs"
"github.com/beego/beego/v2/server/web"
"github.com/kardianos/service" "github.com/kardianos/service"
"github.com/mindoc-org/mindoc/commands" "github.com/mindoc-org/mindoc/commands"
"github.com/mindoc-org/mindoc/conf" "github.com/mindoc-org/mindoc/conf"
@ -53,7 +54,7 @@ func (d *Daemon) Run() {
commands.RegisterError() commands.RegisterError()
beego.ErrorController(&controllers.ErrorController{}) web.ErrorController(&controllers.ErrorController{})
f, err := filepath.Abs(os.Args[0]) f, err := filepath.Abs(os.Args[0])
@ -63,7 +64,7 @@ func (d *Daemon) Run() {
fmt.Printf("MinDoc version => %s\nbuild time => %s\nstart directory => %s\n%s\n", conf.VERSION, conf.BUILD_TIME, f, conf.GO_VERSION) fmt.Printf("MinDoc version => %s\nbuild time => %s\nstart directory => %s\n%s\n", conf.VERSION, conf.BUILD_TIME, f, conf.GO_VERSION)
beego.Run() web.Run()
} }
func (d *Daemon) Stop(s service.Service) error { func (d *Daemon) Stop(s service.Service) error {
@ -80,15 +81,15 @@ func Install() {
s, err := service.New(d, d.config) s, err := service.New(d, d.config)
if err != nil { if err != nil {
beego.Error("Create service error => ", err) logs.Error("Create service error => ", err)
os.Exit(1) os.Exit(1)
} }
err = s.Install() err = s.Install()
if err != nil { if err != nil {
beego.Error("Install service error:", err) logs.Error("Install service error:", err)
os.Exit(1) os.Exit(1)
} else { } else {
beego.Info("Service installed!") logs.Info("Service installed!")
} }
os.Exit(0) os.Exit(0)
@ -99,15 +100,15 @@ func Uninstall() {
s, err := service.New(d, d.config) s, err := service.New(d, d.config)
if err != nil { if err != nil {
beego.Error("Create service error => ", err) logs.Error("Create service error => ", err)
os.Exit(1) os.Exit(1)
} }
err = s.Uninstall() err = s.Uninstall()
if err != nil { if err != nil {
beego.Error("Install service error:", err) logs.Error("Install service error:", err)
os.Exit(1) os.Exit(1)
} else { } else {
beego.Info("Service uninstalled!") logs.Info("Service uninstalled!")
} }
os.Exit(0) os.Exit(0)
} }
@ -117,15 +118,15 @@ func Restart() {
s, err := service.New(d, d.config) s, err := service.New(d, d.config)
if err != nil { if err != nil {
beego.Error("Create service error => ", err) logs.Error("Create service error => ", err)
os.Exit(1) os.Exit(1)
} }
err = s.Restart() err = s.Restart()
if err != nil { if err != nil {
beego.Error("Install service error:", err) logs.Error("Install service error:", err)
os.Exit(1) os.Exit(1)
} else { } else {
beego.Info("Service Restart!") logs.Info("Service Restart!")
} }
os.Exit(0) os.Exit(0)
} }

View File

@ -1,14 +1,15 @@
package commands package commands
import ( import (
"errors"
"fmt" "fmt"
"os" "os"
"time" "time"
"flag" "flag"
"github.com/astaxie/beego" "github.com/beego/beego/v2/client/orm"
"github.com/astaxie/beego/orm" "github.com/beego/beego/v2/core/logs"
"github.com/mindoc-org/mindoc/conf" "github.com/mindoc-org/mindoc/conf"
"github.com/mindoc-org/mindoc/models" "github.com/mindoc-org/mindoc/models"
"github.com/mindoc-org/mindoc/utils" "github.com/mindoc-org/mindoc/utils"
@ -24,7 +25,6 @@ func Install() {
initialization() initialization()
} else { } else {
panic(err.Error()) panic(err.Error())
os.Exit(1)
} }
fmt.Println("Install Successfully!") fmt.Println("Install Successfully!")
os.Exit(0) os.Exit(0)
@ -40,7 +40,7 @@ func Version() {
//修改用户密码 //修改用户密码
func ModifyPassword() { func ModifyPassword() {
var account,password string var account, password string
//账号和密码需要解析参数后才能获取 //账号和密码需要解析参数后才能获取
if len(os.Args) >= 2 && os.Args[1] == "password" { if len(os.Args) >= 2 && os.Args[1] == "password" {
@ -50,7 +50,7 @@ func ModifyPassword() {
flagSet.StringVar(&password, "password", "", "用户密码.") flagSet.StringVar(&password, "password", "", "用户密码.")
if err := flagSet.Parse(os.Args[2:]); err != nil { if err := flagSet.Parse(os.Args[2:]); err != nil {
beego.Error("解析参数失败 -> ",err) logs.Error("解析参数失败 -> ", err)
os.Exit(1) os.Exit(1)
} }
@ -67,30 +67,29 @@ func ModifyPassword() {
fmt.Println("Password cannot be empty.") fmt.Println("Password cannot be empty.")
os.Exit(1) os.Exit(1)
} }
member,err := models.NewMember().FindByAccount(account) member, err := models.NewMember().FindByAccount(account)
if err != nil { if err != nil {
fmt.Println("Failed to change password:",err) fmt.Println("Failed to change password:", err)
os.Exit(1) os.Exit(1)
} }
pwd,err := utils.PasswordHash(password) pwd, err := utils.PasswordHash(password)
if err != nil { if err != nil {
fmt.Println("Failed to change password:",err) fmt.Println("Failed to change password:", err)
os.Exit(1) os.Exit(1)
} }
member.Password = pwd member.Password = pwd
err = member.Update("password") err = member.Update("password")
if err != nil { if err != nil {
fmt.Println("Failed to change password:",err) fmt.Println("Failed to change password:", err)
os.Exit(1) os.Exit(1)
} }
fmt.Println("Successfully modified.") fmt.Println("Successfully modified.")
os.Exit(0) os.Exit(0)
} }
} }
//初始化数据 //初始化数据
@ -100,24 +99,26 @@ func initialization() {
if err != nil { if err != nil {
panic(err.Error()) panic(err.Error())
os.Exit(1)
} }
member, err := models.NewMember().FindByFieldFirst("account", "admin") member, err := models.NewMember().FindByFieldFirst("account", "admin")
if err == orm.ErrNoRows { if errors.Is(err, orm.ErrNoRows) {
// create admin user
logs.Info("creating admin user")
member.Account = "admin" member.Account = "admin"
member.Avatar = conf.URLForWithCdnImage("/static/images/headimgurl.jpg") member.Avatar = conf.URLForWithCdnImage("/static/images/headimgurl.jpg")
member.Password = "123456" member.Password = "123456"
member.AuthMethod = "local" member.AuthMethod = "local"
member.Role = 0 member.Role = conf.MemberSuperRole
member.Email = "admin@iminho.me" member.Email = "admin@iminho.me"
if err := member.Add(); err != nil { if err := member.Add(); err != nil {
panic("Member.Add => " + err.Error()) panic("Member.Add => " + err.Error())
os.Exit(0)
} }
// create demo book
logs.Info("creating demo book")
book := models.NewBook() book := models.NewBook()
book.MemberId = member.MemberId book.MemberId = member.MemberId
@ -138,8 +139,9 @@ func initialization() {
if err := book.Insert(); err != nil { if err := book.Insert(); err != nil {
panic("初始化项目失败 -> " + err.Error()) panic("初始化项目失败 -> " + err.Error())
os.Exit(1)
} }
} else if err != nil {
panic(fmt.Errorf("occur errors when initialize: %s", err))
} }
if !models.NewItemsets().Exist(1) { if !models.NewItemsets().Exist(1) {
@ -148,7 +150,6 @@ func initialization() {
item.MemberId = 1 item.MemberId = 1
if err := item.Save(); err != nil { if err := item.Save(); err != nil {
panic("初始化项目空间失败 -> " + err.Error()) panic("初始化项目空间失败 -> " + err.Error())
os.Exit(1)
} }
} }
} }

View File

@ -11,6 +11,7 @@
// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
// License for the specific language governing permissions and limitations // License for the specific language governing permissions and limitations
// under the License. // under the License.
package migrate package migrate
import ( import (
@ -20,8 +21,8 @@ import (
"fmt" "fmt"
"log" "log"
"github.com/astaxie/beego" "github.com/beego/beego/v2/client/orm"
"github.com/astaxie/beego/orm" "github.com/beego/beego/v2/server/web"
"github.com/mindoc-org/mindoc/models" "github.com/mindoc-org/mindoc/models"
) )
@ -113,17 +114,17 @@ func RunMigration() {
//导出数据库的表结构 //导出数据库的表结构
func ExportDatabaseTable() ([]string, error) { func ExportDatabaseTable() ([]string, error) {
db_adapter := beego.AppConfig.String("db_adapter") dbadapter, _ := web.AppConfig.String("db_adapter")
db_database := beego.AppConfig.String("db_database") dbdatabase, _ := web.AppConfig.String("db_database")
tables := make([]string, 0) tables := make([]string, 0)
o := orm.NewOrm() o := orm.NewOrm()
switch db_adapter { switch dbadapter {
case "mysql": case "mysql":
{ {
var lists []orm.Params var lists []orm.Params
_, err := o.Raw(fmt.Sprintf("SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = '%s'", db_database)).Values(&lists) _, err := o.Raw(fmt.Sprintf("SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = '%s'", dbdatabase)).Values(&lists)
if err != nil { if err != nil {
return tables, err return tables, err
} }

View File

@ -6,7 +6,7 @@ import (
"strings" "strings"
"time" "time"
"github.com/astaxie/beego/orm" "github.com/beego/beego/v2/client/orm"
"github.com/mindoc-org/mindoc/models" "github.com/mindoc-org/mindoc/models"
) )

View File

@ -7,7 +7,7 @@ import (
"net/http" "net/http"
"os" "os"
"github.com/astaxie/beego" "github.com/beego/beego/v2/core/logs"
"github.com/mindoc-org/mindoc/conf" "github.com/mindoc-org/mindoc/conf"
) )
@ -17,14 +17,14 @@ func CheckUpdate() {
resp, err := http.Get("https://api.github.com/repos/lifei6671/mindoc/tags") resp, err := http.Get("https://api.github.com/repos/lifei6671/mindoc/tags")
if err != nil { if err != nil {
beego.Error("CheckUpdate => ", err) logs.Error("CheckUpdate => ", err)
os.Exit(1) os.Exit(1)
} }
defer resp.Body.Close() defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body) body, err := ioutil.ReadAll(resp.Body)
if err != nil { if err != nil {
beego.Error("CheckUpdate => ", err) logs.Error("CheckUpdate => ", err)
os.Exit(1) os.Exit(1)
} }
@ -35,7 +35,7 @@ func CheckUpdate() {
err = json.Unmarshal(body, &result) err = json.Unmarshal(body, &result)
fmt.Println("MinDoc current version => ", conf.VERSION) fmt.Println("MinDoc current version => ", conf.VERSION)
if err != nil { if err != nil {
beego.Error("CheckUpdate => ", err) logs.Error("CheckUpdate => ", err)
os.Exit(0) os.Exit(0)
} }

View File

@ -7,7 +7,7 @@ runmode = "${MINDOC_RUN_MODE||dev}"
sessionon = true sessionon = true
sessionname = mindoc_id sessionname = mindoc_id
copyrequestbody = true copyrequestbody = true
enablexsrf = "${MINDOC_ENABLE_XSRF||true}" enablexsrf = "${MINDOC_ENABLE_XSRF||false}"
#系统完整URL(http://doc.iminho.me),如果该项不设置,会从请求头中获取地址。 #系统完整URL(http://doc.iminho.me),如果该项不设置,会从请求头中获取地址。
baseurl="${MINDOC_BASE_URL}" baseurl="${MINDOC_BASE_URL}"

View File

@ -9,7 +9,7 @@ import (
"path/filepath" "path/filepath"
"strconv" "strconv"
"github.com/astaxie/beego" "github.com/beego/beego/v2/server/web"
) )
// 登录用户的Session名 // 登录用户的Session名
@ -81,32 +81,32 @@ var (
// app_key // app_key
func GetAppKey() string { func GetAppKey() string {
return beego.AppConfig.DefaultString("app_key", "mindoc") return web.AppConfig.DefaultString("app_key", "mindoc")
} }
func GetDatabasePrefix() string { func GetDatabasePrefix() string {
return beego.AppConfig.DefaultString("db_prefix", "md_") return web.AppConfig.DefaultString("db_prefix", "md_")
} }
//获取默认头像 //获取默认头像
func GetDefaultAvatar() string { func GetDefaultAvatar() string {
return URLForWithCdnImage(beego.AppConfig.DefaultString("avatar", "/static/images/headimgurl.jpg")) return URLForWithCdnImage(web.AppConfig.DefaultString("avatar", "/static/images/headimgurl.jpg"))
} }
//获取阅读令牌长度. //获取阅读令牌长度.
func GetTokenSize() int { func GetTokenSize() int {
return beego.AppConfig.DefaultInt("token_size", 12) return web.AppConfig.DefaultInt("token_size", 12)
} }
//获取默认文档封面. //获取默认文档封面.
func GetDefaultCover() string { func GetDefaultCover() string {
return URLForWithCdnImage(beego.AppConfig.DefaultString("cover", "/static/images/book.jpg")) return URLForWithCdnImage(web.AppConfig.DefaultString("cover", "/static/images/book.jpg"))
} }
//获取允许的商城文件的类型. //获取允许的商城文件的类型.
func GetUploadFileExt() []string { func GetUploadFileExt() []string {
ext := beego.AppConfig.DefaultString("upload_file_ext", "png|jpg|jpeg|gif|txt|doc|docx|pdf") ext := web.AppConfig.DefaultString("upload_file_ext", "png|jpg|jpeg|gif|txt|doc|docx|pdf")
temp := strings.Split(ext, "|") temp := strings.Split(ext, "|")
@ -124,7 +124,7 @@ func GetUploadFileExt() []string {
// 获取上传文件允许的最大值 // 获取上传文件允许的最大值
func GetUploadFileSize() int64 { func GetUploadFileSize() int64 {
size := beego.AppConfig.DefaultString("upload_file_size", "0") size := web.AppConfig.DefaultString("upload_file_size", "0")
if strings.HasSuffix(size, "MB") { if strings.HasSuffix(size, "MB") {
if s, e := strconv.ParseInt(size[0:len(size)-2], 10, 64); e == nil { if s, e := strconv.ParseInt(size[0:len(size)-2], 10, 64); e == nil {
@ -149,12 +149,12 @@ func GetUploadFileSize() int64 {
//是否启用导出 //是否启用导出
func GetEnableExport() bool { func GetEnableExport() bool {
return beego.AppConfig.DefaultBool("enable_export", true) return web.AppConfig.DefaultBool("enable_export", true)
} }
//同一项目导出线程的并发数 //同一项目导出线程的并发数
func GetExportProcessNum() int { func GetExportProcessNum() int {
exportProcessNum := beego.AppConfig.DefaultInt("export_process_num", 1) exportProcessNum := web.AppConfig.DefaultInt("export_process_num", 1)
if exportProcessNum <= 0 || exportProcessNum > 4 { if exportProcessNum <= 0 || exportProcessNum > 4 {
exportProcessNum = 1 exportProcessNum = 1
@ -164,7 +164,7 @@ func GetExportProcessNum() int {
//导出项目队列的并发数量 //导出项目队列的并发数量
func GetExportLimitNum() int { func GetExportLimitNum() int {
exportLimitNum := beego.AppConfig.DefaultInt("export_limit_num", 1) exportLimitNum := web.AppConfig.DefaultInt("export_limit_num", 1)
if exportLimitNum < 0 { if exportLimitNum < 0 {
exportLimitNum = 1 exportLimitNum = 1
@ -174,7 +174,7 @@ func GetExportLimitNum() int {
//等待导出队列的长度 //等待导出队列的长度
func GetExportQueueLimitNum() int { func GetExportQueueLimitNum() int {
exportQueueLimitNum := beego.AppConfig.DefaultInt("export_queue_limit_num", 10) exportQueueLimitNum := web.AppConfig.DefaultInt("export_queue_limit_num", 10)
if exportQueueLimitNum <= 0 { if exportQueueLimitNum <= 0 {
exportQueueLimitNum = 100 exportQueueLimitNum = 100
@ -184,7 +184,7 @@ func GetExportQueueLimitNum() int {
//默认导出项目的缓存目录 //默认导出项目的缓存目录
func GetExportOutputPath() string { func GetExportOutputPath() string {
exportOutputPath := filepath.Join(beego.AppConfig.DefaultString("export_output_path", filepath.Join(WorkingDirectory, "cache")), "books") exportOutputPath := filepath.Join(web.AppConfig.DefaultString("export_output_path", filepath.Join(WorkingDirectory, "cache")), "books")
return exportOutputPath return exportOutputPath
} }
@ -210,8 +210,8 @@ func IsAllowUploadFileExt(ext string) bool {
//重写生成URL的方法加上完整的域名 //重写生成URL的方法加上完整的域名
func URLFor(endpoint string, values ...interface{}) string { func URLFor(endpoint string, values ...interface{}) string {
baseUrl := beego.AppConfig.DefaultString("baseurl", "") baseUrl := web.AppConfig.DefaultString("baseurl", "")
pathUrl := beego.URLFor(endpoint, values...) pathUrl := web.URLFor(endpoint, values...)
if baseUrl == "" { if baseUrl == "" {
baseUrl = BaseUrl baseUrl = BaseUrl
@ -225,12 +225,12 @@ func URLFor(endpoint string, values ...interface{}) string {
if !strings.HasPrefix(pathUrl, "/") && !strings.HasSuffix(baseUrl, "/") { if !strings.HasPrefix(pathUrl, "/") && !strings.HasSuffix(baseUrl, "/") {
return baseUrl + "/" + pathUrl return baseUrl + "/" + pathUrl
} }
return baseUrl + beego.URLFor(endpoint, values...) return baseUrl + web.URLFor(endpoint, values...)
} }
func URLForNotHost(endpoint string, values ...interface{}) string { func URLForNotHost(endpoint string, values ...interface{}) string {
baseUrl := beego.AppConfig.DefaultString("baseurl", "") baseUrl := web.AppConfig.DefaultString("baseurl", "")
pathUrl := beego.URLFor(endpoint, values...) pathUrl := web.URLFor(endpoint, values...)
if baseUrl == "" { if baseUrl == "" {
baseUrl = "/" baseUrl = "/"
@ -244,17 +244,17 @@ func URLForNotHost(endpoint string, values ...interface{}) string {
if !strings.HasPrefix(pathUrl, "/") && !strings.HasSuffix(baseUrl, "/") { if !strings.HasPrefix(pathUrl, "/") && !strings.HasSuffix(baseUrl, "/") {
return baseUrl + "/" + pathUrl return baseUrl + "/" + pathUrl
} }
return baseUrl + beego.URLFor(endpoint, values...) return baseUrl + web.URLFor(endpoint, values...)
} }
func URLForWithCdnImage(p string) string { func URLForWithCdnImage(p string) string {
if strings.HasPrefix(p, "http://") || strings.HasPrefix(p, "https://") { if strings.HasPrefix(p, "http://") || strings.HasPrefix(p, "https://") {
return p return p
} }
cdn := beego.AppConfig.DefaultString("cdnimg", "") cdn := web.AppConfig.DefaultString("cdnimg", "")
//如果没有设置cdn则使用baseURL拼接 //如果没有设置cdn则使用baseURL拼接
if cdn == "" { if cdn == "" {
baseUrl := beego.AppConfig.DefaultString("baseurl", "/") baseUrl := web.AppConfig.DefaultString("baseurl", "/")
if strings.HasPrefix(p, "/") && strings.HasSuffix(baseUrl, "/") { if strings.HasPrefix(p, "/") && strings.HasSuffix(baseUrl, "/") {
return baseUrl + p[1:] return baseUrl + p[1:]
@ -274,7 +274,7 @@ func URLForWithCdnImage(p string) string {
} }
func URLForWithCdnCss(p string, v ...string) string { func URLForWithCdnCss(p string, v ...string) string {
cdn := beego.AppConfig.DefaultString("cdncss", "") cdn := web.AppConfig.DefaultString("cdncss", "")
if strings.HasPrefix(p, "http://") || strings.HasPrefix(p, "https://") { if strings.HasPrefix(p, "http://") || strings.HasPrefix(p, "https://") {
return p return p
} }
@ -285,7 +285,7 @@ func URLForWithCdnCss(p string, v ...string) string {
} }
//如果没有设置cdn则使用baseURL拼接 //如果没有设置cdn则使用baseURL拼接
if cdn == "" { if cdn == "" {
baseUrl := beego.AppConfig.DefaultString("baseurl", "/") baseUrl := web.AppConfig.DefaultString("baseurl", "/")
if strings.HasPrefix(p, "/") && strings.HasSuffix(baseUrl, "/") { if strings.HasPrefix(p, "/") && strings.HasSuffix(baseUrl, "/") {
return baseUrl + p[1:] return baseUrl + p[1:]
@ -305,7 +305,7 @@ func URLForWithCdnCss(p string, v ...string) string {
} }
func URLForWithCdnJs(p string, v ...string) string { func URLForWithCdnJs(p string, v ...string) string {
cdn := beego.AppConfig.DefaultString("cdnjs", "") cdn := web.AppConfig.DefaultString("cdnjs", "")
if strings.HasPrefix(p, "http://") || strings.HasPrefix(p, "https://") { if strings.HasPrefix(p, "http://") || strings.HasPrefix(p, "https://") {
return p return p
} }
@ -318,7 +318,7 @@ func URLForWithCdnJs(p string, v ...string) string {
//如果没有设置cdn则使用baseURL拼接 //如果没有设置cdn则使用baseURL拼接
if cdn == "" { if cdn == "" {
baseUrl := beego.AppConfig.DefaultString("baseurl", "/") baseUrl := web.AppConfig.DefaultString("baseurl", "/")
if strings.HasPrefix(p, "/") && strings.HasSuffix(baseUrl, "/") { if strings.HasPrefix(p, "/") && strings.HasSuffix(baseUrl, "/") {
return baseUrl + p[1:] return baseUrl + p[1:]

View File

@ -1,8 +1,9 @@
package conf package conf
import ( import (
"github.com/astaxie/beego"
"strings" "strings"
"github.com/beego/beego/v2/server/web"
) )
type SmtpConf struct { type SmtpConf struct {
@ -14,18 +15,18 @@ type SmtpConf struct {
SmtpPort int SmtpPort int
FormUserName string FormUserName string
MailExpired int MailExpired int
Secure string Secure string
} }
func GetMailConfig() *SmtpConf { func GetMailConfig() *SmtpConf {
user_name := beego.AppConfig.String("smtp_user_name") user_name, _ := web.AppConfig.String("smtp_user_name")
password := beego.AppConfig.String("smtp_password") password, _ := web.AppConfig.String("smtp_password")
smtp_host := beego.AppConfig.String("smtp_host") smtp_host, _ := web.AppConfig.String("smtp_host")
smtp_port := beego.AppConfig.DefaultInt("smtp_port", 25) smtp_port := web.AppConfig.DefaultInt("smtp_port", 25)
form_user_name := beego.AppConfig.String("form_user_name") form_user_name, _ := web.AppConfig.String("form_user_name")
enable_mail := beego.AppConfig.String("enable_mail") enable_mail, _ := web.AppConfig.String("enable_mail")
mail_number := beego.AppConfig.DefaultInt("mail_number", 5) mail_number := web.AppConfig.DefaultInt("mail_number", 5)
secure := beego.AppConfig.DefaultString("secure","NONE") secure := web.AppConfig.DefaultString("secure", "NONE")
if secure != "NONE" && secure != "LOGIN" && secure != "SSL" { if secure != "NONE" && secure != "LOGIN" && secure != "SSL" {
secure = "NONE" secure = "NONE"
@ -38,7 +39,7 @@ func GetMailConfig() *SmtpConf {
SmtpPassword: password, SmtpPassword: password,
FormUserName: form_user_name, FormUserName: form_user_name,
SmtpPort: smtp_port, SmtpPort: smtp_port,
Secure:secure, Secure: secure,
} }
return c return c
} }

View File

@ -8,7 +8,8 @@ import (
"html/template" "html/template"
"github.com/astaxie/beego" "github.com/beego/beego/v2/core/logs"
"github.com/beego/beego/v2/server/web"
"github.com/lifei6671/gocaptcha" "github.com/lifei6671/gocaptcha"
"github.com/mindoc-org/mindoc/conf" "github.com/mindoc-org/mindoc/conf"
"github.com/mindoc-org/mindoc/mail" "github.com/mindoc-org/mindoc/mail"
@ -32,12 +33,14 @@ func (c *AccountController) referer() string {
func (c *AccountController) Prepare() { func (c *AccountController) Prepare() {
c.BaseController.Prepare() c.BaseController.Prepare()
c.EnableXSRF = beego.AppConfig.DefaultBool("enablexsrf", true) c.EnableXSRF = web.AppConfig.DefaultBool("enablexsrf", true)
c.Data["xsrfdata"] = template.HTML(c.XSRFFormHTML()) c.Data["xsrfdata"] = template.HTML(c.XSRFFormHTML())
c.Data["corpID"] = beego.AppConfig.String("dingtalk_corpid") c.Data["corpID"], _ = web.AppConfig.String("dingtalk_corpid")
c.Data["ENABLE_QR_DINGTALK"] = (beego.AppConfig.String("dingtalk_corpid") != "") if dtcorpid, _ := web.AppConfig.String("dingtalk_corpid"); dtcorpid != "" {
c.Data["dingtalk_qr_key"] = beego.AppConfig.String("dingtalk_qr_key") c.Data["ENABLE_QR_DINGTALK"] = true
}
c.Data["dingtalk_qr_key"], _ = web.AppConfig.String("dingtalk_qr_key")
if !c.EnableXSRF { if !c.EnableXSRF {
return return
@ -133,7 +136,7 @@ func (c *AccountController) Login() {
c.JsonResult(0, "ok", c.referer()) c.JsonResult(0, "ok", c.referer())
} else { } else {
beego.Error("用户登录 ->", err) logs.Error("用户登录 ->", err)
c.JsonResult(500, "账号或密码错误", nil) c.JsonResult(500, "账号或密码错误", nil)
} }
} else { } else {
@ -150,9 +153,9 @@ func (c *AccountController) DingTalkLogin() {
c.JsonResult(500, "获取身份信息失败", nil) c.JsonResult(500, "获取身份信息失败", nil)
} }
appKey := beego.AppConfig.String("dingtalk_app_key") appKey, _ := web.AppConfig.String("dingtalk_app_key")
appSecret := beego.AppConfig.String("dingtalk_app_secret") appSecret, _ := web.AppConfig.String("dingtalk_app_secret")
tmpReader := beego.AppConfig.String("dingtalk_tmp_reader") tmpReader, _ := web.AppConfig.String("dingtalk_tmp_reader")
if appKey == "" || appSecret == "" || tmpReader == "" { if appKey == "" || appSecret == "" || tmpReader == "" {
c.JsonResult(500, "未开启钉钉自动登录功能", nil) c.JsonResult(500, "未开启钉钉自动登录功能", nil)
@ -162,21 +165,21 @@ func (c *AccountController) DingTalkLogin() {
dingtalkAgent := dingtalk.NewDingTalkAgent(appSecret, appKey) dingtalkAgent := dingtalk.NewDingTalkAgent(appSecret, appKey)
err := dingtalkAgent.GetAccesstoken() err := dingtalkAgent.GetAccesstoken()
if err != nil { if err != nil {
beego.Warn("获取钉钉临时Token失败 ->", err) logs.Warn("获取钉钉临时Token失败 ->", err)
c.JsonResult(500, "自动登录失败", nil) c.JsonResult(500, "自动登录失败", nil)
c.StopRun() c.StopRun()
} }
userid, err := dingtalkAgent.GetUserIDByCode(code) userid, err := dingtalkAgent.GetUserIDByCode(code)
if err != nil { if err != nil {
beego.Warn("获取钉钉用户ID失败 ->", err) logs.Warn("获取钉钉用户ID失败 ->", err)
c.JsonResult(500, "自动登录失败", nil) c.JsonResult(500, "自动登录失败", nil)
c.StopRun() c.StopRun()
} }
username, avatar, err := dingtalkAgent.GetUserNameAndAvatarByUserID(userid) username, avatar, err := dingtalkAgent.GetUserNameAndAvatarByUserID(userid)
if err != nil { if err != nil {
beego.Warn("获取钉钉用户信息失败 ->", err) logs.Warn("获取钉钉用户信息失败 ->", err)
c.JsonResult(500, "自动登录失败", nil) c.JsonResult(500, "自动登录失败", nil)
c.StopRun() c.StopRun()
} }
@ -210,39 +213,39 @@ func (c *AccountController) QRLogin() {
c.Redirect(conf.URLFor("AccountController.Login"), 302) c.Redirect(conf.URLFor("AccountController.Login"), 302)
c.StopRun() c.StopRun()
} }
appKey := beego.AppConfig.String("dingtalk_qr_key") appKey, _ := web.AppConfig.String("dingtalk_qr_key")
appSecret := beego.AppConfig.String("dingtalk_qr_secret") appSecret, _ := web.AppConfig.String("dingtalk_qr_secret")
qrDingtalk := dingtalk.NewDingtalkQRLogin(appSecret, appKey) qrDingtalk := dingtalk.NewDingtalkQRLogin(appSecret, appKey)
unionID, err := qrDingtalk.GetUnionIDByCode(code) unionID, err := qrDingtalk.GetUnionIDByCode(code)
if err != nil { if err != nil {
beego.Warn("获取钉钉临时UnionID失败 ->", err) logs.Warn("获取钉钉临时UnionID失败 ->", err)
c.Redirect(conf.URLFor("AccountController.Login"), 302) c.Redirect(conf.URLFor("AccountController.Login"), 302)
c.StopRun() c.StopRun()
} }
appKey = beego.AppConfig.String("dingtalk_app_key") appKey, _ = web.AppConfig.String("dingtalk_app_key")
appSecret = beego.AppConfig.String("dingtalk_app_secret") appSecret, _ = web.AppConfig.String("dingtalk_app_secret")
tmpReader := beego.AppConfig.String("dingtalk_tmp_reader") tmpReader, _ := web.AppConfig.String("dingtalk_tmp_reader")
dingtalkAgent := dingtalk.NewDingTalkAgent(appSecret, appKey) dingtalkAgent := dingtalk.NewDingTalkAgent(appSecret, appKey)
err = dingtalkAgent.GetAccesstoken() err = dingtalkAgent.GetAccesstoken()
if err != nil { if err != nil {
beego.Warn("获取钉钉临时Token失败 ->", err) logs.Warn("获取钉钉临时Token失败 ->", err)
c.Redirect(conf.URLFor("AccountController.Login"), 302) c.Redirect(conf.URLFor("AccountController.Login"), 302)
c.StopRun() c.StopRun()
} }
userid, err := dingtalkAgent.GetUserIDByUnionID(unionID) userid, err := dingtalkAgent.GetUserIDByUnionID(unionID)
if err != nil { if err != nil {
beego.Warn("获取钉钉用户ID失败 ->", err) logs.Warn("获取钉钉用户ID失败 ->", err)
c.Redirect(conf.URLFor("AccountController.Login"), 302) c.Redirect(conf.URLFor("AccountController.Login"), 302)
c.StopRun() c.StopRun()
} }
username, avatar, err := dingtalkAgent.GetUserNameAndAvatarByUserID(userid) username, avatar, err := dingtalkAgent.GetUserNameAndAvatarByUserID(userid)
if err != nil { if err != nil {
beego.Warn("获取钉钉用户信息失败 ->", err) logs.Warn("获取钉钉用户信息失败 ->", err)
c.Redirect(conf.URLFor("AccountController.Login"), 302) c.Redirect(conf.URLFor("AccountController.Login"), 302)
c.StopRun() c.StopRun()
} }
@ -385,7 +388,7 @@ func (c *AccountController) FindPassword() {
count, err := models.NewMemberToken().FindSendCount(email, time.Now().Add(-1*time.Hour), time.Now()) count, err := models.NewMemberToken().FindSendCount(email, time.Now().Add(-1*time.Hour), time.Now())
if err != nil { if err != nil {
beego.Error(err) logs.Error(err)
c.JsonResult(6008, "发送邮件失败") c.JsonResult(6008, "发送邮件失败")
} }
if count > mailConf.MailNumber { if count > mailConf.MailNumber {
@ -410,7 +413,7 @@ func (c *AccountController) FindPassword() {
body, err := c.ExecuteViewPathTemplate("account/mail_template.tpl", data) body, err := c.ExecuteViewPathTemplate("account/mail_template.tpl", data)
if err != nil { if err != nil {
beego.Error(err) logs.Error(err)
c.JsonResult(6003, "邮件发送失败") c.JsonResult(6003, "邮件发送失败")
} }
@ -424,7 +427,7 @@ func (c *AccountController) FindPassword() {
Secure: mailConf.Secure, Secure: mailConf.Secure,
Identity: "", Identity: "",
} }
beego.Info(mailConfig) logs.Info(mailConfig)
c := mail.NewSMTPClient(mailConfig) c := mail.NewSMTPClient(mailConfig)
m := mail.NewMail() m := mail.NewMail()
@ -436,9 +439,9 @@ func (c *AccountController) FindPassword() {
m.AddTo(email) m.AddTo(email)
if e := c.Send(m); e != nil { if e := c.Send(m); e != nil {
beego.Error("发送邮件失败:" + e.Error()) logs.Error("发送邮件失败:" + e.Error())
} else { } else {
beego.Info("邮件发送成功:" + email) logs.Info("邮件发送成功:" + email)
} }
//auth := smtp.PlainAuth( //auth := smtp.PlainAuth(
// "", // "",
@ -458,7 +461,7 @@ func (c *AccountController) FindPassword() {
// []byte(subject+mime+"\n"+body), // []byte(subject+mime+"\n"+body),
//) //)
//if err != nil { //if err != nil {
// beego.Error("邮件发送失败 => ", email, err) // logs.Error("邮件发送失败 => ", email, err)
//} //}
}(mailConf, email, body) }(mailConf, email, body)
@ -472,12 +475,12 @@ func (c *AccountController) FindPassword() {
memberToken, err := models.NewMemberToken().FindByFieldFirst("token", token) memberToken, err := models.NewMemberToken().FindByFieldFirst("token", token)
if err != nil { if err != nil {
beego.Error(err) logs.Error(err)
c.Data["ErrorMessage"] = "邮件已失效" c.Data["ErrorMessage"] = "邮件已失效"
c.TplName = "errors/error.tpl" c.TplName = "errors/error.tpl"
return return
} }
subTime := memberToken.SendTime.Sub(time.Now()) subTime := time.Until(memberToken.SendTime)
if !strings.EqualFold(memberToken.Email, email) || subTime.Minutes() > float64(mailConf.MailExpired) || !memberToken.ValidTime.IsZero() { if !strings.EqualFold(memberToken.Email, email) || subTime.Minutes() > float64(mailConf.MailExpired) || !memberToken.ValidTime.IsZero() {
c.Data["ErrorMessage"] = "验证码已过期,请重新操作。" c.Data["ErrorMessage"] = "验证码已过期,请重新操作。"
@ -524,10 +527,10 @@ func (c *AccountController) ValidEmail() {
memberToken, err := models.NewMemberToken().FindByFieldFirst("token", token) memberToken, err := models.NewMemberToken().FindByFieldFirst("token", token)
if err != nil { if err != nil {
beego.Error(err) logs.Error(err)
c.JsonResult(6007, "邮件已失效") c.JsonResult(6007, "邮件已失效")
} }
subTime := memberToken.SendTime.Sub(time.Now()) subTime := time.Until(memberToken.SendTime)
if !strings.EqualFold(memberToken.Email, email) || subTime.Minutes() > float64(mailConf.MailExpired) || !memberToken.ValidTime.IsZero() { if !strings.EqualFold(memberToken.Email, email) || subTime.Minutes() > float64(mailConf.MailExpired) || !memberToken.ValidTime.IsZero() {
@ -535,13 +538,13 @@ func (c *AccountController) ValidEmail() {
} }
member, err := models.NewMember().Find(memberToken.MemberId) member, err := models.NewMember().Find(memberToken.MemberId)
if err != nil { if err != nil {
beego.Error(err) logs.Error(err)
c.JsonResult(6005, "用户不存在") c.JsonResult(6005, "用户不存在")
} }
hash, err := utils.PasswordHash(password1) hash, err := utils.PasswordHash(password1)
if err != nil { if err != nil {
beego.Error(err) logs.Error(err)
c.JsonResult(6006, "保存密码失败") c.JsonResult(6006, "保存密码失败")
} }
@ -553,7 +556,7 @@ func (c *AccountController) ValidEmail() {
memberToken.InsertOrUpdate() memberToken.InsertOrUpdate()
if err != nil { if err != nil {
beego.Error(err) logs.Error(err)
c.JsonResult(6006, "保存密码失败") c.JsonResult(6006, "保存密码失败")
} }
c.JsonResult(0, "ok", conf.URLFor("AccountController.Login")) c.JsonResult(0, "ok", conf.URLFor("AccountController.Login"))
@ -577,7 +580,7 @@ func (c *AccountController) Captcha() {
captchaImage := gocaptcha.NewCaptchaImage(140, 40, gocaptcha.RandLightColor()) captchaImage := gocaptcha.NewCaptchaImage(140, 40, gocaptcha.RandLightColor())
//if err != nil { //if err != nil {
// beego.Error(err) // logs.Error(err)
// c.Abort("500") // c.Abort("500")
//} //}

View File

@ -12,14 +12,15 @@ import (
"io/ioutil" "io/ioutil"
"path/filepath" "path/filepath"
"github.com/astaxie/beego" "github.com/beego/beego/v2/core/logs"
"github.com/beego/beego/v2/server/web"
"github.com/mindoc-org/mindoc/conf" "github.com/mindoc-org/mindoc/conf"
"github.com/mindoc-org/mindoc/models" "github.com/mindoc-org/mindoc/models"
"github.com/mindoc-org/mindoc/utils" "github.com/mindoc-org/mindoc/utils"
) )
type BaseController struct { type BaseController struct {
beego.Controller web.Controller
Member *models.Member Member *models.Member
Option map[string]string Option map[string]string
EnableAnonymous bool EnableAnonymous bool
@ -73,15 +74,16 @@ func (c *BaseController) Prepare() {
c.EnableAnonymous = strings.EqualFold(c.Option["ENABLE_ANONYMOUS"], "true") c.EnableAnonymous = strings.EqualFold(c.Option["ENABLE_ANONYMOUS"], "true")
c.EnableDocumentHistory = strings.EqualFold(c.Option["ENABLE_DOCUMENT_HISTORY"], "true") c.EnableDocumentHistory = strings.EqualFold(c.Option["ENABLE_DOCUMENT_HISTORY"], "true")
} }
c.Data["HighlightStyle"] = beego.AppConfig.DefaultString("highlight_style", "github") c.Data["HighlightStyle"] = web.AppConfig.DefaultString("highlight_style", "github")
if b, err := ioutil.ReadFile(filepath.Join(beego.BConfig.WebConfig.ViewsPath, "widgets", "scripts.tpl")); err == nil { if b, err := ioutil.ReadFile(filepath.Join(web.BConfig.WebConfig.ViewsPath, "widgets", "scripts.tpl")); err == nil {
c.Data["Scripts"] = template.HTML(string(b)) c.Data["Scripts"] = template.HTML(string(b))
} }
} }
//判断用户是否登录. //判断用户是否登录.
func (c *BaseController)isUserLoggedIn() bool { func (c *BaseController) isUserLoggedIn() bool {
return c.Member != nil && c.Member.MemberId > 0 return c.Member != nil && c.Member.MemberId > 0
} }
@ -112,7 +114,7 @@ func (c *BaseController) JsonResult(errCode int, errMsg string, data ...interfac
returnJSON, err := json.Marshal(jsonData) returnJSON, err := json.Marshal(jsonData)
if err != nil { if err != nil {
beego.Error(err) logs.Error(err)
} }
c.Ctx.ResponseWriter.Header().Set("Content-Type", "application/json; charset=utf-8") c.Ctx.ResponseWriter.Header().Set("Content-Type", "application/json; charset=utf-8")
@ -123,7 +125,7 @@ func (c *BaseController) JsonResult(errCode int, errMsg string, data ...interfac
} }
//如果错误不为空,则响应错误信息到浏览器. //如果错误不为空,则响应错误信息到浏览器.
func (c *BaseController) CheckJsonError(code int,err error) { func (c *BaseController) CheckJsonError(code int, err error) {
if err == nil { if err == nil {
return return
@ -136,7 +138,7 @@ func (c *BaseController) CheckJsonError(code int,err error) {
returnJSON, err := json.Marshal(jsonData) returnJSON, err := json.Marshal(jsonData)
if err != nil { if err != nil {
beego.Error(err) logs.Error(err)
} }
c.Ctx.ResponseWriter.Header().Set("Content-Type", "application/json; charset=utf-8") c.Ctx.ResponseWriter.Header().Set("Content-Type", "application/json; charset=utf-8")
@ -153,18 +155,18 @@ func (c *BaseController) ExecuteViewPathTemplate(tplName string, data interface{
viewPath := c.ViewPath viewPath := c.ViewPath
if c.ViewPath == "" { if c.ViewPath == "" {
viewPath = beego.BConfig.WebConfig.ViewsPath viewPath = web.BConfig.WebConfig.ViewsPath
} }
if err := beego.ExecuteViewPathTemplate(&buf, tplName, viewPath, data); err != nil { if err := web.ExecuteViewPathTemplate(&buf, tplName, viewPath, data); err != nil {
return "", err return "", err
} }
return buf.String(), nil return buf.String(), nil
} }
func (c *BaseController) BaseUrl() string { func (c *BaseController) BaseUrl() string {
baseUrl := beego.AppConfig.DefaultString("baseurl", "") baseUrl := web.AppConfig.DefaultString("baseurl", "")
if baseUrl != "" { if baseUrl != "" {
if strings.HasSuffix(baseUrl, "/") { if strings.HasSuffix(baseUrl, "/") {
baseUrl = strings.TrimSuffix(baseUrl, "/") baseUrl = strings.TrimSuffix(baseUrl, "/")
@ -184,7 +186,7 @@ func (c *BaseController) ShowErrorPage(errCode int, errMsg string) {
var buf bytes.Buffer var buf bytes.Buffer
if err := beego.ExecuteViewPathTemplate(&buf, "errors/error.tpl", beego.BConfig.WebConfig.ViewsPath, map[string]interface{}{"ErrorMessage": errMsg, "ErrorCode": errCode, "BaseUrl": conf.BaseUrl}); err != nil { if err := web.ExecuteViewPathTemplate(&buf, "errors/error.tpl", web.BConfig.WebConfig.ViewsPath, map[string]interface{}{"ErrorMessage": errMsg, "ErrorCode": errCode, "BaseUrl": conf.BaseUrl}); err != nil {
c.Abort("500") c.Abort("500")
} }
if errCode >= 200 && errCode <= 510 { if errCode >= 200 && errCode <= 510 {
@ -194,8 +196,7 @@ func (c *BaseController) ShowErrorPage(errCode int, errMsg string) {
} }
} }
func (c *BaseController) CheckErrorResult(code int, err error) {
func (c *BaseController) CheckErrorResult(code int,err error) {
if err != nil { if err != nil {
c.ShowErrorPage(code, err.Error()) c.ShowErrorPage(code, err.Error())
} }

View File

@ -1,6 +1,7 @@
package controllers package controllers
import ( import (
"context"
"encoding/json" "encoding/json"
"fmt" "fmt"
"html/template" "html/template"
@ -12,8 +13,9 @@ import (
"strings" "strings"
"time" "time"
"github.com/astaxie/beego" "github.com/beego/beego/v2/client/orm"
"github.com/astaxie/beego/orm" "github.com/beego/beego/v2/core/logs"
"github.com/beego/beego/v2/server/web"
"github.com/mindoc-org/mindoc/conf" "github.com/mindoc-org/mindoc/conf"
"github.com/mindoc-org/mindoc/models" "github.com/mindoc-org/mindoc/models"
"github.com/mindoc-org/mindoc/utils" "github.com/mindoc-org/mindoc/utils"
@ -49,16 +51,16 @@ func (c *BlogController) Index() {
} }
if c.Ctx.Input.IsPost() { if c.Ctx.Input.IsPost() {
password := c.GetString("password"); password := c.GetString("password")
if blog.BlogStatus == "password" && password != blog.Password { if blog.BlogStatus == "password" && password != blog.Password {
c.JsonResult(6001, "文章密码不正确") c.JsonResult(6001, "文章密码不正确")
} else if blog.BlogStatus == "password" && password == blog.Password { } else if blog.BlogStatus == "password" && password == blog.Password {
//如果密码输入正确则存入session中 //如果密码输入正确则存入session中
_ = c.CruSession.Set(blogReadSession, blogId) _ = c.CruSession.Set(context.TODO(), blogReadSession, blogId)
c.JsonResult(0, "OK") c.JsonResult(0, "OK")
} }
c.JsonResult(0, "OK") c.JsonResult(0, "OK")
} else if blog.BlogStatus == "password" && (c.CruSession.Get(blogReadSession) == nil || (c.Member != nil && blog.MemberId != c.Member.MemberId && !c.Member.IsAdministrator())) { } else if blog.BlogStatus == "password" && (c.CruSession.Get(context.TODO(), blogReadSession) == nil || (c.Member != nil && blog.MemberId != c.Member.MemberId && !c.Member.IsAdministrator())) {
//如果不存在已输入密码的标记 //如果不存在已输入密码的标记
c.TplName = "blog/index_password.tpl" c.TplName = "blog/index_password.tpl"
} }
@ -250,7 +252,7 @@ func (c *BlogController) ManageSetting() {
blog.Password = blogPassword blog.Password = blogPassword
if err := blog.Save(); err != nil { if err := blog.Save(); err != nil {
beego.Error("保存文章失败 -> ", err) logs.Error("保存文章失败 -> ", err)
c.JsonResult(6011, "保存文章失败") c.JsonResult(6011, "保存文章失败")
} else { } else {
c.JsonResult(0, "ok", blog) c.JsonResult(0, "ok", blog)
@ -263,7 +265,7 @@ func (c *BlogController) ManageSetting() {
} }
blogId, err := strconv.Atoi(c.Ctx.Input.Param(":id")) blogId, err := strconv.Atoi(c.Ctx.Input.Param(":id"))
c.Data["DocumentIdentify"] = ""; c.Data["DocumentIdentify"] = ""
if err == nil { if err == nil {
blog, err := models.NewBlog().FindByIdAndMemberId(blogId, c.Member.MemberId) blog, err := models.NewBlog().FindByIdAndMemberId(blogId, c.Member.MemberId)
if err != nil { if err != nil {
@ -301,7 +303,7 @@ func (c *BlogController) ManageEdit() {
blog, err = models.NewBlog().FindByIdAndMemberId(blogId, c.Member.MemberId) blog, err = models.NewBlog().FindByIdAndMemberId(blogId, c.Member.MemberId)
} }
if err != nil { if err != nil {
beego.Error("查询文章失败 ->", err) logs.Error("查询文章失败 ->", err)
c.JsonResult(6002, "查询文章失败") c.JsonResult(6002, "查询文章失败")
} }
if version > 0 && blog.Version != version && cover != "yes" { if version > 0 && blog.Version != version && cover != "yes" {
@ -311,7 +313,7 @@ func (c *BlogController) ManageEdit() {
if blog.BlogType == 1 { if blog.BlogType == 1 {
doc, err := models.NewDocument().Find(blog.DocumentId) doc, err := models.NewDocument().Find(blog.DocumentId)
if err != nil { if err != nil {
beego.Error("查询关联项目文档时出错 ->", err) logs.Error("查询关联项目文档时出错 ->", err)
c.JsonResult(6003, "查询关联项目文档时出错") c.JsonResult(6003, "查询关联项目文档时出错")
} }
book, err := models.NewBook().Find(doc.BookId) book, err := models.NewBook().Find(doc.BookId)
@ -324,7 +326,7 @@ func (c *BlogController) ManageEdit() {
bookResult, err := models.NewBookResult().FindByIdentify(book.Identify, c.Member.MemberId) bookResult, err := models.NewBookResult().FindByIdentify(book.Identify, c.Member.MemberId)
if err != nil || bookResult.RoleId == conf.BookObserver { if err != nil || bookResult.RoleId == conf.BookObserver {
beego.Error("FindByIdentify => ", err) logs.Error("FindByIdentify => ", err)
c.JsonResult(6002, "关联文档不存在或权限不足") c.JsonResult(6002, "关联文档不存在或权限不足")
} }
} }
@ -335,7 +337,7 @@ func (c *BlogController) ManageEdit() {
doc.ModifyTime = time.Now() doc.ModifyTime = time.Now()
doc.ModifyAt = c.Member.MemberId doc.ModifyAt = c.Member.MemberId
if err := doc.InsertOrUpdate("markdown", "release", "content", "modify_time", "modify_at"); err != nil { if err := doc.InsertOrUpdate("markdown", "release", "content", "modify_time", "modify_at"); err != nil {
beego.Error("保存关联文档时出错 ->", err) logs.Error("保存关联文档时出错 ->", err)
c.JsonResult(6004, "保存关联文档时出错") c.JsonResult(6004, "保存关联文档时出错")
} }
} }
@ -346,7 +348,7 @@ func (c *BlogController) ManageEdit() {
blog.Modified = time.Now() blog.Modified = time.Now()
if err := blog.Save("blog_content", "blog_release", "modify_at", "modify_time", "version"); err != nil { if err := blog.Save("blog_content", "blog_release", "modify_at", "modify_time", "version"); err != nil {
beego.Error("保存文章失败 -> ", err) logs.Error("保存文章失败 -> ", err)
c.JsonResult(6011, "保存文章失败") c.JsonResult(6011, "保存文章失败")
} else { } else {
c.JsonResult(0, "ok", blog) c.JsonResult(0, "ok", blog)
@ -374,7 +376,7 @@ func (c *BlogController) ManageEdit() {
if len(blog.AttachList) > 0 { if len(blog.AttachList) > 0 {
returnJSON, err := json.Marshal(blog.AttachList) returnJSON, err := json.Marshal(blog.AttachList)
if err != nil { if err != nil {
beego.Error("序列化文章附件时出错 ->", err) logs.Error("序列化文章附件时出错 ->", err)
} else { } else {
c.Data["AttachList"] = template.JS(string(returnJSON)) c.Data["AttachList"] = template.JS(string(returnJSON))
} }
@ -384,7 +386,7 @@ func (c *BlogController) ManageEdit() {
if conf.GetUploadFileSize() > 0 { if conf.GetUploadFileSize() > 0 {
c.Data["UploadFileSize"] = conf.GetUploadFileSize() c.Data["UploadFileSize"] = conf.GetUploadFileSize()
} else { } else {
c.Data["UploadFileSize"] = "undefined"; c.Data["UploadFileSize"] = "undefined"
} }
c.Data["Model"] = blog c.Data["Model"] = blog
} }
@ -466,7 +468,7 @@ func (c *BlogController) Upload() {
c.JsonResult(6003, "无法解析文件的格式") c.JsonResult(6003, "无法解析文件的格式")
} }
//如果文件类型设置为 * 标识不限制文件类型 //如果文件类型设置为 * 标识不限制文件类型
if beego.AppConfig.DefaultString("upload_file_ext", "") != "*" { if web.AppConfig.DefaultString("upload_file_ext", "") != "*" {
if !conf.IsAllowUploadFileExt(ext) { if !conf.IsAllowUploadFileExt(ext) {
c.JsonResult(6004, "不允许的文件类型") c.JsonResult(6004, "不允许的文件类型")
} }
@ -484,7 +486,7 @@ func (c *BlogController) Upload() {
_, err := models.NewBlog().FindByIdAndMemberId(blogId, c.Member.MemberId) _, err := models.NewBlog().FindByIdAndMemberId(blogId, c.Member.MemberId)
if err != nil { if err != nil {
beego.Error("查询文章时出错 -> ", err) logs.Error("查询文章时出错 -> ", err)
if err == orm.ErrNoRows { if err == orm.ErrNoRows {
c.JsonResult(6006, "权限不足") c.JsonResult(6006, "权限不足")
} }
@ -504,7 +506,7 @@ func (c *BlogController) Upload() {
err = c.SaveToFile(name, filePath) err = c.SaveToFile(name, filePath)
if err != nil { if err != nil {
beego.Error("SaveToFile => ", err) logs.Error("SaveToFile => ", err)
c.JsonResult(6005, "保存文件失败") c.JsonResult(6005, "保存文件失败")
} }
@ -537,14 +539,14 @@ func (c *BlogController) Upload() {
if err := attachment.Insert(); err != nil { if err := attachment.Insert(); err != nil {
os.Remove(filePath) os.Remove(filePath)
beego.Error("保存文件附件失败 -> ", err) logs.Error("保存文件附件失败 -> ", err)
c.JsonResult(6006, "文件保存失败") c.JsonResult(6006, "文件保存失败")
} }
if attachment.HttpPath == "" { if attachment.HttpPath == "" {
attachment.HttpPath = conf.URLForNotHost("BlogController.Download", ":id", blogId, ":attach_id", attachment.AttachmentId) attachment.HttpPath = conf.URLForNotHost("BlogController.Download", ":id", blogId, ":attach_id", attachment.AttachmentId)
if err := attachment.Update(); err != nil { if err := attachment.Update(); err != nil {
beego.Error("保存文件失败 -> ",attachment.FilePath, err) logs.Error("保存文件失败 -> ", attachment.FilePath, err)
c.JsonResult(6005, "保存文件失败") c.JsonResult(6005, "保存文件失败")
} }
} }
@ -581,7 +583,7 @@ func (c *BlogController) RemoveAttachment() {
attach, err := models.NewAttachment().Find(attachId) attach, err := models.NewAttachment().Find(attachId)
if err != nil { if err != nil {
beego.Error(err) logs.Error(err)
c.JsonResult(6002, "附件不存在") c.JsonResult(6002, "附件不存在")
} }
@ -589,7 +591,7 @@ func (c *BlogController) RemoveAttachment() {
_, err := models.NewBlog().FindByIdAndMemberId(attach.DocumentId, c.Member.MemberId) _, err := models.NewBlog().FindByIdAndMemberId(attach.DocumentId, c.Member.MemberId)
if err != nil { if err != nil {
beego.Error(err) logs.Error(err)
c.JsonResult(6003, "文档不存在") c.JsonResult(6003, "文档不存在")
} }
} }
@ -601,7 +603,7 @@ func (c *BlogController) RemoveAttachment() {
} }
if err := attach.Delete(); err != nil { if err := attach.Delete(); err != nil {
beego.Error(err) logs.Error(err)
c.JsonResult(6005, "删除失败") c.JsonResult(6005, "删除失败")
} }
@ -628,7 +630,7 @@ func (c *BlogController) Download() {
} }
blogReadSession := fmt.Sprintf("blog:read:%d", blogId) blogReadSession := fmt.Sprintf("blog:read:%d", blogId)
//如果没有启动匿名访问,或者设置了访问密码 //如果没有启动匿名访问,或者设置了访问密码
if (c.Member == nil && !c.EnableAnonymous) || (blog.BlogStatus == "password" && password != blog.Password && c.CruSession.Get(blogReadSession) == nil) { if (c.Member == nil && !c.EnableAnonymous) || (blog.BlogStatus == "password" && password != blog.Password && c.CruSession.Get(context.TODO(), blogReadSession) == nil) {
c.ShowErrorPage(403, "没有下载权限") c.ShowErrorPage(403, "没有下载权限")
} }
@ -639,7 +641,7 @@ func (c *BlogController) Download() {
if err == orm.ErrNoRows { if err == orm.ErrNoRows {
c.ShowErrorPage(404, "附件不存在") c.ShowErrorPage(404, "附件不存在")
} else { } else {
beego.Error("查询附件时出现异常 -> ", err) logs.Error("查询附件时出现异常 -> ", err)
c.ShowErrorPage(500, "查询附件时出现异常") c.ShowErrorPage(500, "查询附件时出现异常")
} }
} }
@ -647,7 +649,7 @@ func (c *BlogController) Download() {
//如果是链接的文章需要校验文档ID是否一致如果不是需要保证附件的项目ID为0且文档的ID等于博文ID //如果是链接的文章需要校验文档ID是否一致如果不是需要保证附件的项目ID为0且文档的ID等于博文ID
if blog.BlogType == 1 && attachment.DocumentId != blog.DocumentId { if blog.BlogType == 1 && attachment.DocumentId != blog.DocumentId {
c.ShowErrorPage(404, "附件不存在") c.ShowErrorPage(404, "附件不存在")
} else if blog.BlogType != 1 && (attachment.BookId != 0 || attachment.DocumentId != blogId ) { } else if blog.BlogType != 1 && (attachment.BookId != 0 || attachment.DocumentId != blogId) {
c.ShowErrorPage(404, "附件不存在") c.ShowErrorPage(404, "附件不存在")
} }

View File

@ -1,6 +1,7 @@
package controllers package controllers
import ( import (
"context"
"encoding/json" "encoding/json"
"errors" "errors"
"fmt" "fmt"
@ -16,15 +17,14 @@ import (
"net/http" "net/http"
"github.com/astaxie/beego" "github.com/beego/beego/v2/client/orm"
"github.com/astaxie/beego/logs" "github.com/beego/beego/v2/core/logs"
"github.com/astaxie/beego/orm"
"github.com/mindoc-org/mindoc/conf" "github.com/mindoc-org/mindoc/conf"
"github.com/mindoc-org/mindoc/graphics" "github.com/mindoc-org/mindoc/graphics"
"github.com/mindoc-org/mindoc/models" "github.com/mindoc-org/mindoc/models"
"github.com/mindoc-org/mindoc/utils" "github.com/mindoc-org/mindoc/utils"
"github.com/mindoc-org/mindoc/utils/pagination" "github.com/mindoc-org/mindoc/utils/pagination"
"gopkg.in/russross/blackfriday.v2" "github.com/russross/blackfriday/v2"
) )
type BookController struct { type BookController struct {
@ -210,7 +210,7 @@ func (c *BookController) SaveBook() {
bookResult.Description = description bookResult.Description = description
bookResult.CommentStatus = commentStatus bookResult.CommentStatus = commentStatus
beego.Info("用户 [", c.Member.Account, "] 修改了项目 ->", book) logs.Info("用户 [", c.Member.Account, "] 修改了项目 ->", book)
c.JsonResult(0, "ok", bookResult) c.JsonResult(0, "ok", bookResult)
} }
@ -255,7 +255,7 @@ func (c *BookController) PrivatelyOwned() {
logs.Error("PrivatelyOwned => ", err) logs.Error("PrivatelyOwned => ", err)
c.JsonResult(6004, "保存失败") c.JsonResult(6004, "保存失败")
} }
beego.Info("用户 【", c.Member.Account, "]修改了项目权限 ->", state) logs.Info("用户 【", c.Member.Account, "]修改了项目权限 ->", state)
c.JsonResult(0, "ok") c.JsonResult(0, "ok")
} }
@ -390,7 +390,7 @@ func (c *BookController) UploadCover() {
if oldCover != conf.GetDefaultCover() { if oldCover != conf.GetDefaultCover() {
os.Remove("." + oldCover) os.Remove("." + oldCover)
} }
beego.Info("用户[", c.Member.Account, "]上传了项目封面 ->", book.BookName, book.BookId, book.Cover) logs.Info("用户[", c.Member.Account, "]上传了项目封面 ->", book.BookName, book.BookId, book.Cover)
c.JsonResult(0, "ok", url) c.JsonResult(0, "ok", url)
} }
@ -534,10 +534,10 @@ func (c *BookController) Create() {
bookResult, err := models.NewBookResult().FindByIdentify(book.Identify, c.Member.MemberId) bookResult, err := models.NewBookResult().FindByIdentify(book.Identify, c.Member.MemberId)
if err != nil { if err != nil {
beego.Error(err) logs.Error(err)
} }
beego.Info("用户[", c.Member.Account, "]创建了项目 ->", book) logs.Info("用户[", c.Member.Account, "]创建了项目 ->", book)
c.JsonResult(0, "ok", bookResult) c.JsonResult(0, "ok", bookResult)
} }
c.JsonResult(6001, "error") c.JsonResult(6001, "error")
@ -562,7 +562,7 @@ func (c *BookController) Copy() {
} else { } else {
bookResult, err := models.NewBookResult().FindByIdentify(book.Identify, c.Member.MemberId) bookResult, err := models.NewBookResult().FindByIdentify(book.Identify, c.Member.MemberId)
if err != nil { if err != nil {
beego.Error("查询失败") logs.Error("查询失败")
} }
c.JsonResult(0, "ok", bookResult) c.JsonResult(0, "ok", bookResult)
} }
@ -614,7 +614,7 @@ func (c *BookController) Import() {
c.JsonResult(6006, "项目标识已存在") c.JsonResult(6006, "项目标识已存在")
} }
tempPath := filepath.Join(os.TempDir(), c.CruSession.SessionID()) tempPath := filepath.Join(os.TempDir(), c.CruSession.SessionID(context.TODO()))
os.MkdirAll(tempPath, 0766) os.MkdirAll(tempPath, 0766)
@ -643,7 +643,7 @@ func (c *BookController) Import() {
go book.ImportBook(tempPath) go book.ImportBook(tempPath)
beego.Info("用户[", c.Member.Account, "]导入了项目 ->", book) logs.Info("用户[", c.Member.Account, "]导入了项目 ->", book)
c.JsonResult(0, "项目正在后台转换中,请稍后查看") c.JsonResult(0, "项目正在后台转换中,请稍后查看")
} }
@ -680,7 +680,7 @@ func (c *BookController) Import() {
// logs.Error("生成阅读令牌失败 => ", err) // logs.Error("生成阅读令牌失败 => ", err)
// c.JsonResult(6003, "生成阅读令牌失败") // c.JsonResult(6003, "生成阅读令牌失败")
// } // }
// beego.Info("用户[", c.Member.Account, "]创建项目令牌 ->", book.PrivateToken) // logs.Info("用户[", c.Member.Account, "]创建项目令牌 ->", book.PrivateToken)
// c.JsonResult(0, "ok", conf.URLFor("DocumentController.Index", ":key", book.Identify, "token", book.PrivateToken)) // c.JsonResult(0, "ok", conf.URLFor("DocumentController.Index", ":key", book.Identify, "token", book.PrivateToken))
// } else { // } else {
// book.PrivateToken = "" // book.PrivateToken = ""
@ -688,7 +688,7 @@ func (c *BookController) Import() {
// logs.Error("CreateToken => ", err) // logs.Error("CreateToken => ", err)
// c.JsonResult(6004, "删除令牌失败") // c.JsonResult(6004, "删除令牌失败")
// } // }
// beego.Info("用户[", c.Member.Account, "]创建项目令牌 ->", book.PrivateToken) // logs.Info("用户[", c.Member.Account, "]创建项目令牌 ->", book.PrivateToken)
// c.JsonResult(0, "ok", "") // c.JsonResult(0, "ok", "")
// } // }
//} //}
@ -716,7 +716,7 @@ func (c *BookController) Delete() {
logs.Error("删除项目 => ", err) logs.Error("删除项目 => ", err)
c.JsonResult(6003, "删除失败") c.JsonResult(6003, "删除失败")
} }
beego.Info("用户[", c.Member.Account, "]删除了项目 ->", bookResult) logs.Info("用户[", c.Member.Account, "]删除了项目 ->", bookResult)
c.JsonResult(0, "ok") c.JsonResult(0, "ok")
} }
@ -731,7 +731,7 @@ func (c *BookController) Release() {
if c.Member.IsAdministrator() { if c.Member.IsAdministrator() {
book, err := models.NewBook().FindByFieldFirst("identify", identify) book, err := models.NewBook().FindByFieldFirst("identify", identify)
if err != nil { if err != nil {
beego.Error("发布文档失败 ->", err) logs.Error("发布文档失败 ->", err)
c.JsonResult(6003, "文档不存在") c.JsonResult(6003, "文档不存在")
return return
} }
@ -746,7 +746,7 @@ func (c *BookController) Release() {
if err == orm.ErrNoRows { if err == orm.ErrNoRows {
c.JsonResult(6002, "项目不存在") c.JsonResult(6002, "项目不存在")
} }
beego.Error(err) logs.Error(err)
c.JsonResult(6003, "未知错误") c.JsonResult(6003, "未知错误")
} }
if book.RoleId != conf.BookAdmin && book.RoleId != conf.BookFounder && book.RoleId != conf.BookEditor { if book.RoleId != conf.BookAdmin && book.RoleId != conf.BookFounder && book.RoleId != conf.BookEditor {
@ -772,14 +772,14 @@ func (c *BookController) SaveSort() {
if c.Member.IsAdministrator() { if c.Member.IsAdministrator() {
book, err := models.NewBook().FindByFieldFirst("identify", identify) book, err := models.NewBook().FindByFieldFirst("identify", identify)
if err != nil || book == nil { if err != nil || book == nil {
c.JsonResult(6001,"项目不存在") c.JsonResult(6001, "项目不存在")
return return
} }
bookId = book.BookId bookId = book.BookId
} else { } else {
bookResult, err := models.NewBookResult().FindByIdentify(identify, c.Member.MemberId) bookResult, err := models.NewBookResult().FindByIdentify(identify, c.Member.MemberId)
if err != nil { if err != nil {
beego.Error("DocumentController.Edit => ", err) logs.Error("DocumentController.Edit => ", err)
c.Abort("403") c.Abort("403")
} }
@ -796,7 +796,7 @@ func (c *BookController) SaveSort() {
err := json.Unmarshal(content, &docs) err := json.Unmarshal(content, &docs)
if err != nil { if err != nil {
beego.Error(err) logs.Error(err)
c.JsonResult(6003, "数据错误") c.JsonResult(6003, "数据错误")
} }
@ -804,7 +804,7 @@ func (c *BookController) SaveSort() {
if docId, ok := item["id"].(float64); ok { if docId, ok := item["id"].(float64); ok {
doc, err := models.NewDocument().Find(int(docId)) doc, err := models.NewDocument().Find(int(docId))
if err != nil { if err != nil {
beego.Error(err) logs.Error(err)
continue continue
} }
if doc.BookId != bookId { if doc.BookId != bookId {
@ -813,12 +813,12 @@ func (c *BookController) SaveSort() {
} }
sort, ok := item["sort"].(float64) sort, ok := item["sort"].(float64)
if !ok { if !ok {
beego.Info("排序数字转换失败 => ", item) logs.Info("排序数字转换失败 => ", item)
continue continue
} }
parentId, ok := item["parent"].(float64) parentId, ok := item["parent"].(float64)
if !ok { if !ok {
beego.Info("父分类转换失败 => ", item) logs.Info("父分类转换失败 => ", item)
continue continue
} }
if parentId > 0 { if parentId > 0 {
@ -830,7 +830,7 @@ func (c *BookController) SaveSort() {
doc.ParentId = int(parentId) doc.ParentId = int(parentId)
if err := doc.InsertOrUpdate(); err != nil { if err := doc.InsertOrUpdate(); err != nil {
fmt.Printf("%s", err.Error()) fmt.Printf("%s", err.Error())
beego.Error(err) logs.Error(err)
} }
} else { } else {
fmt.Printf("文档ID转换失败 => %+v", item) fmt.Printf("文档ID转换失败 => %+v", item)

View File

@ -3,9 +3,8 @@ package controllers
import ( import (
"errors" "errors"
"github.com/astaxie/beego" "github.com/beego/beego/v2/client/orm"
"github.com/astaxie/beego/logs" "github.com/beego/beego/v2/core/logs"
"github.com/astaxie/beego/orm"
"github.com/mindoc-org/mindoc/conf" "github.com/mindoc-org/mindoc/conf"
"github.com/mindoc-org/mindoc/models" "github.com/mindoc-org/mindoc/models"
) )
@ -17,9 +16,9 @@ type BookMemberController struct {
// AddMember 参加参与用户. // AddMember 参加参与用户.
func (c *BookMemberController) AddMember() { func (c *BookMemberController) AddMember() {
identify := c.GetString("identify") identify := c.GetString("identify")
account,_ := c.GetInt("account") account, _ := c.GetInt("account")
roleId, _ := c.GetInt("role_id", 3) roleId, _ := c.GetInt("role_id", 3)
beego.Info(account) logs.Info(account)
if identify == "" || account <= 0 { if identify == "" || account <= 0 {
c.JsonResult(6001, "参数错误") c.JsonResult(6001, "参数错误")
} }
@ -29,7 +28,6 @@ func (c *BookMemberController) AddMember() {
c.JsonResult(6001, err.Error()) c.JsonResult(6001, err.Error())
} }
member := models.NewMember() member := models.NewMember()
if _, err := member.Find(account); err != nil { if _, err := member.Find(account); err != nil {

View File

@ -1,6 +1,7 @@
package controllers package controllers
import ( import (
"context"
"encoding/json" "encoding/json"
"fmt" "fmt"
"html/template" "html/template"
@ -14,9 +15,9 @@ import (
"strings" "strings"
"time" "time"
"github.com/astaxie/beego" "github.com/beego/beego/v2/client/orm"
"github.com/astaxie/beego/logs" "github.com/beego/beego/v2/core/logs"
"github.com/astaxie/beego/orm" "github.com/beego/beego/v2/server/web"
"github.com/boombuler/barcode" "github.com/boombuler/barcode"
"github.com/boombuler/barcode/qr" "github.com/boombuler/barcode/qr"
"github.com/mindoc-org/mindoc/conf" "github.com/mindoc-org/mindoc/conf"
@ -26,7 +27,7 @@ import (
"github.com/mindoc-org/mindoc/utils/filetil" "github.com/mindoc-org/mindoc/utils/filetil"
"github.com/mindoc-org/mindoc/utils/gopool" "github.com/mindoc-org/mindoc/utils/gopool"
"github.com/mindoc-org/mindoc/utils/pagination" "github.com/mindoc-org/mindoc/utils/pagination"
"gopkg.in/russross/blackfriday.v2" "github.com/russross/blackfriday/v2"
) )
// DocumentController struct // DocumentController struct
@ -77,7 +78,7 @@ func (c *DocumentController) Index() {
if err == orm.ErrNoRows { if err == orm.ErrNoRows {
c.ShowErrorPage(404, "当前项目没有文档") c.ShowErrorPage(404, "当前项目没有文档")
} else { } else {
beego.Error("生成项目文档树时出错 -> ", err) logs.Error("生成项目文档树时出错 -> ", err)
c.ShowErrorPage(500, "生成项目文档树时出错") c.ShowErrorPage(500, "生成项目文档树时出错")
} }
} }
@ -115,7 +116,7 @@ func (c *DocumentController) Read() {
if docId, err := strconv.Atoi(id); err == nil { if docId, err := strconv.Atoi(id); err == nil {
doc, err = doc.FromCacheById(docId) doc, err = doc.FromCacheById(docId)
if err != nil || doc == nil { if err != nil || doc == nil {
beego.Error("从缓存中读取文档时失败 ->", err) logs.Error("从缓存中读取文档时失败 ->", err)
c.ShowErrorPage(404, "文档不存在或已删除") c.ShowErrorPage(404, "文档不存在或已删除")
return return
} }
@ -125,7 +126,7 @@ func (c *DocumentController) Read() {
if err == orm.ErrNoRows { if err == orm.ErrNoRows {
c.ShowErrorPage(404, "文档不存在或已删除") c.ShowErrorPage(404, "文档不存在或已删除")
} else { } else {
beego.Error("从缓存查询文档时出错 ->", err) logs.Error("从缓存查询文档时出错 ->", err)
c.ShowErrorPage(500, "未知异常") c.ShowErrorPage(500, "未知异常")
} }
return return
@ -143,17 +144,22 @@ func (c *DocumentController) Read() {
doc.AttachList = attach doc.AttachList = attach
} }
doc.IncrViewCount(doc.DocumentId)
c.Data["ViewCount"] = doc.ViewCount + 1
if c.IsAjax() { if c.IsAjax() {
var data struct { var data struct {
DocTitle string `json:"doc_title"` DocTitle string `json:"doc_title"`
Body string `json:"body"` Body string `json:"body"`
Title string `json:"title"` Title string `json:"title"`
Version int64 `json:"version"` Version int64 `json:"version"`
ViewCount int `json:"view_count"`
} }
data.DocTitle = doc.DocumentName data.DocTitle = doc.DocumentName
data.Body = doc.Release data.Body = doc.Release
data.Title = doc.DocumentName + " - Powered by MinDoc" data.Title = doc.DocumentName + " - Powered by MinDoc"
data.Version = doc.Version data.Version = doc.Version
data.ViewCount = doc.ViewCount + 1
c.JsonResult(0, "ok", data) c.JsonResult(0, "ok", data)
} }
@ -161,7 +167,7 @@ func (c *DocumentController) Read() {
tree, err := models.NewDocument().CreateDocumentTreeForHtml(bookResult.BookId, doc.DocumentId) tree, err := models.NewDocument().CreateDocumentTreeForHtml(bookResult.BookId, doc.DocumentId)
if err != nil && err != orm.ErrNoRows { if err != nil && err != orm.ErrNoRows {
beego.Error("生成项目文档树时出错 ->", err) logs.Error("生成项目文档树时出错 ->", err)
c.ShowErrorPage(500, "生成项目文档树时出错") c.ShowErrorPage(500, "生成项目文档树时出错")
} }
@ -201,7 +207,7 @@ func (c *DocumentController) Edit() {
if err == orm.ErrNoRows || err == models.ErrPermissionDenied { if err == orm.ErrNoRows || err == models.ErrPermissionDenied {
c.ShowErrorPage(403, "项目不存在或没有权限") c.ShowErrorPage(403, "项目不存在或没有权限")
} else { } else {
beego.Error("查询项目时出错 -> ", err) logs.Error("查询项目时出错 -> ", err)
c.ShowErrorPage(500, "查询项目时出错") c.ShowErrorPage(500, "查询项目时出错")
} }
return return
@ -231,7 +237,7 @@ func (c *DocumentController) Edit() {
trees, err := models.NewDocument().FindDocumentTree(bookResult.BookId) trees, err := models.NewDocument().FindDocumentTree(bookResult.BookId)
if err != nil { if err != nil {
beego.Error("FindDocumentTree => ", err) logs.Error("FindDocumentTree => ", err)
} else { } else {
if len(trees) > 0 { if len(trees) > 0 {
if jtree, err := json.Marshal(trees); err == nil { if jtree, err := json.Marshal(trees); err == nil {
@ -242,7 +248,7 @@ func (c *DocumentController) Edit() {
} }
} }
c.Data["BaiDuMapKey"] = beego.AppConfig.DefaultString("baidumapkey", "") c.Data["BaiDuMapKey"] = web.AppConfig.DefaultString("baidumapkey", "")
if conf.GetUploadFileSize() > 0 { if conf.GetUploadFileSize() > 0 {
c.Data["UploadFileSize"] = conf.GetUploadFileSize() c.Data["UploadFileSize"] = conf.GetUploadFileSize()
@ -274,7 +280,7 @@ func (c *DocumentController) Create() {
if c.Member.IsAdministrator() { if c.Member.IsAdministrator() {
book, err := models.NewBook().FindByFieldFirst("identify", identify) book, err := models.NewBook().FindByFieldFirst("identify", identify)
if err != nil { if err != nil {
beego.Error(err) logs.Error(err)
c.JsonResult(6002, "项目不存在或权限不足") c.JsonResult(6002, "项目不存在或权限不足")
} }
@ -283,7 +289,7 @@ func (c *DocumentController) Create() {
bookResult, err := models.NewBookResult().FindByIdentify(identify, c.Member.MemberId) bookResult, err := models.NewBookResult().FindByIdentify(identify, c.Member.MemberId)
if err != nil || bookResult.RoleId == conf.BookObserver { if err != nil || bookResult.RoleId == conf.BookObserver {
beego.Error("FindByIdentify => ", err) logs.Error("FindByIdentify => ", err)
c.JsonResult(6002, "项目不存在或权限不足") c.JsonResult(6002, "项目不存在或权限不足")
} }
@ -327,7 +333,7 @@ func (c *DocumentController) Create() {
} }
if err := document.InsertOrUpdate(); err != nil { if err := document.InsertOrUpdate(); err != nil {
beego.Error("添加或更新文档时出错 -> ", err) logs.Error("添加或更新文档时出错 -> ", err)
c.JsonResult(6005, "保存失败") c.JsonResult(6005, "保存失败")
} else { } else {
c.JsonResult(0, "ok", document) c.JsonResult(0, "ok", document)
@ -395,7 +401,7 @@ func (c *DocumentController) Upload() {
book, err := models.NewBookResult().FindByIdentify(identify, c.Member.MemberId) book, err := models.NewBookResult().FindByIdentify(identify, c.Member.MemberId)
if err != nil { if err != nil {
beego.Error("DocumentController.Edit => ", err) logs.Error("DocumentController.Edit => ", err)
if err == orm.ErrNoRows { if err == orm.ErrNoRows {
c.JsonResult(6006, "权限不足") c.JsonResult(6006, "权限不足")
} }
@ -439,7 +445,7 @@ func (c *DocumentController) Upload() {
err = c.SaveToFile(name, filePath) err = c.SaveToFile(name, filePath)
if err != nil { if err != nil {
beego.Error("保存文件失败 -> ", err) logs.Error("保存文件失败 -> ", err)
c.JsonResult(6005, "保存文件失败") c.JsonResult(6005, "保存文件失败")
} }
@ -472,7 +478,7 @@ func (c *DocumentController) Upload() {
if err != nil { if err != nil {
os.Remove(filePath) os.Remove(filePath)
beego.Error("文件保存失败 ->", err) logs.Error("文件保存失败 ->", err)
c.JsonResult(6006, "文件保存失败") c.JsonResult(6006, "文件保存失败")
} }
@ -480,7 +486,7 @@ func (c *DocumentController) Upload() {
attachment.HttpPath = conf.URLForNotHost("DocumentController.DownloadAttachment", ":key", identify, ":attach_id", attachment.AttachmentId) attachment.HttpPath = conf.URLForNotHost("DocumentController.DownloadAttachment", ":key", identify, ":attach_id", attachment.AttachmentId)
if err := attachment.Update(); err != nil { if err := attachment.Update(); err != nil {
beego.Error("保存文件失败 ->", err) logs.Error("保存文件失败 ->", err)
c.JsonResult(6005, "保存文件失败") c.JsonResult(6005, "保存文件失败")
} }
} }
@ -525,7 +531,7 @@ func (c *DocumentController) DownloadAttachment() {
if err == orm.ErrNoRows { if err == orm.ErrNoRows {
c.ShowErrorPage(404, "项目不存在或已删除") c.ShowErrorPage(404, "项目不存在或已删除")
} else { } else {
beego.Error("查找项目时出错 ->", err) logs.Error("查找项目时出错 ->", err)
c.ShowErrorPage(500, "系统错误") c.ShowErrorPage(500, "系统错误")
} }
} }
@ -547,7 +553,7 @@ func (c *DocumentController) DownloadAttachment() {
attachment, err := models.NewAttachment().Find(attachId) attachment, err := models.NewAttachment().Find(attachId)
if err != nil { if err != nil {
beego.Error("查找附件时出错 -> ", err) logs.Error("查找附件时出错 -> ", err)
if err == orm.ErrNoRows { if err == orm.ErrNoRows {
c.ShowErrorPage(404, "附件不存在或已删除") c.ShowErrorPage(404, "附件不存在或已删除")
} else { } else {
@ -575,21 +581,21 @@ func (c *DocumentController) RemoveAttachment() {
attach, err := models.NewAttachment().Find(attachId) attach, err := models.NewAttachment().Find(attachId)
if err != nil { if err != nil {
beego.Error(err) logs.Error(err)
c.JsonResult(6002, "附件不存在") c.JsonResult(6002, "附件不存在")
} }
document, err := models.NewDocument().Find(attach.DocumentId) document, err := models.NewDocument().Find(attach.DocumentId)
if err != nil { if err != nil {
beego.Error(err) logs.Error(err)
c.JsonResult(6003, "文档不存在") c.JsonResult(6003, "文档不存在")
} }
if c.Member.Role != conf.MemberSuperRole { if c.Member.Role != conf.MemberSuperRole {
rel, err := models.NewRelationship().FindByBookIdAndMemberId(document.BookId, c.Member.MemberId) rel, err := models.NewRelationship().FindByBookIdAndMemberId(document.BookId, c.Member.MemberId)
if err != nil { if err != nil {
beego.Error(err) logs.Error(err)
c.JsonResult(6004, "权限不足") c.JsonResult(6004, "权限不足")
} }
@ -600,7 +606,7 @@ func (c *DocumentController) RemoveAttachment() {
err = attach.Delete() err = attach.Delete()
if err != nil { if err != nil {
beego.Error(err) logs.Error(err)
c.JsonResult(6005, "删除失败") c.JsonResult(6005, "删除失败")
} }
@ -622,7 +628,7 @@ func (c *DocumentController) Delete() {
if c.Member.IsAdministrator() { if c.Member.IsAdministrator() {
book, err := models.NewBook().FindByFieldFirst("identify", identify) book, err := models.NewBook().FindByFieldFirst("identify", identify)
if err != nil { if err != nil {
beego.Error("FindByIdentify => ", err) logs.Error("FindByIdentify => ", err)
c.JsonResult(6002, "项目不存在或权限不足") c.JsonResult(6002, "项目不存在或权限不足")
} }
@ -631,7 +637,7 @@ func (c *DocumentController) Delete() {
bookResult, err := models.NewBookResult().FindByIdentify(identify, c.Member.MemberId) bookResult, err := models.NewBookResult().FindByIdentify(identify, c.Member.MemberId)
if err != nil || bookResult.RoleId == conf.BookObserver { if err != nil || bookResult.RoleId == conf.BookObserver {
beego.Error("FindByIdentify => ", err) logs.Error("FindByIdentify => ", err)
c.JsonResult(6002, "项目不存在或权限不足") c.JsonResult(6002, "项目不存在或权限不足")
} }
@ -645,7 +651,7 @@ func (c *DocumentController) Delete() {
doc, err := models.NewDocument().Find(docId) doc, err := models.NewDocument().Find(docId)
if err != nil { if err != nil {
beego.Error("Delete => ", err) logs.Error("Delete => ", err)
c.JsonResult(6003, "删除失败") c.JsonResult(6003, "删除失败")
} }
// 如果文档所属项目错误 // 如果文档所属项目错误
@ -692,7 +698,7 @@ func (c *DocumentController) Content() {
bookResult, err := models.NewBookResult().FindByIdentify(identify, c.Member.MemberId) bookResult, err := models.NewBookResult().FindByIdentify(identify, c.Member.MemberId)
if err != nil || bookResult.RoleId == conf.BookObserver { if err != nil || bookResult.RoleId == conf.BookObserver {
beego.Error("项目不存在或权限不足 -> ", err) logs.Error("项目不存在或权限不足 -> ", err)
c.JsonResult(6002, "项目不存在或权限不足") c.JsonResult(6002, "项目不存在或权限不足")
} }
@ -722,7 +728,7 @@ func (c *DocumentController) Content() {
} }
if doc.Version != version && !strings.EqualFold(isCover, "yes") { if doc.Version != version && !strings.EqualFold(isCover, "yes") {
beego.Info("%d|", version, doc.Version) logs.Info("%d|", version, doc.Version)
c.JsonResult(6005, "文档已被修改确定要覆盖吗?") c.JsonResult(6005, "文档已被修改确定要覆盖吗?")
} }
@ -749,7 +755,7 @@ func (c *DocumentController) Content() {
doc.ModifyAt = c.Member.MemberId doc.ModifyAt = c.Member.MemberId
if err := doc.InsertOrUpdate(); err != nil { if err := doc.InsertOrUpdate(); err != nil {
beego.Error("InsertOrUpdate => ", err) logs.Error("InsertOrUpdate => ", err)
c.JsonResult(6006, "保存失败") c.JsonResult(6006, "保存失败")
} }
@ -759,7 +765,7 @@ func (c *DocumentController) Content() {
if c.EnableDocumentHistory && cryptil.Md5Crypt(history.Markdown) != cryptil.Md5Crypt(doc.Markdown) { if c.EnableDocumentHistory && cryptil.Md5Crypt(history.Markdown) != cryptil.Md5Crypt(doc.Markdown) {
_, err = history.InsertOrUpdate() _, err = history.InsertOrUpdate()
if err != nil { if err != nil {
beego.Error("DocumentHistory InsertOrUpdate => ", err) logs.Error("DocumentHistory InsertOrUpdate => ", err)
} }
} }
}(history) }(history)
@ -819,7 +825,7 @@ func (c *DocumentController) Export() {
if err == orm.ErrNoRows { if err == orm.ErrNoRows {
c.ShowErrorPage(404, "项目不存在") c.ShowErrorPage(404, "项目不存在")
} else { } else {
beego.Error("查找项目时出错 ->", err) logs.Error("查找项目时出错 ->", err)
c.ShowErrorPage(500, "查找项目时出错") c.ShowErrorPage(500, "查找项目时出错")
} }
} }
@ -839,7 +845,7 @@ func (c *DocumentController) Export() {
if bookResult.Editor != "markdown" { if bookResult.Editor != "markdown" {
c.ShowErrorPage(500, "当前项目不支持Markdown编辑器") c.ShowErrorPage(500, "当前项目不支持Markdown编辑器")
} }
p, err := bookResult.ExportMarkdown(c.CruSession.SessionID()) p, err := bookResult.ExportMarkdown(c.CruSession.SessionID(context.TODO()))
if err != nil { if err != nil {
c.ShowErrorPage(500, "导出文档失败") c.ShowErrorPage(500, "导出文档失败")
@ -874,7 +880,7 @@ func (c *DocumentController) Export() {
c.Abort("200") c.Abort("200")
} else if output == "pdf" || output == "epub" || output == "docx" || output == "mobi" { } else if output == "pdf" || output == "epub" || output == "docx" || output == "mobi" {
if err := models.BackgroundConvert(c.CruSession.SessionID(), bookResult); err != nil && err != gopool.ErrHandlerIsExist { if err := models.BackgroundConvert(c.CruSession.SessionID(context.TODO()), bookResult); err != nil && err != gopool.ErrHandlerIsExist {
c.ShowErrorPage(500, "导出失败,请查看系统日志") c.ShowErrorPage(500, "导出失败,请查看系统日志")
} }
@ -900,13 +906,13 @@ func (c *DocumentController) QrCode() {
uri := conf.URLFor("DocumentController.Index", ":key", identify) uri := conf.URLFor("DocumentController.Index", ":key", identify)
code, err := qr.Encode(uri, qr.L, qr.Unicode) code, err := qr.Encode(uri, qr.L, qr.Unicode)
if err != nil { if err != nil {
beego.Error("生成二维码失败 ->", err) logs.Error("生成二维码失败 ->", err)
c.ShowErrorPage(500, "生成二维码失败") c.ShowErrorPage(500, "生成二维码失败")
} }
code, err = barcode.Scale(code, 150, 150) code, err = barcode.Scale(code, 150, 150)
if err != nil { if err != nil {
beego.Error("生成二维码失败 ->", err) logs.Error("生成二维码失败 ->", err)
c.ShowErrorPage(500, "生成二维码失败") c.ShowErrorPage(500, "生成二维码失败")
} }
@ -916,7 +922,7 @@ func (c *DocumentController) QrCode() {
err = png.Encode(c.Ctx.ResponseWriter, code) err = png.Encode(c.Ctx.ResponseWriter, code)
if err != nil { if err != nil {
beego.Error("生成二维码失败 ->", err) logs.Error("生成二维码失败 ->", err)
c.ShowErrorPage(500, "生成二维码失败") c.ShowErrorPage(500, "生成二维码失败")
} }
} }
@ -942,7 +948,7 @@ func (c *DocumentController) Search() {
docs, err := models.NewDocumentSearchResult().SearchDocument(keyword, bookResult.BookId) docs, err := models.NewDocumentSearchResult().SearchDocument(keyword, bookResult.BookId)
if err != nil { if err != nil {
beego.Error(err) logs.Error(err)
c.JsonResult(6002, "搜索结果错误") c.JsonResult(6002, "搜索结果错误")
} }
@ -976,7 +982,7 @@ func (c *DocumentController) History() {
if c.Member.IsAdministrator() { if c.Member.IsAdministrator() {
book, err := models.NewBook().FindByFieldFirst("identify", identify) book, err := models.NewBook().FindByFieldFirst("identify", identify)
if err != nil { if err != nil {
beego.Error("查找项目失败 ->", err) logs.Error("查找项目失败 ->", err)
c.Data["ErrorMessage"] = "项目不存在或权限不足" c.Data["ErrorMessage"] = "项目不存在或权限不足"
return return
} }
@ -986,7 +992,7 @@ func (c *DocumentController) History() {
} else { } else {
bookResult, err := models.NewBookResult().FindByIdentify(identify, c.Member.MemberId) bookResult, err := models.NewBookResult().FindByIdentify(identify, c.Member.MemberId)
if err != nil || bookResult.RoleId == conf.BookObserver { if err != nil || bookResult.RoleId == conf.BookObserver {
beego.Error("查找项目失败 ->", err) logs.Error("查找项目失败 ->", err)
c.Data["ErrorMessage"] = "项目不存在或权限不足" c.Data["ErrorMessage"] = "项目不存在或权限不足"
return return
} }
@ -1002,7 +1008,7 @@ func (c *DocumentController) History() {
doc, err := models.NewDocument().Find(docId) doc, err := models.NewDocument().Find(docId)
if err != nil { if err != nil {
beego.Error("Delete => ", err) logs.Error("Delete => ", err)
c.Data["ErrorMessage"] = "获取历史失败" c.Data["ErrorMessage"] = "获取历史失败"
return return
} }
@ -1015,7 +1021,7 @@ func (c *DocumentController) History() {
histories, totalCount, err := models.NewDocumentHistory().FindToPager(docId, pageIndex, conf.PageSize) histories, totalCount, err := models.NewDocumentHistory().FindToPager(docId, pageIndex, conf.PageSize)
if err != nil { if err != nil {
beego.Error("分页查找文档历史失败 ->", err) logs.Error("分页查找文档历史失败 ->", err)
c.Data["ErrorMessage"] = "获取历史失败" c.Data["ErrorMessage"] = "获取历史失败"
return return
} }
@ -1049,7 +1055,7 @@ func (c *DocumentController) DeleteHistory() {
if c.Member.IsAdministrator() { if c.Member.IsAdministrator() {
book, err := models.NewBook().FindByFieldFirst("identify", identify) book, err := models.NewBook().FindByFieldFirst("identify", identify)
if err != nil { if err != nil {
beego.Error("查找项目失败 ->", err) logs.Error("查找项目失败 ->", err)
c.JsonResult(6002, "项目不存在或权限不足") c.JsonResult(6002, "项目不存在或权限不足")
} }
@ -1057,7 +1063,7 @@ func (c *DocumentController) DeleteHistory() {
} else { } else {
bookResult, err := models.NewBookResult().FindByIdentify(identify, c.Member.MemberId) bookResult, err := models.NewBookResult().FindByIdentify(identify, c.Member.MemberId)
if err != nil || bookResult.RoleId == conf.BookObserver { if err != nil || bookResult.RoleId == conf.BookObserver {
beego.Error("查找项目失败 ->", err) logs.Error("查找项目失败 ->", err)
c.JsonResult(6002, "项目不存在或权限不足") c.JsonResult(6002, "项目不存在或权限不足")
} }
@ -1070,7 +1076,7 @@ func (c *DocumentController) DeleteHistory() {
doc, err := models.NewDocument().Find(docId) doc, err := models.NewDocument().Find(docId)
if err != nil { if err != nil {
beego.Error("Delete => ", err) logs.Error("Delete => ", err)
c.JsonResult(6001, "获取历史失败") c.JsonResult(6001, "获取历史失败")
} }
@ -1081,7 +1087,7 @@ func (c *DocumentController) DeleteHistory() {
err = models.NewDocumentHistory().Delete(historyId, docId) err = models.NewDocumentHistory().Delete(historyId, docId)
if err != nil { if err != nil {
beego.Error(err) logs.Error(err)
c.JsonResult(6002, "删除失败") c.JsonResult(6002, "删除失败")
} }
@ -1107,7 +1113,7 @@ func (c *DocumentController) RestoreHistory() {
if c.Member.IsAdministrator() { if c.Member.IsAdministrator() {
book, err := models.NewBook().FindByFieldFirst("identify", identify) book, err := models.NewBook().FindByFieldFirst("identify", identify)
if err != nil { if err != nil {
beego.Error("FindByIdentify => ", err) logs.Error("FindByIdentify => ", err)
c.JsonResult(6002, "项目不存在或权限不足") c.JsonResult(6002, "项目不存在或权限不足")
} }
@ -1115,7 +1121,7 @@ func (c *DocumentController) RestoreHistory() {
} else { } else {
bookResult, err := models.NewBookResult().FindByIdentify(identify, c.Member.MemberId) bookResult, err := models.NewBookResult().FindByIdentify(identify, c.Member.MemberId)
if err != nil || bookResult.RoleId == conf.BookObserver { if err != nil || bookResult.RoleId == conf.BookObserver {
beego.Error("FindByIdentify => ", err) logs.Error("FindByIdentify => ", err)
c.JsonResult(6002, "项目不存在或权限不足") c.JsonResult(6002, "项目不存在或权限不足")
} }
@ -1128,7 +1134,7 @@ func (c *DocumentController) RestoreHistory() {
doc, err := models.NewDocument().Find(docId) doc, err := models.NewDocument().Find(docId)
if err != nil { if err != nil {
beego.Error("Delete => ", err) logs.Error("Delete => ", err)
c.JsonResult(6001, "获取历史失败") c.JsonResult(6001, "获取历史失败")
} }
@ -1139,7 +1145,7 @@ func (c *DocumentController) RestoreHistory() {
err = models.NewDocumentHistory().Restore(historyId, docId, c.Member.MemberId) err = models.NewDocumentHistory().Restore(historyId, docId, c.Member.MemberId)
if err != nil { if err != nil {
beego.Error(err) logs.Error(err)
c.JsonResult(6002, "删除失败") c.JsonResult(6002, "删除失败")
} }
@ -1161,7 +1167,7 @@ func (c *DocumentController) Compare() {
if c.Member.IsAdministrator() { if c.Member.IsAdministrator() {
book, err := models.NewBook().FindByFieldFirst("identify", identify) book, err := models.NewBook().FindByFieldFirst("identify", identify)
if err != nil { if err != nil {
beego.Error("DocumentController.Compare => ", err) logs.Error("DocumentController.Compare => ", err)
c.ShowErrorPage(403, "权限不足") c.ShowErrorPage(403, "权限不足")
return return
} }
@ -1172,7 +1178,7 @@ func (c *DocumentController) Compare() {
} else { } else {
bookResult, err := models.NewBookResult().FindByIdentify(identify, c.Member.MemberId) bookResult, err := models.NewBookResult().FindByIdentify(identify, c.Member.MemberId)
if err != nil || bookResult.RoleId == conf.BookObserver { if err != nil || bookResult.RoleId == conf.BookObserver {
beego.Error("FindByIdentify => ", err) logs.Error("FindByIdentify => ", err)
c.ShowErrorPage(403, "权限不足") c.ShowErrorPage(403, "权限不足")
return return
} }
@ -1188,7 +1194,7 @@ func (c *DocumentController) Compare() {
history, err := models.NewDocumentHistory().Find(historyId) history, err := models.NewDocumentHistory().Find(historyId)
if err != nil { if err != nil {
beego.Error("DocumentController.Compare => ", err) logs.Error("DocumentController.Compare => ", err)
c.ShowErrorPage(60003, err.Error()) c.ShowErrorPage(60003, err.Error())
} }
@ -1215,7 +1221,7 @@ func (c *DocumentController) isReadable(identify, token string) *models.BookResu
book, err := models.NewBook().FindByFieldFirst("identify", identify) book, err := models.NewBook().FindByFieldFirst("identify", identify)
if err != nil { if err != nil {
beego.Error(err) logs.Error(err)
c.ShowErrorPage(500, "项目不存在") c.ShowErrorPage(500, "项目不存在")
} }
bookResult := models.NewBookResult().ToBookResult(*book) bookResult := models.NewBookResult().ToBookResult(*book)
@ -1240,7 +1246,7 @@ func (c *DocumentController) isReadable(identify, token string) *models.BookResu
if token != "" && strings.EqualFold(token, book.PrivateToken) { if token != "" && strings.EqualFold(token, book.PrivateToken) {
c.SetSession(identify, token) c.SetSession(identify, token)
} else if token, ok := c.GetSession(identify).(string); !ok || !strings.EqualFold(token, book.PrivateToken) { } else if token, ok := c.GetSession(identify).(string); !ok || !strings.EqualFold(token, book.PrivateToken) {
beego.Info("尝试访问文档但权限不足 ->", identify, token) logs.Info("尝试访问文档但权限不足 ->", identify, token)
c.ShowErrorPage(403, "权限不足") c.ShowErrorPage(403, "权限不足")
} }
} else if password := c.GetString("bPassword", ""); !isOk && book.BookPassword != "" && password != "" { } else if password := c.GetString("bPassword", ""); !isOk && book.BookPassword != "" && password != "" {
@ -1260,12 +1266,12 @@ func (c *DocumentController) isReadable(identify, token string) *models.BookResu
if password, ok := c.GetSession(identify).(string); !ok || !strings.EqualFold(password, book.BookPassword) { if password, ok := c.GetSession(identify).(string); !ok || !strings.EqualFold(password, book.BookPassword) {
body, err := c.ExecuteViewPathTemplate("document/document_password.tpl", map[string]string{"Identify": book.Identify}) body, err := c.ExecuteViewPathTemplate("document/document_password.tpl", map[string]string{"Identify": book.Identify})
if err != nil { if err != nil {
beego.Error("显示密码页面失败 ->", err) logs.Error("显示密码页面失败 ->", err)
} }
c.CustomAbort(200, body) c.CustomAbort(200, body)
} }
} else { } else {
beego.Info("尝试访问文档但权限不足 ->", identify, token) logs.Info("尝试访问文档但权限不足 ->", identify, token)
c.ShowErrorPage(403, "权限不足") c.ShowErrorPage(403, "权限不足")
} }
} }
@ -1276,8 +1282,8 @@ func (c *DocumentController) isReadable(identify, token string) *models.BookResu
} }
func promptUserToLogIn(c *DocumentController) { func promptUserToLogIn(c *DocumentController) {
beego.Info("Access " + c.Ctx.Request.URL.RequestURI() + " not permitted.") logs.Info("Access " + c.Ctx.Request.URL.RequestURI() + " not permitted.")
beego.Info(" Access will be redirected to login page(SessionId: " + c.CruSession.SessionID() + ").") logs.Info(" Access will be redirected to login page(SessionId: " + c.CruSession.SessionID(context.TODO()) + ").")
if c.IsAjax() { if c.IsAjax() {
c.JsonResult(6000, "请重新登录。") c.JsonResult(6000, "请重新登录。")

View File

@ -4,7 +4,7 @@ import (
"math" "math"
"net/url" "net/url"
"github.com/astaxie/beego" "github.com/beego/beego/v2/core/logs"
"github.com/mindoc-org/mindoc/conf" "github.com/mindoc-org/mindoc/conf"
"github.com/mindoc-org/mindoc/models" "github.com/mindoc-org/mindoc/models"
"github.com/mindoc-org/mindoc/utils/pagination" "github.com/mindoc-org/mindoc/utils/pagination"
@ -37,7 +37,7 @@ func (c *HomeController) Index() {
books, totalCount, err := models.NewBook().FindForHomeToPager(pageIndex, pageSize, memberId) books, totalCount, err := models.NewBook().FindForHomeToPager(pageIndex, pageSize, memberId)
if err != nil { if err != nil {
beego.Error(err) logs.Error(err)
c.Abort("500") c.Abort("500")
} }
if totalCount > 0 { if totalCount > 0 {

View File

@ -1,8 +1,8 @@
package controllers package controllers
import ( import (
"github.com/astaxie/beego" "github.com/beego/beego/v2/client/orm"
"github.com/astaxie/beego/orm" "github.com/beego/beego/v2/core/logs"
"github.com/mindoc-org/mindoc/conf" "github.com/mindoc-org/mindoc/conf"
"github.com/mindoc-org/mindoc/models" "github.com/mindoc-org/mindoc/models"
"github.com/mindoc-org/mindoc/utils/pagination" "github.com/mindoc-org/mindoc/utils/pagination"
@ -11,6 +11,7 @@ import (
type ItemsetsController struct { type ItemsetsController struct {
BaseController BaseController
} }
func (c *ItemsetsController) Prepare() { func (c *ItemsetsController) Prepare() {
c.BaseController.Prepare() c.BaseController.Prepare()
@ -65,7 +66,7 @@ func (c *ItemsetsController) List() {
if err == orm.ErrNoRows { if err == orm.ErrNoRows {
c.Abort("404") c.Abort("404")
} else { } else {
beego.Error(err) logs.Error(err)
c.Abort("500") c.Abort("500")
} }
} }

View File

@ -3,8 +3,8 @@ package controllers
import ( import (
"math" "math"
"github.com/astaxie/beego" "github.com/beego/beego/v2/client/orm"
"github.com/astaxie/beego/orm" "github.com/beego/beego/v2/core/logs"
"github.com/mindoc-org/mindoc/conf" "github.com/mindoc-org/mindoc/conf"
"github.com/mindoc-org/mindoc/models" "github.com/mindoc-org/mindoc/models"
"github.com/mindoc-org/mindoc/utils/pagination" "github.com/mindoc-org/mindoc/utils/pagination"
@ -40,7 +40,7 @@ func (c *LabelController) Index() {
if err == orm.ErrNoRows { if err == orm.ErrNoRows {
c.Abort("404") c.Abort("404")
} else { } else {
beego.Error(err) logs.Error(err)
c.Abort("500") c.Abort("500")
} }
} }
@ -51,7 +51,7 @@ func (c *LabelController) Index() {
searchResult, totalCount, err := models.NewBook().FindForLabelToPager(labelName, pageIndex, conf.PageSize, memberId) searchResult, totalCount, err := models.NewBook().FindForLabelToPager(labelName, pageIndex, conf.PageSize, memberId)
if err != nil && err != orm.ErrNoRows { if err != nil && err != orm.ErrNoRows {
beego.Error("查询标签时出错 ->", err) logs.Error("查询标签时出错 ->", err)
c.ShowErrorPage(500, "查询文档列表时出错") c.ShowErrorPage(500, "查询文档列表时出错")
} }
if totalCount > 0 { if totalCount > 0 {

View File

@ -13,15 +13,15 @@ import (
"io/ioutil" "io/ioutil"
"os" "os"
"github.com/astaxie/beego" "github.com/beego/beego/v2/client/orm"
"github.com/astaxie/beego/logs" "github.com/beego/beego/v2/core/logs"
"github.com/astaxie/beego/orm" "github.com/beego/beego/v2/server/web"
"github.com/mindoc-org/mindoc/conf" "github.com/mindoc-org/mindoc/conf"
"github.com/mindoc-org/mindoc/models" "github.com/mindoc-org/mindoc/models"
"github.com/mindoc-org/mindoc/utils" "github.com/mindoc-org/mindoc/utils"
"github.com/mindoc-org/mindoc/utils/filetil" "github.com/mindoc-org/mindoc/utils/filetil"
"github.com/mindoc-org/mindoc/utils/pagination" "github.com/mindoc-org/mindoc/utils/pagination"
"gopkg.in/russross/blackfriday.v2" "github.com/russross/blackfriday/v2"
) )
type ManagerController struct { type ManagerController struct {
@ -210,7 +210,7 @@ func (c *ManagerController) EditMember() {
member, err := models.NewMember().Find(member_id) member, err := models.NewMember().Find(member_id)
if err != nil { if err != nil {
beego.Error(err) logs.Error(err)
c.Abort("404") c.Abort("404")
} }
if c.Ctx.Input.IsPost() { if c.Ctx.Input.IsPost() {
@ -235,7 +235,7 @@ func (c *ManagerController) EditMember() {
if password1 != "" { if password1 != "" {
password, err := utils.PasswordHash(password1) password, err := utils.PasswordHash(password1)
if err != nil { if err != nil {
beego.Error(err) logs.Error(err)
c.JsonResult(6003, "对用户密码加密时出错") c.JsonResult(6003, "对用户密码加密时出错")
} }
member.Password = password member.Password = password
@ -261,7 +261,7 @@ func (c *ManagerController) DeleteMember() {
member, err := models.NewMember().Find(member_id) member, err := models.NewMember().Find(member_id)
if err != nil { if err != nil {
beego.Error(err) logs.Error(err)
c.JsonResult(500, "用户不存在") c.JsonResult(500, "用户不存在")
} }
if member.Role == conf.MemberSuperRole { if member.Role == conf.MemberSuperRole {
@ -270,14 +270,14 @@ func (c *ManagerController) DeleteMember() {
superMember, err := models.NewMember().FindByFieldFirst("role", 0) superMember, err := models.NewMember().FindByFieldFirst("role", 0)
if err != nil { if err != nil {
beego.Error(err) logs.Error(err)
c.JsonResult(5001, "未能找到超级管理员") c.JsonResult(5001, "未能找到超级管理员")
} }
err = models.NewMember().Delete(member_id, superMember.MemberId) err = models.NewMember().Delete(member_id, superMember.MemberId)
if err != nil { if err != nil {
beego.Error(err) logs.Error(err)
c.JsonResult(5002, "删除失败") c.JsonResult(5002, "删除失败")
} }
c.JsonResult(0, "ok") c.JsonResult(0, "ok")
@ -341,7 +341,7 @@ func (c *ManagerController) EditBook() {
autoRelease := strings.TrimSpace(c.GetString("auto_release")) == "on" autoRelease := strings.TrimSpace(c.GetString("auto_release")) == "on"
publisher := strings.TrimSpace(c.GetString("publisher")) publisher := strings.TrimSpace(c.GetString("publisher"))
historyCount, _ := c.GetInt("history_count", 0) historyCount, _ := c.GetInt("history_count", 0)
itemId,_ := c.GetInt("itemId") itemId, _ := c.GetInt("itemId")
if strings.Count(description, "") > 500 { if strings.Count(description, "") > 500 {
c.JsonResult(6004, "项目描述不能大于500字") c.JsonResult(6004, "项目描述不能大于500字")
@ -356,7 +356,7 @@ func (c *ManagerController) EditBook() {
} }
} }
if !models.NewItemsets().Exist(itemId) { if !models.NewItemsets().Exist(itemId) {
c.JsonResult(6006,"项目空间不存在") c.JsonResult(6006, "项目空间不存在")
} }
book.Publisher = publisher book.Publisher = publisher
book.HistoryCount = historyCount book.HistoryCount = historyCount
@ -517,7 +517,7 @@ func (c *ManagerController) Transfer() {
rel, err := models.NewRelationship().FindFounder(book.BookId) rel, err := models.NewRelationship().FindFounder(book.BookId)
if err != nil { if err != nil {
beego.Error("FindFounder => ", err) logs.Error("FindFounder => ", err)
c.JsonResult(6009, "查询项目创始人失败") c.JsonResult(6009, "查询项目创始人失败")
} }
if member.MemberId == rel.MemberId { if member.MemberId == rel.MemberId {
@ -647,7 +647,7 @@ func (c *ManagerController) AttachDetailed() {
attach, err := models.NewAttachmentResult().Find(attach_id) attach, err := models.NewAttachmentResult().Find(attach_id)
if err != nil { if err != nil {
beego.Error("AttachDetailed => ", err) logs.Error("AttachDetailed => ", err)
if err == orm.ErrNoRows { if err == orm.ErrNoRows {
c.Abort("404") c.Abort("404")
} else { } else {
@ -674,13 +674,13 @@ func (c *ManagerController) AttachDelete() {
attach, err := models.NewAttachment().Find(attachId) attach, err := models.NewAttachment().Find(attachId)
if err != nil { if err != nil {
beego.Error("AttachDelete => ", err) logs.Error("AttachDelete => ", err)
c.JsonResult(6001, err.Error()) c.JsonResult(6001, err.Error())
} }
attach.FilePath = filepath.Join(conf.WorkingDirectory, attach.FilePath) attach.FilePath = filepath.Join(conf.WorkingDirectory, attach.FilePath)
if err := attach.Delete(); err != nil { if err := attach.Delete(); err != nil {
beego.Error("AttachDelete => ", err) logs.Error("AttachDelete => ", err)
c.JsonResult(6002, err.Error()) c.JsonResult(6002, err.Error())
} }
c.JsonResult(0, "ok") c.JsonResult(0, "ok")
@ -714,7 +714,7 @@ func (c *ManagerController) LabelDelete() {
labelId, err := strconv.Atoi(c.Ctx.Input.Param(":id")) labelId, err := strconv.Atoi(c.Ctx.Input.Param(":id"))
if err != nil { if err != nil {
beego.Error("获取删除标签参数时出错:", err) logs.Error("获取删除标签参数时出错:", err)
c.JsonResult(50001, "参数错误") c.JsonResult(50001, "参数错误")
} }
if labelId <= 0 { if labelId <= 0 {
@ -723,7 +723,7 @@ func (c *ManagerController) LabelDelete() {
label, err := models.NewLabel().FindFirst("label_id", labelId) label, err := models.NewLabel().FindFirst("label_id", labelId)
if err != nil { if err != nil {
beego.Error("查询标签时出错:", err) logs.Error("查询标签时出错:", err)
c.JsonResult(50001, "查询标签时出错:"+err.Error()) c.JsonResult(50001, "查询标签时出错:"+err.Error())
} }
if err := label.Delete(); err != nil { if err := label.Delete(); err != nil {
@ -744,22 +744,22 @@ func (c *ManagerController) Config() {
tf, err := ioutil.TempFile(os.TempDir(), "mindoc") tf, err := ioutil.TempFile(os.TempDir(), "mindoc")
if err != nil { if err != nil {
beego.Error("创建临时文件失败 ->", err) logs.Error("创建临时文件失败 ->", err)
c.JsonResult(5001, "创建临时文件失败") c.JsonResult(5001, "创建临时文件失败")
} }
defer tf.Close() defer tf.Close()
tf.WriteString(content) tf.WriteString(content)
err = beego.LoadAppConfig("ini", tf.Name()) err = web.LoadAppConfig("ini", tf.Name())
if err != nil { if err != nil {
beego.Error("加载配置文件失败 ->", err) logs.Error("加载配置文件失败 ->", err)
c.JsonResult(5002, "加载配置文件失败") c.JsonResult(5002, "加载配置文件失败")
} }
err = filetil.CopyFile(tf.Name(), conf.ConfigurationFile) err = filetil.CopyFile(tf.Name(), conf.ConfigurationFile)
if err != nil { if err != nil {
beego.Error("保存配置文件失败 ->", err) logs.Error("保存配置文件失败 ->", err)
c.JsonResult(5003, "保存配置文件失败") c.JsonResult(5003, "保存配置文件失败")
} }
c.JsonResult(0, "保存成功") c.JsonResult(0, "保存成功")
@ -903,7 +903,7 @@ func (c *ManagerController) TeamMemberList() {
b, err := json.Marshal(teams) b, err := json.Marshal(teams)
if err != nil { if err != nil {
beego.Error("编码 JSON 结果失败 ->", err) logs.Error("编码 JSON 结果失败 ->", err)
c.Data["Result"] = template.JS("[]") c.Data["Result"] = template.JS("[]")
} else { } else {
c.Data["Result"] = template.JS(string(b)) c.Data["Result"] = template.JS(string(b))
@ -1030,7 +1030,7 @@ func (c *ManagerController) TeamBookList() {
b, err := json.Marshal(teams) b, err := json.Marshal(teams)
if err != nil { if err != nil {
beego.Error("编码 JSON 结果失败 ->", err) logs.Error("编码 JSON 结果失败 ->", err)
c.Data["Result"] = template.JS("[]") c.Data["Result"] = template.JS("[]")
} else { } else {
c.Data["Result"] = template.JS(string(b)) c.Data["Result"] = template.JS(string(b))
@ -1124,7 +1124,6 @@ func (c *ManagerController) Itemsets() {
c.Data["Lists"] = items c.Data["Lists"] = items
} }
//编辑或添加项目空间. //编辑或添加项目空间.

View File

@ -4,7 +4,7 @@ import (
"strconv" "strconv"
"strings" "strings"
"github.com/astaxie/beego" "github.com/beego/beego/v2/core/logs"
"github.com/mindoc-org/mindoc/conf" "github.com/mindoc-org/mindoc/conf"
"github.com/mindoc-org/mindoc/models" "github.com/mindoc-org/mindoc/models"
"github.com/mindoc-org/mindoc/utils" "github.com/mindoc-org/mindoc/utils"
@ -41,20 +41,20 @@ func (c *SearchController) Index() {
searchResult, totalCount, err := models.NewDocumentSearchResult().FindToPager(sqltil.EscapeLike(keyword), pageIndex, conf.PageSize, memberId) searchResult, totalCount, err := models.NewDocumentSearchResult().FindToPager(sqltil.EscapeLike(keyword), pageIndex, conf.PageSize, memberId)
if err != nil { if err != nil {
beego.Error("搜索失败 ->",err) logs.Error("搜索失败 ->", err)
return return
} }
if totalCount > 0 { if totalCount > 0 {
pager := pagination.NewPagination(c.Ctx.Request, totalCount, conf.PageSize,c.BaseUrl()) pager := pagination.NewPagination(c.Ctx.Request, totalCount, conf.PageSize, c.BaseUrl())
c.Data["PageHtml"] = pager.HtmlPages() c.Data["PageHtml"] = pager.HtmlPages()
} else { } else {
c.Data["PageHtml"] = "" c.Data["PageHtml"] = ""
} }
if len(searchResult) > 0 { if len(searchResult) > 0 {
keywords := strings.Split(keyword," ") keywords := strings.Split(keyword, " ")
for _, item := range searchResult { for _, item := range searchResult {
for _,word := range keywords { for _, word := range keywords {
item.DocumentName = strings.Replace(item.DocumentName, word, "<em>"+word+"</em>", -1) item.DocumentName = strings.Replace(item.DocumentName, word, "<em>"+word+"</em>", -1)
if item.Description != "" { if item.Description != "" {
src := item.Description src := item.Description
@ -102,7 +102,7 @@ func (c *SearchController) User() {
//members, err := models.NewMemberRelationshipResult().FindNotJoinUsersByAccount(book.BookId, 10, "%"+keyword+"%") //members, err := models.NewMemberRelationshipResult().FindNotJoinUsersByAccount(book.BookId, 10, "%"+keyword+"%")
members, err := models.NewMemberRelationshipResult().FindNotJoinUsersByAccountOrRealName(book.BookId, 10, "%"+keyword+"%") members, err := models.NewMemberRelationshipResult().FindNotJoinUsersByAccountOrRealName(book.BookId, 10, "%"+keyword+"%")
if err != nil { if err != nil {
beego.Error("查询用户列表出错:" + err.Error()) logs.Error("查询用户列表出错:" + err.Error())
c.JsonResult(500, err.Error()) c.JsonResult(500, err.Error())
} }
result := models.SelectMemberResult{} result := models.SelectMemberResult{}

View File

@ -8,7 +8,7 @@ import (
"strings" "strings"
"time" "time"
"github.com/astaxie/beego/logs" "github.com/beego/beego/v2/core/logs"
"github.com/mindoc-org/mindoc/conf" "github.com/mindoc-org/mindoc/conf"
"github.com/mindoc-org/mindoc/graphics" "github.com/mindoc-org/mindoc/graphics"
"github.com/mindoc-org/mindoc/models" "github.com/mindoc-org/mindoc/models"

View File

@ -4,7 +4,7 @@ import (
"errors" "errors"
"strings" "strings"
"github.com/astaxie/beego/orm" "github.com/beego/beego/v2/client/orm"
"github.com/mindoc-org/mindoc/conf" "github.com/mindoc-org/mindoc/conf"
"github.com/mindoc-org/mindoc/models" "github.com/mindoc-org/mindoc/models"
) )
@ -14,7 +14,7 @@ type TemplateController struct {
BookId int BookId int
} }
func (c *TemplateController) isPermission() (error) { func (c *TemplateController) isPermission() error {
c.Prepare() c.Prepare()
bookIdentify := c.GetString("identify", "") bookIdentify := c.GetString("identify", "")
@ -44,39 +44,40 @@ func (c *TemplateController) isPermission() (error) {
} }
return nil return nil
} }
//获取指定模板信息 //获取指定模板信息
func (c *TemplateController) Get() { func (c *TemplateController) Get() {
if err := c.isPermission() ; err != nil { if err := c.isPermission(); err != nil {
c.JsonResult(500,err.Error()) c.JsonResult(500, err.Error())
} }
templateId, _ := c.GetInt("template_id",0) templateId, _ := c.GetInt("template_id", 0)
template,err := models.NewTemplate().Find(templateId) template, err := models.NewTemplate().Find(templateId)
if err != nil { if err != nil {
c.JsonResult(500,"读取模板失败") c.JsonResult(500, "读取模板失败")
} }
if template.IsGlobal == 0 && template.BookId != c.BookId { if template.IsGlobal == 0 && template.BookId != c.BookId {
c.JsonResult(404,"模板不存在或已删除") c.JsonResult(404, "模板不存在或已删除")
} }
c.JsonResult(0,"OK",template) c.JsonResult(0, "OK", template)
} }
//获取模板列表 //获取模板列表
func (c *TemplateController) List() { func (c *TemplateController) List() {
c.TplName = "template/list.tpl" c.TplName = "template/list.tpl"
if err := c.isPermission() ; err != nil { if err := c.isPermission(); err != nil {
c.Data["ErrorMessage"] = err.Error() c.Data["ErrorMessage"] = err.Error()
return return
} }
templateList,err := models.NewTemplate().FindAllByBookId(c.BookId) templateList, err := models.NewTemplate().FindAllByBookId(c.BookId)
if err != nil && err != orm.ErrNoRows{ if err != nil && err != orm.ErrNoRows {
c.Data["ErrorMessage"] = "查询项目模板失败" c.Data["ErrorMessage"] = "查询项目模板失败"
} }
if templateList != nil { if templateList != nil {
for i,t := range templateList { for i, t := range templateList {
templateList[i] = t.Preload() templateList[i] = t.Preload()
} }
} }
@ -86,32 +87,30 @@ func (c *TemplateController) List() {
//添加模板 //添加模板
func (c *TemplateController) Add() { func (c *TemplateController) Add() {
if err := c.isPermission() ; err != nil { if err := c.isPermission(); err != nil {
c.JsonResult(500,err.Error()) c.JsonResult(500, err.Error())
} }
templateId, _ := c.GetInt("template_id",0) templateId, _ := c.GetInt("template_id", 0)
content := c.GetString("content") content := c.GetString("content")
isGlobal,_ := c.GetInt("is_global",0) isGlobal, _ := c.GetInt("is_global", 0)
templateName := c.GetString("template_name","") templateName := c.GetString("template_name", "")
if templateName == "" || strings.Count(templateName,"") > 300 { if templateName == "" || strings.Count(templateName, "") > 300 {
c.JsonResult(500,"模板名称不能为空且必须小于300字") c.JsonResult(500, "模板名称不能为空且必须小于300字")
} }
template := models.NewTemplate() template := models.NewTemplate()
if templateId > 0 { if templateId > 0 {
t,err := template.Find(templateId); t, err := template.Find(templateId)
if err != nil { if err != nil {
c.JsonResult(500,"模板不存在") c.JsonResult(500, "模板不存在")
} }
template = t template = t
template.ModifyAt = c.Member.MemberId template.ModifyAt = c.Member.MemberId
} }
template.TemplateId = templateId template.TemplateId = templateId
template.BookId = c.BookId template.BookId = c.BookId
template.TemplateContent = content template.TemplateContent = content
@ -120,16 +119,16 @@ func (c *TemplateController) Add() {
//只有管理员才能设置全局模板 //只有管理员才能设置全局模板
if c.Member.IsAdministrator() { if c.Member.IsAdministrator() {
template.IsGlobal = isGlobal template.IsGlobal = isGlobal
}else{ } else {
template.IsGlobal = 0 template.IsGlobal = 0
//如果不是管理员需要判断是否有项目权限 //如果不是管理员需要判断是否有项目权限
rel,err := models.NewRelationship().FindByBookIdAndMemberId(c.BookId,c.Member.MemberId) rel, err := models.NewRelationship().FindByBookIdAndMemberId(c.BookId, c.Member.MemberId)
if err != nil || rel.RoleId == conf.BookObserver { if err != nil || rel.RoleId == conf.BookObserver {
c.JsonResult(403,"没有权限") c.JsonResult(403, "没有权限")
} }
//如果修改的模板不是本人创建的,并且又不是项目创建者则禁止修改 //如果修改的模板不是本人创建的,并且又不是项目创建者则禁止修改
if template.MemberId > 0 && template.MemberId != c.Member.MemberId && rel.RoleId != conf.BookFounder { if template.MemberId > 0 && template.MemberId != c.Member.MemberId && rel.RoleId != conf.BookFounder {
c.JsonResult(403,"没有权限") c.JsonResult(403, "没有权限")
} }
} }
template.MemberId = c.Member.MemberId template.MemberId = c.Member.MemberId
@ -137,51 +136,51 @@ func (c *TemplateController) Add() {
var cols []string var cols []string
if templateId > 0 { if templateId > 0 {
cols = []string{ "template_content", "modify_time","modify_at","version" } cols = []string{"template_content", "modify_time", "modify_at", "version"}
} }
if err := template.Save(cols...); err != nil { if err := template.Save(cols...); err != nil {
c.JsonResult(500,"报错模板失败") c.JsonResult(500, "报错模板失败")
} }
c.JsonResult(0,"OK",template) c.JsonResult(0, "OK", template)
} }
//删除模板 //删除模板
func (c *TemplateController) Delete() { func (c *TemplateController) Delete() {
if err := c.isPermission() ; err != nil { if err := c.isPermission(); err != nil {
c.JsonResult(500,err.Error()) c.JsonResult(500, err.Error())
} }
templateId, _ := c.GetInt("template_id",0) templateId, _ := c.GetInt("template_id", 0)
template,err := models.NewTemplate().Find(templateId) template, err := models.NewTemplate().Find(templateId)
if err != nil { if err != nil {
c.JsonResult(404,"模板不存在") c.JsonResult(404, "模板不存在")
} }
if c.Member.IsAdministrator() { if c.Member.IsAdministrator() {
err := models.NewTemplate().Delete(templateId,0) err := models.NewTemplate().Delete(templateId, 0)
if err != nil { if err != nil {
c.JsonResult(500,"删除失败") c.JsonResult(500, "删除失败")
} }
}else{ } else {
//如果不是管理员需要判断是否有项目权限 //如果不是管理员需要判断是否有项目权限
rel,err := models.NewRelationship().FindByBookIdAndMemberId(template.BookId,c.Member.MemberId) rel, err := models.NewRelationship().FindByBookIdAndMemberId(template.BookId, c.Member.MemberId)
if err != nil || rel.RoleId == conf.BookObserver { if err != nil || rel.RoleId == conf.BookObserver {
c.JsonResult(403,"没有权限") c.JsonResult(403, "没有权限")
} }
//如果是创始人或管理者可以直接删除模板 //如果是创始人或管理者可以直接删除模板
if rel.RoleId == conf.BookFounder || rel.RoleId == conf.BookAdmin { if rel.RoleId == conf.BookFounder || rel.RoleId == conf.BookAdmin {
err := models.NewTemplate().Delete(templateId,0) err := models.NewTemplate().Delete(templateId, 0)
if err != nil { if err != nil {
c.JsonResult(500,"删除失败") c.JsonResult(500, "删除失败")
} }
} }
if err := models.NewTemplate().Delete(templateId,c.Member.MemberId);err != nil { if err := models.NewTemplate().Delete(templateId, c.Member.MemberId); err != nil {
c.JsonResult(500,"删除失败") c.JsonResult(500, "删除失败")
} }
} }
c.JsonResult(0,"OK") c.JsonResult(0, "OK")
} }

10
go.mod
View File

@ -1,11 +1,11 @@
module github.com/mindoc-org/mindoc module github.com/mindoc-org/mindoc
go 1.12 go 1.13
require ( require (
github.com/PuerkitoBio/goquery v1.4.1 github.com/PuerkitoBio/goquery v1.4.1
github.com/andybalholm/cascadia v1.2.0 // indirect github.com/andybalholm/cascadia v1.2.0 // indirect
github.com/astaxie/beego v1.12.3 github.com/beego/beego/v2 v2.0.2-0.20210322114547-10ea897525a5
github.com/boombuler/barcode v1.0.0 github.com/boombuler/barcode v1.0.0
github.com/bradfitz/gomemcache v0.0.0-20190913173617-a41fca850d0b // indirect github.com/bradfitz/gomemcache v0.0.0-20190913173617-a41fca850d0b // indirect
github.com/howeyc/fsnotify v0.9.0 github.com/howeyc/fsnotify v0.9.0
@ -14,13 +14,9 @@ require (
github.com/lifei6671/gocaptcha v0.1.1 github.com/lifei6671/gocaptcha v0.1.1
github.com/mattn/go-sqlite3 v2.0.3+incompatible github.com/mattn/go-sqlite3 v2.0.3+incompatible
github.com/nfnt/resize v0.0.0-20180221191011-83c6a9932646 github.com/nfnt/resize v0.0.0-20180221191011-83c6a9932646
github.com/shurcooL/sanitized_anchor_name v1.0.0 // indirect github.com/russross/blackfriday/v2 v2.1.0
golang.org/x/crypto v0.0.0-20200604202706-70a84ac30bf9 // indirect
golang.org/x/net v0.0.0-20200602114024-627f9648deb9 // indirect
golang.org/x/text v0.3.2 // indirect
gopkg.in/asn1-ber.v1 v1.0.0-00010101000000-000000000000 // indirect gopkg.in/asn1-ber.v1 v1.0.0-00010101000000-000000000000 // indirect
gopkg.in/ldap.v2 v2.5.1 gopkg.in/ldap.v2 v2.5.1
gopkg.in/russross/blackfriday.v2 v2.0.0
gopkg.in/yaml.v2 v2.3.0 // indirect gopkg.in/yaml.v2 v2.3.0 // indirect
) )

126
go.sum
View File

@ -1,3 +1,4 @@
cloud.google.com/go v0.26.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw=
github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU= github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU=
github.com/Knetic/govaluate v3.0.0+incompatible/go.mod h1:r7JcOSlj0wfOMncg0iLm8Leh48TZaKVeNIfJntJ2wa0= github.com/Knetic/govaluate v3.0.0+incompatible/go.mod h1:r7JcOSlj0wfOMncg0iLm8Leh48TZaKVeNIfJntJ2wa0=
github.com/PuerkitoBio/goquery v1.4.1 h1:smcIRGdYm/w7JSbcdeLHEMzxmsBQvl8lhf0dSw2nzMI= github.com/PuerkitoBio/goquery v1.4.1 h1:smcIRGdYm/w7JSbcdeLHEMzxmsBQvl8lhf0dSw2nzMI=
@ -10,8 +11,8 @@ github.com/alicebob/gopher-json v0.0.0-20180125190556-5a6b3ba71ee6/go.mod h1:SGn
github.com/alicebob/miniredis v2.5.0+incompatible/go.mod h1:8HZjEj4yU0dwhYHky+DxYx+6BMjkBbe5ONFIF1MXffk= github.com/alicebob/miniredis v2.5.0+incompatible/go.mod h1:8HZjEj4yU0dwhYHky+DxYx+6BMjkBbe5ONFIF1MXffk=
github.com/andybalholm/cascadia v1.2.0 h1:vuRCkM5Ozh/BfmsaTm26kbjm0mIOM3yS5Ek/F5h18aE= github.com/andybalholm/cascadia v1.2.0 h1:vuRCkM5Ozh/BfmsaTm26kbjm0mIOM3yS5Ek/F5h18aE=
github.com/andybalholm/cascadia v1.2.0/go.mod h1:YCyR8vOZT9aZ1CHEd8ap0gMVm2aFgxBp0T0eFw1RUQY= github.com/andybalholm/cascadia v1.2.0/go.mod h1:YCyR8vOZT9aZ1CHEd8ap0gMVm2aFgxBp0T0eFw1RUQY=
github.com/astaxie/beego v1.12.3 h1:SAQkdD2ePye+v8Gn1r4X6IKZM1wd28EyUOVQ3PDSOOQ= github.com/beego/beego/v2 v2.0.2-0.20210322114547-10ea897525a5 h1:i0swsv6hmoF6pkeG2S/dvOWwOKFPGDKhrmTlWH6I1nM=
github.com/astaxie/beego v1.12.3/go.mod h1:p3qIm0Ryx7zeBHLljmd7omloyca1s4yu1a8kM1FkpIA= github.com/beego/beego/v2 v2.0.2-0.20210322114547-10ea897525a5/go.mod h1:JlRUJ/NVNygorqjyt7/lQ8R++KSE0qXvxeIfbnIUd7Q=
github.com/beego/goyaml2 v0.0.0-20130207012346-5545475820dd/go.mod h1:1b+Y/CofkYwXMUU0OhQqGvsY2Bvgr4j6jfT699wyZKQ= github.com/beego/goyaml2 v0.0.0-20130207012346-5545475820dd/go.mod h1:1b+Y/CofkYwXMUU0OhQqGvsY2Bvgr4j6jfT699wyZKQ=
github.com/beego/x2j v0.0.0-20131220205130-a0352aadc542/go.mod h1:kSeGC/p1AbBiEp5kat81+DSQrZenVBZXklMLaELspWU= github.com/beego/x2j v0.0.0-20131220205130-a0352aadc542/go.mod h1:kSeGC/p1AbBiEp5kat81+DSQrZenVBZXklMLaELspWU=
github.com/beorn7/perks v0.0.0-20180321164747-3a771d992973/go.mod h1:Dwedo/Wpr24TaqPxmxbtue+5NUziq4I4S80YR8gNf3Q= github.com/beorn7/perks v0.0.0-20180321164747-3a771d992973/go.mod h1:Dwedo/Wpr24TaqPxmxbtue+5NUziq4I4S80YR8gNf3Q=
@ -24,12 +25,18 @@ github.com/bradfitz/gomemcache v0.0.0-20180710155616-bc664df96737/go.mod h1:PmM6
github.com/bradfitz/gomemcache v0.0.0-20190913173617-a41fca850d0b h1:L/QXpzIa3pOvUGt1D1lA5KjYhPBAN/3iWdP7xeFS9F0= github.com/bradfitz/gomemcache v0.0.0-20190913173617-a41fca850d0b h1:L/QXpzIa3pOvUGt1D1lA5KjYhPBAN/3iWdP7xeFS9F0=
github.com/bradfitz/gomemcache v0.0.0-20190913173617-a41fca850d0b/go.mod h1:H0wQNHz2YrLsuXOZozoeDmnHXkNCRmMW0gwFWDfEZDA= github.com/bradfitz/gomemcache v0.0.0-20190913173617-a41fca850d0b/go.mod h1:H0wQNHz2YrLsuXOZozoeDmnHXkNCRmMW0gwFWDfEZDA=
github.com/casbin/casbin v1.7.0/go.mod h1:c67qKN6Oum3UF5Q1+BByfFxkwKvhwW57ITjqwtzR1KE= github.com/casbin/casbin v1.7.0/go.mod h1:c67qKN6Oum3UF5Q1+BByfFxkwKvhwW57ITjqwtzR1KE=
github.com/census-instrumentation/opencensus-proto v0.2.1/go.mod h1:f6KPmirojxKA12rnyqOA5BBL4O983OfeGPqjHWSTneU=
github.com/cespare/xxhash/v2 v2.1.1 h1:6MnRN8NT7+YBpUIWxHtefFZOKTAPgGjpQSxqLNn0+qY= github.com/cespare/xxhash/v2 v2.1.1 h1:6MnRN8NT7+YBpUIWxHtefFZOKTAPgGjpQSxqLNn0+qY=
github.com/cespare/xxhash/v2 v2.1.1/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs= github.com/cespare/xxhash/v2 v2.1.1/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=
github.com/client9/misspell v0.3.4/go.mod h1:qj6jICC3Q7zFZvVWo7KLAzC3yx5G7kyvSDkc90ppPyw=
github.com/cloudflare/golz4 v0.0.0-20150217214814-ef862a3cdc58/go.mod h1:EOBUe0h4xcZ5GoxqC5SDxFQ8gwyZPKQoEzownBlhI80= github.com/cloudflare/golz4 v0.0.0-20150217214814-ef862a3cdc58/go.mod h1:EOBUe0h4xcZ5GoxqC5SDxFQ8gwyZPKQoEzownBlhI80=
github.com/couchbase/go-couchbase v0.0.0-20200519150804-63f3cdb75e0d/go.mod h1:TWI8EKQMs5u5jLKW/tsb9VwauIrMIxQG1r5fMsswK5U= github.com/coreos/etcd v3.3.25+incompatible/go.mod h1:uF7uidLiAD3TWHmW31ZFd/JWoc32PjwdhPthX9715RE=
github.com/couchbase/gomemcached v0.0.0-20200526233749-ec430f949808/go.mod h1:srVSlQLB8iXBVXHgnqemxUXqN6FCvClgCMPCsjBDR7c= github.com/coreos/go-semver v0.3.0/go.mod h1:nnelYz7RCh+5ahJtPPxZlU+153eP4D4r3EedlOD2RNk=
github.com/couchbase/goutils v0.0.0-20180530154633-e865a1461c8a/go.mod h1:BQwMFlJzDjFDG3DJUdU0KORxn88UlsOULuxLExMh3Hs= github.com/coreos/go-systemd v0.0.0-20191104093116-d3cd4ed1dbcf/go.mod h1:F5haX7vjVVG0kc13fIWeqUViNPyEJxv/OmvnBo0Yme4=
github.com/coreos/pkg v0.0.0-20180928190104-399ea9e2e55f/go.mod h1:E3G3o1h8I7cfcXa63jLwjI0eiQQMgzzUDFVpN/nH/eA=
github.com/couchbase/go-couchbase v0.0.0-20210126152612-8e416c37c8ef/go.mod h1:+/bddYDxXsf9qt0xpDUtRR47A2GjaXmGGAqQ/k3GJ8A=
github.com/couchbase/gomemcached v0.1.2-0.20210126151728-840240974836/go.mod h1:mxliKQxOv84gQ0bJWbI+w9Wxdpt9HjDvgW9MjCym5Vo=
github.com/couchbase/goutils v0.0.0-20201030094643-5e82bb967e67/go.mod h1:BQwMFlJzDjFDG3DJUdU0KORxn88UlsOULuxLExMh3Hs=
github.com/cupcake/rdb v0.0.0-20161107195141-43ba34106c76/go.mod h1:vYwsqCOLxGiisLwp9rITslkFNpZD5rz43tf41QFkTWY= github.com/cupcake/rdb v0.0.0-20161107195141-43ba34106c76/go.mod h1:vYwsqCOLxGiisLwp9rITslkFNpZD5rz43tf41QFkTWY=
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= 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 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
@ -38,6 +45,9 @@ github.com/edsrzf/mmap-go v0.0.0-20170320065105-0bce6a688712/go.mod h1:YO35OhQPt
github.com/elastic/go-elasticsearch/v6 v6.8.5/go.mod h1:UwaDJsD3rWLM5rKNFzv9hgox93HoX8utj1kxD9aFUcI= github.com/elastic/go-elasticsearch/v6 v6.8.5/go.mod h1:UwaDJsD3rWLM5rKNFzv9hgox93HoX8utj1kxD9aFUcI=
github.com/elazarl/go-bindata-assetfs v1.0.0 h1:G/bYguwHIzWq9ZoyUQqrjTmJbbYn3j3CKKpKinvZLFk= github.com/elazarl/go-bindata-assetfs v1.0.0 h1:G/bYguwHIzWq9ZoyUQqrjTmJbbYn3j3CKKpKinvZLFk=
github.com/elazarl/go-bindata-assetfs v1.0.0/go.mod h1:v+YaWX3bdea5J/mo8dSETolEo7R71Vk1u8bnjau5yw4= 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=
github.com/envoyproxy/protoc-gen-validate v0.1.0/go.mod h1:iSmxcyjqTsJpI2R4NaDN7+kN2VEUnK/pcBlmesArF7c=
github.com/fsnotify/fsnotify v1.4.7 h1:IXs+QLmnXW2CcXuY+8Mzv/fWEsPGWxqefPtCP5CnV9I=
github.com/fsnotify/fsnotify v1.4.7/go.mod h1:jwhsz4b93w/PPRr/qN1Yymfu8t87LnFCMoQvtojpjFo= github.com/fsnotify/fsnotify v1.4.7/go.mod h1:jwhsz4b93w/PPRr/qN1Yymfu8t87LnFCMoQvtojpjFo=
github.com/glendc/gopher-json v0.0.0-20170414221815-dc4743023d0c/go.mod h1:Gja1A+xZ9BoviGJNA2E9vFkPjjsl+CoJxSXiQM1UXtw= github.com/glendc/gopher-json v0.0.0-20170414221815-dc4743023d0c/go.mod h1:Gja1A+xZ9BoviGJNA2E9vFkPjjsl+CoJxSXiQM1UXtw=
github.com/go-asn1-ber/asn1-ber v1.5.0 h1:/S4hO/AO6tLMlPX0oftGSOcdGJJN/MuYzfgWRMn199E= github.com/go-asn1-ber/asn1-ber v1.5.0 h1:/S4hO/AO6tLMlPX0oftGSOcdGJJN/MuYzfgWRMn199E=
@ -46,13 +56,19 @@ github.com/go-kit/kit v0.8.0/go.mod h1:xBxKIO96dXMWWy0MnWVtmwkA9/13aqxPnvrjFYMA2
github.com/go-kit/kit v0.9.0/go.mod h1:xBxKIO96dXMWWy0MnWVtmwkA9/13aqxPnvrjFYMA2as= github.com/go-kit/kit v0.9.0/go.mod h1:xBxKIO96dXMWWy0MnWVtmwkA9/13aqxPnvrjFYMA2as=
github.com/go-logfmt/logfmt v0.3.0/go.mod h1:Qt1PoO58o5twSAckw1HlFXLmHsOX5/0LbT9GBnD5lWE= github.com/go-logfmt/logfmt v0.3.0/go.mod h1:Qt1PoO58o5twSAckw1HlFXLmHsOX5/0LbT9GBnD5lWE=
github.com/go-logfmt/logfmt v0.4.0/go.mod h1:3RMwSq7FuexP4Kalkev3ejPJsZTpXXBr9+V4qmtdjCk= github.com/go-logfmt/logfmt v0.4.0/go.mod h1:3RMwSq7FuexP4Kalkev3ejPJsZTpXXBr9+V4qmtdjCk=
github.com/go-redis/redis v6.14.2+incompatible h1:UE9pLhzmWf+xHNmZsoccjXosPicuiNaInPgym8nzfg0=
github.com/go-redis/redis v6.14.2+incompatible/go.mod h1:NAIEuMOZ/fxfXJIrKDQDz8wamY7mA7PouImQ2Jvg6kA= github.com/go-redis/redis v6.14.2+incompatible/go.mod h1:NAIEuMOZ/fxfXJIrKDQDz8wamY7mA7PouImQ2Jvg6kA=
github.com/go-redis/redis/v7 v7.4.0 h1:7obg6wUoj05T0EpY0o8B59S9w5yeMWql7sw2kwNW1x4=
github.com/go-redis/redis/v7 v7.4.0/go.mod h1:JDNMw23GTyLNC4GZu9njt15ctBQVn7xjRfnwdHj/Dcg=
github.com/go-sql-driver/mysql v1.5.0 h1:ozyZYNQW3x3HtqT1jira07DN2PArx2v7/mN66gGcHOs= 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/go-sql-driver/mysql v1.5.0/go.mod h1:DCzpHaOWr8IXmIStZouvnhqoel9Qv2LBy8hT2VhHyBg=
github.com/go-stack/stack v1.8.0/go.mod h1:v0f6uXyyMGvRgIKkXu+yp6POWl0qKG85gN/melR3HDY= github.com/go-stack/stack v1.8.0/go.mod h1:v0f6uXyyMGvRgIKkXu+yp6POWl0qKG85gN/melR3HDY=
github.com/gogo/protobuf v1.1.1/go.mod h1:r8qH/GZQm5c6nD/R0oafs1akxWv10x8SbQlK7atdtwQ= github.com/gogo/protobuf v1.1.1/go.mod h1:r8qH/GZQm5c6nD/R0oafs1akxWv10x8SbQlK7atdtwQ=
github.com/gogo/protobuf v1.3.1/go.mod h1:SlYgWuQ5SjCEi6WLHjHCa1yvBfUnHcTbrrZtXPKa29o=
github.com/golang/freetype v0.0.0-20170609003504-e2365dfdc4a0 h1:DACJavvAHhabrF08vX0COfcOBJRhZ8lUbR+ZWIs0Y5g= github.com/golang/freetype v0.0.0-20170609003504-e2365dfdc4a0 h1:DACJavvAHhabrF08vX0COfcOBJRhZ8lUbR+ZWIs0Y5g=
github.com/golang/freetype v0.0.0-20170609003504-e2365dfdc4a0/go.mod h1:E/TSTwGwJL78qG/PmXZO1EjYhfJinVAhrmmHX6Z8B9k= github.com/golang/freetype v0.0.0-20170609003504-e2365dfdc4a0/go.mod h1:E/TSTwGwJL78qG/PmXZO1EjYhfJinVAhrmmHX6Z8B9k=
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= github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U=
github.com/golang/protobuf v1.3.1/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= github.com/golang/protobuf v1.3.1/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U=
github.com/golang/protobuf v1.3.2/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= github.com/golang/protobuf v1.3.2/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U=
@ -67,21 +83,29 @@ github.com/golang/snappy v0.0.0-20170215233205-553a64147049/go.mod h1:/XxbfmMg8l
github.com/golang/snappy v0.0.0-20180518054509-2e65f85255db/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q= github.com/golang/snappy v0.0.0-20180518054509-2e65f85255db/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q=
github.com/gomodule/redigo v2.0.0+incompatible h1:K/R+8tc58AaqLkqG2Ol3Qk+DR/TlNuhuh457pBFPtt0= github.com/gomodule/redigo v2.0.0+incompatible h1:K/R+8tc58AaqLkqG2Ol3Qk+DR/TlNuhuh457pBFPtt0=
github.com/gomodule/redigo v2.0.0+incompatible/go.mod h1:B4C85qUVwatsJoIUNIfCRsp7qO0iAmpGFZ4EELWSbC4= github.com/gomodule/redigo v2.0.0+incompatible/go.mod h1:B4C85qUVwatsJoIUNIfCRsp7qO0iAmpGFZ4EELWSbC4=
github.com/google/go-cmp v0.2.0/go.mod h1:oXzfMopK8JAjlY9xF4vHSVASa0yLyX7SntLO5aqRK0M=
github.com/google/go-cmp v0.3.0/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU= 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.3.1/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU=
github.com/google/go-cmp v0.4.0 h1:xsAVV57WRhGj6kEIi8ReJzQlHHqcBYCElAvkovg3B/4=
github.com/google/go-cmp v0.4.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= 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/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=
github.com/google/renameio v0.1.0/go.mod h1:KWCgfxg9yswjAJkECMjeO8J8rahYeXnNhOm40UhjYkI=
github.com/google/uuid v1.1.1/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
github.com/grpc-ecosystem/go-grpc-prometheus v1.2.0/go.mod h1:8NvIoxWQoOIhqOTXgfV/d3M/q6VIi02HzZEHgUlZvzk=
github.com/hashicorp/golang-lru v0.5.4 h1:YDjusn29QI/Das2iO9M0BHnIbxPeyuCHsjMW+lJfyTc= github.com/hashicorp/golang-lru v0.5.4 h1:YDjusn29QI/Das2iO9M0BHnIbxPeyuCHsjMW+lJfyTc=
github.com/hashicorp/golang-lru v0.5.4/go.mod h1:iADmTwqILo4mZ8BN3D2Q6+9jd8WM5uGBxy+E8yxSoD4= github.com/hashicorp/golang-lru v0.5.4/go.mod h1:iADmTwqILo4mZ8BN3D2Q6+9jd8WM5uGBxy+E8yxSoD4=
github.com/howeyc/fsnotify v0.9.0 h1:0gtV5JmOKH4A8SsFxG2BczSeXWWPvcMT0euZt5gDAxY= github.com/howeyc/fsnotify v0.9.0 h1:0gtV5JmOKH4A8SsFxG2BczSeXWWPvcMT0euZt5gDAxY=
github.com/howeyc/fsnotify v0.9.0/go.mod h1:41HzSPxBGeFRQKEEwgh49TRw/nKBsYZ2cF1OzPjSJsA= github.com/howeyc/fsnotify v0.9.0/go.mod h1:41HzSPxBGeFRQKEEwgh49TRw/nKBsYZ2cF1OzPjSJsA=
github.com/hpcloud/tail v1.0.0 h1:nfCOvKYfkgYP8hkirhJocXT2+zOD8yUNjXaWfTlyFKI=
github.com/hpcloud/tail v1.0.0/go.mod h1:ab1qPbhIpdTxEkNHXyeSf5vhxWSCs/tWer42PpOxQnU= github.com/hpcloud/tail v1.0.0/go.mod h1:ab1qPbhIpdTxEkNHXyeSf5vhxWSCs/tWer42PpOxQnU=
github.com/json-iterator/go v1.1.6/go.mod h1:+SdeFBvtyEkXs7REEP0seUULqWtbJapLOCVDaaPEHmU= github.com/json-iterator/go v1.1.6/go.mod h1:+SdeFBvtyEkXs7REEP0seUULqWtbJapLOCVDaaPEHmU=
github.com/json-iterator/go v1.1.10/go.mod h1:KdQUCv79m/52Kvf8AW2vK1V8akMuk1QjK/uOdHXbAo4= github.com/json-iterator/go v1.1.10/go.mod h1:KdQUCv79m/52Kvf8AW2vK1V8akMuk1QjK/uOdHXbAo4=
github.com/julienschmidt/httprouter v1.2.0/go.mod h1:SYymIcj16QtmaHHD7aYtjjsJG7VTCxuUUipMqKk8s4w= github.com/julienschmidt/httprouter v1.2.0/go.mod h1:SYymIcj16QtmaHHD7aYtjjsJG7VTCxuUUipMqKk8s4w=
github.com/kardianos/service v1.1.0 h1:QV2SiEeWK42P0aEmGcsAgjApw/lRxkwopvT+Gu6t1/0= github.com/kardianos/service v1.1.0 h1:QV2SiEeWK42P0aEmGcsAgjApw/lRxkwopvT+Gu6t1/0=
github.com/kardianos/service v1.1.0/go.mod h1:RrJI2xn5vve/r32U5suTbeaSGoMU6GbNPoj36CVYcHc= github.com/kardianos/service v1.1.0/go.mod h1:RrJI2xn5vve/r32U5suTbeaSGoMU6GbNPoj36CVYcHc=
github.com/kisielk/errcheck v1.2.0/go.mod h1:/BMXB+zMLi60iA8Vv6Ksmxu/1UDYcXs4uQLJ+jE2L00=
github.com/kisielk/gotool v1.0.0/go.mod h1:XhKaO+MFFWcvkIS/tQcRk01m1F5IRFswLeQ+oQHNcck=
github.com/konsorten/go-windows-terminal-sequences v1.0.1/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ= github.com/konsorten/go-windows-terminal-sequences v1.0.1/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ=
github.com/kr/logfmt v0.0.0-20140226030751-b84e30acd515/go.mod h1:+0opPa2QZZtGFBFZlji/RkVcI2GknAs/DXo4wKdlNEc= github.com/kr/logfmt v0.0.0-20140226030751-b84e30acd515/go.mod h1:+0opPa2QZZtGFBFZlji/RkVcI2GknAs/DXo4wKdlNEc=
github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo= github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo=
@ -98,6 +122,8 @@ github.com/mattn/go-sqlite3 v2.0.3+incompatible h1:gXHsfypPkaMZrKbD5209QV9jbUTJK
github.com/mattn/go-sqlite3 v2.0.3+incompatible/go.mod h1:FPy6KqzDD04eiIsT53CuJW3U88zkxoIYsOqkbpncsNc= github.com/mattn/go-sqlite3 v2.0.3+incompatible/go.mod h1:FPy6KqzDD04eiIsT53CuJW3U88zkxoIYsOqkbpncsNc=
github.com/matttproud/golang_protobuf_extensions v1.0.1 h1:4hp9jkHxhMHkqkrB3Ix0jegS5sx/RkqARlsWZ6pIwiU= github.com/matttproud/golang_protobuf_extensions v1.0.1 h1:4hp9jkHxhMHkqkrB3Ix0jegS5sx/RkqARlsWZ6pIwiU=
github.com/matttproud/golang_protobuf_extensions v1.0.1/go.mod h1:D8He9yQNgCq6Z5Ld7szi9bcBfOoFv/3dc6xSMkL2PC0= github.com/matttproud/golang_protobuf_extensions v1.0.1/go.mod h1:D8He9yQNgCq6Z5Ld7szi9bcBfOoFv/3dc6xSMkL2PC0=
github.com/mitchellh/mapstructure v1.3.3 h1:SzB1nHZ2Xi+17FP0zVQBHIZqvwRN9408fJO8h+eeNA8=
github.com/mitchellh/mapstructure v1.3.3/go.mod h1:bFUtVrKA4DC2yAKiSyO/QUcy7e+RRV2QTWOzhPopBRo=
github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
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=
@ -108,10 +134,15 @@ github.com/nfnt/resize v0.0.0-20180221191011-83c6a9932646/go.mod h1:jpp1/29i3P1S
github.com/niemeyer/pretty v0.0.0-20200227124842-a10e7caefd8e h1:fD57ERR4JtEqsWbfPhv4DMiApHyliiK5xCTNVSPiaAs= github.com/niemeyer/pretty v0.0.0-20200227124842-a10e7caefd8e h1:fD57ERR4JtEqsWbfPhv4DMiApHyliiK5xCTNVSPiaAs=
github.com/niemeyer/pretty v0.0.0-20200227124842-a10e7caefd8e/go.mod h1:zD1mROLANZcx1PVRCS0qkT7pwLkGfwJo4zjcN/Tysno= github.com/niemeyer/pretty v0.0.0-20200227124842-a10e7caefd8e/go.mod h1:zD1mROLANZcx1PVRCS0qkT7pwLkGfwJo4zjcN/Tysno=
github.com/onsi/ginkgo v1.6.0/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE= github.com/onsi/ginkgo v1.6.0/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE=
github.com/onsi/ginkgo v1.10.1/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE=
github.com/onsi/ginkgo v1.12.0 h1:Iw5WCbBcaAAd0fpRb1c9r5YCylv4XDoCSigm1zLevwU=
github.com/onsi/ginkgo v1.12.0/go.mod h1:oUhWkIvk5aDxtKvDDuw8gItl8pKl42LzjC9KZE0HfGg= github.com/onsi/ginkgo v1.12.0/go.mod h1:oUhWkIvk5aDxtKvDDuw8gItl8pKl42LzjC9KZE0HfGg=
github.com/onsi/gomega v1.7.0/go.mod h1:ex+gbHU/CVuBBDIJjb2X0qEXbFg53c61hWP/1CpauHY=
github.com/onsi/gomega v1.7.1 h1:K0jcRCwNQM3vFGh1ppMtDh/+7ApJrjldlX8fA0jDTLQ=
github.com/onsi/gomega v1.7.1/go.mod h1:XdKZgCCFLUoM/7CFJVPcG8C1xQ1AJ0vpAezJrB7JYyY= github.com/onsi/gomega v1.7.1/go.mod h1:XdKZgCCFLUoM/7CFJVPcG8C1xQ1AJ0vpAezJrB7JYyY=
github.com/opentracing/opentracing-go v1.2.0/go.mod h1:GxEUsuufX4nBwe+T+Wl9TAgYrxe9dPLANfrWvHYVTgc=
github.com/pelletier/go-toml v1.0.1/go.mod h1:5z9KED0ma1S8pY6P1sdut58dfprrGBbd/94hg7ilaic= github.com/pelletier/go-toml v1.0.1/go.mod h1:5z9KED0ma1S8pY6P1sdut58dfprrGBbd/94hg7ilaic=
github.com/pelletier/go-toml v1.2.0/go.mod h1:5z9KED0ma1S8pY6P1sdut58dfprrGBbd/94hg7ilaic= github.com/pelletier/go-toml v1.8.1/go.mod h1:T2/BmBdy8dvIRq1a/8aqjN41wvWlN4lrapLU/GW4pbc=
github.com/peterh/liner v1.0.1-0.20171122030339-3681c2a91233/go.mod h1:xIteQHvHuaLYG9IFj6mSxM0fCKrs34IrEQUhOYuGPHc= github.com/peterh/liner v1.0.1-0.20171122030339-3681c2a91233/go.mod h1:xIteQHvHuaLYG9IFj6mSxM0fCKrs34IrEQUhOYuGPHc=
github.com/pkg/errors v0.8.0/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= github.com/pkg/errors v0.8.0/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
github.com/pkg/errors v0.8.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= github.com/pkg/errors v0.8.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
@ -125,6 +156,7 @@ github.com/prometheus/client_golang v1.7.0 h1:wCi7urQOGBsYcQROHqpUUX4ct84xp40t9R
github.com/prometheus/client_golang v1.7.0/go.mod h1:PY5Wy2awLA44sXw4AOSfFBetzPP4j5+D6mVACh+pe2M= github.com/prometheus/client_golang v1.7.0/go.mod h1:PY5Wy2awLA44sXw4AOSfFBetzPP4j5+D6mVACh+pe2M=
github.com/prometheus/client_model v0.0.0-20180712105110-5c3871d89910/go.mod h1:MbSGuTsp3dbXC40dX6PRTWyKYBIrTGTE9sqQNg2J8bo= github.com/prometheus/client_model v0.0.0-20180712105110-5c3871d89910/go.mod h1:MbSGuTsp3dbXC40dX6PRTWyKYBIrTGTE9sqQNg2J8bo=
github.com/prometheus/client_model v0.0.0-20190129233127-fd36f4220a90/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA= github.com/prometheus/client_model v0.0.0-20190129233127-fd36f4220a90/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA=
github.com/prometheus/client_model v0.0.0-20190812154241-14fe0d1b01d4/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA=
github.com/prometheus/client_model v0.2.0 h1:uq5h0d+GuxiXLJLNABMgp2qUWDPiLvgCzz2dUR+/W/M= github.com/prometheus/client_model v0.2.0 h1:uq5h0d+GuxiXLJLNABMgp2qUWDPiLvgCzz2dUR+/W/M=
github.com/prometheus/client_model v0.2.0/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA= github.com/prometheus/client_model v0.2.0/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA=
github.com/prometheus/common v0.4.1/go.mod h1:TNfzLD0ON7rHzMJeJkieUDPYmFC7Snx/y86RQel1bk4= github.com/prometheus/common v0.4.1/go.mod h1:TNfzLD0ON7rHzMJeJkieUDPYmFC7Snx/y86RQel1bk4=
@ -134,10 +166,11 @@ github.com/prometheus/procfs v0.0.0-20181005140218-185b4288413d/go.mod h1:c3At6R
github.com/prometheus/procfs v0.0.2/go.mod h1:TjEm7ze935MbeOT/UhFTIMYKhuLP4wbCsTZCD3I8kEA= github.com/prometheus/procfs v0.0.2/go.mod h1:TjEm7ze935MbeOT/UhFTIMYKhuLP4wbCsTZCD3I8kEA=
github.com/prometheus/procfs v0.1.3 h1:F0+tqvhOksq22sc6iCHF5WGlWjdwj92p0udFh1VFBS8= github.com/prometheus/procfs v0.1.3 h1:F0+tqvhOksq22sc6iCHF5WGlWjdwj92p0udFh1VFBS8=
github.com/prometheus/procfs v0.1.3/go.mod h1:lV6e/gmhEcM9IjHGsFOCxxuZ+z1YqCvr4OA4YeYWdaU= github.com/prometheus/procfs v0.1.3/go.mod h1:lV6e/gmhEcM9IjHGsFOCxxuZ+z1YqCvr4OA4YeYWdaU=
github.com/rogpeppe/go-internal v1.3.0/go.mod h1:M8bDsm7K2OlrFYOpmOWEs/qY81heoFRclV5y23lUDJ4=
github.com/russross/blackfriday/v2 v2.1.0 h1:JIOH55/0cWyOuilr9/qlrm0BSXldqnqwMsf35Ld67mk=
github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM=
github.com/shiena/ansicolor v0.0.0-20151119151921-a422bbe96644 h1:X+yvsM2yrEktyI+b2qND5gpH8YhURn0k8OCaeRnkINo= github.com/shiena/ansicolor v0.0.0-20151119151921-a422bbe96644 h1:X+yvsM2yrEktyI+b2qND5gpH8YhURn0k8OCaeRnkINo=
github.com/shiena/ansicolor v0.0.0-20151119151921-a422bbe96644/go.mod h1:nkxAfR/5quYxwPZhyDxgasBMnRtBZd0FCEpawpjMUFg= github.com/shiena/ansicolor v0.0.0-20151119151921-a422bbe96644/go.mod h1:nkxAfR/5quYxwPZhyDxgasBMnRtBZd0FCEpawpjMUFg=
github.com/shurcooL/sanitized_anchor_name v1.0.0 h1:PdmoCO6wvbs+7yrJyMORt4/BmY5IYyJwS/kOiWx8mHo=
github.com/shurcooL/sanitized_anchor_name v1.0.0/go.mod h1:1NzhyTcUVG4SuEtjjoZeVRXNmyL/1OwPU0+IJeTBvfc=
github.com/siddontang/go v0.0.0-20170517070808-cb568a3e5cc0/go.mod h1:3yhqj7WBBfRhbBlzyOC3gUxftwsU0u8gqevxwIHQpMw= github.com/siddontang/go v0.0.0-20170517070808-cb568a3e5cc0/go.mod h1:3yhqj7WBBfRhbBlzyOC3gUxftwsU0u8gqevxwIHQpMw=
github.com/siddontang/goredis v0.0.0-20150324035039-760763f78400/go.mod h1:DDcKzU3qCuvj/tPnimWSsZZzvk9qvkvrIL5naVBPh5s= github.com/siddontang/goredis v0.0.0-20150324035039-760763f78400/go.mod h1:DDcKzU3qCuvj/tPnimWSsZZzvk9qvkvrIL5naVBPh5s=
github.com/siddontang/rdb v0.0.0-20150307021120-fc89ed2e418d/go.mod h1:AMEsy7v5z92TR1JKMkLLoaOQk++LVnOKL3ScbJ8GNGA= github.com/siddontang/rdb v0.0.0-20150307021120-fc89ed2e418d/go.mod h1:AMEsy7v5z92TR1JKMkLLoaOQk++LVnOKL3ScbJ8GNGA=
@ -154,26 +187,51 @@ github.com/syndtr/goleveldb v0.0.0-20160425020131-cfa635847112/go.mod h1:Z4AUp2K
github.com/syndtr/goleveldb v0.0.0-20181127023241-353a9fca669c/go.mod h1:Z4AUp2Km+PwemOoO/VB5AOx9XSsIItzFjoJlOSiYmn0= github.com/syndtr/goleveldb v0.0.0-20181127023241-353a9fca669c/go.mod h1:Z4AUp2Km+PwemOoO/VB5AOx9XSsIItzFjoJlOSiYmn0=
github.com/ugorji/go v0.0.0-20171122102828-84cb69a8af83/go.mod h1:hnLbHMwcvSihnDhEfx2/BzKp2xb0Y+ErdfYcrs9tkJQ= github.com/ugorji/go v0.0.0-20171122102828-84cb69a8af83/go.mod h1:hnLbHMwcvSihnDhEfx2/BzKp2xb0Y+ErdfYcrs9tkJQ=
github.com/wendal/errors v0.0.0-20130201093226-f66c77a7882b/go.mod h1:Q12BUT7DqIlHRmgv3RskH+UCM/4eqVMgI0EMmlSpAXc= github.com/wendal/errors v0.0.0-20130201093226-f66c77a7882b/go.mod h1:Q12BUT7DqIlHRmgv3RskH+UCM/4eqVMgI0EMmlSpAXc=
github.com/yuin/goldmark v1.2.1/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74=
github.com/yuin/gopher-lua v0.0.0-20171031051903-609c9cd26973/go.mod h1:aEV29XrmTYFr3CiRxZeGHpkvbwq+prZduBqMaascyCU= github.com/yuin/gopher-lua v0.0.0-20171031051903-609c9cd26973/go.mod h1:aEV29XrmTYFr3CiRxZeGHpkvbwq+prZduBqMaascyCU=
go.etcd.io/etcd v3.3.25+incompatible/go.mod h1:yaeTdrJi5lOmYerz05bd8+V7KubZs8YSFZfzsF9A6aI=
go.uber.org/atomic v1.6.0/go.mod h1:sABNBOSYdrvTF6hTgEIbc7YasKWGhgEQZyfxyTvoXHQ=
go.uber.org/multierr v1.5.0/go.mod h1:FeouvMocqHpRaaGuG9EjoKcStLC43Zu/fmqdUMPcKYU=
go.uber.org/tools v0.0.0-20190618225709-2cfd321de3ee/go.mod h1:vJERXedbb3MVM5f9Ejo0C68/HhF8uaILCdgjnY+goOA=
go.uber.org/zap v1.15.0/go.mod h1:Mb2vm2krFEG5DV0W9qcHBYFtp/Wku1cvYaqPsS/WYfc=
golang.org/x/crypto v0.0.0-20180904163835-0709b304e793/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4= golang.org/x/crypto v0.0.0-20180904163835-0709b304e793/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4=
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
golang.org/x/crypto v0.0.0-20190510104115-cbcb75029529/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI=
golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI=
golang.org/x/crypto v0.0.0-20200604202706-70a84ac30bf9 h1:vEg9joUBmeBcK9iSJftGNf3coIG4HqZElCPehJsfAYM= golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9 h1:psW17arqaxU48Z5kZ0CQnkZWQJsqcURM6tKiBApRjXI=
golang.org/x/crypto v0.0.0-20200604202706-70a84ac30bf9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto=
golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA=
golang.org/x/image v0.0.0-20190227222117-0694c2d4d067 h1:KYGJGHOQy8oSi1fDlSpcZF0+juKwk/hEMv5SiwHogR0= golang.org/x/image v0.0.0-20190227222117-0694c2d4d067 h1:KYGJGHOQy8oSi1fDlSpcZF0+juKwk/hEMv5SiwHogR0=
golang.org/x/image v0.0.0-20190227222117-0694c2d4d067/go.mod h1:kZ7UVZpmo3dzQBMxlp+ypCbDeSB+sBbTgSJuh5dn5js= golang.org/x/image v0.0.0-20190227222117-0694c2d4d067/go.mod h1:kZ7UVZpmo3dzQBMxlp+ypCbDeSB+sBbTgSJuh5dn5js=
golang.org/x/lint v0.0.0-20181026193005-c67002cb31c3/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE=
golang.org/x/lint v0.0.0-20190227174305-5b3e6a55c961/go.mod h1:wehouNa3lNwaWXcvxsM5YxQ5yQlVC4a0KAMCusXpPoU=
golang.org/x/lint v0.0.0-20190313153728-d0100b6bd8b3/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc=
golang.org/x/lint v0.0.0-20190930215403-16217165b5de/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc=
golang.org/x/lint v0.0.0-20201208152925-83fdc39ff7b5/go.mod h1:3xt1FjdF8hUf6vQPIChWIBhFzV8gjjsPE/fR3IyQdNY=
golang.org/x/mod v0.0.0-20190513183733-4bf6d317e70e/go.mod h1:mXi4GBBbnImb6dmsKGUJ2LatrhH/nqhxcFungHvyanc=
golang.org/x/mod v0.1.1-0.20191105210325-c90efee705ee/go.mod h1:QqPTAvyqsEbceGzBzNggFXnrqF1CaUcvgkdR5Ot7KZg=
golang.org/x/mod v0.3.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA=
golang.org/x/net v0.0.0-20180218175443-cbe0f9307d01/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20180218175443-cbe0f9307d01/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
golang.org/x/net v0.0.0-20180724234803-3673e40ba225/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
golang.org/x/net v0.0.0-20180826012351-8a410e7b638d/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
golang.org/x/net v0.0.0-20180906233101-161cd47e91fd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20180906233101-161cd47e91fd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
golang.org/x/net v0.0.0-20181114220301-adae6a3d119a/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20181114220301-adae6a3d119a/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
golang.org/x/net v0.0.0-20190213061140-3a22650c66bd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
golang.org/x/net v0.0.0-20190311183353-d8887717615a/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
golang.org/x/net v0.0.0-20190613194153-d28f0bde5980/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= golang.org/x/net v0.0.0-20190613194153-d28f0bde5980/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
golang.org/x/net v0.0.0-20200602114024-627f9648deb9 h1:pNX+40auqi2JqRfOP1akLGtYcn15TUbkhwuCO3foqqM= golang.org/x/net v0.0.0-20190923162816-aa69164e4478/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
golang.org/x/net v0.0.0-20200602114024-627f9648deb9/go.mod h1:qpuaurCH72eLCgpAm/N6yyVIVM9cpaDIP3A8BGJEC5A= golang.org/x/net v0.0.0-20201021035429-f5854403a974 h1:IX6qOQeG5uLjB/hjjwjedwfjND0hgjPMMyO1RoIXQNI=
golang.org/x/net v0.0.0-20201021035429-f5854403a974/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU=
golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U=
golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20181108010431-42b317875d0f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20181108010431-42b317875d0f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20181221193216-37e7f081c4d4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20181221193216-37e7f081c4d4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20190911185100-cd5d95a43a6e/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20190911185100-cd5d95a43a6e/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20201020160332-67f06af15bc9/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sys v0.0.0-20180830151530-49385e6e1522/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20180905080454-ebe1bf3edb33/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20180905080454-ebe1bf3edb33/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20180909124046-d0be0721c37e/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20180909124046-d0be0721c37e/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20181116152217-5ac8a444bdc5/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20181116152217-5ac8a444bdc5/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
@ -181,17 +239,41 @@ golang.org/x/sys v0.0.0-20190204203706-41f3e6584952/go.mod h1:STP8DvDyc/dI5b8T5h
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20190422165155-953cdadca894/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20190422165155-953cdadca894/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20191010194322-b09406accb47/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20191120155948-bd437916bb0e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20191120155948-bd437916bb0e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20200106162015-b016eb3dc98e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20200106162015-b016eb3dc98e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20200323222414-85ca7c5b95cd/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20200615200032-f1bc736245b1 h1:ogLJMz+qpzav7lGMh10LMvAkM/fAoGlaiiHYiFYdm80=
golang.org/x/sys v0.0.0-20200615200032-f1bc736245b1/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20200615200032-f1bc736245b1/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20200930185726-fdedc70b468f h1:+Nyd8tzPX9R7BWHguqsrbFdRx3WQ/1ib8I44HXV5yTA=
golang.org/x/sys v0.0.0-20200930185726-fdedc70b468f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
golang.org/x/text v0.3.2 h1:tW2bmiBqwgJj/UpqtC8EpXEZVYOwU0yG4iWbprSVAcs=
golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk= golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk=
golang.org/x/text v0.3.3 h1:cokOdA+Jmi5PJGXLlLllQSgYigAEfHXJAERHVMaCc2k=
golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543 h1:E7g+9GITq07hpfrRu66IVDexMakfv52eLZ2CXBWiKr4= golang.org/x/tools v0.0.0-20181030221726-6c7e314b6563/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
golang.org/x/tools v0.0.0-20190114222345-bf090417da8b/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
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/tools v0.0.0-20190621195816-6e04913cbbac/go.mod h1:/rFqwRUd4F7ZHNgwSSTFct+R/Kf4OFW1sUzUTQQTgfc=
golang.org/x/tools v0.0.0-20191029041327-9cc4af7d6b2c/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
golang.org/x/tools v0.0.0-20191029190741-b9c20aec41a5/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
golang.org/x/tools v0.0.0-20191130070609-6e064ea0cf2d/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
golang.org/x/tools v0.0.0-20200130002326-2f3ba24bd6e7/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28=
golang.org/x/tools v0.0.0-20201211185031-d93e913c1a58/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA=
golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1 h1:go1bK/D/BFZV2I8cIQd1NKEZ+0owSTG1fDTci4IqFcE=
golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1/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=
google.golang.org/genproto v0.0.0-20180817151627-c66870c02cf8/go.mod h1:JiN7NxoALGmiZfu7CAH4rXhgtRTLTxftemlI0sWmxmc=
google.golang.org/genproto v0.0.0-20190819201941-24fa4b261c55/go.mod h1:DMBHOl98Agz4BDEuKkezgsaosCRResVns1a3J2ZsMNc=
google.golang.org/grpc v1.19.0/go.mod h1:mqu4LbDTu4XGKhr4mRzUsmM4RtVoemTSY81AxZiDr8c=
google.golang.org/grpc v1.23.0/go.mod h1:Y5yQAOtifL1yxbo5wqy6BxZv8vAUGQwXBOALyacEbxg=
google.golang.org/grpc v1.26.0/go.mod h1:qbnxyOmOxrQa7FizSgH+ReBfzJrCY1pSN7KXBS8abTk=
google.golang.org/protobuf v0.0.0-20200109180630-ec00e32a8dfd/go.mod h1:DFci5gLYBciE7Vtevhsrf46CRTquxDuWsQurQQe4oz8= google.golang.org/protobuf v0.0.0-20200109180630-ec00e32a8dfd/go.mod h1:DFci5gLYBciE7Vtevhsrf46CRTquxDuWsQurQQe4oz8=
google.golang.org/protobuf v0.0.0-20200221191635-4d8936d0db64/go.mod h1:kwYJMbMJ01Woi6D6+Kah6886xMZcty6N08ah7+eCXa0= google.golang.org/protobuf v0.0.0-20200221191635-4d8936d0db64/go.mod h1:kwYJMbMJ01Woi6D6+Kah6886xMZcty6N08ah7+eCXa0=
google.golang.org/protobuf v0.0.0-20200228230310-ab0ca4ff8a60/go.mod h1:cfTl7dwQJ+fmap5saPgwCLgHXTUD7jkjRqWcaiX5VyM= google.golang.org/protobuf v0.0.0-20200228230310-ab0ca4ff8a60/go.mod h1:cfTl7dwQJ+fmap5saPgwCLgHXTUD7jkjRqWcaiX5VyM=
@ -201,15 +283,17 @@ google.golang.org/protobuf v1.23.0 h1:4MY060fB1DLGMB/7MBTLnwQUY6+F09GEiz6SsrNqyz
google.golang.org/protobuf v1.23.0/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU= google.golang.org/protobuf v1.23.0/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU=
gopkg.in/alecthomas/kingpin.v2 v2.2.6/go.mod h1:FMv+mEhP44yOT+4EoQTLFTRgOQ1FBLkstjWtayDeSgw= gopkg.in/alecthomas/kingpin.v2 v2.2.6/go.mod h1:FMv+mEhP44yOT+4EoQTLFTRgOQ1FBLkstjWtayDeSgw=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/check.v1 v1.0.0-20200227125254-8fa46927fb4f h1:BLraFXnmrev5lT+xlilqcH8XK9/i0At2xKjWk4p6zsU= gopkg.in/check.v1 v1.0.0-20200227125254-8fa46927fb4f h1:BLraFXnmrev5lT+xlilqcH8XK9/i0At2xKjWk4p6zsU=
gopkg.in/check.v1 v1.0.0-20200227125254-8fa46927fb4f/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/check.v1 v1.0.0-20200227125254-8fa46927fb4f/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/errgo.v2 v2.1.0/go.mod h1:hNsd1EY+bozCKY1Ytp96fpM3vjJbqLJn88ws8XvfDNI=
gopkg.in/fsnotify.v1 v1.4.7 h1:xOHLXZwVvI9hhs+cLKq5+I5onOuwQLhQwiu63xxlHs4=
gopkg.in/fsnotify.v1 v1.4.7/go.mod h1:Tz8NjZHkW78fSQdbUxIjBTcgA1z1m8ZHf0WmKUhAMys= gopkg.in/fsnotify.v1 v1.4.7/go.mod h1:Tz8NjZHkW78fSQdbUxIjBTcgA1z1m8ZHf0WmKUhAMys=
gopkg.in/ldap.v2 v2.5.1 h1:wiu0okdNfjlBzg6UWvd1Hn8Y+Ux17/u/4nlk4CQr6tU= gopkg.in/ldap.v2 v2.5.1 h1:wiu0okdNfjlBzg6UWvd1Hn8Y+Ux17/u/4nlk4CQr6tU=
gopkg.in/ldap.v2 v2.5.1/go.mod h1:oI0cpe/D7HRtBQl8aTg+ZmzFUAvu4lsv3eLXMLGFxWk= gopkg.in/ldap.v2 v2.5.1/go.mod h1:oI0cpe/D7HRtBQl8aTg+ZmzFUAvu4lsv3eLXMLGFxWk=
gopkg.in/mgo.v2 v2.0.0-20190816093944-a6b53ec6cb22/go.mod h1:yeKp02qBN3iKW1OzL3MGk2IdtZzaj7SFntXj72NppTA= gopkg.in/mgo.v2 v2.0.0-20190816093944-a6b53ec6cb22/go.mod h1:yeKp02qBN3iKW1OzL3MGk2IdtZzaj7SFntXj72NppTA=
gopkg.in/russross/blackfriday.v2 v2.0.0 h1:+FlnIV8DSQnT7NZ43hcVKcdJdzZoeCmJj4Ql8gq5keA= gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7 h1:uRGJdciOHaEIrze2W8Q3AKkepLTh2hOroT7a+7czfdQ=
gopkg.in/russross/blackfriday.v2 v2.0.0/go.mod h1:6sSBNz/GtOm/pJTuh5UmBK2ZHfmnxGbl2NZg1UliSOI=
gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7/go.mod h1:dt/ZhP58zS4L8KSrWDmTeBkI65Dw0HsyUHuEVlX15mw= gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7/go.mod h1:dt/ZhP58zS4L8KSrWDmTeBkI65Dw0HsyUHuEVlX15mw=
gopkg.in/yaml.v2 v2.2.1/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= gopkg.in/yaml.v2 v2.2.1/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
@ -218,3 +302,7 @@ gopkg.in/yaml.v2 v2.2.5/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
gopkg.in/yaml.v2 v2.2.8/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= gopkg.in/yaml.v2 v2.2.8/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
gopkg.in/yaml.v2 v2.3.0 h1:clyUAQHOM3G0M3f5vQj7LuJrETvjVot3Z5el9nffUtU= gopkg.in/yaml.v2 v2.3.0 h1:clyUAQHOM3G0M3f5vQj7LuJrETvjVot3Z5el9nffUtU=
gopkg.in/yaml.v2 v2.3.0/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= gopkg.in/yaml.v2 v2.3.0/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
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.1-2019.2.3/go.mod h1:a3bituU0lyd329TUQxRnasdCoJDkEUEAqEt0JzvZhAg=
honnef.co/go/tools v0.0.1-2020.1.5/go.mod h1:X/FiERA/W4tHapMX5mGpAtMSVEeEUOyHaw9vFzvIQ3k=

View File

@ -17,7 +17,8 @@ import (
"regexp" "regexp"
"strconv" "strconv"
"strings" "strings"
"github.com/astaxie/beego"
"github.com/beego/beego/v2/core/logs"
) )
var ( var (
@ -229,7 +230,6 @@ func (c *SMTPClient) SendTLS(m Mail, message bytes.Buffer) error {
return err return err
} }
ct, err = smtp.NewClient(conn, c.host) ct, err = smtp.NewClient(conn, c.host)
if err != nil { if err != nil {
log.Println(err) log.Println(err)
@ -247,8 +247,8 @@ func (c *SMTPClient) SendTLS(m Mail, message bytes.Buffer) error {
//} //}
fmt.Println(c.smtpAuth) fmt.Println(c.smtpAuth)
if ok,s := ct.Extension("AUTH"); ok { if ok, s := ct.Extension("AUTH"); ok {
beego.Info(s) logs.Info(s)
// Auth // Auth
if err = ct.Auth(c.smtpAuth); err != nil { if err = ct.Auth(c.smtpAuth); err != nil {
log.Println("Auth Error:", log.Println("Auth Error:",

View File

@ -5,10 +5,9 @@ import (
"log" "log"
"os" "os"
_ "github.com/astaxie/beego/session/memcache" _ "github.com/beego/beego/v2/server/web/session/memcache"
_ "github.com/astaxie/beego/session/mysql" _ "github.com/beego/beego/v2/server/web/session/mysql"
_ "github.com/beego/beego/v2/server/web/session/redis"
_ "github.com/astaxie/beego/session/redis"
"github.com/kardianos/service" "github.com/kardianos/service"
_ "github.com/mattn/go-sqlite3" _ "github.com/mattn/go-sqlite3"
"github.com/mindoc-org/mindoc/commands" "github.com/mindoc-org/mindoc/commands"

View File

@ -8,8 +8,8 @@ import (
"strings" "strings"
"github.com/astaxie/beego" "github.com/beego/beego/v2/client/orm"
"github.com/astaxie/beego/orm" "github.com/beego/beego/v2/core/logs"
"github.com/mindoc-org/mindoc/conf" "github.com/mindoc-org/mindoc/conf"
"github.com/mindoc-org/mindoc/utils/filetil" "github.com/mindoc-org/mindoc/utils/filetil"
) )
@ -65,7 +65,7 @@ func (m *Attachment) Delete() error {
if err == nil { if err == nil {
if err1 := os.Remove(m.FilePath); err1 != nil { if err1 := os.Remove(m.FilePath); err1 != nil {
beego.Error(err1) logs.Error(err1)
} }
} }
@ -110,7 +110,7 @@ func (m *Attachment) FindToPager(pageIndex, pageSize int) (attachList []*Attachm
if err != nil { if err != nil {
if err == orm.ErrNoRows { if err == orm.ErrNoRows {
beego.Info("没有查到附件 ->", err) logs.Info("没有查到附件 ->", err)
err = nil err = nil
} }
return return

View File

@ -3,7 +3,7 @@ package models
import ( import (
"strings" "strings"
"github.com/astaxie/beego/orm" "github.com/beego/beego/v2/client/orm"
"github.com/mindoc-org/mindoc/utils/filetil" "github.com/mindoc-org/mindoc/utils/filetil"
) )

View File

@ -7,8 +7,9 @@ import (
"time" "time"
"github.com/PuerkitoBio/goquery" "github.com/PuerkitoBio/goquery"
"github.com/astaxie/beego" "github.com/beego/beego/v2/client/orm"
"github.com/astaxie/beego/orm" "github.com/beego/beego/v2/core/logs"
"github.com/beego/beego/v2/server/web"
"github.com/mindoc-org/mindoc/cache" "github.com/mindoc-org/mindoc/cache"
"github.com/mindoc-org/mindoc/conf" "github.com/mindoc-org/mindoc/conf"
"github.com/mindoc-org/mindoc/utils" "github.com/mindoc-org/mindoc/utils"
@ -94,7 +95,7 @@ func (b *Blog) Find(blogId int) (*Blog, error) {
err := o.QueryTable(b.TableNameWithPrefix()).Filter("blog_id", blogId).One(b) err := o.QueryTable(b.TableNameWithPrefix()).Filter("blog_id", blogId).One(b)
if err != nil { if err != nil {
beego.Error("查询文章时失败 -> ", err) logs.Error("查询文章时失败 -> ", err)
return nil, err return nil, err
} }
@ -103,23 +104,23 @@ func (b *Blog) Find(blogId int) (*Blog, error) {
//从缓存中读取文章 //从缓存中读取文章
func (b *Blog) FindFromCache(blogId int) (blog *Blog, err error) { func (b *Blog) FindFromCache(blogId int) (blog *Blog, err error) {
key := fmt.Sprintf("blog-id-%d", blogId); key := fmt.Sprintf("blog-id-%d", blogId)
var temp Blog var temp Blog
err = cache.Get(key, &temp); err = cache.Get(key, &temp)
if err == nil { if err == nil {
b = &temp b = &temp
b.Link() b.Link()
beego.Debug("从缓存读取文章成功 ->", key) logs.Debug("从缓存读取文章成功 ->", key)
return b, nil return b, nil
} else { } else {
beego.Error("读取缓存失败 ->", err) logs.Error("读取缓存失败 ->", err)
} }
blog, err = b.Find(blogId) blog, err = b.Find(blogId)
if err == nil { if err == nil {
//默认一个小时 //默认一个小时
if err := cache.Put(key, blog, time.Hour*1); err != nil { if err := cache.Put(key, blog, time.Hour*1); err != nil {
beego.Error("将文章存入缓存失败 ->", err) logs.Error("将文章存入缓存失败 ->", err)
} }
} }
return return
@ -131,7 +132,7 @@ func (b *Blog) FindByIdAndMemberId(blogId, memberId int) (*Blog, error) {
err := o.QueryTable(b.TableNameWithPrefix()).Filter("blog_id", blogId).Filter("member_id", memberId).One(b) err := o.QueryTable(b.TableNameWithPrefix()).Filter("blog_id", blogId).Filter("member_id", memberId).One(b)
if err != nil { if err != nil {
beego.Error("查询文章时失败 -> ", err) logs.Error("查询文章时失败 -> ", err)
return nil, err return nil, err
} }
@ -144,7 +145,7 @@ func (b *Blog) FindByIdentify(identify string) (*Blog, error) {
err := o.QueryTable(b.TableNameWithPrefix()).Filter("blog_identify", identify).One(b) err := o.QueryTable(b.TableNameWithPrefix()).Filter("blog_identify", identify).One(b)
if err != nil { if err != nil {
beego.Error("查询文章时失败 -> ", err) logs.Error("查询文章时失败 -> ", err)
return nil, err return nil, err
} }
return b, nil return b, nil
@ -157,7 +158,7 @@ func (b *Blog) Link() (*Blog, error) {
if b.BlogType == 1 && b.DocumentId > 0 { if b.BlogType == 1 && b.DocumentId > 0 {
doc := NewDocument() doc := NewDocument()
if err := o.QueryTable(doc.TableNameWithPrefix()).Filter("document_id", b.DocumentId).One(doc, "release", "markdown", "identify", "book_id"); err != nil { if err := o.QueryTable(doc.TableNameWithPrefix()).Filter("document_id", b.DocumentId).One(doc, "release", "markdown", "identify", "book_id"); err != nil {
beego.Error("查询文章链接对象时出错 -> ", err) logs.Error("查询文章链接对象时出错 -> ", err)
} else { } else {
b.DocumentIdentify = doc.Identify b.DocumentIdentify = doc.Identify
b.BlogRelease = doc.Release b.BlogRelease = doc.Release
@ -166,7 +167,7 @@ func (b *Blog) Link() (*Blog, error) {
b.BlogContent = doc.Markdown b.BlogContent = doc.Markdown
book := NewBook() book := NewBook()
if err := o.QueryTable(book.TableNameWithPrefix()).Filter("book_id", doc.BookId).One(book, "identify"); err != nil { if err := o.QueryTable(book.TableNameWithPrefix()).Filter("book_id", doc.BookId).One(book, "identify"); err != nil {
beego.Error("查询关联文档的项目时出错 ->", err) logs.Error("查询关联文档的项目时出错 ->", err)
} else { } else {
b.BookIdentify = book.Identify b.BookIdentify = book.Identify
b.BookId = doc.BookId b.BookId = doc.BookId
@ -174,13 +175,13 @@ func (b *Blog) Link() (*Blog, error) {
//处理链接文档存在源文档修改时间的问题 //处理链接文档存在源文档修改时间的问题
if content, err := goquery.NewDocumentFromReader(bytes.NewBufferString(b.BlogRelease)); err == nil { if content, err := goquery.NewDocumentFromReader(bytes.NewBufferString(b.BlogRelease)); err == nil {
content.Find(".wiki-bottom").Remove() content.Find(".wiki-bottom").Remove()
if html,err := content.Html();err == nil { if html, err := content.Html(); err == nil {
b.BlogRelease = html b.BlogRelease = html
} else { } else {
beego.Error("处理文章失败 ->",err) logs.Error("处理文章失败 ->", err)
} }
}else { } else {
beego.Error("处理文章失败 ->",err) logs.Error("处理文章失败 ->", err)
} }
} }
} }
@ -224,7 +225,7 @@ func (b *Blog) Save(cols ...string) error {
if b.OrderIndex <= 0 { if b.OrderIndex <= 0 {
blog := NewBlog() blog := NewBlog()
if err := o.QueryTable(blog.TableNameWithPrefix()).OrderBy("-blog_id").Limit(1).One(blog, "blog_id"); err == nil { if err := o.QueryTable(blog.TableNameWithPrefix()).OrderBy("-blog_id").Limit(1).One(blog, "blog_id"); err == nil {
b.OrderIndex = blog.BlogId + 1; b.OrderIndex = blog.BlogId + 1
} else { } else {
c, _ := o.QueryTable(b.TableNameWithPrefix()).Count() c, _ := o.QueryTable(b.TableNameWithPrefix()).Count()
b.OrderIndex = int(c) + 1 b.OrderIndex = int(c) + 1
@ -260,7 +261,7 @@ func (b *Blog) Processor() *Blog {
content.Find("a").Each(func(i int, contentSelection *goquery.Selection) { content.Find("a").Each(func(i int, contentSelection *goquery.Selection) {
if src, ok := contentSelection.Attr("href"); ok { if src, ok := contentSelection.Attr("href"); ok {
if strings.HasPrefix(src, "http://") || strings.HasPrefix(src, "https://") { if strings.HasPrefix(src, "http://") || strings.HasPrefix(src, "https://") {
//beego.Info(src,conf.BaseUrl,strings.HasPrefix(src,conf.BaseUrl)) //logs.Info(src,conf.BaseUrl,strings.HasPrefix(src,conf.BaseUrl))
if conf.BaseUrl != "" && !strings.HasPrefix(src, conf.BaseUrl) { if conf.BaseUrl != "" && !strings.HasPrefix(src, conf.BaseUrl) {
contentSelection.SetAttr("target", "_blank") contentSelection.SetAttr("target", "_blank")
if html, err := content.Html(); err == nil { if html, err := content.Html(); err == nil {
@ -272,7 +273,7 @@ func (b *Blog) Processor() *Blog {
} }
}) })
//设置图片为CDN地址 //设置图片为CDN地址
if cdnimg := beego.AppConfig.String("cdnimg"); cdnimg != "" { if cdnimg, _ := web.AppConfig.String("cdnimg"); cdnimg != "" {
content.Find("img").Each(func(i int, contentSelection *goquery.Selection) { content.Find("img").Each(func(i int, contentSelection *goquery.Selection) {
if src, ok := contentSelection.Attr("src"); ok && strings.HasPrefix(src, "/uploads/") { if src, ok := contentSelection.Attr("src"); ok && strings.HasPrefix(src, "/uploads/") {
contentSelection.SetAttr("src", utils.JoinURI(cdnimg, src)) contentSelection.SetAttr("src", utils.JoinURI(cdnimg, src))
@ -306,13 +307,13 @@ func (b *Blog) FindToPager(pageIndex, pageSize int, memberId int, status string)
if err == orm.ErrNoRows { if err == orm.ErrNoRows {
err = nil err = nil
} }
beego.Error("获取文章列表时出错 ->", err) logs.Error("获取文章列表时出错 ->", err)
return return
} }
count, err := query.Count() count, err := query.Count()
if err != nil { if err != nil {
beego.Error("获取文章数量时出错 ->", err) logs.Error("获取文章数量时出错 ->", err)
return nil, 0, err return nil, 0, err
} }
totalCount = int(count) totalCount = int(count)
@ -331,7 +332,7 @@ func (b *Blog) Delete(blogId int) error {
_, err := o.QueryTable(b.TableNameWithPrefix()).Filter("blog_id", blogId).Delete() _, err := o.QueryTable(b.TableNameWithPrefix()).Filter("blog_id", blogId).Delete()
if err != nil { if err != nil {
beego.Error("删除文章失败 ->", err) logs.Error("删除文章失败 ->", err)
} }
return err return err
} }
@ -342,14 +343,14 @@ func (b *Blog) QueryNext(blogId int) (*Blog, error) {
blog := NewBlog() blog := NewBlog()
if err := o.QueryTable(b.TableNameWithPrefix()).Filter("blog_id", blogId).One(blog, "order_index"); err != nil { if err := o.QueryTable(b.TableNameWithPrefix()).Filter("blog_id", blogId).One(blog, "order_index"); err != nil {
beego.Error("查询文章时出错 ->", err) logs.Error("查询文章时出错 ->", err)
return b, err return b, err
} }
err := o.QueryTable(b.TableNameWithPrefix()).Filter("order_index__gte", blog.OrderIndex).Filter("blog_id__gt", blogId).OrderBy("order_index", "blog_id").One(blog) err := o.QueryTable(b.TableNameWithPrefix()).Filter("order_index__gte", blog.OrderIndex).Filter("blog_id__gt", blogId).OrderBy("order_index", "blog_id").One(blog)
if err != nil && err != orm.ErrNoRows { if err != nil && err != orm.ErrNoRows {
beego.Error("查询文章时出错 ->", err) logs.Error("查询文章时出错 ->", err)
} }
return blog, err return blog, err
} }
@ -360,14 +361,14 @@ func (b *Blog) QueryPrevious(blogId int) (*Blog, error) {
blog := NewBlog() blog := NewBlog()
if err := o.QueryTable(b.TableNameWithPrefix()).Filter("blog_id", blogId).One(blog, "order_index"); err != nil { if err := o.QueryTable(b.TableNameWithPrefix()).Filter("blog_id", blogId).One(blog, "order_index"); err != nil {
beego.Error("查询文章时出错 ->", err) logs.Error("查询文章时出错 ->", err)
return b, err return b, err
} }
err := o.QueryTable(b.TableNameWithPrefix()).Filter("order_index__lte", blog.OrderIndex).Filter("blog_id__lt", blogId).OrderBy("-order_index", "-blog_id").One(blog) err := o.QueryTable(b.TableNameWithPrefix()).Filter("order_index__lte", blog.OrderIndex).Filter("blog_id__lt", blogId).OrderBy("-order_index", "-blog_id").One(blog)
if err != nil && err != orm.ErrNoRows { if err != nil && err != orm.ErrNoRows {
beego.Error("查询文章时出错 ->", err) logs.Error("查询文章时出错 ->", err)
} }
return blog, err return blog, err
} }
@ -382,13 +383,13 @@ func (b *Blog) LinkAttach() (err error) {
if b.BlogType != 1 || b.DocumentId <= 0 { if b.BlogType != 1 || b.DocumentId <= 0 {
_, err = o.QueryTable(NewAttachment().TableNameWithPrefix()).Filter("document_id", b.BlogId).Filter("book_id", 0).All(&attachList) _, err = o.QueryTable(NewAttachment().TableNameWithPrefix()).Filter("document_id", b.BlogId).Filter("book_id", 0).All(&attachList)
if err != nil && err != orm.ErrNoRows { if err != nil && err != orm.ErrNoRows {
beego.Error("查询文章附件时出错 ->", err) logs.Error("查询文章附件时出错 ->", err)
} }
} else { } else {
_, err = o.QueryTable(NewAttachment().TableNameWithPrefix()).Filter("document_id", b.DocumentId).Filter("book_id", b.BookId).All(&attachList) _, err = o.QueryTable(NewAttachment().TableNameWithPrefix()).Filter("document_id", b.DocumentId).Filter("book_id", b.BookId).All(&attachList)
if err != nil && err != orm.ErrNoRows { if err != nil && err != orm.ErrNoRows {
beego.Error("查询文章附件时出错 ->", err) logs.Error("查询文章附件时出错 ->", err)
} }
} }
b.AttachList = attachList b.AttachList = attachList

View File

@ -1,6 +1,7 @@
package models package models
import ( import (
"context"
"crypto/md5" "crypto/md5"
"errors" "errors"
"fmt" "fmt"
@ -16,16 +17,15 @@ import (
"encoding/json" "encoding/json"
"github.com/astaxie/beego" "github.com/beego/beego/v2/client/orm"
"github.com/astaxie/beego/logs" "github.com/beego/beego/v2/core/logs"
"github.com/astaxie/beego/orm"
"github.com/mindoc-org/mindoc/conf" "github.com/mindoc-org/mindoc/conf"
"github.com/mindoc-org/mindoc/utils" "github.com/mindoc-org/mindoc/utils"
"github.com/mindoc-org/mindoc/utils/cryptil" "github.com/mindoc-org/mindoc/utils/cryptil"
"github.com/mindoc-org/mindoc/utils/filetil" "github.com/mindoc-org/mindoc/utils/filetil"
"github.com/mindoc-org/mindoc/utils/requests" "github.com/mindoc-org/mindoc/utils/requests"
"github.com/mindoc-org/mindoc/utils/ziptil" "github.com/mindoc-org/mindoc/utils/ziptil"
"gopkg.in/russross/blackfriday.v2" "github.com/russross/blackfriday/v2"
) )
var releaseQueue = make(chan int, 500) var releaseQueue = make(chan int, 500)
@ -194,11 +194,11 @@ func (book *Book) Copy(identify string) error {
err := o.QueryTable(book.TableNameWithPrefix()).Filter("identify", identify).One(book) err := o.QueryTable(book.TableNameWithPrefix()).Filter("identify", identify).One(book)
if err != nil { if err != nil {
beego.Error("查询项目时出错 -> ", err) logs.Error("查询项目时出错 -> ", err)
return err return err
} }
if err := o.Begin(); err != nil { if _, err := o.Begin(); err != nil {
beego.Error("开启事物时出错 -> ", err) logs.Error("开启事物时出错 -> ", err)
return err return err
} }
@ -210,49 +210,87 @@ func (book *Book) Copy(identify string) error {
book.CommentCount = 0 book.CommentCount = 0
book.HistoryCount = 0 book.HistoryCount = 0
if _, err := o.Insert(book); err != nil { /* v2 version of beego remove the o.Rollback api for transaction operation.
beego.Error("复制项目时出错 -> ", err) * typically, in v1, you can write code like this:
o.Rollback() *
* o := orm.NewOrm()
* if err := o.Operateion(); err != nil {
* o.Rollback()
* ...
* }
*
* however, in v2, this is not available. beego will handles the transaction in new way using
* cluster. the new code is like below:
*
* o := orm.NewOrm()
* if err := o.DoTx(func(ctx context.Context, txOrm orm.TxOrmer) error{
* err := o.Operations()
* if err != nil {
* return err
* }
* ...
* }); err != nil {
* ...
* }
*
* when operation failed, it will automatically calls o.Rollback() for TxOrmer.
* more details see https://beego.me/docs/mvc/model/transaction.md
*/
if err := o.DoTx(func(ctx context.Context, txo orm.TxOrmer) error {
_, err := txo.Insert(book)
return err
}); err != nil {
logs.Error("复制项目时出错: %s", err)
return err return err
} }
var rels []*Relationship var rels []*Relationship
if _, err := o.QueryTable(NewRelationship().TableNameWithPrefix()).Filter("book_id", bookId).All(&rels); err != nil { if err := o.DoTx(func(ctx context.Context, txo orm.TxOrmer) error {
beego.Error("复制项目关系时出错 -> ", err) _, err := txo.QueryTable(NewRelationship().TableNameWithPrefix()).Filter("book_id", bookId).All(&rels)
o.Rollback() return err
}); err != nil {
logs.Error("复制项目关系时出错 -> ", err)
return err return err
} }
for _, rel := range rels { for _, rel := range rels {
rel.BookId = book.BookId rel.BookId = book.BookId
rel.RelationshipId = 0 rel.RelationshipId = 0
if _, err := o.Insert(rel); err != nil { if err := o.DoTx(func(ctx context.Context, txo orm.TxOrmer) error {
beego.Error("复制项目关系时出错 -> ", err) _, err := txo.Insert(rel)
o.Rollback() return err
}); err != nil {
logs.Error("复制项目关系时出错 -> ", err)
return err return err
} }
} }
var docs []*Document var docs []*Document
if _, err := o.QueryTable(NewDocument().TableNameWithPrefix()).Filter("book_id", bookId).Filter("parent_id", 0).All(&docs); err != nil && err != orm.ErrNoRows { if err := o.DoTx(func(ctx context.Context, txOrm orm.TxOrmer) error {
beego.Error("读取项目文档时出错 -> ", err) _, err := txOrm.QueryTable(NewDocument().TableNameWithPrefix()).Filter("book_id", bookId).Filter("parent_id", 0).All(&docs)
o.Rollback() return err
}); err != nil && err != orm.ErrNoRows {
logs.Error("读取项目文档时出错 -> ", err)
return err return err
} }
if len(docs) > 0 { if len(docs) > 0 {
if err := recursiveInsertDocument(docs, o, book.BookId, 0); err != nil { if err := o.DoTx(func(ctx context.Context, txOrm orm.TxOrmer) error {
beego.Error("复制项目时出错 -> ", err) return recursiveInsertDocument(docs, txOrm, book.BookId, 0)
o.Rollback() }); err != nil {
logs.Error("复制项目时出错 -> ", err)
return err return err
} }
} }
return o.Commit() return nil
} }
//递归的复制文档 //递归的复制文档
func recursiveInsertDocument(docs []*Document, o orm.Ormer, bookId int, parentId int) error { func recursiveInsertDocument(docs []*Document, o orm.TxOrmer, bookId int, parentId int) error {
for _, doc := range docs { for _, doc := range docs {
docId := doc.DocumentId docId := doc.DocumentId
@ -262,7 +300,7 @@ func recursiveInsertDocument(docs []*Document, o orm.Ormer, bookId int, parentId
doc.Version = time.Now().Unix() doc.Version = time.Now().Unix()
if _, err := o.Insert(doc); err != nil { if _, err := o.Insert(doc); err != nil {
beego.Error("插入项目时出错 -> ", err) logs.Error("插入项目时出错 -> ", err)
return err return err
} }
@ -281,7 +319,7 @@ func recursiveInsertDocument(docs []*Document, o orm.Ormer, bookId int, parentId
var subDocs []*Document var subDocs []*Document
if _, err := o.QueryTable(NewDocument().TableNameWithPrefix()).Filter("parent_id", docId).All(&subDocs); err != nil && err != orm.ErrNoRows { if _, err := o.QueryTable(NewDocument().TableNameWithPrefix()).Filter("parent_id", docId).All(&subDocs); err != nil && err != orm.ErrNoRows {
beego.Error("读取文档时出错 -> ", err) logs.Error("读取文档时出错 -> ", err)
return err return err
} }
if len(subDocs) > 0 { if len(subDocs) > 0 {
@ -419,42 +457,49 @@ func (book *Book) ThoroughDeleteBook(id int) error {
o.Begin() o.Begin()
//删除附件,这里没有删除实际物理文件 //删除附件,这里没有删除实际物理文件
_, err = o.Raw("DELETE FROM "+NewAttachment().TableNameWithPrefix()+" WHERE book_id=?", book.BookId).Exec() if err := o.DoTx(func(ctx context.Context, txOrm orm.TxOrmer) error {
if err != nil { _, err = txOrm.Raw("DELETE FROM "+NewAttachment().TableNameWithPrefix()+" WHERE book_id=?", book.BookId).Exec()
o.Rollback() return err
}); err != nil {
return err return err
} }
//删除文档 //删除文档
_, err = o.Raw("DELETE FROM "+NewDocument().TableNameWithPrefix()+" WHERE book_id = ?", book.BookId).Exec() if err := o.DoTx(func(ctx context.Context, txOrm orm.TxOrmer) error {
_, err = txOrm.Raw("DELETE FROM "+NewDocument().TableNameWithPrefix()+" WHERE book_id = ?", book.BookId).Exec()
if err != nil { return err
o.Rollback() }); err != nil {
return err return err
} }
//删除项目 //删除项目
_, err = o.Raw("DELETE FROM "+book.TableNameWithPrefix()+" WHERE book_id = ?", book.BookId).Exec() if err := o.DoTx(func(ctx context.Context, txOrm orm.TxOrmer) error {
_, err = txOrm.Raw("DELETE FROM "+book.TableNameWithPrefix()+" WHERE book_id = ?", book.BookId).Exec()
if err != nil { return err
o.Rollback() }); err != nil {
return err return err
} }
//删除关系 //删除关系
_, err = o.Raw("DELETE FROM "+NewRelationship().TableNameWithPrefix()+" WHERE book_id = ?", book.BookId).Exec()
if err != nil { if err := o.DoTx(func(ctx context.Context, txOrm orm.TxOrmer) error {
o.Rollback() _, err = txOrm.Raw("DELETE FROM "+NewRelationship().TableNameWithPrefix()+" WHERE book_id = ?", book.BookId).Exec()
return err
}); err != nil {
return err return err
} }
_, err = o.Raw(fmt.Sprintf("DELETE FROM %s WHERE book_id=?", NewTeamRelationship().TableNameWithPrefix()), book.BookId).Exec()
if err != nil { if err := o.DoTx(func(ctx context.Context, txOrm orm.TxOrmer) error {
o.Rollback() _, err = txOrm.Raw(fmt.Sprintf("DELETE FROM %s WHERE book_id=?", NewTeamRelationship().TableNameWithPrefix()), book.BookId).Exec()
return err
}); err != nil {
return err return err
} }
//删除模板 //删除模板
_, err = o.Raw("DELETE FROM "+NewTemplate().TableNameWithPrefix()+" WHERE book_id = ?", book.BookId).Exec()
if err != nil { if err := o.DoTx(func(ctx context.Context, txOrm orm.TxOrmer) error {
o.Rollback() _, err = txOrm.Raw("DELETE FROM "+NewTemplate().TableNameWithPrefix()+" WHERE book_id = ?", book.BookId).Exec()
return err
}); err != nil {
return err return err
} }
@ -464,14 +509,14 @@ func (book *Book) ThoroughDeleteBook(id int) error {
//删除导出缓存 //删除导出缓存
if err := os.RemoveAll(filepath.Join(conf.GetExportOutputPath(), strconv.Itoa(id))); err != nil { if err := os.RemoveAll(filepath.Join(conf.GetExportOutputPath(), strconv.Itoa(id))); err != nil {
beego.Error("删除项目缓存失败 ->", err) logs.Error("删除项目缓存失败 ->", err)
} }
//删除附件和图片 //删除附件和图片
if err := os.RemoveAll(filepath.Join(conf.WorkingDirectory, "uploads", book.Identify)); err != nil { if err := os.RemoveAll(filepath.Join(conf.WorkingDirectory, "uploads", book.Identify)); err != nil {
beego.Error("删除项目附件和图片失败 ->", err) logs.Error("删除项目附件和图片失败 ->", err)
} }
return o.Commit() return nil
} }
@ -592,7 +637,7 @@ func (book *Book) ReleaseContent(bookId int) {
go func() { go func() {
defer func() { defer func() {
if err := recover(); err != nil { if err := recover(); err != nil {
beego.Error("协程崩溃 ->", err) logs.Error("协程崩溃 ->", err)
} }
}() }()
for bookId := range releaseQueue { for bookId := range releaseQueue {
@ -602,7 +647,7 @@ func (book *Book) ReleaseContent(bookId int) {
_, err := o.QueryTable(NewDocument().TableNameWithPrefix()).Filter("book_id", bookId).All(&docs) _, err := o.QueryTable(NewDocument().TableNameWithPrefix()).Filter("book_id", bookId).All(&docs)
if err != nil { if err != nil {
beego.Error("发布失败 =>", bookId, err) logs.Error("发布失败 =>", bookId, err)
continue continue
} }
for _, item := range docs { for _, item := range docs {
@ -626,10 +671,10 @@ func (book *Book) ResetDocumentNumber(bookId int) {
if err == nil { if err == nil {
_, err = o.Raw("UPDATE md_books SET doc_count = ? WHERE book_id = ?", int(totalCount), bookId).Exec() _, err = o.Raw("UPDATE md_books SET doc_count = ? WHERE book_id = ?", int(totalCount), bookId).Exec()
if err != nil { if err != nil {
beego.Error("重置文档数量失败 =>", bookId, err) logs.Error("重置文档数量失败 =>", bookId, err)
} }
} else { } else {
beego.Error("获取文档数量失败 =>", bookId, err) logs.Error("获取文档数量失败 =>", bookId, err)
} }
} }
@ -648,7 +693,7 @@ func (book *Book) ImportBook(zipPath string) error {
tempPath := filepath.Join(os.TempDir(), md5str) tempPath := filepath.Join(os.TempDir(), md5str)
if err := os.MkdirAll(tempPath, 0766); err != nil { if err := os.MkdirAll(tempPath, 0766); err != nil {
beego.Error("创建导入目录出错 => ", err) logs.Error("创建导入目录出错 => ", err)
} }
//如果加压缩失败 //如果加压缩失败
if err := ziptil.Unzip(zipPath, tempPath); err != nil { if err := ziptil.Unzip(zipPath, tempPath); err != nil {
@ -693,7 +738,7 @@ func (book *Book) ImportBook(zipPath string) error {
ext := filepath.Ext(info.Name()) ext := filepath.Ext(info.Name())
//如果是Markdown文件 //如果是Markdown文件
if strings.EqualFold(ext, ".md") || strings.EqualFold(ext, ".markdown") { if strings.EqualFold(ext, ".md") || strings.EqualFold(ext, ".markdown") {
beego.Info("正在处理 =>", path, info.Name()) logs.Info("正在处理 =>", path, info.Name())
doc := NewDocument() doc := NewDocument()
doc.BookId = book.BookId doc.BookId = book.BookId
doc.MemberId = book.MemberId doc.MemberId = book.MemberId
@ -796,11 +841,11 @@ func (book *Book) ImportBook(zipPath string) error {
//如果本地存在该链接 //如果本地存在该链接
if filetil.FileExists(linkPath) { if filetil.FileExists(linkPath) {
ext := filepath.Ext(linkPath) ext := filepath.Ext(linkPath)
//beego.Info("当前后缀 -> ",ext) //logs.Info("当前后缀 -> ",ext)
//如果链接是Markdown文件则生成文档标识,否则,将目标文件复制到项目目录 //如果链接是Markdown文件则生成文档标识,否则,将目标文件复制到项目目录
if strings.EqualFold(ext, ".md") || strings.EqualFold(ext, ".markdown") { if strings.EqualFold(ext, ".md") || strings.EqualFold(ext, ".markdown") {
docIdentify := strings.Replace(strings.TrimPrefix(strings.Replace(linkPath, "\\", "/", -1), tempPath+"/"), "/", "-", -1) docIdentify := strings.Replace(strings.TrimPrefix(strings.Replace(linkPath, "\\", "/", -1), tempPath+"/"), "/", "-", -1)
//beego.Info(originalLink, "|", linkPath, "|", docIdentify) //logs.Info(originalLink, "|", linkPath, "|", docIdentify)
if ok, err := regexp.MatchString(`[a-z]+[a-zA-Z0-9_.\-]*$`, docIdentify); !ok || err != nil { if ok, err := regexp.MatchString(`[a-z]+[a-zA-Z0-9_.\-]*$`, docIdentify); !ok || err != nil {
docIdentify = "import-" + docIdentify docIdentify = "import-" + docIdentify
} }
@ -819,7 +864,7 @@ func (book *Book) ImportBook(zipPath string) error {
} }
} else { } else {
beego.Info("文件不存在 ->", linkPath) logs.Info("文件不存在 ->", linkPath)
} }
} }
@ -829,7 +874,7 @@ func (book *Book) ImportBook(zipPath string) error {
//codeRe := regexp.MustCompile("```\\w+") //codeRe := regexp.MustCompile("```\\w+")
//doc.Markdown = codeRe.ReplaceAllStringFunc(doc.Markdown, func(s string) string { //doc.Markdown = codeRe.ReplaceAllStringFunc(doc.Markdown, func(s string) string {
// //beego.Info(s) // //logs.Info(s)
// return strings.Replace(s,"```","``` ",-1) // return strings.Replace(s,"```","``` ",-1)
//}) //})
@ -863,21 +908,21 @@ func (book *Book) ImportBook(zipPath string) error {
} }
} }
if strings.EqualFold(info.Name(), "README.md") { if strings.EqualFold(info.Name(), "README.md") {
beego.Info(path, "|", info.Name(), "|", parentIdentify, "|", parentId) logs.Info(path, "|", info.Name(), "|", parentIdentify, "|", parentId)
} }
isInsert := false isInsert := false
//如果当前文件是README.md则将内容更新到父级 //如果当前文件是README.md则将内容更新到父级
if strings.EqualFold(info.Name(), "README.md") && parentId != 0 { if strings.EqualFold(info.Name(), "README.md") && parentId != 0 {
doc.DocumentId = parentId doc.DocumentId = parentId
//beego.Info(path,"|",parentId) //logs.Info(path,"|",parentId)
} else { } else {
//beego.Info(path,"|",parentIdentify) //logs.Info(path,"|",parentIdentify)
doc.ParentId = parentId doc.ParentId = parentId
isInsert = true isInsert = true
} }
if err := doc.InsertOrUpdate("document_name", "markdown", "content"); err != nil { if err := doc.InsertOrUpdate("document_name", "markdown", "content"); err != nil {
beego.Error(doc.DocumentId, err) logs.Error(doc.DocumentId, err)
} }
if isInsert { if isInsert {
docMap[docIdentify] = doc.DocumentId docMap[docIdentify] = doc.DocumentId
@ -886,7 +931,7 @@ func (book *Book) ImportBook(zipPath string) error {
} else { } else {
//如果当前目录下存在Markdown文件则需要创建此节点 //如果当前目录下存在Markdown文件则需要创建此节点
if filetil.HasFileOfExt(path, []string{".md", ".markdown"}) { if filetil.HasFileOfExt(path, []string{".md", ".markdown"}) {
beego.Info("正在处理 =>", path, info.Name()) logs.Info("正在处理 =>", path, info.Name())
identify := strings.Replace(strings.Trim(strings.TrimPrefix(path, tempPath), "/"), "/", "-", -1) identify := strings.Replace(strings.Trim(strings.TrimPrefix(path, tempPath), "/"), "/", "-", -1)
if ok, err := regexp.MatchString(`[a-z]+[a-zA-Z0-9_.\-]*$`, identify); !ok || err != nil { if ok, err := regexp.MatchString(`[a-z]+[a-zA-Z0-9_.\-]*$`, identify); !ok || err != nil {
identify = "import-" + identify identify = "import-" + identify
@ -911,11 +956,11 @@ func (book *Book) ImportBook(zipPath string) error {
parentDoc.ParentId = parentId parentDoc.ParentId = parentId
if err := parentDoc.InsertOrUpdate(); err != nil { if err := parentDoc.InsertOrUpdate(); err != nil {
beego.Error(err) logs.Error(err)
} }
docMap[identify] = parentDoc.DocumentId docMap[identify] = parentDoc.DocumentId
//beego.Info(path,"|",parentDoc.DocumentId,"|",identify,"|",info.Name(),"|",parentIdentify) //logs.Info(path,"|",parentDoc.DocumentId,"|",identify,"|",info.Name(),"|",parentIdentify)
} }
} }
@ -923,10 +968,10 @@ func (book *Book) ImportBook(zipPath string) error {
}) })
if err != nil { if err != nil {
beego.Error("导入项目异常 => ", err) logs.Error("导入项目异常 => ", err)
book.Description = "【项目导入存在错误:" + err.Error() + "】" book.Description = "【项目导入存在错误:" + err.Error() + "】"
} }
beego.Info("项目导入完毕 => ", book.BookName) logs.Info("项目导入完毕 => ", book.BookName)
book.ReleaseContent(book.BookId) book.ReleaseContent(book.BookId)
return err return err
} }
@ -953,7 +998,7 @@ where mtr.book_id = ? and mtm.member_id = ? order by mtm.role_id asc limit 1;`
err = o.Raw(sql, bookId, memberId).QueryRow(&roleId) err = o.Raw(sql, bookId, memberId).QueryRow(&roleId)
if err != nil { if err != nil {
beego.Error("查询用户项目角色出错 -> book_id=", bookId, " member_id=", memberId, err) logs.Error("查询用户项目角色出错 -> book_id=", bookId, " member_id=", memberId, err)
return 0, err return 0, err
} }
return conf.BookRole(roleId), nil return conf.BookRole(roleId), nil

View File

@ -14,9 +14,9 @@ import (
"regexp" "regexp"
"github.com/PuerkitoBio/goquery" "github.com/PuerkitoBio/goquery"
"github.com/astaxie/beego" "github.com/beego/beego/v2/client/orm"
"github.com/astaxie/beego/logs" "github.com/beego/beego/v2/core/logs"
"github.com/astaxie/beego/orm" "github.com/beego/beego/v2/server/web"
"github.com/mindoc-org/mindoc/conf" "github.com/mindoc-org/mindoc/conf"
"github.com/mindoc-org/mindoc/converter" "github.com/mindoc-org/mindoc/converter"
"github.com/mindoc-org/mindoc/utils/cryptil" "github.com/mindoc-org/mindoc/utils/cryptil"
@ -24,7 +24,7 @@ import (
"github.com/mindoc-org/mindoc/utils/gopool" "github.com/mindoc-org/mindoc/utils/gopool"
"github.com/mindoc-org/mindoc/utils/requests" "github.com/mindoc-org/mindoc/utils/requests"
"github.com/mindoc-org/mindoc/utils/ziptil" "github.com/mindoc-org/mindoc/utils/ziptil"
"gopkg.in/russross/blackfriday.v2" "github.com/russross/blackfriday/v2"
) )
var ( var (
@ -97,7 +97,7 @@ func (m *BookResult) FindByIdentify(identify string, memberId int) (*BookResult,
err := NewBook().QueryTable().Filter("identify", identify).One(&book) err := NewBook().QueryTable().Filter("identify", identify).One(&book)
if err != nil { if err != nil {
beego.Error("获取项目失败 ->", err) logs.Error("获取项目失败 ->", err)
return m, err return m, err
} }
@ -229,7 +229,7 @@ func (m *BookResult) ToBookResult(book Book) *BookResult {
} }
if m.ItemId > 0 { if m.ItemId > 0 {
if item,err := NewItemsets().First(m.ItemId); err == nil { if item, err := NewItemsets().First(m.ItemId); err == nil {
m.ItemName = item.ItemName m.ItemName = item.ItemName
} }
} }
@ -240,7 +240,7 @@ func (m *BookResult) ToBookResult(book Book) *BookResult {
func BackgroundConvert(sessionId string, bookResult *BookResult) error { func BackgroundConvert(sessionId string, bookResult *BookResult) error {
if err := converter.CheckConvertCommand(); err != nil { if err := converter.CheckConvertCommand(); err != nil {
beego.Error("检查转换程序失败 -> ", err) logs.Error("检查转换程序失败 -> ", err)
return err return err
} }
err := exportLimitWorkerChannel.LoadOrStore(bookResult.Identify, func() { err := exportLimitWorkerChannel.LoadOrStore(bookResult.Identify, func() {
@ -249,7 +249,7 @@ func BackgroundConvert(sessionId string, bookResult *BookResult) error {
if err != nil { if err != nil {
beego.Error("将导出任务加入任务队列失败 -> ", err) logs.Error("将导出任务加入任务队列失败 -> ", err)
return err return err
} }
exportLimitWorkerChannel.Start() exportLimitWorkerChannel.Start()
@ -262,7 +262,7 @@ func (m *BookResult) Converter(sessionId string) (ConvertBookResult, error) {
convertBookResult := ConvertBookResult{} convertBookResult := ConvertBookResult{}
outputPath := filepath.Join(conf.GetExportOutputPath(), strconv.Itoa(m.BookId)) outputPath := filepath.Join(conf.GetExportOutputPath(), strconv.Itoa(m.BookId))
viewPath := beego.BConfig.WebConfig.ViewsPath viewPath := web.BConfig.WebConfig.ViewsPath
pdfpath := filepath.Join(outputPath, "book.pdf") pdfpath := filepath.Join(outputPath, "book.pdf")
epubpath := filepath.Join(outputPath, "book.epub") epubpath := filepath.Join(outputPath, "book.epub")
@ -272,18 +272,18 @@ func (m *BookResult) Converter(sessionId string) (ConvertBookResult, error) {
//先将转换的文件储存到临时目录 //先将转换的文件储存到临时目录
tempOutputPath := filepath.Join(os.TempDir(), sessionId, m.Identify, "source") //filepath.Abs(filepath.Join("cache", sessionId)) tempOutputPath := filepath.Join(os.TempDir(), sessionId, m.Identify, "source") //filepath.Abs(filepath.Join("cache", sessionId))
sourceDir := strings.TrimSuffix(tempOutputPath, "source"); sourceDir := strings.TrimSuffix(tempOutputPath, "source")
if filetil.FileExists(sourceDir) { if filetil.FileExists(sourceDir) {
if err := os.RemoveAll(sourceDir); err != nil { if err := os.RemoveAll(sourceDir); err != nil {
beego.Error("删除临时目录失败 ->", sourceDir, err) logs.Error("删除临时目录失败 ->", sourceDir, err)
} }
} }
if err := os.MkdirAll(outputPath, 0766); err != nil { if err := os.MkdirAll(outputPath, 0766); err != nil {
beego.Error("创建目录失败 -> ", outputPath, err) logs.Error("创建目录失败 -> ", outputPath, err)
} }
if err := os.MkdirAll(tempOutputPath, 0766); err != nil { if err := os.MkdirAll(tempOutputPath, 0766); err != nil {
beego.Error("创建目录失败 -> ", tempOutputPath, err) logs.Error("创建目录失败 -> ", tempOutputPath, err)
} }
os.MkdirAll(filepath.Join(tempOutputPath, "Images"), 0755) os.MkdirAll(filepath.Join(tempOutputPath, "Images"), 0755)
@ -359,7 +359,7 @@ func (m *BookResult) Converter(sessionId string) (ConvertBookResult, error) {
} }
if tempOutputPath, err = filepath.Abs(tempOutputPath); err != nil { if tempOutputPath, err = filepath.Abs(tempOutputPath); err != nil {
beego.Error("导出目录配置错误:" + err.Error()) logs.Error("导出目录配置错误:" + err.Error())
return convertBookResult, err return convertBookResult, err
} }
@ -373,7 +373,7 @@ func (m *BookResult) Converter(sessionId string) (ConvertBookResult, error) {
} }
var buf bytes.Buffer var buf bytes.Buffer
if err := beego.ExecuteViewPathTemplate(&buf, "document/export.tpl", viewPath, map[string]interface{}{"Model": m, "Lists": item, "BaseUrl": conf.BaseUrl}); err != nil { if err := web.ExecuteViewPathTemplate(&buf, "document/export.tpl", viewPath, map[string]interface{}{"Model": m, "Lists": item, "BaseUrl": conf.BaseUrl}); err != nil {
return convertBookResult, err return convertBookResult, err
} }
html := buf.String() html := buf.String()
@ -396,7 +396,7 @@ func (m *BookResult) Converter(sessionId string) (ConvertBookResult, error) {
if strings.HasPrefix(src, "/") { if strings.HasPrefix(src, "/") {
spath := filepath.Join(conf.WorkingDirectory, src) spath := filepath.Join(conf.WorkingDirectory, src)
if filetil.CopyFile(spath, filepath.Join(tempOutputPath, dstSrcString)); err != nil { if filetil.CopyFile(spath, filepath.Join(tempOutputPath, dstSrcString)); err != nil {
beego.Error("复制图片失败 -> ", err, src) logs.Error("复制图片失败 -> ", err, src)
return return
} }
@ -415,15 +415,15 @@ func (m *BookResult) Converter(sessionId string) (ConvertBookResult, error) {
if body, err := ioutil.ReadAll(resp.Body); err == nil { if body, err := ioutil.ReadAll(resp.Body); err == nil {
//encodeString = base64.StdEncoding.EncodeToString(body) //encodeString = base64.StdEncoding.EncodeToString(body)
if err := ioutil.WriteFile(filepath.Join(tempOutputPath, dstSrcString), body, 0755); err != nil { if err := ioutil.WriteFile(filepath.Join(tempOutputPath, dstSrcString), body, 0755); err != nil {
beego.Error("下载图片失败 -> ", err, src) logs.Error("下载图片失败 -> ", err, src)
return return
} }
} else { } else {
beego.Error("下载图片失败 -> ", err, src) logs.Error("下载图片失败 -> ", err, src)
return return
} }
} else { } else {
beego.Error("下载图片失败 -> ", err, src) logs.Error("下载图片失败 -> ", err, src)
return return
} }
} }
@ -446,27 +446,27 @@ func (m *BookResult) Converter(sessionId string) (ConvertBookResult, error) {
} }
if err := filetil.CopyFile(filepath.Join(conf.WorkingDirectory, "static", "css", "kancloud.css"), filepath.Join(tempOutputPath, "styles", "css", "kancloud.css")); err != nil { if err := filetil.CopyFile(filepath.Join(conf.WorkingDirectory, "static", "css", "kancloud.css"), filepath.Join(tempOutputPath, "styles", "css", "kancloud.css")); err != nil {
beego.Error("复制CSS样式出错 -> static/css/kancloud.css", err) logs.Error("复制CSS样式出错 -> static/css/kancloud.css", err)
} }
if err := filetil.CopyFile(filepath.Join(conf.WorkingDirectory, "static", "css", "export.css"), filepath.Join(tempOutputPath, "styles", "css", "export.css")); err != nil { if err := filetil.CopyFile(filepath.Join(conf.WorkingDirectory, "static", "css", "export.css"), filepath.Join(tempOutputPath, "styles", "css", "export.css")); err != nil {
beego.Error("复制CSS样式出错 -> static/css/export.css", err) logs.Error("复制CSS样式出错 -> static/css/export.css", err)
} }
if err := filetil.CopyFile(filepath.Join(conf.WorkingDirectory, "static", "editor.md", "css", "editormd.preview.css"), filepath.Join(tempOutputPath, "styles", "editor.md", "css", "editormd.preview.css")); err != nil { if err := filetil.CopyFile(filepath.Join(conf.WorkingDirectory, "static", "editor.md", "css", "editormd.preview.css"), filepath.Join(tempOutputPath, "styles", "editor.md", "css", "editormd.preview.css")); err != nil {
beego.Error("复制CSS样式出错 -> static/editor.md/css/editormd.preview.css", err) logs.Error("复制CSS样式出错 -> static/editor.md/css/editormd.preview.css", err)
} }
if err := filetil.CopyFile(filepath.Join(conf.WorkingDirectory, "static", "css", "markdown.preview.css"), filepath.Join(tempOutputPath, "styles", "css", "markdown.preview.css")); err != nil { if err := filetil.CopyFile(filepath.Join(conf.WorkingDirectory, "static", "css", "markdown.preview.css"), filepath.Join(tempOutputPath, "styles", "css", "markdown.preview.css")); err != nil {
beego.Error("复制CSS样式出错 -> static/css/markdown.preview.css", err) logs.Error("复制CSS样式出错 -> static/css/markdown.preview.css", err)
} }
if err := filetil.CopyFile(filepath.Join(conf.WorkingDirectory, "static", "editor.md", "lib", "highlight", "styles", "github.css"), filepath.Join(tempOutputPath, "styles", "css", "github.css")); err != nil { if err := filetil.CopyFile(filepath.Join(conf.WorkingDirectory, "static", "editor.md", "lib", "highlight", "styles", "github.css"), filepath.Join(tempOutputPath, "styles", "css", "github.css")); err != nil {
beego.Error("复制CSS样式出错 -> static/editor.md/lib/highlight/styles/github.css", err) logs.Error("复制CSS样式出错 -> static/editor.md/lib/highlight/styles/github.css", err)
} }
if err := filetil.CopyDir(filepath.Join(conf.WorkingDirectory, "static", "font-awesome"), filepath.Join(tempOutputPath, "styles", "font-awesome")); err != nil { if err := filetil.CopyDir(filepath.Join(conf.WorkingDirectory, "static", "font-awesome"), filepath.Join(tempOutputPath, "styles", "font-awesome")); err != nil {
beego.Error("复制CSS样式出错 -> static/font-awesome", err) logs.Error("复制CSS样式出错 -> static/font-awesome", err)
} }
if err := filetil.CopyFile(filepath.Join(conf.WorkingDirectory, "static", "editor.md", "lib", "mermaid", "mermaid.css"), filepath.Join(tempOutputPath, "styles", "css", "mermaid.css")); err != nil { if err := filetil.CopyFile(filepath.Join(conf.WorkingDirectory, "static", "editor.md", "lib", "mermaid", "mermaid.css"), filepath.Join(tempOutputPath, "styles", "css", "mermaid.css")); err != nil {
beego.Error("复制CSS样式出错 -> static/editor.md/lib/mermaid/mermaid.css", err) logs.Error("复制CSS样式出错 -> static/editor.md/lib/mermaid/mermaid.css", err)
} }
eBookConverter := &converter.Converter{ eBookConverter := &converter.Converter{
@ -480,22 +480,22 @@ func (m *BookResult) Converter(sessionId string) (ConvertBookResult, error) {
os.MkdirAll(eBookConverter.OutputPath, 0766) os.MkdirAll(eBookConverter.OutputPath, 0766)
if err := eBookConverter.Convert(); err != nil { if err := eBookConverter.Convert(); err != nil {
beego.Error("转换文件错误:" + m.BookName + " -> " + err.Error()) logs.Error("转换文件错误:" + m.BookName + " -> " + err.Error())
return convertBookResult, err return convertBookResult, err
} }
beego.Info("文档转换完成:" + m.BookName) logs.Info("文档转换完成:" + m.BookName)
if err := filetil.CopyFile(filepath.Join(eBookConverter.OutputPath, "output", "book.mobi"), mobipath, ); err != nil { if err := filetil.CopyFile(filepath.Join(eBookConverter.OutputPath, "output", "book.mobi"), mobipath); err != nil {
beego.Error("复制文档失败 -> ", filepath.Join(eBookConverter.OutputPath, "output", "book.mobi"), err) logs.Error("复制文档失败 -> ", filepath.Join(eBookConverter.OutputPath, "output", "book.mobi"), err)
} }
if err := filetil.CopyFile(filepath.Join(eBookConverter.OutputPath, "output", "book.pdf"), pdfpath); err != nil { if err := filetil.CopyFile(filepath.Join(eBookConverter.OutputPath, "output", "book.pdf"), pdfpath); err != nil {
beego.Error("复制文档失败 -> ", filepath.Join(eBookConverter.OutputPath, "output", "book.pdf"), err) logs.Error("复制文档失败 -> ", filepath.Join(eBookConverter.OutputPath, "output", "book.pdf"), err)
} }
if err := filetil.CopyFile(filepath.Join(eBookConverter.OutputPath, "output", "book.epub"), epubpath); err != nil { if err := filetil.CopyFile(filepath.Join(eBookConverter.OutputPath, "output", "book.epub"), epubpath); err != nil {
beego.Error("复制文档失败 -> ", filepath.Join(eBookConverter.OutputPath, "output", "book.epub"), err) logs.Error("复制文档失败 -> ", filepath.Join(eBookConverter.OutputPath, "output", "book.epub"), err)
} }
if err := filetil.CopyFile(filepath.Join(eBookConverter.OutputPath, "output", "book.docx"), docxpath); err != nil { if err := filetil.CopyFile(filepath.Join(eBookConverter.OutputPath, "output", "book.docx"), docxpath); err != nil {
beego.Error("复制文档失败 -> ", filepath.Join(eBookConverter.OutputPath, "output", "book.docx"), err) logs.Error("复制文档失败 -> ", filepath.Join(eBookConverter.OutputPath, "output", "book.docx"), err)
} }
convertBookResult.MobiPath = mobipath convertBookResult.MobiPath = mobipath
@ -525,7 +525,7 @@ func (m *BookResult) ExportMarkdown(sessionId string) (string, error) {
} }
if err := ziptil.Compress(outputPath, tempOutputPath); err != nil { if err := ziptil.Compress(outputPath, tempOutputPath); err != nil {
beego.Error("导出Markdown失败->", err) logs.Error("导出Markdown失败->", err)
return "", err return "", err
} }
return outputPath, nil return outputPath, nil
@ -540,7 +540,7 @@ func exportMarkdown(p string, parentId int, bookId int, baseDir string, bookUrl
_, err := o.QueryTable(NewDocument().TableNameWithPrefix()).Filter("book_id", bookId).Filter("parent_id", parentId).All(&docs) _, err := o.QueryTable(NewDocument().TableNameWithPrefix()).Filter("book_id", bookId).Filter("parent_id", parentId).All(&docs)
if err != nil { if err != nil {
beego.Error("导出Markdown失败->", err) logs.Error("导出Markdown失败->", err)
return err return err
} }
for _, doc := range docs { for _, doc := range docs {
@ -548,7 +548,7 @@ func exportMarkdown(p string, parentId int, bookId int, baseDir string, bookUrl
subDocCount, err := o.QueryTable(NewDocument().TableNameWithPrefix()).Filter("parent_id", doc.DocumentId).Count() subDocCount, err := o.QueryTable(NewDocument().TableNameWithPrefix()).Filter("parent_id", doc.DocumentId).Count()
if err != nil { if err != nil {
beego.Error("导出Markdown失败->", err) logs.Error("导出Markdown失败->", err)
return err return err
} }
@ -623,13 +623,13 @@ func exportMarkdown(p string, parentId int, bookId int, baseDir string, bookUrl
if id, err := strconv.Atoi(docIdentify); err == nil && id > 0 { if id, err := strconv.Atoi(docIdentify); err == nil && id > 0 {
err := o.QueryTable(NewDocument().TableNameWithPrefix()).Filter("document_id", id).One(tempDoc, "identify", "parent_id", "document_id") err := o.QueryTable(NewDocument().TableNameWithPrefix()).Filter("document_id", id).One(tempDoc, "identify", "parent_id", "document_id")
if err != nil { if err != nil {
beego.Error(err) logs.Error(err)
return link return link
} }
} else { } else {
err := o.QueryTable(NewDocument().TableNameWithPrefix()).Filter("identify", docIdentify).One(tempDoc, "identify", "parent_id", "document_id") err := o.QueryTable(NewDocument().TableNameWithPrefix()).Filter("identify", docIdentify).One(tempDoc, "identify", "parent_id", "document_id")
if err != nil { if err != nil {
beego.Error(err) logs.Error(err)
return link return link
} }
} }
@ -644,7 +644,7 @@ func exportMarkdown(p string, parentId int, bookId int, baseDir string, bookUrl
relative = strings.TrimSuffix(strings.TrimPrefix(relative, "/"), "/") relative = strings.TrimSuffix(strings.TrimPrefix(relative, "/"), "/")
repeat = strings.Count(relative, "/") + 1 repeat = strings.Count(relative, "/") + 1
} }
beego.Info(repeat, "|", relative, "|", p, "|", baseDir) logs.Info(repeat, "|", relative, "|", p, "|", baseDir)
tempLink = strings.Repeat("../", repeat) + tempLink tempLink = strings.Repeat("../", repeat) + tempLink
link = strings.TrimSuffix(link, originalLink+")") + tempLink + ")" link = strings.TrimSuffix(link, originalLink+")") + tempLink + ")"
@ -658,7 +658,7 @@ func exportMarkdown(p string, parentId int, bookId int, baseDir string, bookUrl
markdown = "# " + doc.DocumentName + "\n" markdown = "# " + doc.DocumentName + "\n"
} }
if err := ioutil.WriteFile(docPath, []byte(markdown), 0644); err != nil { if err := ioutil.WriteFile(docPath, []byte(markdown), 0644); err != nil {
beego.Error("导出Markdown失败->", err) logs.Error("导出Markdown失败->", err)
return err return err
} }
@ -679,7 +679,7 @@ func recursiveJoinDocumentIdentify(parentDocId int, identify string) string {
err := o.QueryTable(NewDocument().TableNameWithPrefix()).Filter("document_id", parentDocId).One(doc, "identify", "parent_id", "document_id") err := o.QueryTable(NewDocument().TableNameWithPrefix()).Filter("document_id", parentDocId).One(doc, "identify", "parent_id", "document_id")
if err != nil { if err != nil {
beego.Error(err) logs.Error(err)
return identify return identify
} }

View File

@ -1,6 +1,6 @@
package models package models
import "github.com/astaxie/beego/orm" import "github.com/beego/beego/v2/client/orm"
type Dashboard struct { type Dashboard struct {
BookNumber int64 `json:"book_number"` BookNumber int64 `json:"book_number"`

View File

@ -3,8 +3,8 @@ package models
import ( import (
"time" "time"
"github.com/astaxie/beego" "github.com/beego/beego/v2/client/orm"
"github.com/astaxie/beego/orm" "github.com/beego/beego/v2/core/logs"
"github.com/mindoc-org/mindoc/conf" "github.com/mindoc-org/mindoc/conf"
) )
@ -21,7 +21,7 @@ type DocumentHistory struct {
ModifyTime time.Time `orm:"column(modify_time);type(datetime);auto_now" json:"modify_time"` ModifyTime time.Time `orm:"column(modify_time);type(datetime);auto_now" json:"modify_time"`
ModifyAt int `orm:"column(modify_at);type(int)" json:"-"` ModifyAt int `orm:"column(modify_at);type(int)" json:"-"`
Version int64 `orm:"type(bigint);column(version)" json:"version"` Version int64 `orm:"type(bigint);column(version)" json:"version"`
IsOpen int `orm:"column(is_open);type(int);default(0)" json:"is_open"` IsOpen int `orm:"column(is_open);type(int);default(0)" json:"is_open"`
} }
type DocumentHistorySimpleResult struct { type DocumentHistorySimpleResult struct {
@ -127,22 +127,22 @@ func (m *DocumentHistory) InsertOrUpdate() (history *DocumentHistory, err error)
} else { } else {
_, err = o.Insert(m) _, err = o.Insert(m)
if err == nil { if err == nil {
if doc,e := NewDocument().Find(m.DocumentId);e == nil { if doc, e := NewDocument().Find(m.DocumentId); e == nil {
if book,e := NewBook().Find(doc.BookId);e == nil && book.HistoryCount > 0 { if book, e := NewBook().Find(doc.BookId); e == nil && book.HistoryCount > 0 {
//如果已存在的历史记录大于指定的记录,则清除旧记录 //如果已存在的历史记录大于指定的记录,则清除旧记录
if c,e := o.QueryTable(m.TableNameWithPrefix()).Filter("document_id",doc.DocumentId).Count(); e == nil && c > int64(book.HistoryCount) { if c, e := o.QueryTable(m.TableNameWithPrefix()).Filter("document_id", doc.DocumentId).Count(); e == nil && c > int64(book.HistoryCount) {
count := c - int64(book.HistoryCount) count := c - int64(book.HistoryCount)
beego.Info("需要删除的历史文档数量:" ,count) logs.Info("需要删除的历史文档数量:", count)
var lists []DocumentHistory var lists []DocumentHistory
if _,e := o.QueryTable(m.TableNameWithPrefix()).Filter("document_id",doc.DocumentId).OrderBy("history_id").Limit(count).All(&lists,"history_id"); e == nil { if _, e := o.QueryTable(m.TableNameWithPrefix()).Filter("document_id", doc.DocumentId).OrderBy("history_id").Limit(count).All(&lists, "history_id"); e == nil {
for _,d := range lists { for _, d := range lists {
o.Delete(&d) o.Delete(&d)
} }
} }
}else{ } else {
beego.Info(book.HistoryCount) logs.Info(book.HistoryCount)
} }
} }
} }

View File

@ -12,8 +12,9 @@ import (
"strings" "strings"
"github.com/PuerkitoBio/goquery" "github.com/PuerkitoBio/goquery"
"github.com/astaxie/beego" "github.com/beego/beego/v2/client/orm"
"github.com/astaxie/beego/orm" "github.com/beego/beego/v2/core/logs"
"github.com/beego/beego/v2/server/web"
"github.com/mindoc-org/mindoc/cache" "github.com/mindoc-org/mindoc/cache"
"github.com/mindoc-org/mindoc/conf" "github.com/mindoc-org/mindoc/conf"
"github.com/mindoc-org/mindoc/utils" "github.com/mindoc-org/mindoc/utils"
@ -41,6 +42,7 @@ type Document struct {
Version int64 `orm:"column(version);type(bigint);" json:"version"` Version int64 `orm:"column(version);type(bigint);" json:"version"`
//是否展开子目录0 否/1 是 /2 空间节点,单击时展开下一级 //是否展开子目录0 否/1 是 /2 空间节点,单击时展开下一级
IsOpen int `orm:"column(is_open);type(int);default(0)" json:"is_open"` IsOpen int `orm:"column(is_open);type(int);default(0)" json:"is_open"`
ViewCount int `orm:"column(view_count);type(int)" json:"view_count"`
AttachList []*Attachment `orm:"-" json:"attach"` AttachList []*Attachment `orm:"-" json:"attach"`
} }
@ -142,7 +144,7 @@ func (item *Document) RecursiveDocument(docId int) error {
_, err := o.Raw("SELECT document_id FROM " + item.TableNameWithPrefix() + " WHERE parent_id=" + strconv.Itoa(docId)).Values(&maps) _, err := o.Raw("SELECT document_id FROM " + item.TableNameWithPrefix() + " WHERE parent_id=" + strconv.Itoa(docId)).Values(&maps)
if err != nil { if err != nil {
beego.Error("RecursiveDocument => ", err) logs.Error("RecursiveDocument => ", err)
return err return err
} }
@ -164,11 +166,11 @@ func (item *Document) PutToCache() {
if m.Identify == "" { if m.Identify == "" {
if err := cache.Put("Document.Id."+strconv.Itoa(m.DocumentId), m, time.Second*3600); err != nil { if err := cache.Put("Document.Id."+strconv.Itoa(m.DocumentId), m, time.Second*3600); err != nil {
beego.Info("文档缓存失败:", m.DocumentId) logs.Info("文档缓存失败:", m.DocumentId)
} }
} else { } else {
if err := cache.Put(fmt.Sprintf("Document.BookId.%d.Identify.%s", m.BookId, m.Identify), m, time.Second*3600); err != nil { if err := cache.Put(fmt.Sprintf("Document.BookId.%d.Identify.%s", m.BookId, m.Identify), m, time.Second*3600); err != nil {
beego.Info("文档缓存失败:", m.DocumentId) logs.Info("文档缓存失败:", m.DocumentId)
} }
} }
@ -190,7 +192,7 @@ func (item *Document) RemoveCache() {
func (item *Document) FromCacheById(id int) (*Document, error) { func (item *Document) FromCacheById(id int) (*Document, error) {
if err := cache.Get("Document.Id."+strconv.Itoa(id), &item); err == nil && item.DocumentId > 0 { if err := cache.Get("Document.Id."+strconv.Itoa(id), &item); err == nil && item.DocumentId > 0 {
beego.Info("从缓存中获取文档信息成功 ->", item.DocumentId) logs.Info("从缓存中获取文档信息成功 ->", item.DocumentId)
return item, nil return item, nil
} }
@ -211,7 +213,7 @@ func (item *Document) FromCacheByIdentify(identify string, bookId int) (*Documen
key := fmt.Sprintf("Document.BookId.%d.Identify.%s", bookId, identify) key := fmt.Sprintf("Document.BookId.%d.Identify.%s", bookId, identify)
if err := cache.Get(key, item); err == nil && item.DocumentId > 0 { if err := cache.Get(key, item); err == nil && item.DocumentId > 0 {
beego.Info("从缓存中获取文档信息成功 ->", key) logs.Info("从缓存中获取文档信息成功 ->", key)
return item, nil return item, nil
} }
@ -247,14 +249,14 @@ func (item *Document) ReleaseContent() error {
err := item.Processor().InsertOrUpdate("release") err := item.Processor().InsertOrUpdate("release")
if err != nil { if err != nil {
beego.Error(fmt.Sprintf("发布失败 -> %+v", item), err) logs.Error(fmt.Sprintf("发布失败 -> %+v", item), err)
return err return err
} }
//当文档发布后,需要清除已缓存的转换文档和文档缓存 //当文档发布后,需要清除已缓存的转换文档和文档缓存
item.RemoveCache() item.RemoveCache()
if err := os.RemoveAll(filepath.Join(conf.WorkingDirectory, "uploads", "books", strconv.Itoa(item.BookId))); err != nil { if err := os.RemoveAll(filepath.Join(conf.WorkingDirectory, "uploads", "books", strconv.Itoa(item.BookId))); err != nil {
beego.Error("删除已缓存的文档目录失败 -> ", filepath.Join(conf.WorkingDirectory, "uploads", "books", strconv.Itoa(item.BookId))) logs.Error("删除已缓存的文档目录失败 -> ", filepath.Join(conf.WorkingDirectory, "uploads", "books", strconv.Itoa(item.BookId)))
return err return err
} }
@ -285,7 +287,7 @@ func (item *Document) Processor() *Document {
} }
content.WriteString("</ul></div>") content.WriteString("</ul></div>")
if docQuery == nil { if docQuery == nil {
docQuery, err = goquery.NewDocumentFromReader(content); docQuery, err = goquery.NewDocumentFromReader(content)
} else { } else {
if selector := docQuery.Find("div.wiki-bottom").First(); selector.Size() > 0 { if selector := docQuery.Find("div.wiki-bottom").First(); selector.Size() > 0 {
selector.BeforeHtml(content.String()) selector.BeforeHtml(content.String())
@ -303,17 +305,8 @@ func (item *Document) Processor() *Document {
//处理文档结尾信息 //处理文档结尾信息
docCreator, err := NewMember().Find(item.MemberId, "real_name", "account") docCreator, err := NewMember().Find(item.MemberId, "real_name", "account")
release := "<div class=\"wiki-bottom\">" release := "<div class=\"wiki-bottom\">"
if item.ModifyAt > 0 {
docModify, err := NewMember().Find(item.ModifyAt, "real_name", "account") release += "作者:"
if err == nil {
if docModify.RealName != "" {
release += "最后编辑: " + docModify.RealName + " &nbsp;"
} else {
release += "最后编辑: " + docModify.Account + " &nbsp;"
}
}
}
release += "文档更新时间: " + item.ModifyTime.Local().Format("2006-01-02 15:04") + " &nbsp;&nbsp;作者:"
if err == nil && docCreator != nil { if err == nil && docCreator != nil {
if docCreator.RealName != "" { if docCreator.RealName != "" {
release += docCreator.RealName release += docCreator.RealName
@ -321,6 +314,19 @@ func (item *Document) Processor() *Document {
release += docCreator.Account release += docCreator.Account
} }
} }
release += " &nbsp;创建时间:" + item.CreateTime.Local().Format("2006-01-02 15:04") + "<br>"
if item.ModifyAt > 0 {
docModify, err := NewMember().Find(item.ModifyAt, "real_name", "account")
if err == nil {
if docModify.RealName != "" {
release += "最后编辑:" + docModify.RealName
} else {
release += "最后编辑:" + docModify.Account
}
}
}
release += " &nbsp;更新时间:" + item.ModifyTime.Local().Format("2006-01-02 15:04") + "<br>"
release += "</div>" release += "</div>"
if selector := docQuery.Find("div.markdown-article").First(); selector.Size() > 0 { if selector := docQuery.Find("div.markdown-article").First(); selector.Size() > 0 {
@ -329,7 +335,7 @@ func (item *Document) Processor() *Document {
selector.First().AppendHtml(release) selector.First().AppendHtml(release)
} }
} }
cdnimg := beego.AppConfig.String("cdnimg") cdnimg,_ := web.AppConfig.String("cdnimg")
docQuery.Find("img").Each(func(i int, selection *goquery.Selection) { docQuery.Find("img").Each(func(i int, selection *goquery.Selection) {
@ -356,7 +362,7 @@ func (item *Document) Processor() *Document {
selection.SetAttr("href", "#") selection.SetAttr("href", "#")
return return
} }
val = strings.Replace(strings.ToLower(val), " ", "",-1) val = strings.Replace(strings.ToLower(val), " ", "", -1)
//移除危险脚本链接 //移除危险脚本链接
if strings.HasPrefix(val, "data:text/html") || if strings.HasPrefix(val, "data:text/html") ||
strings.HasPrefix(val, "vbscript:") || strings.HasPrefix(val, "vbscript:") ||
@ -380,3 +386,11 @@ func (item *Document) Processor() *Document {
} }
return item return item
} }
// 增加阅读次数
func (item *Document) IncrViewCount(id int) {
o := orm.NewOrm()
o.QueryTable(item.TableNameWithPrefix()).Filter("document_id", id).Update(orm.Params{
"view_count": orm.ColValue(orm.ColAdd, 1),
})
}

View File

@ -3,9 +3,10 @@ package models
import ( import (
"time" "time"
"github.com/astaxie/beego/orm"
"github.com/astaxie/beego"
"strings" "strings"
"github.com/beego/beego/v2/client/orm"
"github.com/beego/beego/v2/core/logs"
) )
type DocumentSearchResult struct { type DocumentSearchResult struct {
@ -33,7 +34,7 @@ func (m *DocumentSearchResult) FindToPager(keyword string, pageIndex, pageSize,
offset := (pageIndex - 1) * pageSize offset := (pageIndex - 1) * pageSize
keyword = "%" + strings.Replace(keyword," ","%",-1) + "%" keyword = "%" + strings.Replace(keyword, " ", "%", -1) + "%"
if memberId <= 0 { if memberId <= 0 {
sql1 := `SELECT count(doc.document_id) as total_count FROM md_documents AS doc sql1 := `SELECT count(doc.document_id) as total_count FROM md_documents AS doc
@ -99,7 +100,7 @@ LIMIT ?, ?;`
err = o.Raw(sql1, keyword, keyword).QueryRow(&totalCount) err = o.Raw(sql1, keyword, keyword).QueryRow(&totalCount)
if err != nil { if err != nil {
beego.Error("查询搜索结果失败 -> ",err) logs.Error("查询搜索结果失败 -> ", err)
return return
} }
sql3 := ` SELECT sql3 := ` SELECT
@ -110,7 +111,7 @@ LIMIT ?, ?;`
c := 0 c := 0
err = o.Raw(sql3, keyword, keyword).QueryRow(&c) err = o.Raw(sql3, keyword, keyword).QueryRow(&c)
if err != nil { if err != nil {
beego.Error("查询搜索结果失败 -> ",err) logs.Error("查询搜索结果失败 -> ", err)
return return
} }
@ -121,15 +122,15 @@ WHERE book.privately_owned = 0 AND (book.book_name LIKE ? OR book.description LI
err = o.Raw(sql4, keyword, keyword).QueryRow(&c) err = o.Raw(sql4, keyword, keyword).QueryRow(&c)
if err != nil { if err != nil {
beego.Error("查询搜索结果失败 -> ",err) logs.Error("查询搜索结果失败 -> ", err)
return return
} }
totalCount += c totalCount += c
_, err = o.Raw(sql2, keyword, keyword,keyword,keyword,keyword,keyword, offset, pageSize).QueryRows(&searchResult) _, err = o.Raw(sql2, keyword, keyword, keyword, keyword, keyword, keyword, offset, pageSize).QueryRows(&searchResult)
if err != nil { if err != nil {
beego.Error("查询搜索结果失败 -> ",err) logs.Error("查询搜索结果失败 -> ", err)
return return
} }
} else { } else {
@ -236,9 +237,9 @@ LIMIT ?, ?;`
(blog.blog_release LIKE ? OR blog.blog_title LIKE ?);` (blog.blog_release LIKE ? OR blog.blog_title LIKE ?);`
c := 0 c := 0
err = o.Raw(sql3,memberId, keyword, keyword).QueryRow(&c) err = o.Raw(sql3, memberId, keyword, keyword).QueryRow(&c)
if err != nil { if err != nil {
beego.Error("查询搜索结果失败 -> ",err) logs.Error("查询搜索结果失败 -> ", err)
return return
} }
@ -253,15 +254,15 @@ LIMIT ?, ?;`
on team.book_id = book.book_id on team.book_id = book.book_id
WHERE (book.privately_owned = 0 OR rel1.relationship_id > 0 or team.team_member_id > 0) AND (book.book_name LIKE ? OR book.description LIKE ?);` WHERE (book.privately_owned = 0 OR rel1.relationship_id > 0 or team.team_member_id > 0) AND (book.book_name LIKE ? OR book.description LIKE ?);`
err = o.Raw(sql4,memberId, memberId,keyword, keyword).QueryRow(&c) err = o.Raw(sql4, memberId, memberId, keyword, keyword).QueryRow(&c)
if err != nil { if err != nil {
beego.Error("查询搜索结果失败 -> ",err) logs.Error("查询搜索结果失败 -> ", err)
return return
} }
totalCount += c totalCount += c
_, err = o.Raw(sql2, memberId, memberId, keyword, keyword,memberId,memberId,keyword, keyword,memberId,keyword, keyword,offset, pageSize).QueryRows(&searchResult) _, err = o.Raw(sql2, memberId, memberId, keyword, keyword, memberId, memberId, keyword, keyword, memberId, keyword, keyword, offset, pageSize).QueryRows(&searchResult)
if err != nil { if err != nil {
return return
} }

View File

@ -6,7 +6,7 @@ import (
"html/template" "html/template"
"math" "math"
"github.com/astaxie/beego/orm" "github.com/beego/beego/v2/client/orm"
"github.com/mindoc-org/mindoc/conf" "github.com/mindoc-org/mindoc/conf"
) )

View File

@ -5,8 +5,8 @@ import (
"strings" "strings"
"time" "time"
"github.com/astaxie/beego" "github.com/beego/beego/v2/client/orm"
"github.com/astaxie/beego/orm" "github.com/beego/beego/v2/core/logs"
"github.com/mindoc-org/mindoc/conf" "github.com/mindoc-org/mindoc/conf"
"github.com/mindoc-org/mindoc/utils" "github.com/mindoc-org/mindoc/utils"
"github.com/mindoc-org/mindoc/utils/cryptil" "github.com/mindoc-org/mindoc/utils/cryptil"
@ -55,7 +55,7 @@ func (item *Itemsets) First(itemId int) (*Itemsets, error) {
} }
err := item.QueryTable().Filter("item_id", itemId).One(item) err := item.QueryTable().Filter("item_id", itemId).One(item)
if err != nil { if err != nil {
beego.Error("查询项目空间失败 -> item_id=", itemId, err) logs.Error("查询项目空间失败 -> item_id=", itemId, err)
} else { } else {
item.Include() item.Include()
} }
@ -65,7 +65,7 @@ func (item *Itemsets) First(itemId int) (*Itemsets, error) {
func (item *Itemsets) FindFirst(itemKey string) (*Itemsets, error) { func (item *Itemsets) FindFirst(itemKey string) (*Itemsets, error) {
err := item.QueryTable().Filter("item_key", itemKey).One(item) err := item.QueryTable().Filter("item_key", itemKey).One(item)
if err != nil { if err != nil {
beego.Error("查询项目空间失败 -> itemKey=", itemKey, err) logs.Error("查询项目空间失败 -> itemKey=", itemKey, err)
} else { } else {
item.Include() item.Include()
} }
@ -112,19 +112,20 @@ func (item *Itemsets) Delete(itemId int) (err error) {
if !item.Exist(itemId) { if !item.Exist(itemId) {
return errors.New("项目空间不存在") return errors.New("项目空间不存在")
} }
o := orm.NewOrm() ormer := orm.NewOrm()
if err := o.Begin(); err != nil { o, err := ormer.Begin()
beego.Error("开启事物失败 ->", err) if err != nil {
logs.Error("开启事物失败 ->", err)
return err return err
} }
_, err = o.QueryTable(item.TableNameWithPrefix()).Filter("item_id", itemId).Delete() _, err = o.QueryTable(item.TableNameWithPrefix()).Filter("item_id", itemId).Delete()
if err != nil { if err != nil {
beego.Error("删除项目空间失败 -> item_id=", itemId, err) logs.Error("删除项目空间失败 -> item_id=", itemId, err)
o.Rollback() o.Rollback()
} }
_, err = o.Raw("update md_books set item_id=1 where item_id=?;", itemId).Exec() _, err = o.Raw("update md_books set item_id=1 where item_id=?;", itemId).Exec()
if err != nil { if err != nil {
beego.Error("删除项目空间失败 -> item_id=", itemId, err) logs.Error("删除项目空间失败 -> item_id=", itemId, err)
o.Rollback() o.Rollback()
} }
@ -190,7 +191,7 @@ func (item *Itemsets) FindItemsetsByName(name string, limit int) (*SelectMemberR
_, err = item.QueryTable().Filter("item_name__icontains", name).Limit(limit).All(&itemsets) _, err = item.QueryTable().Filter("item_name__icontains", name).Limit(limit).All(&itemsets)
} }
if err != nil { if err != nil {
beego.Error("查询项目空间失败 ->", err) logs.Error("查询项目空间失败 ->", err)
return &result, err return &result, err
} }
@ -214,7 +215,7 @@ func (item *Itemsets) FindItemsetsByItemKey(key string, pageIndex, pageSize, mem
err = item.QueryTable().Filter("item_key", key).One(item) err = item.QueryTable().Filter("item_key", key).One(item)
if err != nil { if err != nil {
beego.Error("查询项目空间时出错 ->", key, err) logs.Error("查询项目空间时出错 ->", key, err)
return nil, 0, err return nil, 0, err
} }
offset := (pageIndex - 1) * pageSize offset := (pageIndex - 1) * pageSize
@ -232,7 +233,7 @@ WHERE book.item_id = ? AND (book.privately_owned = 0 or rel.role_id >= 0 or team
err = o.Raw(sql1, memberId, memberId, item.ItemId).QueryRow(&totalCount) err = o.Raw(sql1, memberId, memberId, item.ItemId).QueryRow(&totalCount)
if err != nil { if err != nil {
beego.Error("查询项目空间时出错 ->", key, err) logs.Error("查询项目空间时出错 ->", key, err)
return return
} }
sql2 := `SELECT book.*,rel1.*,member.account AS create_name FROM md_books AS book sql2 := `SELECT book.*,rel1.*,member.account AS create_name FROM md_books AS book

View File

@ -3,8 +3,8 @@ package models
import ( import (
"strings" "strings"
"github.com/astaxie/beego" "github.com/beego/beego/v2/client/orm"
"github.com/astaxie/beego/orm" "github.com/beego/beego/v2/core/logs"
"github.com/mindoc-org/mindoc/conf" "github.com/mindoc-org/mindoc/conf"
) )
@ -74,10 +74,11 @@ func (m *Label) InsertOrUpdateMulti(labels string) {
} }
} }
} }
//删除标签 //删除标签
func (m *Label) Delete() error { func (m *Label) Delete() error {
o := orm.NewOrm() o := orm.NewOrm()
_,err := o.Raw("DELETE FROM " + m.TableNameWithPrefix() + " WHERE label_id= ?",m.LabelId).Exec() _, err := o.Raw("DELETE FROM "+m.TableNameWithPrefix()+" WHERE label_id= ?", m.LabelId).Exec()
if err != nil { if err != nil {
return err return err
@ -101,13 +102,9 @@ func (m *Label) FindToPager(pageIndex, pageSize int) (labels []*Label, totalCoun
_, err = o.QueryTable(m.TableNameWithPrefix()).OrderBy("-book_number").Offset(offset).Limit(pageSize).All(&labels) _, err = o.QueryTable(m.TableNameWithPrefix()).OrderBy("-book_number").Offset(offset).Limit(pageSize).All(&labels)
if err == orm.ErrNoRows { if err == orm.ErrNoRows {
beego.Info("没有查询到标签 ->",err) logs.Info("没有查询到标签 ->", err)
err = nil err = nil
return return
} }
return return
} }

View File

@ -5,7 +5,7 @@ import (
"sync/atomic" "sync/atomic"
"time" "time"
"github.com/astaxie/beego/orm" "github.com/beego/beego/v2/client/orm"
"github.com/mindoc-org/mindoc/conf" "github.com/mindoc-org/mindoc/conf"
) )

View File

@ -19,9 +19,9 @@ import (
"math" "math"
"github.com/astaxie/beego" "github.com/beego/beego/v2/client/orm"
"github.com/astaxie/beego/logs" "github.com/beego/beego/v2/core/logs"
"github.com/astaxie/beego/orm" "github.com/beego/beego/v2/server/web"
"github.com/mindoc-org/mindoc/conf" "github.com/mindoc-org/mindoc/conf"
"github.com/mindoc-org/mindoc/utils" "github.com/mindoc-org/mindoc/utils"
) )
@ -74,14 +74,14 @@ func (m *Member) Login(account string, password string) (*Member, error) {
err := o.Raw("select * from md_members where (account = ? or email = ?) and status = 0 limit 1;", account, account).QueryRow(member) err := o.Raw("select * from md_members where (account = ? or email = ?) and status = 0 limit 1;", account, account).QueryRow(member)
if err != nil { if err != nil {
if beego.AppConfig.DefaultBool("ldap_enable", false) == true { if web.AppConfig.DefaultBool("ldap_enable", false) {
logs.Info("转入LDAP登陆 ->", account) logs.Info("转入LDAP登陆 ->", account)
return member.ldapLogin(account, password) return member.ldapLogin(account, password)
} else if beego.AppConfig.String("http_login_url") != "" { } else if url, err := web.AppConfig.String("http_login_url"); url != "" {
logs.Info("转入 HTTP 接口登陆 ->", account) logs.Info("转入 HTTP 接口登陆 ->", account)
return member.httpLogin(account, password) return member.httpLogin(account, password)
} else { } else {
logs.Error("用户登录 ->", err) logs.Error("user login for `%s`: %s", account, err)
return member, ErrMemberNoExist return member, ErrMemberNoExist
} }
} }
@ -118,32 +118,38 @@ func (m *Member) TmpLogin(account string) (*Member, error) {
//ldapLogin 通过LDAP登陆 //ldapLogin 通过LDAP登陆
func (m *Member) ldapLogin(account string, password string) (*Member, error) { func (m *Member) ldapLogin(account string, password string) (*Member, error) {
if beego.AppConfig.DefaultBool("ldap_enable", false) == false { if !web.AppConfig.DefaultBool("ldap_enable", false) {
return m, ErrMemberAuthMethodInvalid return m, ErrMemberAuthMethodInvalid
} }
var err error var err error
lc, err := ldap.Dial("tcp", fmt.Sprintf("%s:%d", beego.AppConfig.String("ldap_host"), beego.AppConfig.DefaultInt("ldap_port", 3268))) ldaphost, _ := web.AppConfig.String("ldap_host")
lc, err := ldap.Dial("tcp", fmt.Sprintf("%s:%d", ldaphost, web.AppConfig.DefaultInt("ldap_port", 3268)))
if err != nil { if err != nil {
beego.Error("绑定 LDAP 用户失败 ->", err) logs.Error("绑定 LDAP 用户失败 ->", err)
return m, ErrLDAPConnect return m, ErrLDAPConnect
} }
defer lc.Close() defer lc.Close()
err = lc.Bind(beego.AppConfig.String("ldap_user"), beego.AppConfig.String("ldap_password")) ldapuser, _ := web.AppConfig.String("ldap_user")
ldappass, _ := web.AppConfig.String("ldap_password")
err = lc.Bind(ldapuser, ldappass)
if err != nil { if err != nil {
beego.Error("绑定 LDAP 用户失败 ->", err) logs.Error("绑定 LDAP 用户失败 ->", err)
return m, ErrLDAPFirstBind return m, ErrLDAPFirstBind
} }
ldapbase, _ := web.AppConfig.String("ldap_base")
ldapfilter, _ := web.AppConfig.String("ldap_filter")
ldapattr, _ := web.AppConfig.String("ldap_attribute")
searchRequest := ldap.NewSearchRequest( searchRequest := ldap.NewSearchRequest(
beego.AppConfig.String("ldap_base"), ldapbase,
ldap.ScopeWholeSubtree, ldap.NeverDerefAliases, 0, 0, false, ldap.ScopeWholeSubtree, ldap.NeverDerefAliases, 0, 0, false,
//修改objectClass通过配置文件获取值 //修改objectClass通过配置文件获取值
fmt.Sprintf("(&(%s)(%s=%s))", beego.AppConfig.String("ldap_filter"), beego.AppConfig.String("ldap_attribute"), account), fmt.Sprintf("(&(%s)(%s=%s))", ldapfilter, ldapattr, account),
[]string{"dn", "mail"}, []string{"dn", "mail"},
nil, nil,
) )
searchResult, err := lc.Search(searchRequest) searchResult, err := lc.Search(searchRequest)
if err != nil { if err != nil {
beego.Error("绑定 LDAP 用户失败 ->", err) logs.Error("绑定 LDAP 用户失败 ->", err)
return m, ErrLDAPSearch return m, ErrLDAPSearch
} }
if len(searchResult.Entries) != 1 { if len(searchResult.Entries) != 1 {
@ -152,7 +158,7 @@ func (m *Member) ldapLogin(account string, password string) (*Member, error) {
userdn := searchResult.Entries[0].DN userdn := searchResult.Entries[0].DN
err = lc.Bind(userdn, password) err = lc.Bind(userdn, password)
if err != nil { if err != nil {
beego.Error("绑定 LDAP 用户失败 ->", err) logs.Error("绑定 LDAP 用户失败 ->", err)
return m, ErrorMemberPasswordError return m, ErrorMemberPasswordError
} }
if m.MemberId <= 0 { if m.MemberId <= 0 {
@ -160,12 +166,12 @@ func (m *Member) ldapLogin(account string, password string) (*Member, error) {
m.Email = searchResult.Entries[0].GetAttributeValue("mail") m.Email = searchResult.Entries[0].GetAttributeValue("mail")
m.AuthMethod = "ldap" m.AuthMethod = "ldap"
m.Avatar = "/static/images/headimgurl.jpg" m.Avatar = "/static/images/headimgurl.jpg"
m.Role = conf.SystemRole(beego.AppConfig.DefaultInt("ldap_user_role", 2)) m.Role = conf.SystemRole(web.AppConfig.DefaultInt("ldap_user_role", 2))
m.CreateTime = time.Now() m.CreateTime = time.Now()
err = m.Add() err = m.Add()
if err != nil { if err != nil {
beego.Error("自动注册LDAP用户错误", err) logs.Error("自动注册LDAP用户错误", err)
return m, ErrorMemberPasswordError return m, ErrorMemberPasswordError
} }
m.ResolveRoleName() m.ResolveRoleName()
@ -174,7 +180,7 @@ func (m *Member) ldapLogin(account string, password string) (*Member, error) {
} }
func (m *Member) httpLogin(account, password string) (*Member, error) { func (m *Member) httpLogin(account, password string) (*Member, error) {
urlStr := beego.AppConfig.String("http_login_url") urlStr, _ := web.AppConfig.String("http_login_url")
if urlStr == "" { if urlStr == "" {
return nil, ErrMemberAuthMethodInvalid return nil, ErrMemberAuthMethodInvalid
} }
@ -185,28 +191,28 @@ func (m *Member) httpLogin(account, password string) (*Member, error) {
"time": []string{strconv.FormatInt(time.Now().Unix(), 10)}, "time": []string{strconv.FormatInt(time.Now().Unix(), 10)},
} }
h := md5.New() h := md5.New()
h.Write([]byte(val.Encode() + beego.AppConfig.DefaultString("http_login_secret", ""))) h.Write([]byte(val.Encode() + web.AppConfig.DefaultString("http_login_secret", "")))
val.Add("sn", hex.EncodeToString(h.Sum(nil))) val.Add("sn", hex.EncodeToString(h.Sum(nil)))
resp, err := http.PostForm(urlStr, val) resp, err := http.PostForm(urlStr, val)
if err != nil { if err != nil {
beego.Error("通过接口登录失败 -> ", urlStr, account, err) logs.Error("通过接口登录失败 -> ", urlStr, account, err)
return nil, ErrHTTPServerFail return nil, ErrHTTPServerFail
} }
defer resp.Body.Close() defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body) body, err := ioutil.ReadAll(resp.Body)
if err != nil { if err != nil {
beego.Error("读取接口返回值失败 -> ", urlStr, account, err) logs.Error("读取接口返回值失败 -> ", urlStr, account, err)
return nil, ErrHTTPServerFail return nil, ErrHTTPServerFail
} }
beego.Info("HTTP 登录接口返回数据 ->", string(body)) logs.Info("HTTP 登录接口返回数据 ->", string(body))
var result map[string]interface{} var result map[string]interface{}
if err := json.Unmarshal(body, &result); err != nil { if err := json.Unmarshal(body, &result); err != nil {
beego.Error("解析接口返回值失败 -> ", urlStr, account, string(body)) logs.Error("解析接口返回值失败 -> ", urlStr, account, string(body))
return nil, ErrHTTPServerFail return nil, ErrHTTPServerFail
} }
@ -237,10 +243,10 @@ func (m *Member) httpLogin(account, password string) (*Member, error) {
member.Account = account member.Account = account
member.Password = password member.Password = password
member.AuthMethod = "http" member.AuthMethod = "http"
member.Role = conf.SystemRole(beego.AppConfig.DefaultInt("ldap_user_role", 2)) member.Role = conf.SystemRole(web.AppConfig.DefaultInt("ldap_user_role", 2))
member.CreateTime = time.Now() member.CreateTime = time.Now()
if err := member.Add(); err != nil { if err := member.Add(); err != nil {
beego.Error("自动注册用户错误", err) logs.Error("自动注册用户错误", err)
return m, ErrorMemberPasswordError return m, ErrorMemberPasswordError
} }
member.ResolveRoleName() member.ResolveRoleName()
@ -274,7 +280,7 @@ func (m *Member) Add() error {
hash, err := utils.PasswordHash(m.Password) hash, err := utils.PasswordHash(m.Password)
if err != nil { if err != nil {
beego.Error("加密用户密码失败 =>", err) logs.Error("加密用户密码失败 =>", err)
return errors.New("加密用户密码失败") return errors.New("加密用户密码失败")
} }
@ -285,7 +291,7 @@ func (m *Member) Add() error {
_, err = o.Insert(m) _, err = o.Insert(m)
if err != nil { if err != nil {
beego.Error("保存用户数据到数据时失败 =>", err) logs.Error("保存用户数据到数据时失败 =>", err)
return errors.New("保存用户失败") return errors.New("保存用户失败")
} }
m.ResolveRoleName() m.ResolveRoleName()
@ -303,7 +309,7 @@ func (m *Member) Update(cols ...string) error {
return errors.New("邮箱已被使用") return errors.New("邮箱已被使用")
} }
if _, err := o.Update(m, cols...); err != nil { if _, err := o.Update(m, cols...); err != nil {
beego.Error("保存用户信息失败=>", err) logs.Error("保存用户信息失败=>", err)
return errors.New("保存用户信息失败") return errors.New("保存用户信息失败")
} }
return nil return nil
@ -456,9 +462,9 @@ func (m *Member) Valid(is_hash_password bool) error {
//删除一个用户. //删除一个用户.
func (m *Member) Delete(oldId int, newId int) error { func (m *Member) Delete(oldId int, newId int) error {
o := orm.NewOrm() ormer := orm.NewOrm()
err := o.Begin() o, err := ormer.Begin()
if err != nil { if err != nil {
return err return err
@ -552,18 +558,18 @@ func (m *Member) Delete(oldId int, newId int) error {
err = o.QueryTable(relationship.TableNameWithPrefix()).Filter("book_id", relationship.BookId).Filter("member_id", newId).One(rel) err = o.QueryTable(relationship.TableNameWithPrefix()).Filter("book_id", relationship.BookId).Filter("member_id", newId).One(rel)
if err == nil { if err == nil {
if _, err := o.Delete(relationship); err != nil { if _, err := o.Delete(relationship); err != nil {
beego.Error(err) logs.Error(err)
} }
relationship.RelationshipId = rel.RelationshipId relationship.RelationshipId = rel.RelationshipId
} }
relationship.MemberId = newId relationship.MemberId = newId
relationship.RoleId = 0 relationship.RoleId = 0
if _, err := o.Update(relationship); err != nil { if _, err := o.Update(relationship); err != nil {
beego.Error(err) logs.Error(err)
} }
} else { } else {
if _, err := o.Delete(relationship); err != nil { if _, err := o.Delete(relationship); err != nil {
beego.Error(err) logs.Error(err)
} }
} }
} }

View File

@ -3,7 +3,7 @@ package models
import ( import (
"time" "time"
"github.com/astaxie/beego/orm" "github.com/beego/beego/v2/client/orm"
"github.com/mindoc-org/mindoc/conf" "github.com/mindoc-org/mindoc/conf"
) )
@ -118,8 +118,7 @@ func (m *MemberRelationshipResult) FindNotJoinUsersByAccountOrRealName(bookId, l
var members []*Member var members []*Member
_, err := o.Raw(sql, bookId, keyWord,keyWord, limit).QueryRows(&members) _, err := o.Raw(sql, bookId, keyWord, keyWord, limit).QueryRows(&members)
return members, err return members, err
} }

View File

@ -3,7 +3,7 @@ package models
import ( import (
"time" "time"
"github.com/astaxie/beego/orm" "github.com/beego/beego/v2/client/orm"
"github.com/mindoc-org/mindoc/conf" "github.com/mindoc-org/mindoc/conf"
) )

View File

@ -3,7 +3,7 @@ package models
import ( import (
"time" "time"
"github.com/astaxie/beego/orm" "github.com/beego/beego/v2/client/orm"
"github.com/mindoc-org/mindoc/conf" "github.com/mindoc-org/mindoc/conf"
) )

View File

@ -1,7 +1,7 @@
package models package models
import ( import (
"github.com/astaxie/beego/orm" "github.com/beego/beego/v2/client/orm"
"github.com/mindoc-org/mindoc/conf" "github.com/mindoc-org/mindoc/conf"
) )

View File

@ -3,8 +3,8 @@ package models
import ( import (
"errors" "errors"
"github.com/astaxie/beego/logs" "github.com/beego/beego/v2/client/orm"
"github.com/astaxie/beego/orm" "github.com/beego/beego/v2/core/logs"
"github.com/mindoc-org/mindoc/conf" "github.com/mindoc-org/mindoc/conf"
) )
@ -36,7 +36,7 @@ func (m *Relationship) TableUnique() [][]string {
} }
} }
func (m *Relationship) QueryTable() orm.QuerySeter { func (m *Relationship) QueryTable() orm.QuerySeter {
return orm.NewOrm().QueryTable(m.TableNameWithPrefix()) return orm.NewOrm().QueryTable(m.TableNameWithPrefix())
} }
func NewRelationship() *Relationship { func NewRelationship() *Relationship {
@ -122,11 +122,11 @@ func (m *Relationship) Insert() error {
return err return err
} }
func (m *Relationship) Update() error { func (m *Relationship) Update(txOrm orm.TxOrmer) error {
o := orm.NewOrm() _, err := txOrm.Update(m)
if err != nil {
_, err := o.Update(m) txOrm.Rollback()
}
return err return err
} }
@ -152,11 +152,11 @@ func (m *Relationship) DeleteByBookIdAndMemberId(book_id, member_id int) error {
} }
func (m *Relationship) Transfer(book_id, founder_id, receive_id int) error { func (m *Relationship) Transfer(book_id, founder_id, receive_id int) error {
o := orm.NewOrm() ormer := orm.NewOrm()
founder := NewRelationship() founder := NewRelationship()
err := o.QueryTable(m.TableNameWithPrefix()).Filter("book_id", book_id).Filter("member_id", founder_id).One(founder) err := ormer.QueryTable(m.TableNameWithPrefix()).Filter("book_id", book_id).Filter("member_id", founder_id).One(founder)
if err != nil { if err != nil {
return err return err
@ -166,12 +166,12 @@ func (m *Relationship) Transfer(book_id, founder_id, receive_id int) error {
} }
receive := NewRelationship() receive := NewRelationship()
err = o.QueryTable(m.TableNameWithPrefix()).Filter("book_id", book_id).Filter("member_id", receive_id).One(receive) err = ormer.QueryTable(m.TableNameWithPrefix()).Filter("book_id", book_id).Filter("member_id", receive_id).One(receive)
if err != orm.ErrNoRows && err != nil { if err != orm.ErrNoRows && err != nil {
return err return err
} }
o.Begin() o, _ := ormer.Begin()
founder.RoleId = conf.BookAdmin founder.RoleId = conf.BookAdmin
@ -179,8 +179,7 @@ func (m *Relationship) Transfer(book_id, founder_id, receive_id int) error {
receive.RoleId = conf.BookFounder receive.RoleId = conf.BookFounder
receive.BookId = book_id receive.BookId = book_id
if err := founder.Update(); err != nil { if err := founder.Update(o); err != nil {
o.Rollback()
return err return err
} }
if receive.RelationshipId > 0 { if receive.RelationshipId > 0 {

View File

@ -4,8 +4,8 @@ import (
"errors" "errors"
"time" "time"
"github.com/astaxie/beego" "github.com/beego/beego/v2/client/orm"
"github.com/astaxie/beego/orm" "github.com/beego/beego/v2/core/logs"
"github.com/mindoc-org/mindoc/conf" "github.com/mindoc-org/mindoc/conf"
) )
@ -48,8 +48,8 @@ func (t *Team) First(id int, cols ...string) (*Team, error) {
err := o.QueryTable(t.TableNameWithPrefix()).Filter("team_id", id).One(t, cols...) err := o.QueryTable(t.TableNameWithPrefix()).Filter("team_id", id).One(t, cols...)
if err != nil { if err != nil {
beego.Error("查询团队失败 ->",id, err) logs.Error("查询团队失败 ->", id, err)
return nil,err return nil, err
} }
t.Include() t.Include()
return t, err return t, err
@ -59,34 +59,34 @@ func (t *Team) Delete(id int) (err error) {
if id <= 0 { if id <= 0 {
return ErrInvalidParameter return ErrInvalidParameter
} }
o := orm.NewOrm() ormer := orm.NewOrm()
err = o.Begin() o, err := ormer.Begin()
if err != nil { if err != nil {
beego.Error("开启事物时出错 ->",err) logs.Error("开启事物时出错 ->", err)
return return
} }
_,err = o.QueryTable(t.TableNameWithPrefix()).Filter("team_id",id).Delete() _, err = o.QueryTable(t.TableNameWithPrefix()).Filter("team_id", id).Delete()
if err != nil { if err != nil {
beego.Error("删除团队时出错 ->", err) logs.Error("删除团队时出错 ->", err)
o.Rollback() o.Rollback()
return return
} }
_,err = o.Raw("delete from md_team_member where team_id=?;", id).Exec() _, err = o.Raw("delete from md_team_member where team_id=?;", id).Exec()
if err != nil { if err != nil {
beego.Error("删除团队成员时出错 ->", err) logs.Error("删除团队成员时出错 ->", err)
o.Rollback() o.Rollback()
return return
} }
_,err = o.Raw("delete from md_team_relationship where team_id=?;",id).Exec() _, err = o.Raw("delete from md_team_relationship where team_id=?;", id).Exec()
if err != nil { if err != nil {
beego.Error("删除团队项目时出错 ->", err) logs.Error("删除团队项目时出错 ->", err)
o.Rollback() o.Rollback()
return err return err
} }
@ -113,7 +113,7 @@ func (t *Team) FindToPager(pageIndex, pageSize int) (list []*Team, totalCount in
} }
totalCount = int(c) totalCount = int(c)
for _,item := range list { for _, item := range list {
item.Include() item.Include()
} }
return return
@ -123,23 +123,23 @@ func (t *Team) Include() {
o := orm.NewOrm() o := orm.NewOrm()
if member,err := NewMember().Find(t.MemberId,"account","real_name"); err == nil { if member, err := NewMember().Find(t.MemberId, "account", "real_name"); err == nil {
if member.RealName != "" { if member.RealName != "" {
t.MemberName = member.RealName t.MemberName = member.RealName
} else { } else {
t.MemberName = member.Account t.MemberName = member.Account
} }
} }
if c,err := o.QueryTable(NewTeamRelationship().TableNameWithPrefix()).Filter("team_id", t.TeamId).Count(); err == nil { if c, err := o.QueryTable(NewTeamRelationship().TableNameWithPrefix()).Filter("team_id", t.TeamId).Count(); err == nil {
t.BookCount = int(c) t.BookCount = int(c)
} }
if c,err := o.QueryTable(NewTeamMember().TableNameWithPrefix()).Filter("team_id", t.TeamId).Count(); err == nil { if c, err := o.QueryTable(NewTeamMember().TableNameWithPrefix()).Filter("team_id", t.TeamId).Count(); err == nil {
t.MemberCount = int(c) t.MemberCount = int(c)
} }
} }
//更新或添加一个团队. //更新或添加一个团队.
func (t *Team) Save(cols ... string) (err error) { func (t *Team) Save(cols ...string) (err error) {
if t.TeamName == "" { if t.TeamName == "" {
return NewError(5001, "团队名称不能为空") return NewError(5001, "团队名称不能为空")
} }
@ -155,7 +155,7 @@ func (t *Team) Save(cols ... string) (err error) {
_, err = o.Update(t, cols...) _, err = o.Update(t, cols...)
} }
if err != nil { if err != nil {
beego.Error("在保存团队时出错 ->", err) logs.Error("在保存团队时出错 ->", err)
} }
return return
} }

View File

@ -3,8 +3,8 @@ package models
import ( import (
"errors" "errors"
"github.com/astaxie/beego" "github.com/beego/beego/v2/client/orm"
"github.com/astaxie/beego/orm" "github.com/beego/beego/v2/core/logs"
"github.com/mindoc-org/mindoc/conf" "github.com/mindoc-org/mindoc/conf"
) )
@ -55,7 +55,7 @@ func (m *TeamMember) First(id int, cols ...string) (*TeamMember, error) {
err := o.QueryTable(m.TableNameWithPrefix()).Filter("team_member_id", id).One(m, cols...) err := o.QueryTable(m.TableNameWithPrefix()).Filter("team_member_id", id).One(m, cols...)
if err != nil && err != orm.ErrNoRows { if err != nil && err != orm.ErrNoRows {
beego.Error("查询团队成员错误 ->", err) logs.Error("查询团队成员错误 ->", err)
} }
return m.Include(), err return m.Include(), err
@ -71,7 +71,7 @@ func (m *TeamMember) ChangeRoleId(teamId int, memberId int, roleId conf.BookRole
err = o.QueryTable(m.TableNameWithPrefix()).Filter("team_id", teamId).Filter("member_id", memberId).OrderBy("-team_member_id").One(m) err = o.QueryTable(m.TableNameWithPrefix()).Filter("team_id", teamId).Filter("member_id", memberId).OrderBy("-team_member_id").One(m)
if err != nil { if err != nil {
beego.Error("查询团队用户时失败 ->", err) logs.Error("查询团队用户时失败 ->", err)
return m, err return m, err
} }
m.RoleId = roleId m.RoleId = roleId
@ -93,7 +93,7 @@ func (m *TeamMember) FindFirst(teamId, memberId int) (*TeamMember, error) {
err := o.QueryTable(m.TableNameWithPrefix()).Filter("team_id", teamId).Filter("member_id", memberId).One(m) err := o.QueryTable(m.TableNameWithPrefix()).Filter("team_id", teamId).Filter("member_id", memberId).One(m)
if err != nil { if err != nil {
beego.Error("查询团队用户失败 ->", err) logs.Error("查询团队用户失败 ->", err)
return nil, err return nil, err
} }
return m.Include(), nil return m.Include(), nil
@ -127,7 +127,7 @@ func (m *TeamMember) Save(cols ...string) (err error) {
_, err = o.Update(m, cols...) _, err = o.Update(m, cols...)
} }
if err != nil { if err != nil {
beego.Error("在保存团队时出错 ->", err) logs.Error("在保存团队时出错 ->", err)
} }
return return
} }
@ -141,7 +141,7 @@ func (m *TeamMember) Delete(id int) (err error) {
_, err = orm.NewOrm().QueryTable(m.TableNameWithPrefix()).Filter("team_member_id", id).Delete() _, err = orm.NewOrm().QueryTable(m.TableNameWithPrefix()).Filter("team_member_id", id).Delete()
if err != nil { if err != nil {
beego.Error("删除团队用户时出错 ->", err) logs.Error("删除团队用户时出错 ->", err)
} }
return return
} }
@ -160,7 +160,7 @@ func (m *TeamMember) FindToPager(teamId, pageIndex, pageSize int) (list []*TeamM
if err != nil { if err != nil {
if err != orm.ErrNoRows { if err != orm.ErrNoRows {
beego.Error("查询团队成员失败 ->", err) logs.Error("查询团队成员失败 ->", err)
} }
return return
} }
@ -217,7 +217,7 @@ limit ?;`
_, err := o.Raw(sql, teamId, "%"+account+"%", "%"+account+"%", limit).QueryRows(&members) _, err := o.Raw(sql, teamId, "%"+account+"%", "%"+account+"%", limit).QueryRows(&members)
if err != nil { if err != nil {
beego.Error("查询团队用户时出错 ->", err) logs.Error("查询团队用户时出错 ->", err)
return nil, err return nil, err
} }
@ -250,7 +250,7 @@ and team.member_id = ? order by team.role_id asc limit 1;`
err := o.Raw(sql, bookId, memberId).QueryRow(m) err := o.Raw(sql, bookId, memberId).QueryRow(m)
if err != nil { if err != nil {
beego.Error("查询用户项目所在团队失败 ->bookId=", bookId, " memberId=", memberId, err) logs.Error("查询用户项目所在团队失败 ->bookId=", bookId, " memberId=", memberId, err)
return nil, err return nil, err
} }
return m, nil return m, nil

View File

@ -4,8 +4,8 @@ import (
"errors" "errors"
"time" "time"
"github.com/astaxie/beego" "github.com/beego/beego/v2/client/orm"
"github.com/astaxie/beego/orm" "github.com/beego/beego/v2/core/logs"
"github.com/mindoc-org/mindoc/conf" "github.com/mindoc-org/mindoc/conf"
) )
@ -52,7 +52,7 @@ func (m *TeamRelationship) First(teamId int, cols ...string) (*TeamRelationship,
} }
err := m.QueryTable().Filter("team_id", teamId).One(m, cols...) err := m.QueryTable().Filter("team_id", teamId).One(m, cols...)
if err != nil { if err != nil {
beego.Error("查询项目团队失败 ->", err) logs.Error("查询项目团队失败 ->", err)
} }
return m, err return m, err
} }
@ -64,7 +64,7 @@ func (m *TeamRelationship) FindByBookId(bookId int, teamId int) (*TeamRelationsh
} }
err := m.QueryTable().Filter("team_id", teamId).Filter("book_id", bookId).One(m) err := m.QueryTable().Filter("team_id", teamId).Filter("book_id", bookId).One(m)
if err != nil { if err != nil {
beego.Error("查询项目团队失败 ->", err) logs.Error("查询项目团队失败 ->", err)
} }
return m, err return m, err
} }
@ -73,7 +73,7 @@ func (m *TeamRelationship) FindByBookId(bookId int, teamId int) (*TeamRelationsh
func (m *TeamRelationship) DeleteByBookId(bookId int, teamId int) error { func (m *TeamRelationship) DeleteByBookId(bookId int, teamId int) error {
err := m.QueryTable().Filter("team_id", teamId).Filter("book_id", bookId).One(m) err := m.QueryTable().Filter("team_id", teamId).Filter("book_id", bookId).One(m)
if err != nil { if err != nil {
beego.Error("查询项目团队失败 ->", err) logs.Error("查询项目团队失败 ->", err)
return err return err
} }
m.Include() m.Include()
@ -95,7 +95,7 @@ func (m *TeamRelationship) Save(cols ...string) (err error) {
_, err = orm.NewOrm().Insert(m) _, err = orm.NewOrm().Insert(m)
} }
if err != nil { if err != nil {
beego.Error("保存团队项目时出错 ->", err) logs.Error("保存团队项目时出错 ->", err)
} }
return return
} }
@ -107,7 +107,7 @@ func (m *TeamRelationship) Delete(teamRelId int) (err error) {
_, err = m.QueryTable().Filter("team_relationship_id", teamRelId).Delete() _, err = m.QueryTable().Filter("team_relationship_id", teamRelId).Delete()
if err != nil { if err != nil {
beego.Error("删除团队项目失败 ->", err) logs.Error("删除团队项目失败 ->", err)
} }
return return
} }
@ -125,13 +125,13 @@ func (m *TeamRelationship) FindToPager(teamId, pageIndex, pageSize int) (list []
_, err = o.QueryTable(m.TableNameWithPrefix()).Filter("team_id", teamId).OrderBy("-team_relationship_id").Offset(offset).Limit(pageSize).All(&list) _, err = o.QueryTable(m.TableNameWithPrefix()).Filter("team_id", teamId).OrderBy("-team_relationship_id").Offset(offset).Limit(pageSize).All(&list)
if err != nil { if err != nil {
beego.Error("查询团队项目时出错 ->", err) logs.Error("查询团队项目时出错 ->", err)
return return
} }
count, err := m.QueryTable().Filter("team_id", teamId).Count() count, err := m.QueryTable().Filter("team_id", teamId).Count()
if err != nil { if err != nil {
beego.Error("查询团队项目时出错 ->", err) logs.Error("查询团队项目时出错 ->", err)
return return
} }
totalCount = int(count) totalCount = int(count)
@ -162,8 +162,8 @@ func (m *TeamRelationship) Include() (*TeamRelationship, error) {
} }
} }
} }
if m.TeamId > 0{ if m.TeamId > 0 {
team ,err := NewTeam().First(m.TeamId) team, err := NewTeam().First(m.TeamId)
if err == nil { if err == nil {
m.TeamName = team.TeamName m.TeamName = team.TeamName
m.MemberCount = team.MemberCount m.MemberCount = team.MemberCount
@ -189,7 +189,7 @@ and book.book_name like ? order by book_id desc limit ?;`
_, err := o.Raw(sql, teamId, "%"+bookName+"%", limit).QueryRows(&books) _, err := o.Raw(sql, teamId, "%"+bookName+"%", limit).QueryRows(&books)
if err != nil { if err != nil {
beego.Error("查询团队项目时出错 ->", err) logs.Error("查询团队项目时出错 ->", err)
return nil, err return nil, err
} }
@ -224,7 +224,7 @@ order by team.team_id desc limit ?;`
_, err := o.Raw(sql, bookId, "%"+teamName+"%", limit).QueryRows(&teams) _, err := o.Raw(sql, bookId, "%"+teamName+"%", limit).QueryRows(&teams)
if err != nil { if err != nil {
beego.Error("查询团队项目时出错 ->", err) logs.Error("查询团队项目时出错 ->", err)
return nil, err return nil, err
} }
@ -257,13 +257,13 @@ func (m *TeamRelationship) FindByBookToPager(bookId, pageIndex, pageSize int) (l
_, err = o.QueryTable(m.TableNameWithPrefix()).Filter("book_id", bookId).OrderBy("-team_relationship_id").Offset(offset).Limit(pageSize).All(&list) _, err = o.QueryTable(m.TableNameWithPrefix()).Filter("book_id", bookId).OrderBy("-team_relationship_id").Offset(offset).Limit(pageSize).All(&list)
if err != nil { if err != nil {
beego.Error("查询团队项目时出错 ->", err) logs.Error("查询团队项目时出错 ->", err)
return return
} }
count, err := m.QueryTable().Filter("book_id", bookId).Count() count, err := m.QueryTable().Filter("book_id", bookId).Count()
if err != nil { if err != nil {
beego.Error("查询团队项目时出错 ->", err) logs.Error("查询团队项目时出错 ->", err)
return return
} }
totalCount = int(count) totalCount = int(count)

View File

@ -4,27 +4,26 @@ import (
"errors" "errors"
"time" "time"
"github.com/astaxie/beego" "github.com/beego/beego/v2/client/orm"
"github.com/astaxie/beego/logs" "github.com/beego/beego/v2/core/logs"
"github.com/astaxie/beego/orm"
"github.com/mindoc-org/mindoc/conf" "github.com/mindoc-org/mindoc/conf"
) )
type Template struct { type Template struct {
TemplateId int `orm:"column(template_id);pk;auto;unique;" json:"template_id"` TemplateId int `orm:"column(template_id);pk;auto;unique;" json:"template_id"`
TemplateName string `orm:"column(template_name);size(500);" json:"template_name"` TemplateName string `orm:"column(template_name);size(500);" json:"template_name"`
MemberId int `orm:"column(member_id);index" json:"member_id"` MemberId int `orm:"column(member_id);index" json:"member_id"`
BookId int `orm:"column(book_id);index" json:"book_id"` BookId int `orm:"column(book_id);index" json:"book_id"`
BookName string `orm:"-" json:"book_name"` BookName string `orm:"-" json:"book_name"`
//是否是全局模板0 否/1 是; 全局模板在所有项目中都可以使用;否则只能在创建模板的项目中使用 //是否是全局模板0 否/1 是; 全局模板在所有项目中都可以使用;否则只能在创建模板的项目中使用
IsGlobal int `orm:"column(is_global);default(0)" json:"is_global"` IsGlobal int `orm:"column(is_global);default(0)" json:"is_global"`
TemplateContent string `orm:"column(template_content);type(text);null" json:"template_content"` TemplateContent string `orm:"column(template_content);type(text);null" json:"template_content"`
CreateTime time.Time `orm:"column(create_time);type(datetime);auto_now_add" json:"create_time"` CreateTime time.Time `orm:"column(create_time);type(datetime);auto_now_add" json:"create_time"`
CreateName string `orm:"-" json:"create_name"` CreateName string `orm:"-" json:"create_name"`
ModifyTime time.Time `orm:"column(modify_time);type(datetime);auto_now" json:"modify_time"` ModifyTime time.Time `orm:"column(modify_time);type(datetime);auto_now" json:"modify_time"`
ModifyAt int `orm:"column(modify_at);type(int)" json:"-"` ModifyAt int `orm:"column(modify_at);type(int)" json:"-"`
ModifyName string `orm:"-" json:"modify_name"` ModifyName string `orm:"-" json:"modify_name"`
Version int64 `orm:"type(bigint);column(version)" json:"version"` Version int64 `orm:"type(bigint);column(version)" json:"version"`
} }
// TableName 获取对应数据库表名. // TableName 获取对应数据库表名.
@ -41,82 +40,83 @@ func (m *Template) TableNameWithPrefix() string {
return conf.GetDatabasePrefix() + m.TableName() return conf.GetDatabasePrefix() + m.TableName()
} }
func NewTemplate() *Template { func NewTemplate() *Template {
return &Template{} return &Template{}
} }
//查询指定ID的模板 //查询指定ID的模板
func (t *Template) Find(templateId int) (*Template,error) { func (t *Template) Find(templateId int) (*Template, error) {
if templateId <= 0 { if templateId <= 0 {
return t, ErrInvalidParameter return t, ErrInvalidParameter
} }
o := orm.NewOrm() o := orm.NewOrm()
err := o.QueryTable(t.TableNameWithPrefix()).Filter("template_id",templateId).One(t) err := o.QueryTable(t.TableNameWithPrefix()).Filter("template_id", templateId).One(t)
if err != nil { if err != nil {
logs.Error("查询模板时失败 ->%s",err) logs.Error("查询模板时失败 ->%s", err)
} }
return t,err return t, err
} }
//查询属于指定项目的模板. //查询属于指定项目的模板.
func (t *Template) FindByBookId(bookId int) ([]*Template,error) { func (t *Template) FindByBookId(bookId int) ([]*Template, error) {
if bookId <= 0 { if bookId <= 0 {
return nil,ErrInvalidParameter return nil, ErrInvalidParameter
} }
o := orm.NewOrm() o := orm.NewOrm()
var templateList []*Template var templateList []*Template
_,err := o.QueryTable(t.TableNameWithPrefix()).Filter("book_id",bookId).OrderBy("-template_id").All(&templateList) _, err := o.QueryTable(t.TableNameWithPrefix()).Filter("book_id", bookId).OrderBy("-template_id").All(&templateList)
if err != nil { if err != nil {
beego.Error("查询模板列表失败 ->",err) logs.Error("查询模板列表失败 ->", err)
} }
return templateList,err return templateList, err
} }
//查询指定项目所有可用模板列表. //查询指定项目所有可用模板列表.
func (t *Template) FindAllByBookId(bookId int) ([]*Template,error) { func (t *Template) FindAllByBookId(bookId int) ([]*Template, error) {
if bookId <= 0 { if bookId <= 0 {
return nil,ErrInvalidParameter return nil, ErrInvalidParameter
} }
o := orm.NewOrm() o := orm.NewOrm()
cond := orm.NewCondition() cond := orm.NewCondition()
cond1 := cond.And("book_id",bookId).Or("is_global",1) cond1 := cond.And("book_id", bookId).Or("is_global", 1)
qs := o.QueryTable(t.TableNameWithPrefix()) qs := o.QueryTable(t.TableNameWithPrefix())
var templateList []*Template var templateList []*Template
_,err := qs.SetCond(cond1).OrderBy("-template_id").All(&templateList) _, err := qs.SetCond(cond1).OrderBy("-template_id").All(&templateList)
if err != nil { if err != nil {
beego.Error("查询模板列表失败 ->",err) logs.Error("查询模板列表失败 ->", err)
} }
return templateList,err return templateList, err
} }
//删除一个模板 //删除一个模板
func (t *Template) Delete(templateId int,memberId int) error { func (t *Template) Delete(templateId int, memberId int) error {
if templateId <= 0 { if templateId <= 0 {
return ErrInvalidParameter return ErrInvalidParameter
} }
o := orm.NewOrm() o := orm.NewOrm()
qs := o.QueryTable(t.TableNameWithPrefix()).Filter("template_id",templateId) qs := o.QueryTable(t.TableNameWithPrefix()).Filter("template_id", templateId)
if memberId > 0 { if memberId > 0 {
qs = qs.Filter("member_id",memberId) qs = qs.Filter("member_id", memberId)
} }
_,err := qs.Delete() _, err := qs.Delete()
if err != nil { if err != nil {
beego.Error("删除模板失败 ->",err) logs.Error("删除模板失败 ->", err)
} }
return err return err
} }
@ -129,20 +129,20 @@ func (t *Template) Save(cols ...string) (err error) {
} }
o := orm.NewOrm() o := orm.NewOrm()
if !o.QueryTable(NewBook().TableNameWithPrefix()).Filter("book_id",t.BookId).Exist() { if !o.QueryTable(NewBook().TableNameWithPrefix()).Filter("book_id", t.BookId).Exist() {
return errors.New("项目不存在") return errors.New("项目不存在")
} }
if !o.QueryTable(NewMember().TableNameWithPrefix()).Filter("member_id",t.MemberId).Filter("status",0).Exist() { if !o.QueryTable(NewMember().TableNameWithPrefix()).Filter("member_id", t.MemberId).Filter("status", 0).Exist() {
return errors.New("用户已被禁用") return errors.New("用户已被禁用")
} }
t.Version = time.Now().Unix() t.Version = time.Now().Unix()
if t.TemplateId > 0 { if t.TemplateId > 0 {
t.ModifyTime = time.Now() t.ModifyTime = time.Now()
_,err = o.Update(t,cols...) _, err = o.Update(t, cols...)
}else{ } else {
t.CreateTime = time.Now() t.CreateTime = time.Now()
_,err = o.Insert(t) _, err = o.Insert(t)
} }
return return
@ -152,36 +152,31 @@ func (t *Template) Save(cols ...string) (err error) {
func (t *Template) Preload() *Template { func (t *Template) Preload() *Template {
if t != nil { if t != nil {
if t.MemberId > 0 { if t.MemberId > 0 {
m,err := NewMember().Find(t.MemberId,"account","real_name"); m, err := NewMember().Find(t.MemberId, "account", "real_name")
if err == nil { if err == nil {
if m.RealName != "" { if m.RealName != "" {
t.CreateName = m.RealName t.CreateName = m.RealName
}else{ } else {
t.CreateName = m.Account t.CreateName = m.Account
} }
}else{ } else {
beego.Error("加载模板所有者失败 ->",err) logs.Error("加载模板所有者失败 ->", err)
} }
} }
if t.ModifyAt > 0 { if t.ModifyAt > 0 {
if m,err := NewMember().Find(t.ModifyAt,"account","real_name"); err == nil { if m, err := NewMember().Find(t.ModifyAt, "account", "real_name"); err == nil {
if m.RealName != "" { if m.RealName != "" {
t.ModifyName = m.RealName t.ModifyName = m.RealName
}else{ } else {
t.ModifyName = m.Account t.ModifyName = m.Account
} }
} }
} }
if t.BookId > 0 { if t.BookId > 0 {
if b,err := NewBook().Find(t.BookId,"book_name");err == nil { if b, err := NewBook().Find(t.BookId, "book_name"); err == nil {
t.BookName = b.BookName t.BookName = b.BookName
} }
} }
} }
return t return t
} }

View File

@ -4,7 +4,7 @@ import (
"errors" "errors"
"time" "time"
"github.com/astaxie/beego/orm" "github.com/beego/beego/v2/client/orm"
"github.com/mindoc-org/mindoc/conf" "github.com/mindoc-org/mindoc/conf"
) )

View File

@ -1,6 +1,6 @@
package models package models
import "github.com/astaxie/beego/orm" import "github.com/beego/beego/v2/client/orm"
type CommentResult struct { type CommentResult struct {
Comment Comment

View File

@ -3,7 +3,7 @@ package models
import ( import (
"time" "time"
"github.com/astaxie/beego/orm" "github.com/beego/beego/v2/client/orm"
"github.com/mindoc-org/mindoc/conf" "github.com/mindoc-org/mindoc/conf"
) )

View File

@ -5,8 +5,8 @@ import (
"net/url" "net/url"
"regexp" "regexp"
"github.com/astaxie/beego" "github.com/beego/beego/v2/server/web"
"github.com/astaxie/beego/context" "github.com/beego/beego/v2/server/web/context"
"github.com/mindoc-org/mindoc/conf" "github.com/mindoc-org/mindoc/conf"
"github.com/mindoc-org/mindoc/models" "github.com/mindoc-org/mindoc/models"
) )
@ -30,14 +30,14 @@ func init() {
} }
} }
} }
beego.InsertFilter("/manager", beego.BeforeRouter, FilterUser) web.InsertFilter("/manager", web.BeforeRouter, FilterUser)
beego.InsertFilter("/manager/*", beego.BeforeRouter, FilterUser) web.InsertFilter("/manager/*", web.BeforeRouter, FilterUser)
beego.InsertFilter("/setting", beego.BeforeRouter, FilterUser) web.InsertFilter("/setting", web.BeforeRouter, FilterUser)
beego.InsertFilter("/setting/*", beego.BeforeRouter, FilterUser) web.InsertFilter("/setting/*", web.BeforeRouter, FilterUser)
beego.InsertFilter("/book", beego.BeforeRouter, FilterUser) web.InsertFilter("/book", web.BeforeRouter, FilterUser)
beego.InsertFilter("/book/*", beego.BeforeRouter, FilterUser) web.InsertFilter("/book/*", web.BeforeRouter, FilterUser)
beego.InsertFilter("/api/*", beego.BeforeRouter, FilterUser) web.InsertFilter("/api/*", web.BeforeRouter, FilterUser)
beego.InsertFilter("/manage/*", beego.BeforeRouter, FilterUser) web.InsertFilter("/manage/*", web.BeforeRouter, FilterUser)
var FinishRouter = func(ctx *context.Context) { var FinishRouter = func(ctx *context.Context) {
ctx.ResponseWriter.Header().Add("MinDoc-Version", conf.VERSION) ctx.ResponseWriter.Header().Add("MinDoc-Version", conf.VERSION)
@ -46,7 +46,8 @@ func init() {
} }
var StartRouter = func(ctx *context.Context) { var StartRouter = func(ctx *context.Context) {
sessionId := ctx.Input.Cookie(beego.AppConfig.String("sessionname")) sessname, _ := web.AppConfig.String("sessionname")
sessionId := ctx.Input.Cookie(sessname)
if sessionId != "" { if sessionId != "" {
//sessionId必须是数字字母组成且最小32个字符最大1024字符 //sessionId必须是数字字母组成且最小32个字符最大1024字符
if ok, err := regexp.MatchString(`^[a-zA-Z0-9]{32,512}$`, sessionId); !ok || err != nil { if ok, err := regexp.MatchString(`^[a-zA-Z0-9]{32,512}$`, sessionId); !ok || err != nil {
@ -54,6 +55,6 @@ func init() {
} }
} }
} }
beego.InsertFilter("/*", beego.BeforeStatic, StartRouter, false) web.InsertFilter("/*", web.BeforeStatic, StartRouter, web.WithReturnOnOutput(false))
beego.InsertFilter("/*", beego.BeforeRouter, FinishRouter, false) web.InsertFilter("/*", web.BeforeRouter, FinishRouter, web.WithReturnOnOutput(false))
} }

View File

@ -1,148 +1,148 @@
package routers package routers
import ( import (
"github.com/astaxie/beego" "github.com/beego/beego/v2/server/web"
"github.com/mindoc-org/mindoc/controllers" "github.com/mindoc-org/mindoc/controllers"
) )
func init() { func init() {
beego.Router("/", &controllers.HomeController{}, "*:Index") web.Router("/", &controllers.HomeController{}, "*:Index")
beego.Router("/login", &controllers.AccountController{}, "*:Login") web.Router("/login", &controllers.AccountController{}, "*:Login")
beego.Router("/dingtalk_login", &controllers.AccountController{}, "*:DingTalkLogin") web.Router("/dingtalk_login", &controllers.AccountController{}, "*:DingTalkLogin")
beego.Router("/qrlogin/:app", &controllers.AccountController{}, "*:QRLogin") web.Router("/qrlogin/:app", &controllers.AccountController{}, "*:QRLogin")
beego.Router("/logout", &controllers.AccountController{}, "*:Logout") web.Router("/logout", &controllers.AccountController{}, "*:Logout")
beego.Router("/register", &controllers.AccountController{}, "*:Register") web.Router("/register", &controllers.AccountController{}, "*:Register")
beego.Router("/find_password", &controllers.AccountController{}, "*:FindPassword") web.Router("/find_password", &controllers.AccountController{}, "*:FindPassword")
beego.Router("/valid_email", &controllers.AccountController{}, "post:ValidEmail") web.Router("/valid_email", &controllers.AccountController{}, "post:ValidEmail")
beego.Router("/captcha", &controllers.AccountController{}, "*:Captcha") web.Router("/captcha", &controllers.AccountController{}, "*:Captcha")
beego.Router("/manager", &controllers.ManagerController{}, "*:Index") web.Router("/manager", &controllers.ManagerController{}, "*:Index")
beego.Router("/manager/users", &controllers.ManagerController{}, "*:Users") web.Router("/manager/users", &controllers.ManagerController{}, "*:Users")
beego.Router("/manager/users/edit/:id", &controllers.ManagerController{}, "*:EditMember") web.Router("/manager/users/edit/:id", &controllers.ManagerController{}, "*:EditMember")
beego.Router("/manager/member/create", &controllers.ManagerController{}, "post:CreateMember") web.Router("/manager/member/create", &controllers.ManagerController{}, "post:CreateMember")
beego.Router("/manager/member/delete", &controllers.ManagerController{}, "post:DeleteMember") web.Router("/manager/member/delete", &controllers.ManagerController{}, "post:DeleteMember")
beego.Router("/manager/member/update-member-status", &controllers.ManagerController{}, "post:UpdateMemberStatus") web.Router("/manager/member/update-member-status", &controllers.ManagerController{}, "post:UpdateMemberStatus")
beego.Router("/manager/member/change-member-role", &controllers.ManagerController{}, "post:ChangeMemberRole") web.Router("/manager/member/change-member-role", &controllers.ManagerController{}, "post:ChangeMemberRole")
beego.Router("/manager/books", &controllers.ManagerController{}, "*:Books") web.Router("/manager/books", &controllers.ManagerController{}, "*:Books")
beego.Router("/manager/books/edit/:key", &controllers.ManagerController{}, "*:EditBook") web.Router("/manager/books/edit/:key", &controllers.ManagerController{}, "*:EditBook")
beego.Router("/manager/books/delete", &controllers.ManagerController{}, "*:DeleteBook") web.Router("/manager/books/delete", &controllers.ManagerController{}, "*:DeleteBook")
beego.Router("/manager/comments", &controllers.ManagerController{}, "*:Comments") web.Router("/manager/comments", &controllers.ManagerController{}, "*:Comments")
beego.Router("/manager/setting", &controllers.ManagerController{}, "*:Setting") web.Router("/manager/setting", &controllers.ManagerController{}, "*:Setting")
beego.Router("/manager/books/token", &controllers.ManagerController{}, "post:CreateToken") web.Router("/manager/books/token", &controllers.ManagerController{}, "post:CreateToken")
beego.Router("/manager/books/transfer", &controllers.ManagerController{}, "post:Transfer") web.Router("/manager/books/transfer", &controllers.ManagerController{}, "post:Transfer")
beego.Router("/manager/books/open", &controllers.ManagerController{}, "post:PrivatelyOwned") web.Router("/manager/books/open", &controllers.ManagerController{}, "post:PrivatelyOwned")
beego.Router("/manager/attach/list", &controllers.ManagerController{}, "*:AttachList") web.Router("/manager/attach/list", &controllers.ManagerController{}, "*:AttachList")
beego.Router("/manager/attach/detailed/:id", &controllers.ManagerController{}, "*:AttachDetailed") web.Router("/manager/attach/detailed/:id", &controllers.ManagerController{}, "*:AttachDetailed")
beego.Router("/manager/attach/delete", &controllers.ManagerController{}, "post:AttachDelete") web.Router("/manager/attach/delete", &controllers.ManagerController{}, "post:AttachDelete")
beego.Router("/manager/label/list", &controllers.ManagerController{}, "get:LabelList") web.Router("/manager/label/list", &controllers.ManagerController{}, "get:LabelList")
beego.Router("/manager/label/delete/:id", &controllers.ManagerController{}, "post:LabelDelete") web.Router("/manager/label/delete/:id", &controllers.ManagerController{}, "post:LabelDelete")
//beego.Router("/manager/config", &controllers.ManagerController{}, "*:Config") //web.Router("/manager/config", &controllers.ManagerController{}, "*:Config")
beego.Router("/manager/team", &controllers.ManagerController{}, "*:Team") web.Router("/manager/team", &controllers.ManagerController{}, "*:Team")
beego.Router("/manager/team/create", &controllers.ManagerController{}, "POST:TeamCreate") web.Router("/manager/team/create", &controllers.ManagerController{}, "POST:TeamCreate")
beego.Router("/manager/team/edit", &controllers.ManagerController{}, "POST:TeamEdit") web.Router("/manager/team/edit", &controllers.ManagerController{}, "POST:TeamEdit")
beego.Router("/manager/team/delete", &controllers.ManagerController{}, "POST:TeamDelete") web.Router("/manager/team/delete", &controllers.ManagerController{}, "POST:TeamDelete")
beego.Router("/manager/team/member/list/:id", &controllers.ManagerController{}, "*:TeamMemberList") web.Router("/manager/team/member/list/:id", &controllers.ManagerController{}, "*:TeamMemberList")
beego.Router("/manager/team/member/add", &controllers.ManagerController{}, "POST:TeamMemberAdd") web.Router("/manager/team/member/add", &controllers.ManagerController{}, "POST:TeamMemberAdd")
beego.Router("/manager/team/member/delete", &controllers.ManagerController{}, "POST:TeamMemberDelete") web.Router("/manager/team/member/delete", &controllers.ManagerController{}, "POST:TeamMemberDelete")
beego.Router("/manager/team/member/change_role", &controllers.ManagerController{}, "POST:TeamChangeMemberRole") web.Router("/manager/team/member/change_role", &controllers.ManagerController{}, "POST:TeamChangeMemberRole")
beego.Router("/manager/team/member/search", &controllers.ManagerController{}, "*:TeamSearchMember") web.Router("/manager/team/member/search", &controllers.ManagerController{}, "*:TeamSearchMember")
beego.Router("/manager/team/book/list/:id", &controllers.ManagerController{}, "*:TeamBookList") web.Router("/manager/team/book/list/:id", &controllers.ManagerController{}, "*:TeamBookList")
beego.Router("/manager/team/book/add", &controllers.ManagerController{}, "POST:TeamBookAdd") web.Router("/manager/team/book/add", &controllers.ManagerController{}, "POST:TeamBookAdd")
beego.Router("/manager/team/book/delete", &controllers.ManagerController{}, "POST:TeamBookDelete") web.Router("/manager/team/book/delete", &controllers.ManagerController{}, "POST:TeamBookDelete")
beego.Router("/manager/team/book/search", &controllers.ManagerController{}, "*:TeamSearchBook") web.Router("/manager/team/book/search", &controllers.ManagerController{}, "*:TeamSearchBook")
beego.Router("/manager/itemsets", &controllers.ManagerController{}, "*:Itemsets") web.Router("/manager/itemsets", &controllers.ManagerController{}, "*:Itemsets")
beego.Router("/manager/itemsets/edit", &controllers.ManagerController{}, "post:ItemsetsEdit") web.Router("/manager/itemsets/edit", &controllers.ManagerController{}, "post:ItemsetsEdit")
beego.Router("/manager/itemsets/delete", &controllers.ManagerController{}, "post:ItemsetsDelete") web.Router("/manager/itemsets/delete", &controllers.ManagerController{}, "post:ItemsetsDelete")
beego.Router("/setting", &controllers.SettingController{}, "*:Index") web.Router("/setting", &controllers.SettingController{}, "*:Index")
beego.Router("/setting/password", &controllers.SettingController{}, "*:Password") web.Router("/setting/password", &controllers.SettingController{}, "*:Password")
beego.Router("/setting/upload", &controllers.SettingController{}, "*:Upload") web.Router("/setting/upload", &controllers.SettingController{}, "*:Upload")
beego.Router("/book", &controllers.BookController{}, "*:Index") web.Router("/book", &controllers.BookController{}, "*:Index")
beego.Router("/book/:key/dashboard", &controllers.BookController{}, "*:Dashboard") web.Router("/book/:key/dashboard", &controllers.BookController{}, "*:Dashboard")
beego.Router("/book/:key/setting", &controllers.BookController{}, "*:Setting") web.Router("/book/:key/setting", &controllers.BookController{}, "*:Setting")
beego.Router("/book/:key/users", &controllers.BookController{}, "*:Users") web.Router("/book/:key/users", &controllers.BookController{}, "*:Users")
beego.Router("/book/:key/release", &controllers.BookController{}, "post:Release") web.Router("/book/:key/release", &controllers.BookController{}, "post:Release")
beego.Router("/book/:key/sort", &controllers.BookController{}, "post:SaveSort") web.Router("/book/:key/sort", &controllers.BookController{}, "post:SaveSort")
beego.Router("/book/:key/teams", &controllers.BookController{}, "*:Team") web.Router("/book/:key/teams", &controllers.BookController{}, "*:Team")
beego.Router("/book/create", &controllers.BookController{}, "*:Create") web.Router("/book/create", &controllers.BookController{}, "*:Create")
beego.Router("/book/itemsets/search", &controllers.BookController{}, "*:ItemsetsSearch") web.Router("/book/itemsets/search", &controllers.BookController{}, "*:ItemsetsSearch")
beego.Router("/book/users/create", &controllers.BookMemberController{}, "post:AddMember") web.Router("/book/users/create", &controllers.BookMemberController{}, "post:AddMember")
beego.Router("/book/users/change", &controllers.BookMemberController{}, "post:ChangeRole") web.Router("/book/users/change", &controllers.BookMemberController{}, "post:ChangeRole")
beego.Router("/book/users/delete", &controllers.BookMemberController{}, "post:RemoveMember") web.Router("/book/users/delete", &controllers.BookMemberController{}, "post:RemoveMember")
beego.Router("/book/users/import", &controllers.BookController{}, "post:Import") web.Router("/book/users/import", &controllers.BookController{}, "post:Import")
beego.Router("/book/users/copy", &controllers.BookController{}, "post:Copy") web.Router("/book/users/copy", &controllers.BookController{}, "post:Copy")
beego.Router("/book/setting/save", &controllers.BookController{}, "post:SaveBook") web.Router("/book/setting/save", &controllers.BookController{}, "post:SaveBook")
beego.Router("/book/setting/open", &controllers.BookController{}, "post:PrivatelyOwned") web.Router("/book/setting/open", &controllers.BookController{}, "post:PrivatelyOwned")
beego.Router("/book/setting/transfer", &controllers.BookController{}, "post:Transfer") web.Router("/book/setting/transfer", &controllers.BookController{}, "post:Transfer")
beego.Router("/book/setting/upload", &controllers.BookController{}, "post:UploadCover") web.Router("/book/setting/upload", &controllers.BookController{}, "post:UploadCover")
beego.Router("/book/setting/delete", &controllers.BookController{}, "post:Delete") web.Router("/book/setting/delete", &controllers.BookController{}, "post:Delete")
beego.Router("/book/team/add", &controllers.BookController{}, "POST:TeamAdd") web.Router("/book/team/add", &controllers.BookController{}, "POST:TeamAdd")
beego.Router("/book/team/delete", &controllers.BookController{}, "POST:TeamDelete") web.Router("/book/team/delete", &controllers.BookController{}, "POST:TeamDelete")
beego.Router("/book/team/search", &controllers.BookController{}, "*:TeamSearch") web.Router("/book/team/search", &controllers.BookController{}, "*:TeamSearch")
//管理文章的路由 //管理文章的路由
beego.Router("/manage/blogs", &controllers.BlogController{}, "*:ManageList") web.Router("/manage/blogs", &controllers.BlogController{}, "*:ManageList")
beego.Router("/manage/blogs/setting/?:id", &controllers.BlogController{}, "*:ManageSetting") web.Router("/manage/blogs/setting/?:id", &controllers.BlogController{}, "*:ManageSetting")
beego.Router("/manage/blogs/edit/?:id", &controllers.BlogController{}, "*:ManageEdit") web.Router("/manage/blogs/edit/?:id", &controllers.BlogController{}, "*:ManageEdit")
beego.Router("/manage/blogs/delete", &controllers.BlogController{}, "post:ManageDelete") web.Router("/manage/blogs/delete", &controllers.BlogController{}, "post:ManageDelete")
beego.Router("/manage/blogs/upload", &controllers.BlogController{}, "post:Upload") web.Router("/manage/blogs/upload", &controllers.BlogController{}, "post:Upload")
beego.Router("/manage/blogs/attach/:id", &controllers.BlogController{}, "post:RemoveAttachment") web.Router("/manage/blogs/attach/:id", &controllers.BlogController{}, "post:RemoveAttachment")
//读文章的路由 //读文章的路由
beego.Router("/blogs", &controllers.BlogController{}, "*:List") web.Router("/blogs", &controllers.BlogController{}, "*:List")
beego.Router("/blog-attach/:id:int/:attach_id:int", &controllers.BlogController{}, "get:Download") web.Router("/blog-attach/:id:int/:attach_id:int", &controllers.BlogController{}, "get:Download")
beego.Router("/blog-:id([0-9]+).html", &controllers.BlogController{}, "*:Index") web.Router("/blog-:id([0-9]+).html", &controllers.BlogController{}, "*:Index")
//模板相关接口 //模板相关接口
beego.Router("/api/template/get", &controllers.TemplateController{}, "get:Get") web.Router("/api/template/get", &controllers.TemplateController{}, "get:Get")
beego.Router("/api/template/list", &controllers.TemplateController{}, "post:List") web.Router("/api/template/list", &controllers.TemplateController{}, "post:List")
beego.Router("/api/template/add", &controllers.TemplateController{}, "post:Add") web.Router("/api/template/add", &controllers.TemplateController{}, "post:Add")
beego.Router("/api/template/remove", &controllers.TemplateController{}, "post:Delete") web.Router("/api/template/remove", &controllers.TemplateController{}, "post:Delete")
beego.Router("/api/attach/remove/", &controllers.DocumentController{}, "post:RemoveAttachment") web.Router("/api/attach/remove/", &controllers.DocumentController{}, "post:RemoveAttachment")
beego.Router("/api/:key/edit/?:id", &controllers.DocumentController{}, "*:Edit") web.Router("/api/:key/edit/?:id", &controllers.DocumentController{}, "*:Edit")
beego.Router("/api/upload", &controllers.DocumentController{}, "post:Upload") web.Router("/api/upload", &controllers.DocumentController{}, "post:Upload")
beego.Router("/api/:key/create", &controllers.DocumentController{}, "post:Create") web.Router("/api/:key/create", &controllers.DocumentController{}, "post:Create")
beego.Router("/api/:key/delete", &controllers.DocumentController{}, "post:Delete") web.Router("/api/:key/delete", &controllers.DocumentController{}, "post:Delete")
beego.Router("/api/:key/content/?:id", &controllers.DocumentController{}, "*:Content") web.Router("/api/:key/content/?:id", &controllers.DocumentController{}, "*:Content")
beego.Router("/api/:key/compare/:id", &controllers.DocumentController{}, "*:Compare") web.Router("/api/:key/compare/:id", &controllers.DocumentController{}, "*:Compare")
beego.Router("/api/search/user/:key", &controllers.SearchController{}, "*:User") web.Router("/api/search/user/:key", &controllers.SearchController{}, "*:User")
beego.Router("/history/get", &controllers.DocumentController{}, "get:History") web.Router("/history/get", &controllers.DocumentController{}, "get:History")
beego.Router("/history/delete", &controllers.DocumentController{}, "*:DeleteHistory") web.Router("/history/delete", &controllers.DocumentController{}, "*:DeleteHistory")
beego.Router("/history/restore", &controllers.DocumentController{}, "*:RestoreHistory") web.Router("/history/restore", &controllers.DocumentController{}, "*:RestoreHistory")
beego.Router("/docs/:key", &controllers.DocumentController{}, "*:Index") web.Router("/docs/:key", &controllers.DocumentController{}, "*:Index")
beego.Router("/docs/:key/:id", &controllers.DocumentController{}, "*:Read") web.Router("/docs/:key/:id", &controllers.DocumentController{}, "*:Read")
beego.Router("/docs/:key/search", &controllers.DocumentController{}, "post:Search") web.Router("/docs/:key/search", &controllers.DocumentController{}, "post:Search")
beego.Router("/export/:key", &controllers.DocumentController{}, "*:Export") web.Router("/export/:key", &controllers.DocumentController{}, "*:Export")
beego.Router("/qrcode/:key.png", &controllers.DocumentController{}, "get:QrCode") web.Router("/qrcode/:key.png", &controllers.DocumentController{}, "get:QrCode")
beego.Router("/attach_files/:key/:attach_id", &controllers.DocumentController{}, "get:DownloadAttachment") web.Router("/attach_files/:key/:attach_id", &controllers.DocumentController{}, "get:DownloadAttachment")
beego.Router("/comment/create", &controllers.CommentController{}, "post:Create") web.Router("/comment/create", &controllers.CommentController{}, "post:Create")
beego.Router("/comment/lists", &controllers.CommentController{}, "get:Lists") web.Router("/comment/lists", &controllers.CommentController{}, "get:Lists")
beego.Router("/comment/index", &controllers.CommentController{}, "*:Index") web.Router("/comment/index", &controllers.CommentController{}, "*:Index")
beego.Router("/search", &controllers.SearchController{}, "get:Index") web.Router("/search", &controllers.SearchController{}, "get:Index")
beego.Router("/tag/:key", &controllers.LabelController{}, "get:Index") web.Router("/tag/:key", &controllers.LabelController{}, "get:Index")
beego.Router("/tags", &controllers.LabelController{}, "get:List") web.Router("/tags", &controllers.LabelController{}, "get:List")
beego.Router("/items", &controllers.ItemsetsController{}, "get:Index") web.Router("/items", &controllers.ItemsetsController{}, "get:Index")
beego.Router("/items/:key", &controllers.ItemsetsController{}, "get:List") web.Router("/items/:key", &controllers.ItemsetsController{}, "get:List")
} }

View File

@ -65,6 +65,7 @@ function loadDocument($url, $id, $callback) {
$("title").text(data.title); $("title").text(data.title);
$("#article-title").text(data.doc_title); $("#article-title").text(data.doc_title);
$("#article-info").text(data.doc_info); $("#article-info").text(data.doc_info);
$("#view_count").text("阅读次数:" + data.view_count);
events.trigger('article.open', {$url: $url, $id: $id}); events.trigger('article.open', {$url: $url, $id: $id});
@ -80,6 +81,7 @@ function loadDocument($url, $id, $callback) {
var doc_title = res.data.doc_title; var doc_title = res.data.doc_title;
var title = res.data.title; var title = res.data.title;
var doc_info = res.data.doc_info; var doc_info = res.data.doc_info;
var view_count = res.data.view_count;
$body = body; $body = body;
if (typeof $callback === "function" ) { if (typeof $callback === "function" ) {
@ -90,6 +92,7 @@ function loadDocument($url, $id, $callback) {
$("title").text(title); $("title").text(title);
$("#article-title").text(doc_title); $("#article-title").text(doc_title);
$("#article-info").text(doc_info); $("#article-info").text(doc_info);
$("#view_count").text("阅读次数:" + view_count);
events.data($id, res.data); events.data($id, res.data);

View File

@ -3,7 +3,8 @@ package utils
import ( import (
"errors" "errors"
"fmt" "fmt"
"github.com/astaxie/beego"
"github.com/beego/beego/v2/core/logs"
"gopkg.in/ldap.v2" "gopkg.in/ldap.v2"
) )
@ -24,14 +25,14 @@ func ValidLDAPLogin(password string) (result bool, err error) {
err = nil err = nil
lc, err := ldap.Dial("tcp", fmt.Sprintf("%s:%d", "192.168.3.104", 389)) lc, err := ldap.Dial("tcp", fmt.Sprintf("%s:%d", "192.168.3.104", 389))
if err != nil { if err != nil {
beego.Error("Dial => ", err) logs.Error("Dial => ", err)
return return
} }
defer lc.Close() defer lc.Close()
err = lc.Bind("cn=admin,dc=minho,dc=com", "123456") err = lc.Bind("cn=admin,dc=minho,dc=com", "123456")
if err != nil { if err != nil {
beego.Error("Bind => ", err) logs.Error("Bind => ", err)
return return
} }
searchRequest := ldap.NewSearchRequest( searchRequest := ldap.NewSearchRequest(
@ -43,7 +44,7 @@ func ValidLDAPLogin(password string) (result bool, err error) {
) )
searchResult, err := lc.Search(searchRequest) searchResult, err := lc.Search(searchRequest)
if err != nil { if err != nil {
beego.Error("Search => ", err) logs.Error("Search => ", err)
return return
} }
if len(searchResult.Entries) != 1 { if len(searchResult.Entries) != 1 {
@ -58,7 +59,7 @@ func ValidLDAPLogin(password string) (result bool, err error) {
if err == nil { if err == nil {
result = true result = true
} else { } else {
beego.Error("Bind2 => ", err) logs.Error("Bind2 => ", err)
err = nil err = nil
} }
return return
@ -67,7 +68,7 @@ func ValidLDAPLogin(password string) (result bool, err error) {
func AddMember(account, password string) error { func AddMember(account, password string) error {
lc, err := ldap.Dial("tcp", fmt.Sprintf("%s:%d", "192.168.3.104", 389)) lc, err := ldap.Dial("tcp", fmt.Sprintf("%s:%d", "192.168.3.104", 389))
if err != nil { if err != nil {
beego.Error("Dial => ", err) logs.Error("Dial => ", err)
return err return err
} }
@ -84,33 +85,33 @@ func AddMember(account, password string) error {
err = lc.Bind(user, "") err = lc.Bind(user, "")
if err != nil { if err != nil {
beego.Error("Bind => ", err) logs.Error("Bind => ", err)
return err return err
} }
passwordModifyRequest := ldap.NewPasswordModifyRequest(user, "", "1q2w3e__ABC") passwordModifyRequest := ldap.NewPasswordModifyRequest(user, "", "1q2w3e__ABC")
_, err = lc.PasswordModify(passwordModifyRequest) _, err = lc.PasswordModify(passwordModifyRequest)
if err != nil { if err != nil {
beego.Error("PasswordModify => ", err) logs.Error("PasswordModify => ", err)
return err return err
} }
return nil return nil
} }
beego.Error("Add => ", err) logs.Error("Add => ", err)
return err return err
} }
func ModifyPassword(account, old_password, new_password string) error { func ModifyPassword(account, old_password, new_password string) error {
l, err := ldap.Dial("tcp", fmt.Sprintf("%s:%d", "192.168.3.104", 389)) l, err := ldap.Dial("tcp", fmt.Sprintf("%s:%d", "192.168.3.104", 389))
if err != nil { if err != nil {
beego.Error("Dial => ", err) logs.Error("Dial => ", err)
} }
defer l.Close() defer l.Close()
user := fmt.Sprintf("cn=%s,dc=minho,dc=com", account) user := fmt.Sprintf("cn=%s,dc=minho,dc=com", account)
err = l.Bind(user, old_password) err = l.Bind(user, old_password)
if err != nil { if err != nil {
beego.Error("Bind => ", err) logs.Error("Bind => ", err)
return err return err
} }
@ -118,7 +119,7 @@ func ModifyPassword(account, old_password, new_password string) error {
_, err = l.PasswordModify(passwordModifyRequest) _, err = l.PasswordModify(passwordModifyRequest)
if err != nil { if err != nil {
beego.Error(fmt.Sprintf("Password could not be changed: %s", err.Error())) logs.Error(fmt.Sprintf("Password could not be changed: %s", err.Error()))
return err return err
} }
return nil return nil

View File

@ -102,6 +102,10 @@
<div class="tab-navg"> <div class="tab-navg">
<span data-mode="view" class="navg-item active"><i class="fa fa-align-justify"></i><b class="text">目录</b></span> <span data-mode="view" class="navg-item active"><i class="fa fa-align-justify"></i><b class="text">目录</b></span>
<span data-mode="search" class="navg-item"><i class="fa fa-search"></i><b class="text">搜索</b></span> <span data-mode="search" class="navg-item"><i class="fa fa-search"></i><b class="text">搜索</b></span>
<span id="handlerMenuShow" style="float: right;display: inline-block;padding: 5px;cursor: pointer;">
<i class="fa fa-angle-left" style="font-size: 20px;padding-right: 5px;"></i>
<span class="pull-right" style="padding-top: 4px;">展开</span>
</span>
</div> </div>
<div class="tab-util"> <div class="tab-util">
<span class="manual-fullscreen-switch"> <span class="manual-fullscreen-switch">
@ -142,6 +146,7 @@
</div> </div>
<div class="m-copyright"> <div class="m-copyright">
<p> <p>
<div id="view_count">阅读次数:{{.ViewCount}}</div>
本文档使用 <a href="https://www.iminho.me" target="_blank">MinDoc</a> 发布 本文档使用 <a href="https://www.iminho.me" target="_blank">MinDoc</a> 发布
</p> </p>
</div> </div>
@ -304,6 +309,43 @@ $(function () {
return $(body).highlight(window.keyword); return $(body).highlight(window.keyword);
}); });
}); });
window.menuControl = true;
window.menuSetting = "open" ;
if (menuSetting == 'open' || menuSetting == 'first') {
$('#handlerMenuShow').find('span').text('收起');
$('#handlerMenuShow').find('i').attr("class","fa fa-angle-down");
if (menuSetting == 'open') {
window.jsTree.jstree().open_all()
}
if (menuSetting == 'first') {
window.jsTree.jstree('close_all')
var $target = $('.jstree-container-ul').children('li').filter(function(index){
if($(this).attr('aria-expanded')==false||$(this).attr('aria-expanded')){
return $(this)
}else{
delete $(this)
}
})
$target.children('i').trigger('click')
}
} else {
menuControl = false;
window.jsTree.jstree('close_all')
}
$('#handlerMenuShow').on('click', function(){
if(menuControl){
$(this).find('span').text('展开')
$(this).find('i').attr("class","fa fa-angle-left")
window.menuControl = false
window.jsTree.jstree('close_all')
}else{
window.menuControl = true
$(this).find('span').text('收起')
$(this).find('i').attr("class","fa fa-angle-down")
window.jsTree.jstree().open_all()
}
})
}); });
</script> </script>
{{.Scripts}} {{.Scripts}}

View File

@ -56,7 +56,8 @@
<div class="m-manual manual-editor"> <div class="m-manual manual-editor">
<div class="manual-head" id="editormd-tools" style="min-width: 1200px; position:absolute;"> <div class="manual-head" id="editormd-tools" style="min-width: 1200px; position:absolute;">
<div class="editormd-group"> <div class="editormd-group">
<a href="{{urlfor "BookController.Index"}}" data-toggle="tooltip" data-title="返回"><i class="fa fa-chevron-left" aria-hidden="true"></i></a> <!--a href="{{urlfor "BookController.Index"}}" data-toggle="tooltip" data-title="返回"><i class="fa fa-chevron-left" aria-hidden="true"></i></a-->
<a href="javascript:" onclick="self.location=document.referrer;" data-toggle="tooltip" data-title="返回"><i class="fa fa-chevron-left" aria-hidden="true"></i></a>
</div> </div>
<div class="editormd-group"> <div class="editormd-group">
<a href="javascript:;" id="markdown-save" data-toggle="tooltip" data-title="保存" class="disabled save"><i class="fa fa-save first" aria-hidden="true" name="save"></i></a> <a href="javascript:;" id="markdown-save" data-toggle="tooltip" data-title="保存" class="disabled save"><i class="fa fa-save first" aria-hidden="true" name="save"></i></a>

View File

@ -11,8 +11,8 @@
</div> </div>
{{if .site_beian}} {{if .site_beian}}
<div class="row text-center"> <div class="row text-center">
<a href="http://www.beian.miit.gov.cn" target="_blank">{{.site_beian}}</a> <a href="https://beian.miit.gov.cn/" target="_blank">{{.site_beian}}</a>
</div> </div>
{{end}} {{end}}
</div> </div>
</div> </div>