From eb8f9aa8c4fc7cc00b90b4130bfd7f431ee011ee Mon Sep 17 00:00:00 2001 From: Ben Stone Date: Mon, 29 Mar 2021 17:51:59 +0800 Subject: [PATCH 01/32] Create zh-cn.ini add i18n zh config --- conf/lang/zh-cn.ini | 14 ++++++++++++++ 1 file changed, 14 insertions(+) create mode 100644 conf/lang/zh-cn.ini diff --git a/conf/lang/zh-cn.ini b/conf/lang/zh-cn.ini new file mode 100644 index 00000000..fbc45fe9 --- /dev/null +++ b/conf/lang/zh-cn.ini @@ -0,0 +1,14 @@ +[common] +title = 文档在线管理系统 +home = 首页 +blog = 文章 +project_space = 项目空间 +person_center = 个人中心 +my_project = 我的项目 +my_blog = 我的文章 +manage = 管理后台 +login = 登录 +logout = 退出登录 + +[message] +keyword_placeholder = 请输入关键词... From 7ab07f2ce2047e919849b764c7219c36335f1181 Mon Sep 17 00:00:00 2001 From: Ben Stone Date: Mon, 29 Mar 2021 17:52:29 +0800 Subject: [PATCH 02/32] Create en-us.ini add i18n en-us config --- conf/lang/en-us.ini | 14 ++++++++++++++ 1 file changed, 14 insertions(+) create mode 100644 conf/lang/en-us.ini diff --git a/conf/lang/en-us.ini b/conf/lang/en-us.ini new file mode 100644 index 00000000..8474fdc6 --- /dev/null +++ b/conf/lang/en-us.ini @@ -0,0 +1,14 @@ +[common] +title = mindoc +home = Home +blog = Blog +project_space = Project Space +person_center = Persona Center +my_project = My Project +my_blog = My Article +manage = Management +login = Login +logout = Logout + +[message] +keyword_placeholder = input keyword please... From 0694b4554bb1909f5e89535c273a4de427970b5b Mon Sep 17 00:00:00 2001 From: Ben Stone Date: Mon, 29 Mar 2021 17:56:36 +0800 Subject: [PATCH 03/32] Update BaseController.go i18n, get lang set from url param --- controllers/BaseController.go | 23 +++++++++++++++-------- 1 file changed, 15 insertions(+), 8 deletions(-) diff --git a/controllers/BaseController.go b/controllers/BaseController.go index 046188aa..6ee2df40 100644 --- a/controllers/BaseController.go +++ b/controllers/BaseController.go @@ -2,20 +2,20 @@ package controllers import ( "bytes" + "github.com/beego/i18n" "encoding/json" "io" "strings" "time" + "github.com/astaxie/beego" + "github.com/lifei6671/mindoc/conf" + "github.com/lifei6671/mindoc/models" + "github.com/lifei6671/mindoc/utils" "html/template" "io/ioutil" "path/filepath" - - "github.com/astaxie/beego" - "github.com/mindoc-org/mindoc/conf" - "github.com/mindoc-org/mindoc/models" - "github.com/mindoc-org/mindoc/utils" ) type BaseController struct { @@ -78,10 +78,17 @@ func (c *BaseController) Prepare() { if b, err := ioutil.ReadFile(filepath.Join(beego.BConfig.WebConfig.ViewsPath, "widgets", "scripts.tpl")); err == nil { c.Data["Scripts"] = template.HTML(string(b)) } + lang := c.Input().Get("lang") + if len(lang) == 0 || + !i18n.IsExist(lang) { + lang = "zh-cn" + } + c.Data["Lang"] = lang } + //判断用户是否登录. -func (c *BaseController)isUserLoggedIn() bool { +func (c *BaseController) isUserLoggedIn() bool { return c.Member != nil && c.Member.MemberId > 0 } @@ -123,7 +130,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 { return @@ -195,7 +202,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 { c.ShowErrorPage(code, err.Error()) } From 53310d42895819cb2ec2437316eeab51c0ae52ea Mon Sep 17 00:00:00 2001 From: Ben Stone Date: Mon, 29 Mar 2021 18:00:24 +0800 Subject: [PATCH 04/32] Update command.go load i18n langs config --- commands/command.go | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/commands/command.go b/commands/command.go index 34a35ca2..288233c4 100644 --- a/commands/command.go +++ b/commands/command.go @@ -23,6 +23,7 @@ import ( _ "github.com/astaxie/beego/cache/redis" "github.com/astaxie/beego/logs" "github.com/astaxie/beego/orm" + "github.com/beego/i18n" "github.com/howeyc/fsnotify" "github.com/lifei6671/gocaptcha" "github.com/mindoc-org/mindoc/cache" @@ -277,6 +278,19 @@ func RegisterFunction() { beego.Error("注册函数 date_format 出错 ->", err) os.Exit(-1) } + + err = beego.AddFuncMap("i18n", i18n.Tr) + if err != nil { + beego.Error("注册函数 i18n 出错 ->", err) + os.Exit(-1) + } + langs := strings.Split("en-us|zh-cn", "|") + for _, lang := range langs { + if err := i18n.SetMessage(lang, "conf/lang/" + lang + ".ini"); err != nil { + beego.Error("Fail to set message file: " + err.Error()) + return + } + } } //解析命令 From ef03d5b0a9e06c0a0ef9ef4254dbfcce1969e806 Mon Sep 17 00:00:00 2001 From: Ben Stone Date: Mon, 29 Mar 2021 18:02:57 +0800 Subject: [PATCH 05/32] Update header.tpl i18n --- views/widgets/header.tpl | 38 +++++++++++++++++++------------------- 1 file changed, 19 insertions(+), 19 deletions(-) diff --git a/views/widgets/header.tpl b/views/widgets/header.tpl index 7cd303c1..a5194128 100644 --- a/views/widgets/header.tpl +++ b/views/widgets/header.tpl @@ -11,18 +11,18 @@ @@ -77,28 +77,28 @@ {{else}} -
  • 登录
  • +
  • {{i18n .Lang "common.login"}}
  • {{end}} - \ No newline at end of file + From 0d5d2e4b383fa88996348f33a39c08b17bf1b10b Mon Sep 17 00:00:00 2001 From: Ben Stone Date: Mon, 29 Mar 2021 18:41:10 +0800 Subject: [PATCH 06/32] Update BaseController.go fix bug, change wrong import --- controllers/BaseController.go | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/controllers/BaseController.go b/controllers/BaseController.go index 6ee2df40..e1cfb4f4 100644 --- a/controllers/BaseController.go +++ b/controllers/BaseController.go @@ -10,9 +10,9 @@ import ( "time" "github.com/astaxie/beego" - "github.com/lifei6671/mindoc/conf" - "github.com/lifei6671/mindoc/models" - "github.com/lifei6671/mindoc/utils" + "github.com/mindoc-org/mindoc/conf" + "github.com/mindoc-org/mindoc/models" + "github.com/mindoc-org/mindoc/utils" "html/template" "io/ioutil" "path/filepath" From 782ea44388e068cbb961a380a775d4a8c2ffb79c Mon Sep 17 00:00:00 2001 From: shiqstone Date: Tue, 30 Mar 2021 14:24:14 +0800 Subject: [PATCH 07/32] refactor, replace beego.Error with logs.Error --- cache/cache.go | 16 ++--- commands/command.go | 62 ++++++++--------- commands/daemon/daemon.go | 19 ++--- commands/install.go | 17 +++-- commands/update.go | 8 +-- controllers/AccountController.go | 30 ++++---- controllers/BlogController.go | 39 ++++++----- controllers/BookController.go | 39 +++++------ controllers/BookMemberController.go | 6 +- controllers/DocumentController.go | 104 ++++++++++++++-------------- controllers/HomeController.go | 4 +- controllers/ItemsetsController.go | 5 +- controllers/LabelController.go | 6 +- controllers/ManagerController.go | 37 +++++----- controllers/SearchController.go | 12 ++-- mail/smtp.go | 7 +- models/AttachmentModel.go | 6 +- models/Blog.go | 49 ++++++------- models/BookModel.go | 63 +++++++++-------- models/BookResult.go | 66 +++++++++--------- models/DocumentHistory.go | 20 +++--- models/DocumentModel.go | 17 ++--- models/DocumentSearchResult.go | 24 +++---- models/Itemsets.go | 18 ++--- models/LabelModel.go | 11 ++- models/Member.go | 32 ++++----- models/Team.go | 32 ++++----- models/TeamMember.go | 18 ++--- models/TeamRelationship.go | 28 ++++---- models/Template.go | 99 +++++++++++++------------- utils/ldap.go | 24 +++---- 31 files changed, 454 insertions(+), 464 deletions(-) diff --git a/cache/cache.go b/cache/cache.go index 9ed47d6a..98102fc1 100644 --- a/cache/cache.go +++ b/cache/cache.go @@ -1,15 +1,14 @@ package cache import ( - "github.com/astaxie/beego/cache" - "time" - "encoding/gob" "bytes" + "encoding/gob" "errors" - "github.com/astaxie/beego" + "github.com/astaxie/beego/cache" + "github.com/astaxie/beego/logs" + "time" ) - var bm cache.Cache func Get(key string, e interface{}) error { @@ -27,7 +26,7 @@ func Get(key string, e interface{}) error { err := decoder.Decode(e) if err != nil { - beego.Error("反序列化对象失败 ->", err) + logs.Error("反序列化对象失败 ->", err) } return err } else if s, ok := val.(string); ok && s != "" { @@ -39,14 +38,13 @@ func Get(key string, e interface{}) error { err := decoder.Decode(e) if err != nil { - beego.Error("反序列化对象失败 ->", err) + logs.Error("反序列化对象失败 ->", err) } return err } return errors.New("value is not []byte or string") } - func Put(key string, val interface{}, timeout time.Duration) error { var buf bytes.Buffer @@ -55,7 +53,7 @@ func Put(key string, val interface{}, timeout time.Duration) error { err := encoder.Encode(val) if err != nil { - beego.Error("序列化对象失败 ->", err) + logs.Error("序列化对象失败 ->", err) return err } diff --git a/commands/command.go b/commands/command.go index 288233c4..e03649ab 100644 --- a/commands/command.go +++ b/commands/command.go @@ -34,7 +34,7 @@ import ( // RegisterDataBase 注册数据库 func RegisterDataBase() { - beego.Info("正在初始化数据库配置.") + logs.Info("正在初始化数据库配置.") adapter := beego.AppConfig.String("db_adapter") orm.DefaultTimeLoc = time.Local orm.DefaultRowsLimit = -1 @@ -50,7 +50,7 @@ func RegisterDataBase() { if err == nil { orm.DefaultTimeLoc = location } else { - beego.Error("加载时区配置信息失败,请检查是否存在 ZONEINFO 环境变量->", err) + logs.Error("加载时区配置信息失败,请检查是否存在 ZONEINFO 环境变量->", err) } port := beego.AppConfig.String("db_port") @@ -58,7 +58,7 @@ func RegisterDataBase() { 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 { - beego.Error("注册默认数据库失败->", err) + logs.Error("注册默认数据库失败->", err) os.Exit(1) } @@ -81,13 +81,13 @@ func RegisterDataBase() { err := orm.RegisterDataBase("default", "sqlite3", database) if err != nil { - beego.Error("注册默认数据库失败->", err) + logs.Error("注册默认数据库失败->", err) } } else { - beego.Error("不支持的数据库类型.") + logs.Error("不支持的数据库类型.") os.Exit(1) } - beego.Info("数据库初始化完成.") + logs.Info("数据库初始化完成.") } // RegisterModel 注册Model @@ -190,7 +190,7 @@ func RegisterLogger(log string) { } b, err := json.Marshal(config) if err != nil { - beego.Error("初始化文件日志时出错 ->", err) + logs.Error("初始化文件日志时出错 ->", err) _ = beego.SetLogger("file", `{"filename":"`+logPath+`"}`) } else { _ = beego.SetLogger(logs.AdapterFile, string(b)) @@ -217,7 +217,7 @@ func RegisterFunction() { err := beego.AddFuncMap("config", models.GetOptionValue) if err != nil { - beego.Error("注册函数 config 出错 ->", err) + logs.Error("注册函数 config 出错 ->", err) os.Exit(-1) } err = beego.AddFuncMap("cdn", func(p string) string { @@ -246,48 +246,48 @@ func RegisterFunction() { return cdn + p }) if err != nil { - beego.Error("注册函数 cdn 出错 ->", err) + logs.Error("注册函数 cdn 出错 ->", err) os.Exit(-1) } err = beego.AddFuncMap("cdnjs", conf.URLForWithCdnJs) if err != nil { - beego.Error("注册函数 cdnjs 出错 ->", err) + logs.Error("注册函数 cdnjs 出错 ->", err) os.Exit(-1) } err = beego.AddFuncMap("cdncss", conf.URLForWithCdnCss) if err != nil { - beego.Error("注册函数 cdncss 出错 ->", err) + logs.Error("注册函数 cdncss 出错 ->", err) os.Exit(-1) } err = beego.AddFuncMap("cdnimg", conf.URLForWithCdnImage) if err != nil { - beego.Error("注册函数 cdnimg 出错 ->", err) + logs.Error("注册函数 cdnimg 出错 ->", err) os.Exit(-1) } //重写url生成,支持配置域名以及域名前缀 err = beego.AddFuncMap("urlfor", conf.URLFor) if err != nil { - beego.Error("注册函数 urlfor 出错 ->", err) + logs.Error("注册函数 urlfor 出错 ->", err) os.Exit(-1) } err = beego.AddFuncMap("date_format", func(t time.Time, format string) string { return t.Local().Format(format) }) if err != nil { - beego.Error("注册函数 date_format 出错 ->", err) + logs.Error("注册函数 date_format 出错 ->", err) os.Exit(-1) } - + err = beego.AddFuncMap("i18n", i18n.Tr) if err != nil { - beego.Error("注册函数 i18n 出错 ->", err) + logs.Error("注册函数 i18n 出错 ->", err) os.Exit(-1) } langs := strings.Split("en-us|zh-cn", "|") for _, lang := range langs { - if err := i18n.SetMessage(lang, "conf/lang/" + lang + ".ini"); err != nil { - beego.Error("Fail to set message file: " + err.Error()) + if err := i18n.SetMessage(lang, "conf/lang/"+lang+".ini"); err != nil { + logs.Error("Fail to set message file: " + err.Error()) return } } @@ -368,7 +368,7 @@ func RegisterCache() { cache.Init(&cache.NullCache{}) return } - beego.Info("正常初始化缓存配置.") + logs.Info("正常初始化缓存配置.") cacheProvider := beego.AppConfig.String("cache_provider") if cacheProvider == "file" { cacheFilePath := beego.AppConfig.DefaultString("cache_file_path", "./runtime/cache/") @@ -386,7 +386,7 @@ func RegisterCache() { bc, err := json.Marshal(&fileConfig) if err != nil { - beego.Error("初始化file缓存失败:", err) + logs.Error("初始化file缓存失败:", err) os.Exit(1) } @@ -420,13 +420,13 @@ func RegisterCache() { bc, err := json.Marshal(&redisConfig) if err != nil { - beego.Error("初始化Redis缓存失败:", err) + logs.Error("初始化Redis缓存失败:", err) os.Exit(1) } redisCache, err := beegoCache.NewCache("redis", string(bc)) if err != nil { - beego.Error("初始化Redis缓存失败:", err) + logs.Error("初始化Redis缓存失败:", err) os.Exit(1) } @@ -440,13 +440,13 @@ func RegisterCache() { bc, err := json.Marshal(&memcacheConfig) if err != nil { - beego.Error("初始化 Memcache 缓存失败 ->", err) + logs.Error("初始化 Memcache 缓存失败 ->", err) os.Exit(1) } memcache, err := beegoCache.NewCache("memcache", string(bc)) if err != nil { - beego.Error("初始化 Memcache 缓存失败 ->", err) + logs.Error("初始化 Memcache 缓存失败 ->", err) os.Exit(1) } @@ -457,7 +457,7 @@ func RegisterCache() { beego.Warn("不支持的缓存管道,缓存将禁用 ->", cacheProvider) return } - beego.Info("缓存初始化完成.") + logs.Info("缓存初始化完成.") } //自动加载配置文件.修改了监听端口号和数据库配置无法自动生效. @@ -467,7 +467,7 @@ func RegisterAutoLoadConfig() { watcher, err := fsnotify.NewWatcher() if err != nil { - beego.Error("创建配置文件监控器失败 ->", err) + logs.Error("创建配置文件监控器失败 ->", err) } go func() { for { @@ -476,18 +476,18 @@ func RegisterAutoLoadConfig() { //如果是修改了配置文件 if ev.IsModify() { if err := beego.LoadAppConfig("ini", conf.ConfigurationFile); err != nil { - beego.Error("An error occurred ->", err) + logs.Error("An error occurred ->", err) continue } RegisterCache() RegisterLogger("") - beego.Info("配置文件已加载 ->", conf.ConfigurationFile) + logs.Info("配置文件已加载 ->", conf.ConfigurationFile) } else if ev.IsRename() { _ = watcher.WatchFlags(conf.ConfigurationFile, fsnotify.FSN_MODIFY|fsnotify.FSN_RENAME) } - beego.Info(ev.String()) + logs.Info(ev.String()) case err := <-watcher.Error: - beego.Error("配置文件监控器错误 ->", err) + logs.Error("配置文件监控器错误 ->", err) } } @@ -496,7 +496,7 @@ func RegisterAutoLoadConfig() { err = watcher.WatchFlags(conf.ConfigurationFile, fsnotify.FSN_MODIFY|fsnotify.FSN_RENAME) if err != nil { - beego.Error("监控配置文件失败 ->", err) + logs.Error("监控配置文件失败 ->", err) } } } diff --git a/commands/daemon/daemon.go b/commands/daemon/daemon.go index 7b62c6c3..11075d71 100644 --- a/commands/daemon/daemon.go +++ b/commands/daemon/daemon.go @@ -2,6 +2,7 @@ package daemon import ( "fmt" + "github.com/astaxie/beego/logs" "os" "path/filepath" @@ -80,15 +81,15 @@ func Install() { s, err := service.New(d, d.config) if err != nil { - beego.Error("Create service error => ", err) + logs.Error("Create service error => ", err) os.Exit(1) } err = s.Install() if err != nil { - beego.Error("Install service error:", err) + logs.Error("Install service error:", err) os.Exit(1) } else { - beego.Info("Service installed!") + logs.Info("Service installed!") } os.Exit(0) @@ -99,15 +100,15 @@ func Uninstall() { s, err := service.New(d, d.config) if err != nil { - beego.Error("Create service error => ", err) + logs.Error("Create service error => ", err) os.Exit(1) } err = s.Uninstall() if err != nil { - beego.Error("Install service error:", err) + logs.Error("Install service error:", err) os.Exit(1) } else { - beego.Info("Service uninstalled!") + logs.Info("Service uninstalled!") } os.Exit(0) } @@ -117,15 +118,15 @@ func Restart() { s, err := service.New(d, d.config) if err != nil { - beego.Error("Create service error => ", err) + logs.Error("Create service error => ", err) os.Exit(1) } err = s.Restart() if err != nil { - beego.Error("Install service error:", err) + logs.Error("Install service error:", err) os.Exit(1) } else { - beego.Info("Service Restart!") + logs.Info("Service Restart!") } os.Exit(0) } diff --git a/commands/install.go b/commands/install.go index 4f462bad..34582214 100644 --- a/commands/install.go +++ b/commands/install.go @@ -2,12 +2,12 @@ package commands import ( "fmt" + "github.com/astaxie/beego/logs" "os" "time" "flag" - "github.com/astaxie/beego" "github.com/astaxie/beego/orm" "github.com/mindoc-org/mindoc/conf" "github.com/mindoc-org/mindoc/models" @@ -40,7 +40,7 @@ func Version() { //修改用户密码 func ModifyPassword() { - var account,password string + var account, password string //账号和密码需要解析参数后才能获取 if len(os.Args) >= 2 && os.Args[1] == "password" { @@ -50,7 +50,7 @@ func ModifyPassword() { flagSet.StringVar(&password, "password", "", "用户密码.") if err := flagSet.Parse(os.Args[2:]); err != nil { - beego.Error("解析参数失败 -> ",err) + logs.Error("解析参数失败 -> ", err) os.Exit(1) } @@ -67,30 +67,29 @@ func ModifyPassword() { fmt.Println("Password cannot be empty.") os.Exit(1) } - member,err := models.NewMember().FindByAccount(account) + member, err := models.NewMember().FindByAccount(account) if err != nil { - fmt.Println("Failed to change password:",err) + fmt.Println("Failed to change password:", err) os.Exit(1) } - pwd,err := utils.PasswordHash(password) + pwd, err := utils.PasswordHash(password) if err != nil { - fmt.Println("Failed to change password:",err) + fmt.Println("Failed to change password:", err) os.Exit(1) } member.Password = pwd err = member.Update("password") if err != nil { - fmt.Println("Failed to change password:",err) + fmt.Println("Failed to change password:", err) os.Exit(1) } fmt.Println("Successfully modified.") os.Exit(0) } - } //初始化数据 diff --git a/commands/update.go b/commands/update.go index 396816b9..bac2e4c4 100644 --- a/commands/update.go +++ b/commands/update.go @@ -3,11 +3,11 @@ package commands import ( "encoding/json" "fmt" + "github.com/astaxie/beego/logs" "io/ioutil" "net/http" "os" - "github.com/astaxie/beego" "github.com/mindoc-org/mindoc/conf" ) @@ -17,14 +17,14 @@ func CheckUpdate() { resp, err := http.Get("https://api.github.com/repos/lifei6671/mindoc/tags") if err != nil { - beego.Error("CheckUpdate => ", err) + logs.Error("CheckUpdate => ", err) os.Exit(1) } defer resp.Body.Close() body, err := ioutil.ReadAll(resp.Body) if err != nil { - beego.Error("CheckUpdate => ", err) + logs.Error("CheckUpdate => ", err) os.Exit(1) } @@ -35,7 +35,7 @@ func CheckUpdate() { err = json.Unmarshal(body, &result) fmt.Println("MinDoc current version => ", conf.VERSION) if err != nil { - beego.Error("CheckUpdate => ", err) + logs.Error("CheckUpdate => ", err) os.Exit(0) } diff --git a/controllers/AccountController.go b/controllers/AccountController.go index f7e1f08b..69858e5d 100644 --- a/controllers/AccountController.go +++ b/controllers/AccountController.go @@ -1,6 +1,8 @@ package controllers import ( + "github.com/astaxie/beego/logs" + "github.com/beego/i18n" "net/url" "regexp" "strings" @@ -133,8 +135,8 @@ func (c *AccountController) Login() { c.JsonResult(0, "ok", c.referer()) } else { - beego.Error("用户登录 ->", err) - c.JsonResult(500, "账号或密码错误", nil) + logs.Error("用户登录 ->", err) + c.JsonResult(500, i18n.Tr(c.Lang, "message.wrong_account_password"), nil) } } else { c.Data["url"] = c.referer() @@ -385,7 +387,7 @@ func (c *AccountController) FindPassword() { count, err := models.NewMemberToken().FindSendCount(email, time.Now().Add(-1*time.Hour), time.Now()) if err != nil { - beego.Error(err) + logs.Error(err) c.JsonResult(6008, "发送邮件失败") } if count > mailConf.MailNumber { @@ -410,7 +412,7 @@ func (c *AccountController) FindPassword() { body, err := c.ExecuteViewPathTemplate("account/mail_template.tpl", data) if err != nil { - beego.Error(err) + logs.Error(err) c.JsonResult(6003, "邮件发送失败") } @@ -424,7 +426,7 @@ func (c *AccountController) FindPassword() { Secure: mailConf.Secure, Identity: "", } - beego.Info(mailConfig) + logs.Info(mailConfig) c := mail.NewSMTPClient(mailConfig) m := mail.NewMail() @@ -436,9 +438,9 @@ func (c *AccountController) FindPassword() { m.AddTo(email) if e := c.Send(m); e != nil { - beego.Error("发送邮件失败:" + e.Error()) + logs.Error("发送邮件失败:" + e.Error()) } else { - beego.Info("邮件发送成功:" + email) + logs.Info("邮件发送成功:" + email) } //auth := smtp.PlainAuth( // "", @@ -458,7 +460,7 @@ func (c *AccountController) FindPassword() { // []byte(subject+mime+"\n"+body), //) //if err != nil { - // beego.Error("邮件发送失败 => ", email, err) + // logs.Error("邮件发送失败 => ", email, err) //} }(mailConf, email, body) @@ -472,7 +474,7 @@ func (c *AccountController) FindPassword() { memberToken, err := models.NewMemberToken().FindByFieldFirst("token", token) if err != nil { - beego.Error(err) + logs.Error(err) c.Data["ErrorMessage"] = "邮件已失效" c.TplName = "errors/error.tpl" return @@ -524,7 +526,7 @@ func (c *AccountController) ValidEmail() { memberToken, err := models.NewMemberToken().FindByFieldFirst("token", token) if err != nil { - beego.Error(err) + logs.Error(err) c.JsonResult(6007, "邮件已失效") } subTime := memberToken.SendTime.Sub(time.Now()) @@ -535,13 +537,13 @@ func (c *AccountController) ValidEmail() { } member, err := models.NewMember().Find(memberToken.MemberId) if err != nil { - beego.Error(err) + logs.Error(err) c.JsonResult(6005, "用户不存在") } hash, err := utils.PasswordHash(password1) if err != nil { - beego.Error(err) + logs.Error(err) c.JsonResult(6006, "保存密码失败") } @@ -553,7 +555,7 @@ func (c *AccountController) ValidEmail() { memberToken.InsertOrUpdate() if err != nil { - beego.Error(err) + logs.Error(err) c.JsonResult(6006, "保存密码失败") } c.JsonResult(0, "ok", conf.URLFor("AccountController.Login")) @@ -577,7 +579,7 @@ func (c *AccountController) Captcha() { captchaImage := gocaptcha.NewCaptchaImage(140, 40, gocaptcha.RandLightColor()) //if err != nil { - // beego.Error(err) + // logs.Error(err) // c.Abort("500") //} diff --git a/controllers/BlogController.go b/controllers/BlogController.go index 055ffae0..bc0e0833 100644 --- a/controllers/BlogController.go +++ b/controllers/BlogController.go @@ -3,6 +3,7 @@ package controllers import ( "encoding/json" "fmt" + "github.com/astaxie/beego/logs" "html/template" "net/http" "net/url" @@ -49,7 +50,7 @@ func (c *BlogController) Index() { } if c.Ctx.Input.IsPost() { - password := c.GetString("password"); + password := c.GetString("password") if blog.BlogStatus == "password" && password != blog.Password { c.JsonResult(6001, "文章密码不正确") } else if blog.BlogStatus == "password" && password == blog.Password { @@ -250,7 +251,7 @@ func (c *BlogController) ManageSetting() { blog.Password = blogPassword if err := blog.Save(); err != nil { - beego.Error("保存文章失败 -> ", err) + logs.Error("保存文章失败 -> ", err) c.JsonResult(6011, "保存文章失败") } else { c.JsonResult(0, "ok", blog) @@ -263,7 +264,7 @@ func (c *BlogController) ManageSetting() { } blogId, err := strconv.Atoi(c.Ctx.Input.Param(":id")) - c.Data["DocumentIdentify"] = ""; + c.Data["DocumentIdentify"] = "" if err == nil { blog, err := models.NewBlog().FindByIdAndMemberId(blogId, c.Member.MemberId) if err != nil { @@ -301,7 +302,7 @@ func (c *BlogController) ManageEdit() { blog, err = models.NewBlog().FindByIdAndMemberId(blogId, c.Member.MemberId) } if err != nil { - beego.Error("查询文章失败 ->", err) + logs.Error("查询文章失败 ->", err) c.JsonResult(6002, "查询文章失败") } if version > 0 && blog.Version != version && cover != "yes" { @@ -311,7 +312,7 @@ func (c *BlogController) ManageEdit() { if blog.BlogType == 1 { doc, err := models.NewDocument().Find(blog.DocumentId) if err != nil { - beego.Error("查询关联项目文档时出错 ->", err) + logs.Error("查询关联项目文档时出错 ->", err) c.JsonResult(6003, "查询关联项目文档时出错") } book, err := models.NewBook().Find(doc.BookId) @@ -324,7 +325,7 @@ func (c *BlogController) ManageEdit() { bookResult, err := models.NewBookResult().FindByIdentify(book.Identify, c.Member.MemberId) if err != nil || bookResult.RoleId == conf.BookObserver { - beego.Error("FindByIdentify => ", err) + logs.Error("FindByIdentify => ", err) c.JsonResult(6002, "关联文档不存在或权限不足") } } @@ -335,7 +336,7 @@ func (c *BlogController) ManageEdit() { doc.ModifyTime = time.Now() doc.ModifyAt = c.Member.MemberId if err := doc.InsertOrUpdate("markdown", "release", "content", "modify_time", "modify_at"); err != nil { - beego.Error("保存关联文档时出错 ->", err) + logs.Error("保存关联文档时出错 ->", err) c.JsonResult(6004, "保存关联文档时出错") } } @@ -346,7 +347,7 @@ func (c *BlogController) ManageEdit() { blog.Modified = time.Now() if err := blog.Save("blog_content", "blog_release", "modify_at", "modify_time", "version"); err != nil { - beego.Error("保存文章失败 -> ", err) + logs.Error("保存文章失败 -> ", err) c.JsonResult(6011, "保存文章失败") } else { c.JsonResult(0, "ok", blog) @@ -374,7 +375,7 @@ func (c *BlogController) ManageEdit() { if len(blog.AttachList) > 0 { returnJSON, err := json.Marshal(blog.AttachList) if err != nil { - beego.Error("序列化文章附件时出错 ->", err) + logs.Error("序列化文章附件时出错 ->", err) } else { c.Data["AttachList"] = template.JS(string(returnJSON)) } @@ -384,7 +385,7 @@ func (c *BlogController) ManageEdit() { if conf.GetUploadFileSize() > 0 { c.Data["UploadFileSize"] = conf.GetUploadFileSize() } else { - c.Data["UploadFileSize"] = "undefined"; + c.Data["UploadFileSize"] = "undefined" } c.Data["Model"] = blog } @@ -484,7 +485,7 @@ func (c *BlogController) Upload() { _, err := models.NewBlog().FindByIdAndMemberId(blogId, c.Member.MemberId) if err != nil { - beego.Error("查询文章时出错 -> ", err) + logs.Error("查询文章时出错 -> ", err) if err == orm.ErrNoRows { c.JsonResult(6006, "权限不足") } @@ -504,7 +505,7 @@ func (c *BlogController) Upload() { err = c.SaveToFile(name, filePath) if err != nil { - beego.Error("SaveToFile => ", err) + logs.Error("SaveToFile => ", err) c.JsonResult(6005, "保存文件失败") } @@ -537,14 +538,14 @@ func (c *BlogController) Upload() { if err := attachment.Insert(); err != nil { os.Remove(filePath) - beego.Error("保存文件附件失败 -> ", err) + logs.Error("保存文件附件失败 -> ", err) c.JsonResult(6006, "文件保存失败") } if attachment.HttpPath == "" { attachment.HttpPath = conf.URLForNotHost("BlogController.Download", ":id", blogId, ":attach_id", attachment.AttachmentId) if err := attachment.Update(); err != nil { - beego.Error("保存文件失败 -> ",attachment.FilePath, err) + logs.Error("保存文件失败 -> ", attachment.FilePath, err) c.JsonResult(6005, "保存文件失败") } } @@ -581,7 +582,7 @@ func (c *BlogController) RemoveAttachment() { attach, err := models.NewAttachment().Find(attachId) if err != nil { - beego.Error(err) + logs.Error(err) c.JsonResult(6002, "附件不存在") } @@ -589,7 +590,7 @@ func (c *BlogController) RemoveAttachment() { _, err := models.NewBlog().FindByIdAndMemberId(attach.DocumentId, c.Member.MemberId) if err != nil { - beego.Error(err) + logs.Error(err) c.JsonResult(6003, "文档不存在") } } @@ -601,7 +602,7 @@ func (c *BlogController) RemoveAttachment() { } if err := attach.Delete(); err != nil { - beego.Error(err) + logs.Error(err) c.JsonResult(6005, "删除失败") } @@ -639,7 +640,7 @@ func (c *BlogController) Download() { if err == orm.ErrNoRows { c.ShowErrorPage(404, "附件不存在") } else { - beego.Error("查询附件时出现异常 -> ", err) + logs.Error("查询附件时出现异常 -> ", err) c.ShowErrorPage(500, "查询附件时出现异常") } } @@ -647,7 +648,7 @@ func (c *BlogController) Download() { //如果是链接的文章,需要校验文档ID是否一致,如果不是,需要保证附件的项目ID为0且文档的ID等于博文ID if blog.BlogType == 1 && attachment.DocumentId != blog.DocumentId { 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, "附件不存在") } diff --git a/controllers/BookController.go b/controllers/BookController.go index 30e6a916..9920037f 100644 --- a/controllers/BookController.go +++ b/controllers/BookController.go @@ -16,7 +16,6 @@ import ( "net/http" - "github.com/astaxie/beego" "github.com/astaxie/beego/logs" "github.com/astaxie/beego/orm" "github.com/mindoc-org/mindoc/conf" @@ -210,7 +209,7 @@ func (c *BookController) SaveBook() { bookResult.Description = description bookResult.CommentStatus = commentStatus - beego.Info("用户 [", c.Member.Account, "] 修改了项目 ->", book) + logs.Info("用户 [", c.Member.Account, "] 修改了项目 ->", book) c.JsonResult(0, "ok", bookResult) } @@ -255,7 +254,7 @@ func (c *BookController) PrivatelyOwned() { logs.Error("PrivatelyOwned => ", err) c.JsonResult(6004, "保存失败") } - beego.Info("用户 【", c.Member.Account, "]修改了项目权限 ->", state) + logs.Info("用户 【", c.Member.Account, "]修改了项目权限 ->", state) c.JsonResult(0, "ok") } @@ -390,7 +389,7 @@ func (c *BookController) UploadCover() { if oldCover != conf.GetDefaultCover() { 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) } @@ -534,10 +533,10 @@ func (c *BookController) Create() { bookResult, err := models.NewBookResult().FindByIdentify(book.Identify, c.Member.MemberId) 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(6001, "error") @@ -562,7 +561,7 @@ func (c *BookController) Copy() { } else { bookResult, err := models.NewBookResult().FindByIdentify(book.Identify, c.Member.MemberId) if err != nil { - beego.Error("查询失败") + logs.Error("查询失败") } c.JsonResult(0, "ok", bookResult) } @@ -643,7 +642,7 @@ func (c *BookController) Import() { go book.ImportBook(tempPath) - beego.Info("用户[", c.Member.Account, "]导入了项目 ->", book) + logs.Info("用户[", c.Member.Account, "]导入了项目 ->", book) c.JsonResult(0, "项目正在后台转换中,请稍后查看") } @@ -680,7 +679,7 @@ func (c *BookController) Import() { // logs.Error("生成阅读令牌失败 => ", err) // 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)) // } else { // book.PrivateToken = "" @@ -688,7 +687,7 @@ func (c *BookController) Import() { // logs.Error("CreateToken => ", err) // c.JsonResult(6004, "删除令牌失败") // } -// beego.Info("用户[", c.Member.Account, "]创建项目令牌 ->", book.PrivateToken) +// logs.Info("用户[", c.Member.Account, "]创建项目令牌 ->", book.PrivateToken) // c.JsonResult(0, "ok", "") // } //} @@ -716,7 +715,7 @@ func (c *BookController) Delete() { logs.Error("删除项目 => ", err) c.JsonResult(6003, "删除失败") } - beego.Info("用户[", c.Member.Account, "]删除了项目 ->", bookResult) + logs.Info("用户[", c.Member.Account, "]删除了项目 ->", bookResult) c.JsonResult(0, "ok") } @@ -731,7 +730,7 @@ func (c *BookController) Release() { if c.Member.IsAdministrator() { book, err := models.NewBook().FindByFieldFirst("identify", identify) if err != nil { - beego.Error("发布文档失败 ->", err) + logs.Error("发布文档失败 ->", err) c.JsonResult(6003, "文档不存在") return } @@ -746,7 +745,7 @@ func (c *BookController) Release() { if err == orm.ErrNoRows { c.JsonResult(6002, "项目不存在") } - beego.Error(err) + logs.Error(err) c.JsonResult(6003, "未知错误") } if book.RoleId != conf.BookAdmin && book.RoleId != conf.BookFounder && book.RoleId != conf.BookEditor { @@ -772,14 +771,14 @@ func (c *BookController) SaveSort() { if c.Member.IsAdministrator() { book, err := models.NewBook().FindByFieldFirst("identify", identify) if err != nil || book == nil { - c.JsonResult(6001,"项目不存在") + c.JsonResult(6001, "项目不存在") return } bookId = book.BookId } else { bookResult, err := models.NewBookResult().FindByIdentify(identify, c.Member.MemberId) if err != nil { - beego.Error("DocumentController.Edit => ", err) + logs.Error("DocumentController.Edit => ", err) c.Abort("403") } @@ -796,7 +795,7 @@ func (c *BookController) SaveSort() { err := json.Unmarshal(content, &docs) if err != nil { - beego.Error(err) + logs.Error(err) c.JsonResult(6003, "数据错误") } @@ -804,7 +803,7 @@ func (c *BookController) SaveSort() { if docId, ok := item["id"].(float64); ok { doc, err := models.NewDocument().Find(int(docId)) if err != nil { - beego.Error(err) + logs.Error(err) continue } if doc.BookId != bookId { @@ -813,12 +812,12 @@ func (c *BookController) SaveSort() { } sort, ok := item["sort"].(float64) if !ok { - beego.Info("排序数字转换失败 => ", item) + logs.Info("排序数字转换失败 => ", item) continue } parentId, ok := item["parent"].(float64) if !ok { - beego.Info("父分类转换失败 => ", item) + logs.Info("父分类转换失败 => ", item) continue } if parentId > 0 { @@ -830,7 +829,7 @@ func (c *BookController) SaveSort() { doc.ParentId = int(parentId) if err := doc.InsertOrUpdate(); err != nil { fmt.Printf("%s", err.Error()) - beego.Error(err) + logs.Error(err) } } else { fmt.Printf("文档ID转换失败 => %+v", item) diff --git a/controllers/BookMemberController.go b/controllers/BookMemberController.go index 1706b0b3..782a4824 100644 --- a/controllers/BookMemberController.go +++ b/controllers/BookMemberController.go @@ -3,7 +3,6 @@ package controllers import ( "errors" - "github.com/astaxie/beego" "github.com/astaxie/beego/logs" "github.com/astaxie/beego/orm" "github.com/mindoc-org/mindoc/conf" @@ -17,9 +16,9 @@ type BookMemberController struct { // AddMember 参加参与用户. func (c *BookMemberController) AddMember() { identify := c.GetString("identify") - account,_ := c.GetInt("account") + account, _ := c.GetInt("account") roleId, _ := c.GetInt("role_id", 3) - beego.Info(account) + logs.Info(account) if identify == "" || account <= 0 { c.JsonResult(6001, "参数错误") } @@ -29,7 +28,6 @@ func (c *BookMemberController) AddMember() { c.JsonResult(6001, err.Error()) } - member := models.NewMember() if _, err := member.Find(account); err != nil { diff --git a/controllers/DocumentController.go b/controllers/DocumentController.go index dbbba7c8..a6f1a0dd 100644 --- a/controllers/DocumentController.go +++ b/controllers/DocumentController.go @@ -77,7 +77,7 @@ func (c *DocumentController) Index() { if err == orm.ErrNoRows { c.ShowErrorPage(404, "当前项目没有文档") } else { - beego.Error("生成项目文档树时出错 -> ", err) + logs.Error("生成项目文档树时出错 -> ", err) c.ShowErrorPage(500, "生成项目文档树时出错") } } @@ -115,7 +115,7 @@ func (c *DocumentController) Read() { if docId, err := strconv.Atoi(id); err == nil { doc, err = doc.FromCacheById(docId) if err != nil || doc == nil { - beego.Error("从缓存中读取文档时失败 ->", err) + logs.Error("从缓存中读取文档时失败 ->", err) c.ShowErrorPage(404, "文档不存在或已删除") return } @@ -125,7 +125,7 @@ func (c *DocumentController) Read() { if err == orm.ErrNoRows { c.ShowErrorPage(404, "文档不存在或已删除") } else { - beego.Error("从缓存查询文档时出错 ->", err) + logs.Error("从缓存查询文档时出错 ->", err) c.ShowErrorPage(500, "未知异常") } return @@ -161,7 +161,7 @@ func (c *DocumentController) Read() { tree, err := models.NewDocument().CreateDocumentTreeForHtml(bookResult.BookId, doc.DocumentId) if err != nil && err != orm.ErrNoRows { - beego.Error("生成项目文档树时出错 ->", err) + logs.Error("生成项目文档树时出错 ->", err) c.ShowErrorPage(500, "生成项目文档树时出错") } @@ -201,7 +201,7 @@ func (c *DocumentController) Edit() { if err == orm.ErrNoRows || err == models.ErrPermissionDenied { c.ShowErrorPage(403, "项目不存在或没有权限") } else { - beego.Error("查询项目时出错 -> ", err) + logs.Error("查询项目时出错 -> ", err) c.ShowErrorPage(500, "查询项目时出错") } return @@ -231,7 +231,7 @@ func (c *DocumentController) Edit() { trees, err := models.NewDocument().FindDocumentTree(bookResult.BookId) if err != nil { - beego.Error("FindDocumentTree => ", err) + logs.Error("FindDocumentTree => ", err) } else { if len(trees) > 0 { if jtree, err := json.Marshal(trees); err == nil { @@ -274,7 +274,7 @@ func (c *DocumentController) Create() { if c.Member.IsAdministrator() { book, err := models.NewBook().FindByFieldFirst("identify", identify) if err != nil { - beego.Error(err) + logs.Error(err) c.JsonResult(6002, "项目不存在或权限不足") } @@ -283,7 +283,7 @@ func (c *DocumentController) Create() { bookResult, err := models.NewBookResult().FindByIdentify(identify, c.Member.MemberId) if err != nil || bookResult.RoleId == conf.BookObserver { - beego.Error("FindByIdentify => ", err) + logs.Error("FindByIdentify => ", err) c.JsonResult(6002, "项目不存在或权限不足") } @@ -327,7 +327,7 @@ func (c *DocumentController) Create() { } if err := document.InsertOrUpdate(); err != nil { - beego.Error("添加或更新文档时出错 -> ", err) + logs.Error("添加或更新文档时出错 -> ", err) c.JsonResult(6005, "保存失败") } else { c.JsonResult(0, "ok", document) @@ -395,7 +395,7 @@ func (c *DocumentController) Upload() { book, err := models.NewBookResult().FindByIdentify(identify, c.Member.MemberId) if err != nil { - beego.Error("DocumentController.Edit => ", err) + logs.Error("DocumentController.Edit => ", err) if err == orm.ErrNoRows { c.JsonResult(6006, "权限不足") } @@ -439,7 +439,7 @@ func (c *DocumentController) Upload() { err = c.SaveToFile(name, filePath) if err != nil { - beego.Error("保存文件失败 -> ", err) + logs.Error("保存文件失败 -> ", err) c.JsonResult(6005, "保存文件失败") } @@ -472,7 +472,7 @@ func (c *DocumentController) Upload() { if err != nil { os.Remove(filePath) - beego.Error("文件保存失败 ->", err) + logs.Error("文件保存失败 ->", err) c.JsonResult(6006, "文件保存失败") } @@ -480,7 +480,7 @@ func (c *DocumentController) Upload() { attachment.HttpPath = conf.URLForNotHost("DocumentController.DownloadAttachment", ":key", identify, ":attach_id", attachment.AttachmentId) if err := attachment.Update(); err != nil { - beego.Error("保存文件失败 ->", err) + logs.Error("保存文件失败 ->", err) c.JsonResult(6005, "保存文件失败") } } @@ -525,7 +525,7 @@ func (c *DocumentController) DownloadAttachment() { if err == orm.ErrNoRows { c.ShowErrorPage(404, "项目不存在或已删除") } else { - beego.Error("查找项目时出错 ->", err) + logs.Error("查找项目时出错 ->", err) c.ShowErrorPage(500, "系统错误") } } @@ -547,7 +547,7 @@ func (c *DocumentController) DownloadAttachment() { attachment, err := models.NewAttachment().Find(attachId) if err != nil { - beego.Error("查找附件时出错 -> ", err) + logs.Error("查找附件时出错 -> ", err) if err == orm.ErrNoRows { c.ShowErrorPage(404, "附件不存在或已删除") } else { @@ -575,21 +575,21 @@ func (c *DocumentController) RemoveAttachment() { attach, err := models.NewAttachment().Find(attachId) if err != nil { - beego.Error(err) + logs.Error(err) c.JsonResult(6002, "附件不存在") } document, err := models.NewDocument().Find(attach.DocumentId) if err != nil { - beego.Error(err) + logs.Error(err) c.JsonResult(6003, "文档不存在") } if c.Member.Role != conf.MemberSuperRole { rel, err := models.NewRelationship().FindByBookIdAndMemberId(document.BookId, c.Member.MemberId) if err != nil { - beego.Error(err) + logs.Error(err) c.JsonResult(6004, "权限不足") } @@ -600,7 +600,7 @@ func (c *DocumentController) RemoveAttachment() { err = attach.Delete() if err != nil { - beego.Error(err) + logs.Error(err) c.JsonResult(6005, "删除失败") } @@ -622,7 +622,7 @@ func (c *DocumentController) Delete() { if c.Member.IsAdministrator() { book, err := models.NewBook().FindByFieldFirst("identify", identify) if err != nil { - beego.Error("FindByIdentify => ", err) + logs.Error("FindByIdentify => ", err) c.JsonResult(6002, "项目不存在或权限不足") } @@ -631,7 +631,7 @@ func (c *DocumentController) Delete() { bookResult, err := models.NewBookResult().FindByIdentify(identify, c.Member.MemberId) if err != nil || bookResult.RoleId == conf.BookObserver { - beego.Error("FindByIdentify => ", err) + logs.Error("FindByIdentify => ", err) c.JsonResult(6002, "项目不存在或权限不足") } @@ -645,7 +645,7 @@ func (c *DocumentController) Delete() { doc, err := models.NewDocument().Find(docId) if err != nil { - beego.Error("Delete => ", err) + logs.Error("Delete => ", err) c.JsonResult(6003, "删除失败") } // 如果文档所属项目错误 @@ -692,7 +692,7 @@ func (c *DocumentController) Content() { bookResult, err := models.NewBookResult().FindByIdentify(identify, c.Member.MemberId) if err != nil || bookResult.RoleId == conf.BookObserver { - beego.Error("项目不存在或权限不足 -> ", err) + logs.Error("项目不存在或权限不足 -> ", err) c.JsonResult(6002, "项目不存在或权限不足") } @@ -722,7 +722,7 @@ func (c *DocumentController) Content() { } if doc.Version != version && !strings.EqualFold(isCover, "yes") { - beego.Info("%d|", version, doc.Version) + logs.Info("%d|", version, doc.Version) c.JsonResult(6005, "文档已被修改确定要覆盖吗?") } @@ -749,7 +749,7 @@ func (c *DocumentController) Content() { doc.ModifyAt = c.Member.MemberId if err := doc.InsertOrUpdate(); err != nil { - beego.Error("InsertOrUpdate => ", err) + logs.Error("InsertOrUpdate => ", err) c.JsonResult(6006, "保存失败") } @@ -759,7 +759,7 @@ func (c *DocumentController) Content() { if c.EnableDocumentHistory && cryptil.Md5Crypt(history.Markdown) != cryptil.Md5Crypt(doc.Markdown) { _, err = history.InsertOrUpdate() if err != nil { - beego.Error("DocumentHistory InsertOrUpdate => ", err) + logs.Error("DocumentHistory InsertOrUpdate => ", err) } } }(history) @@ -819,7 +819,7 @@ func (c *DocumentController) Export() { if err == orm.ErrNoRows { c.ShowErrorPage(404, "项目不存在") } else { - beego.Error("查找项目时出错 ->", err) + logs.Error("查找项目时出错 ->", err) c.ShowErrorPage(500, "查找项目时出错") } } @@ -900,13 +900,13 @@ func (c *DocumentController) QrCode() { uri := conf.URLFor("DocumentController.Index", ":key", identify) code, err := qr.Encode(uri, qr.L, qr.Unicode) if err != nil { - beego.Error("生成二维码失败 ->", err) + logs.Error("生成二维码失败 ->", err) c.ShowErrorPage(500, "生成二维码失败") } code, err = barcode.Scale(code, 150, 150) if err != nil { - beego.Error("生成二维码失败 ->", err) + logs.Error("生成二维码失败 ->", err) c.ShowErrorPage(500, "生成二维码失败") } @@ -916,7 +916,7 @@ func (c *DocumentController) QrCode() { err = png.Encode(c.Ctx.ResponseWriter, code) if err != nil { - beego.Error("生成二维码失败 ->", err) + logs.Error("生成二维码失败 ->", err) c.ShowErrorPage(500, "生成二维码失败") } } @@ -942,7 +942,7 @@ func (c *DocumentController) Search() { docs, err := models.NewDocumentSearchResult().SearchDocument(keyword, bookResult.BookId) if err != nil { - beego.Error(err) + logs.Error(err) c.JsonResult(6002, "搜索结果错误") } @@ -976,7 +976,7 @@ func (c *DocumentController) History() { if c.Member.IsAdministrator() { book, err := models.NewBook().FindByFieldFirst("identify", identify) if err != nil { - beego.Error("查找项目失败 ->", err) + logs.Error("查找项目失败 ->", err) c.Data["ErrorMessage"] = "项目不存在或权限不足" return } @@ -986,7 +986,7 @@ func (c *DocumentController) History() { } else { bookResult, err := models.NewBookResult().FindByIdentify(identify, c.Member.MemberId) if err != nil || bookResult.RoleId == conf.BookObserver { - beego.Error("查找项目失败 ->", err) + logs.Error("查找项目失败 ->", err) c.Data["ErrorMessage"] = "项目不存在或权限不足" return } @@ -1002,7 +1002,7 @@ func (c *DocumentController) History() { doc, err := models.NewDocument().Find(docId) if err != nil { - beego.Error("Delete => ", err) + logs.Error("Delete => ", err) c.Data["ErrorMessage"] = "获取历史失败" return } @@ -1015,7 +1015,7 @@ func (c *DocumentController) History() { histories, totalCount, err := models.NewDocumentHistory().FindToPager(docId, pageIndex, conf.PageSize) if err != nil { - beego.Error("分页查找文档历史失败 ->", err) + logs.Error("分页查找文档历史失败 ->", err) c.Data["ErrorMessage"] = "获取历史失败" return } @@ -1049,7 +1049,7 @@ func (c *DocumentController) DeleteHistory() { if c.Member.IsAdministrator() { book, err := models.NewBook().FindByFieldFirst("identify", identify) if err != nil { - beego.Error("查找项目失败 ->", err) + logs.Error("查找项目失败 ->", err) c.JsonResult(6002, "项目不存在或权限不足") } @@ -1057,7 +1057,7 @@ func (c *DocumentController) DeleteHistory() { } else { bookResult, err := models.NewBookResult().FindByIdentify(identify, c.Member.MemberId) if err != nil || bookResult.RoleId == conf.BookObserver { - beego.Error("查找项目失败 ->", err) + logs.Error("查找项目失败 ->", err) c.JsonResult(6002, "项目不存在或权限不足") } @@ -1070,7 +1070,7 @@ func (c *DocumentController) DeleteHistory() { doc, err := models.NewDocument().Find(docId) if err != nil { - beego.Error("Delete => ", err) + logs.Error("Delete => ", err) c.JsonResult(6001, "获取历史失败") } @@ -1081,7 +1081,7 @@ func (c *DocumentController) DeleteHistory() { err = models.NewDocumentHistory().Delete(historyId, docId) if err != nil { - beego.Error(err) + logs.Error(err) c.JsonResult(6002, "删除失败") } @@ -1107,7 +1107,7 @@ func (c *DocumentController) RestoreHistory() { if c.Member.IsAdministrator() { book, err := models.NewBook().FindByFieldFirst("identify", identify) if err != nil { - beego.Error("FindByIdentify => ", err) + logs.Error("FindByIdentify => ", err) c.JsonResult(6002, "项目不存在或权限不足") } @@ -1115,7 +1115,7 @@ func (c *DocumentController) RestoreHistory() { } else { bookResult, err := models.NewBookResult().FindByIdentify(identify, c.Member.MemberId) if err != nil || bookResult.RoleId == conf.BookObserver { - beego.Error("FindByIdentify => ", err) + logs.Error("FindByIdentify => ", err) c.JsonResult(6002, "项目不存在或权限不足") } @@ -1128,7 +1128,7 @@ func (c *DocumentController) RestoreHistory() { doc, err := models.NewDocument().Find(docId) if err != nil { - beego.Error("Delete => ", err) + logs.Error("Delete => ", err) c.JsonResult(6001, "获取历史失败") } @@ -1139,7 +1139,7 @@ func (c *DocumentController) RestoreHistory() { err = models.NewDocumentHistory().Restore(historyId, docId, c.Member.MemberId) if err != nil { - beego.Error(err) + logs.Error(err) c.JsonResult(6002, "删除失败") } @@ -1161,7 +1161,7 @@ func (c *DocumentController) Compare() { if c.Member.IsAdministrator() { book, err := models.NewBook().FindByFieldFirst("identify", identify) if err != nil { - beego.Error("DocumentController.Compare => ", err) + logs.Error("DocumentController.Compare => ", err) c.ShowErrorPage(403, "权限不足") return } @@ -1172,7 +1172,7 @@ func (c *DocumentController) Compare() { } else { bookResult, err := models.NewBookResult().FindByIdentify(identify, c.Member.MemberId) if err != nil || bookResult.RoleId == conf.BookObserver { - beego.Error("FindByIdentify => ", err) + logs.Error("FindByIdentify => ", err) c.ShowErrorPage(403, "权限不足") return } @@ -1188,7 +1188,7 @@ func (c *DocumentController) Compare() { history, err := models.NewDocumentHistory().Find(historyId) if err != nil { - beego.Error("DocumentController.Compare => ", err) + logs.Error("DocumentController.Compare => ", err) c.ShowErrorPage(60003, err.Error()) } @@ -1215,7 +1215,7 @@ func (c *DocumentController) isReadable(identify, token string) *models.BookResu book, err := models.NewBook().FindByFieldFirst("identify", identify) if err != nil { - beego.Error(err) + logs.Error(err) c.ShowErrorPage(500, "项目不存在") } bookResult := models.NewBookResult().ToBookResult(*book) @@ -1240,7 +1240,7 @@ func (c *DocumentController) isReadable(identify, token string) *models.BookResu if token != "" && strings.EqualFold(token, book.PrivateToken) { c.SetSession(identify, token) } 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, "权限不足") } } else if password := c.GetString("bPassword", ""); !isOk && book.BookPassword != "" && password != "" { @@ -1260,12 +1260,12 @@ func (c *DocumentController) isReadable(identify, token string) *models.BookResu 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}) if err != nil { - beego.Error("显示密码页面失败 ->", err) + logs.Error("显示密码页面失败 ->", err) } c.CustomAbort(200, body) } } else { - beego.Info("尝试访问文档但权限不足 ->", identify, token) + logs.Info("尝试访问文档但权限不足 ->", identify, token) c.ShowErrorPage(403, "权限不足") } } @@ -1276,8 +1276,8 @@ func (c *DocumentController) isReadable(identify, token string) *models.BookResu } func promptUserToLogIn(c *DocumentController) { - beego.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 " + c.Ctx.Request.URL.RequestURI() + " not permitted.") + logs.Info(" Access will be redirected to login page(SessionId: " + c.CruSession.SessionID() + ").") if c.IsAjax() { c.JsonResult(6000, "请重新登录。") diff --git a/controllers/HomeController.go b/controllers/HomeController.go index 683c67b1..e4c6f145 100644 --- a/controllers/HomeController.go +++ b/controllers/HomeController.go @@ -1,10 +1,10 @@ package controllers import ( + "github.com/astaxie/beego/logs" "math" "net/url" - "github.com/astaxie/beego" "github.com/mindoc-org/mindoc/conf" "github.com/mindoc-org/mindoc/models" "github.com/mindoc-org/mindoc/utils/pagination" @@ -37,7 +37,7 @@ func (c *HomeController) Index() { books, totalCount, err := models.NewBook().FindForHomeToPager(pageIndex, pageSize, memberId) if err != nil { - beego.Error(err) + logs.Error(err) c.Abort("500") } if totalCount > 0 { diff --git a/controllers/ItemsetsController.go b/controllers/ItemsetsController.go index 935868b4..6cda61aa 100644 --- a/controllers/ItemsetsController.go +++ b/controllers/ItemsetsController.go @@ -1,7 +1,7 @@ package controllers import ( - "github.com/astaxie/beego" + "github.com/astaxie/beego/logs" "github.com/astaxie/beego/orm" "github.com/mindoc-org/mindoc/conf" "github.com/mindoc-org/mindoc/models" @@ -11,6 +11,7 @@ import ( type ItemsetsController struct { BaseController } + func (c *ItemsetsController) Prepare() { c.BaseController.Prepare() @@ -65,7 +66,7 @@ func (c *ItemsetsController) List() { if err == orm.ErrNoRows { c.Abort("404") } else { - beego.Error(err) + logs.Error(err) c.Abort("500") } } diff --git a/controllers/LabelController.go b/controllers/LabelController.go index 9ed2501e..77af36bb 100644 --- a/controllers/LabelController.go +++ b/controllers/LabelController.go @@ -1,9 +1,9 @@ package controllers import ( + "github.com/astaxie/beego/logs" "math" - "github.com/astaxie/beego" "github.com/astaxie/beego/orm" "github.com/mindoc-org/mindoc/conf" "github.com/mindoc-org/mindoc/models" @@ -40,7 +40,7 @@ func (c *LabelController) Index() { if err == orm.ErrNoRows { c.Abort("404") } else { - beego.Error(err) + logs.Error(err) c.Abort("500") } } @@ -51,7 +51,7 @@ func (c *LabelController) Index() { searchResult, totalCount, err := models.NewBook().FindForLabelToPager(labelName, pageIndex, conf.PageSize, memberId) if err != nil && err != orm.ErrNoRows { - beego.Error("查询标签时出错 ->", err) + logs.Error("查询标签时出错 ->", err) c.ShowErrorPage(500, "查询文档列表时出错") } if totalCount > 0 { diff --git a/controllers/ManagerController.go b/controllers/ManagerController.go index 991d4cec..dc7bd4b4 100644 --- a/controllers/ManagerController.go +++ b/controllers/ManagerController.go @@ -210,7 +210,7 @@ func (c *ManagerController) EditMember() { member, err := models.NewMember().Find(member_id) if err != nil { - beego.Error(err) + logs.Error(err) c.Abort("404") } if c.Ctx.Input.IsPost() { @@ -235,7 +235,7 @@ func (c *ManagerController) EditMember() { if password1 != "" { password, err := utils.PasswordHash(password1) if err != nil { - beego.Error(err) + logs.Error(err) c.JsonResult(6003, "对用户密码加密时出错") } member.Password = password @@ -261,7 +261,7 @@ func (c *ManagerController) DeleteMember() { member, err := models.NewMember().Find(member_id) if err != nil { - beego.Error(err) + logs.Error(err) c.JsonResult(500, "用户不存在") } if member.Role == conf.MemberSuperRole { @@ -270,14 +270,14 @@ func (c *ManagerController) DeleteMember() { superMember, err := models.NewMember().FindByFieldFirst("role", 0) if err != nil { - beego.Error(err) + logs.Error(err) c.JsonResult(5001, "未能找到超级管理员") } err = models.NewMember().Delete(member_id, superMember.MemberId) if err != nil { - beego.Error(err) + logs.Error(err) c.JsonResult(5002, "删除失败") } c.JsonResult(0, "ok") @@ -341,7 +341,7 @@ func (c *ManagerController) EditBook() { autoRelease := strings.TrimSpace(c.GetString("auto_release")) == "on" publisher := strings.TrimSpace(c.GetString("publisher")) historyCount, _ := c.GetInt("history_count", 0) - itemId,_ := c.GetInt("itemId") + itemId, _ := c.GetInt("itemId") if strings.Count(description, "") > 500 { c.JsonResult(6004, "项目描述不能大于500字") @@ -356,7 +356,7 @@ func (c *ManagerController) EditBook() { } } if !models.NewItemsets().Exist(itemId) { - c.JsonResult(6006,"项目空间不存在") + c.JsonResult(6006, "项目空间不存在") } book.Publisher = publisher book.HistoryCount = historyCount @@ -517,7 +517,7 @@ func (c *ManagerController) Transfer() { rel, err := models.NewRelationship().FindFounder(book.BookId) if err != nil { - beego.Error("FindFounder => ", err) + logs.Error("FindFounder => ", err) c.JsonResult(6009, "查询项目创始人失败") } if member.MemberId == rel.MemberId { @@ -647,7 +647,7 @@ func (c *ManagerController) AttachDetailed() { attach, err := models.NewAttachmentResult().Find(attach_id) if err != nil { - beego.Error("AttachDetailed => ", err) + logs.Error("AttachDetailed => ", err) if err == orm.ErrNoRows { c.Abort("404") } else { @@ -674,13 +674,13 @@ func (c *ManagerController) AttachDelete() { attach, err := models.NewAttachment().Find(attachId) if err != nil { - beego.Error("AttachDelete => ", err) + logs.Error("AttachDelete => ", err) c.JsonResult(6001, err.Error()) } attach.FilePath = filepath.Join(conf.WorkingDirectory, attach.FilePath) if err := attach.Delete(); err != nil { - beego.Error("AttachDelete => ", err) + logs.Error("AttachDelete => ", err) c.JsonResult(6002, err.Error()) } c.JsonResult(0, "ok") @@ -714,7 +714,7 @@ func (c *ManagerController) LabelDelete() { labelId, err := strconv.Atoi(c.Ctx.Input.Param(":id")) if err != nil { - beego.Error("获取删除标签参数时出错:", err) + logs.Error("获取删除标签参数时出错:", err) c.JsonResult(50001, "参数错误") } if labelId <= 0 { @@ -723,7 +723,7 @@ func (c *ManagerController) LabelDelete() { label, err := models.NewLabel().FindFirst("label_id", labelId) if err != nil { - beego.Error("查询标签时出错:", err) + logs.Error("查询标签时出错:", err) c.JsonResult(50001, "查询标签时出错:"+err.Error()) } if err := label.Delete(); err != nil { @@ -744,7 +744,7 @@ func (c *ManagerController) Config() { tf, err := ioutil.TempFile(os.TempDir(), "mindoc") if err != nil { - beego.Error("创建临时文件失败 ->", err) + logs.Error("创建临时文件失败 ->", err) c.JsonResult(5001, "创建临时文件失败") } defer tf.Close() @@ -754,12 +754,12 @@ func (c *ManagerController) Config() { err = beego.LoadAppConfig("ini", tf.Name()) if err != nil { - beego.Error("加载配置文件失败 ->", err) + logs.Error("加载配置文件失败 ->", err) c.JsonResult(5002, "加载配置文件失败") } err = filetil.CopyFile(tf.Name(), conf.ConfigurationFile) if err != nil { - beego.Error("保存配置文件失败 ->", err) + logs.Error("保存配置文件失败 ->", err) c.JsonResult(5003, "保存配置文件失败") } c.JsonResult(0, "保存成功") @@ -903,7 +903,7 @@ func (c *ManagerController) TeamMemberList() { b, err := json.Marshal(teams) if err != nil { - beego.Error("编码 JSON 结果失败 ->", err) + logs.Error("编码 JSON 结果失败 ->", err) c.Data["Result"] = template.JS("[]") } else { c.Data["Result"] = template.JS(string(b)) @@ -1030,7 +1030,7 @@ func (c *ManagerController) TeamBookList() { b, err := json.Marshal(teams) if err != nil { - beego.Error("编码 JSON 结果失败 ->", err) + logs.Error("编码 JSON 结果失败 ->", err) c.Data["Result"] = template.JS("[]") } else { c.Data["Result"] = template.JS(string(b)) @@ -1124,7 +1124,6 @@ func (c *ManagerController) Itemsets() { c.Data["Lists"] = items - } //编辑或添加项目空间. diff --git a/controllers/SearchController.go b/controllers/SearchController.go index f9868957..069c483b 100644 --- a/controllers/SearchController.go +++ b/controllers/SearchController.go @@ -1,10 +1,10 @@ package controllers import ( + "github.com/astaxie/beego/logs" "strconv" "strings" - "github.com/astaxie/beego" "github.com/mindoc-org/mindoc/conf" "github.com/mindoc-org/mindoc/models" "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) if err != nil { - beego.Error("搜索失败 ->",err) + logs.Error("搜索失败 ->", err) return } 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() } else { c.Data["PageHtml"] = "" } if len(searchResult) > 0 { - keywords := strings.Split(keyword," ") + keywords := strings.Split(keyword, " ") for _, item := range searchResult { - for _,word := range keywords { + for _, word := range keywords { item.DocumentName = strings.Replace(item.DocumentName, word, ""+word+"", -1) if 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().FindNotJoinUsersByAccountOrRealName(book.BookId, 10, "%"+keyword+"%") if err != nil { - beego.Error("查询用户列表出错:" + err.Error()) + logs.Error("查询用户列表出错:" + err.Error()) c.JsonResult(500, err.Error()) } result := models.SelectMemberResult{} diff --git a/mail/smtp.go b/mail/smtp.go index c6df01d3..0ea65ab7 100644 --- a/mail/smtp.go +++ b/mail/smtp.go @@ -8,6 +8,7 @@ import ( "encoding/hex" "errors" "fmt" + "github.com/astaxie/beego/logs" "io/ioutil" "log" "net/mail" @@ -17,7 +18,6 @@ import ( "regexp" "strconv" "strings" - "github.com/astaxie/beego" ) var ( @@ -229,7 +229,6 @@ func (c *SMTPClient) SendTLS(m Mail, message bytes.Buffer) error { return err } - ct, err = smtp.NewClient(conn, c.host) if err != nil { log.Println(err) @@ -247,8 +246,8 @@ func (c *SMTPClient) SendTLS(m Mail, message bytes.Buffer) error { //} fmt.Println(c.smtpAuth) - if ok,s := ct.Extension("AUTH"); ok { - beego.Info(s) + if ok, s := ct.Extension("AUTH"); ok { + logs.Info(s) // Auth if err = ct.Auth(c.smtpAuth); err != nil { log.Println("Auth Error:", diff --git a/models/AttachmentModel.go b/models/AttachmentModel.go index 1eaa7295..4ab105c8 100644 --- a/models/AttachmentModel.go +++ b/models/AttachmentModel.go @@ -2,13 +2,13 @@ package models import ( + "github.com/astaxie/beego/logs" "time" "os" "strings" - "github.com/astaxie/beego" "github.com/astaxie/beego/orm" "github.com/mindoc-org/mindoc/conf" "github.com/mindoc-org/mindoc/utils/filetil" @@ -65,7 +65,7 @@ func (m *Attachment) Delete() error { if err == 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 == orm.ErrNoRows { - beego.Info("没有查到附件 ->", err) + logs.Info("没有查到附件 ->", err) err = nil } return diff --git a/models/Blog.go b/models/Blog.go index 9fc45465..2666faa8 100644 --- a/models/Blog.go +++ b/models/Blog.go @@ -3,6 +3,7 @@ package models import ( "bytes" "fmt" + "github.com/astaxie/beego/logs" "strings" "time" @@ -94,7 +95,7 @@ func (b *Blog) Find(blogId int) (*Blog, error) { err := o.QueryTable(b.TableNameWithPrefix()).Filter("blog_id", blogId).One(b) if err != nil { - beego.Error("查询文章时失败 -> ", err) + logs.Error("查询文章时失败 -> ", 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) { - key := fmt.Sprintf("blog-id-%d", blogId); + key := fmt.Sprintf("blog-id-%d", blogId) var temp Blog - err = cache.Get(key, &temp); + err = cache.Get(key, &temp) if err == nil { b = &temp b.Link() beego.Debug("从缓存读取文章成功 ->", key) return b, nil } else { - beego.Error("读取缓存失败 ->", err) + logs.Error("读取缓存失败 ->", err) } blog, err = b.Find(blogId) if err == nil { //默认一个小时 if err := cache.Put(key, blog, time.Hour*1); err != nil { - beego.Error("将文章存入缓存失败 ->", err) + logs.Error("将文章存入缓存失败 ->", err) } } 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) if err != nil { - beego.Error("查询文章时失败 -> ", err) + logs.Error("查询文章时失败 -> ", 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) if err != nil { - beego.Error("查询文章时失败 -> ", err) + logs.Error("查询文章时失败 -> ", err) return nil, err } return b, nil @@ -157,7 +158,7 @@ func (b *Blog) Link() (*Blog, error) { if b.BlogType == 1 && b.DocumentId > 0 { doc := NewDocument() 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 { b.DocumentIdentify = doc.Identify b.BlogRelease = doc.Release @@ -166,7 +167,7 @@ func (b *Blog) Link() (*Blog, error) { b.BlogContent = doc.Markdown book := NewBook() if err := o.QueryTable(book.TableNameWithPrefix()).Filter("book_id", doc.BookId).One(book, "identify"); err != nil { - beego.Error("查询关联文档的项目时出错 ->", err) + logs.Error("查询关联文档的项目时出错 ->", err) } else { b.BookIdentify = book.Identify 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 { content.Find(".wiki-bottom").Remove() - if html,err := content.Html();err == nil { + if html, err := content.Html(); err == nil { b.BlogRelease = html } else { - beego.Error("处理文章失败 ->",err) + logs.Error("处理文章失败 ->", err) } - }else { - beego.Error("处理文章失败 ->",err) + } else { + logs.Error("处理文章失败 ->", err) } } } @@ -224,7 +225,7 @@ func (b *Blog) Save(cols ...string) error { if b.OrderIndex <= 0 { blog := NewBlog() 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 { c, _ := o.QueryTable(b.TableNameWithPrefix()).Count() b.OrderIndex = int(c) + 1 @@ -260,7 +261,7 @@ func (b *Blog) Processor() *Blog { content.Find("a").Each(func(i int, contentSelection *goquery.Selection) { if src, ok := contentSelection.Attr("href"); ok { 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) { contentSelection.SetAttr("target", "_blank") if html, err := content.Html(); err == nil { @@ -306,13 +307,13 @@ func (b *Blog) FindToPager(pageIndex, pageSize int, memberId int, status string) if err == orm.ErrNoRows { err = nil } - beego.Error("获取文章列表时出错 ->", err) + logs.Error("获取文章列表时出错 ->", err) return } count, err := query.Count() if err != nil { - beego.Error("获取文章数量时出错 ->", err) + logs.Error("获取文章数量时出错 ->", err) return nil, 0, err } totalCount = int(count) @@ -331,7 +332,7 @@ func (b *Blog) Delete(blogId int) error { _, err := o.QueryTable(b.TableNameWithPrefix()).Filter("blog_id", blogId).Delete() if err != nil { - beego.Error("删除文章失败 ->", err) + logs.Error("删除文章失败 ->", err) } return err } @@ -342,14 +343,14 @@ func (b *Blog) QueryNext(blogId int) (*Blog, error) { blog := NewBlog() 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 } 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 { - beego.Error("查询文章时出错 ->", err) + logs.Error("查询文章时出错 ->", err) } return blog, err } @@ -360,14 +361,14 @@ func (b *Blog) QueryPrevious(blogId int) (*Blog, error) { blog := NewBlog() 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 } 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 { - beego.Error("查询文章时出错 ->", err) + logs.Error("查询文章时出错 ->", err) } return blog, err } @@ -382,13 +383,13 @@ func (b *Blog) LinkAttach() (err error) { if b.BlogType != 1 || b.DocumentId <= 0 { _, err = o.QueryTable(NewAttachment().TableNameWithPrefix()).Filter("document_id", b.BlogId).Filter("book_id", 0).All(&attachList) if err != nil && err != orm.ErrNoRows { - beego.Error("查询文章附件时出错 ->", err) + logs.Error("查询文章附件时出错 ->", err) } } else { _, err = o.QueryTable(NewAttachment().TableNameWithPrefix()).Filter("document_id", b.DocumentId).Filter("book_id", b.BookId).All(&attachList) if err != nil && err != orm.ErrNoRows { - beego.Error("查询文章附件时出错 ->", err) + logs.Error("查询文章附件时出错 ->", err) } } b.AttachList = attachList diff --git a/models/BookModel.go b/models/BookModel.go index 4b6766a4..5d3662bf 100644 --- a/models/BookModel.go +++ b/models/BookModel.go @@ -16,7 +16,6 @@ import ( "encoding/json" - "github.com/astaxie/beego" "github.com/astaxie/beego/logs" "github.com/astaxie/beego/orm" "github.com/mindoc-org/mindoc/conf" @@ -194,11 +193,11 @@ func (book *Book) Copy(identify string) error { err := o.QueryTable(book.TableNameWithPrefix()).Filter("identify", identify).One(book) if err != nil { - beego.Error("查询项目时出错 -> ", err) + logs.Error("查询项目时出错 -> ", err) return err } if err := o.Begin(); err != nil { - beego.Error("开启事物时出错 -> ", err) + logs.Error("开启事物时出错 -> ", err) return err } @@ -211,14 +210,14 @@ func (book *Book) Copy(identify string) error { book.HistoryCount = 0 if _, err := o.Insert(book); err != nil { - beego.Error("复制项目时出错 -> ", err) + logs.Error("复制项目时出错 -> ", err) o.Rollback() return err } var rels []*Relationship if _, err := o.QueryTable(NewRelationship().TableNameWithPrefix()).Filter("book_id", bookId).All(&rels); err != nil { - beego.Error("复制项目关系时出错 -> ", err) + logs.Error("复制项目关系时出错 -> ", err) o.Rollback() return err } @@ -227,7 +226,7 @@ func (book *Book) Copy(identify string) error { rel.BookId = book.BookId rel.RelationshipId = 0 if _, err := o.Insert(rel); err != nil { - beego.Error("复制项目关系时出错 -> ", err) + logs.Error("复制项目关系时出错 -> ", err) o.Rollback() return err } @@ -236,13 +235,13 @@ func (book *Book) Copy(identify string) error { var docs []*Document if _, err := o.QueryTable(NewDocument().TableNameWithPrefix()).Filter("book_id", bookId).Filter("parent_id", 0).All(&docs); err != nil && err != orm.ErrNoRows { - beego.Error("读取项目文档时出错 -> ", err) + logs.Error("读取项目文档时出错 -> ", err) o.Rollback() return err } if len(docs) > 0 { if err := recursiveInsertDocument(docs, o, book.BookId, 0); err != nil { - beego.Error("复制项目时出错 -> ", err) + logs.Error("复制项目时出错 -> ", err) o.Rollback() return err } @@ -262,7 +261,7 @@ func recursiveInsertDocument(docs []*Document, o orm.Ormer, bookId int, parentId doc.Version = time.Now().Unix() if _, err := o.Insert(doc); err != nil { - beego.Error("插入项目时出错 -> ", err) + logs.Error("插入项目时出错 -> ", err) return err } @@ -281,7 +280,7 @@ func recursiveInsertDocument(docs []*Document, o orm.Ormer, bookId int, parentId var subDocs []*Document 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 } if len(subDocs) > 0 { @@ -464,11 +463,11 @@ func (book *Book) ThoroughDeleteBook(id int) error { //删除导出缓存 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 { - beego.Error("删除项目附件和图片失败 ->", err) + logs.Error("删除项目附件和图片失败 ->", err) } return o.Commit() @@ -592,7 +591,7 @@ func (book *Book) ReleaseContent(bookId int) { go func() { defer func() { if err := recover(); err != nil { - beego.Error("协程崩溃 ->", err) + logs.Error("协程崩溃 ->", err) } }() for bookId := range releaseQueue { @@ -602,7 +601,7 @@ func (book *Book) ReleaseContent(bookId int) { _, err := o.QueryTable(NewDocument().TableNameWithPrefix()).Filter("book_id", bookId).All(&docs) if err != nil { - beego.Error("发布失败 =>", bookId, err) + logs.Error("发布失败 =>", bookId, err) continue } for _, item := range docs { @@ -626,10 +625,10 @@ func (book *Book) ResetDocumentNumber(bookId int) { if err == nil { _, err = o.Raw("UPDATE md_books SET doc_count = ? WHERE book_id = ?", int(totalCount), bookId).Exec() if err != nil { - beego.Error("重置文档数量失败 =>", bookId, err) + logs.Error("重置文档数量失败 =>", bookId, err) } } else { - beego.Error("获取文档数量失败 =>", bookId, err) + logs.Error("获取文档数量失败 =>", bookId, err) } } @@ -648,7 +647,7 @@ func (book *Book) ImportBook(zipPath string) error { tempPath := filepath.Join(os.TempDir(), md5str) if err := os.MkdirAll(tempPath, 0766); err != nil { - beego.Error("创建导入目录出错 => ", err) + logs.Error("创建导入目录出错 => ", err) } //如果加压缩失败 if err := ziptil.Unzip(zipPath, tempPath); err != nil { @@ -693,7 +692,7 @@ func (book *Book) ImportBook(zipPath string) error { ext := filepath.Ext(info.Name()) //如果是Markdown文件 if strings.EqualFold(ext, ".md") || strings.EqualFold(ext, ".markdown") { - beego.Info("正在处理 =>", path, info.Name()) + logs.Info("正在处理 =>", path, info.Name()) doc := NewDocument() doc.BookId = book.BookId doc.MemberId = book.MemberId @@ -796,11 +795,11 @@ func (book *Book) ImportBook(zipPath string) error { //如果本地存在该链接 if filetil.FileExists(linkPath) { ext := filepath.Ext(linkPath) - //beego.Info("当前后缀 -> ",ext) + //logs.Info("当前后缀 -> ",ext) //如果链接是Markdown文件,则生成文档标识,否则,将目标文件复制到项目目录 if strings.EqualFold(ext, ".md") || strings.EqualFold(ext, ".markdown") { 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 { docIdentify = "import-" + docIdentify } @@ -819,7 +818,7 @@ func (book *Book) ImportBook(zipPath string) error { } } else { - beego.Info("文件不存在 ->", linkPath) + logs.Info("文件不存在 ->", linkPath) } } @@ -829,7 +828,7 @@ func (book *Book) ImportBook(zipPath string) error { //codeRe := regexp.MustCompile("```\\w+") //doc.Markdown = codeRe.ReplaceAllStringFunc(doc.Markdown, func(s string) string { - // //beego.Info(s) + // //logs.Info(s) // return strings.Replace(s,"```","``` ",-1) //}) @@ -863,21 +862,21 @@ func (book *Book) ImportBook(zipPath string) error { } } if strings.EqualFold(info.Name(), "README.md") { - beego.Info(path, "|", info.Name(), "|", parentIdentify, "|", parentId) + logs.Info(path, "|", info.Name(), "|", parentIdentify, "|", parentId) } isInsert := false //如果当前文件是README.md,则将内容更新到父级 if strings.EqualFold(info.Name(), "README.md") && parentId != 0 { doc.DocumentId = parentId - //beego.Info(path,"|",parentId) + //logs.Info(path,"|",parentId) } else { - //beego.Info(path,"|",parentIdentify) + //logs.Info(path,"|",parentIdentify) doc.ParentId = parentId isInsert = true } if err := doc.InsertOrUpdate("document_name", "markdown", "content"); err != nil { - beego.Error(doc.DocumentId, err) + logs.Error(doc.DocumentId, err) } if isInsert { docMap[docIdentify] = doc.DocumentId @@ -886,7 +885,7 @@ func (book *Book) ImportBook(zipPath string) error { } else { //如果当前目录下存在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) if ok, err := regexp.MatchString(`[a-z]+[a-zA-Z0-9_.\-]*$`, identify); !ok || err != nil { identify = "import-" + identify @@ -911,11 +910,11 @@ func (book *Book) ImportBook(zipPath string) error { parentDoc.ParentId = parentId if err := parentDoc.InsertOrUpdate(); err != nil { - beego.Error(err) + logs.Error(err) } docMap[identify] = parentDoc.DocumentId - //beego.Info(path,"|",parentDoc.DocumentId,"|",identify,"|",info.Name(),"|",parentIdentify) + //logs.Info(path,"|",parentDoc.DocumentId,"|",identify,"|",info.Name(),"|",parentIdentify) } } @@ -923,10 +922,10 @@ func (book *Book) ImportBook(zipPath string) error { }) if err != nil { - beego.Error("导入项目异常 => ", err) + logs.Error("导入项目异常 => ", err) book.Description = "【项目导入存在错误:" + err.Error() + "】" } - beego.Info("项目导入完毕 => ", book.BookName) + logs.Info("项目导入完毕 => ", book.BookName) book.ReleaseContent(book.BookId) return err } @@ -953,7 +952,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) 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 conf.BookRole(roleId), nil diff --git a/models/BookResult.go b/models/BookResult.go index 352a6b52..ce628e1c 100644 --- a/models/BookResult.go +++ b/models/BookResult.go @@ -97,7 +97,7 @@ func (m *BookResult) FindByIdentify(identify string, memberId int) (*BookResult, err := NewBook().QueryTable().Filter("identify", identify).One(&book) if err != nil { - beego.Error("获取项目失败 ->", err) + logs.Error("获取项目失败 ->", err) return m, err } @@ -229,7 +229,7 @@ func (m *BookResult) ToBookResult(book Book) *BookResult { } 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 } } @@ -240,7 +240,7 @@ func (m *BookResult) ToBookResult(book Book) *BookResult { func BackgroundConvert(sessionId string, bookResult *BookResult) error { if err := converter.CheckConvertCommand(); err != nil { - beego.Error("检查转换程序失败 -> ", err) + logs.Error("检查转换程序失败 -> ", err) return err } err := exportLimitWorkerChannel.LoadOrStore(bookResult.Identify, func() { @@ -249,7 +249,7 @@ func BackgroundConvert(sessionId string, bookResult *BookResult) error { if err != nil { - beego.Error("将导出任务加入任务队列失败 -> ", err) + logs.Error("将导出任务加入任务队列失败 -> ", err) return err } exportLimitWorkerChannel.Start() @@ -275,15 +275,15 @@ func (m *BookResult) Converter(sessionId string) (ConvertBookResult, error) { sourceDir := strings.TrimSuffix(tempOutputPath, "source") if filetil.FileExists(sourceDir) { if err := os.RemoveAll(sourceDir); err != nil { - beego.Error("删除临时目录失败 ->", sourceDir, err) + logs.Error("删除临时目录失败 ->", sourceDir, err) } } if err := os.MkdirAll(outputPath, 0766); err != nil { - beego.Error("创建目录失败 -> ", outputPath, err) + logs.Error("创建目录失败 -> ", outputPath, err) } if err := os.MkdirAll(tempOutputPath, 0766); err != nil { - beego.Error("创建目录失败 -> ", tempOutputPath, err) + logs.Error("创建目录失败 -> ", tempOutputPath, err) } 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 { - beego.Error("导出目录配置错误:" + err.Error()) + logs.Error("导出目录配置错误:" + err.Error()) return convertBookResult, err } @@ -396,7 +396,7 @@ func (m *BookResult) Converter(sessionId string) (ConvertBookResult, error) { if strings.HasPrefix(src, "/") { spath := filepath.Join(conf.WorkingDirectory, src) if filetil.CopyFile(spath, filepath.Join(tempOutputPath, dstSrcString)); err != nil { - beego.Error("复制图片失败 -> ", err, src) + logs.Error("复制图片失败 -> ", err, src) return } @@ -415,15 +415,15 @@ func (m *BookResult) Converter(sessionId string) (ConvertBookResult, error) { if body, err := ioutil.ReadAll(resp.Body); err == nil { //encodeString = base64.StdEncoding.EncodeToString(body) if err := ioutil.WriteFile(filepath.Join(tempOutputPath, dstSrcString), body, 0755); err != nil { - beego.Error("下载图片失败 -> ", err, src) + logs.Error("下载图片失败 -> ", err, src) return } } else { - beego.Error("下载图片失败 -> ", err, src) + logs.Error("下载图片失败 -> ", err, src) return } } else { - beego.Error("下载图片失败 -> ", err, src) + logs.Error("下载图片失败 -> ", err, src) 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 { - 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 { - 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 { - 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 { - 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 { - 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 { - 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 { - 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{ @@ -480,22 +480,22 @@ func (m *BookResult) Converter(sessionId string) (ConvertBookResult, error) { os.MkdirAll(eBookConverter.OutputPath, 0766) if err := eBookConverter.Convert(); err != nil { - beego.Error("转换文件错误:" + m.BookName + " -> " + err.Error()) + logs.Error("转换文件错误:" + m.BookName + " -> " + err.Error()) 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 { - 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 { - 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 { - 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 { - beego.Error("复制文档失败 -> ", filepath.Join(eBookConverter.OutputPath, "output", "book.docx"), err) + logs.Error("复制文档失败 -> ", filepath.Join(eBookConverter.OutputPath, "output", "book.docx"), err) } convertBookResult.MobiPath = mobipath @@ -525,7 +525,7 @@ func (m *BookResult) ExportMarkdown(sessionId string) (string, error) { } if err := ziptil.Compress(outputPath, tempOutputPath); err != nil { - beego.Error("导出Markdown失败->", err) + logs.Error("导出Markdown失败->", err) return "", err } 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) if err != nil { - beego.Error("导出Markdown失败->", err) + logs.Error("导出Markdown失败->", err) return err } 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() if err != nil { - beego.Error("导出Markdown失败->", err) + logs.Error("导出Markdown失败->", 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 { err := o.QueryTable(NewDocument().TableNameWithPrefix()).Filter("document_id", id).One(tempDoc, "identify", "parent_id", "document_id") if err != nil { - beego.Error(err) + logs.Error(err) return link } } else { err := o.QueryTable(NewDocument().TableNameWithPrefix()).Filter("identify", docIdentify).One(tempDoc, "identify", "parent_id", "document_id") if err != nil { - beego.Error(err) + logs.Error(err) return link } } @@ -644,7 +644,7 @@ func exportMarkdown(p string, parentId int, bookId int, baseDir string, bookUrl relative = strings.TrimSuffix(strings.TrimPrefix(relative, "/"), "/") repeat = strings.Count(relative, "/") + 1 } - beego.Info(repeat, "|", relative, "|", p, "|", baseDir) + logs.Info(repeat, "|", relative, "|", p, "|", baseDir) tempLink = strings.Repeat("../", repeat) + 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" } if err := ioutil.WriteFile(docPath, []byte(markdown), 0644); err != nil { - beego.Error("导出Markdown失败->", err) + logs.Error("导出Markdown失败->", 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") if err != nil { - beego.Error(err) + logs.Error(err) return identify } diff --git a/models/DocumentHistory.go b/models/DocumentHistory.go index 3490f709..d75b3e2b 100644 --- a/models/DocumentHistory.go +++ b/models/DocumentHistory.go @@ -1,9 +1,9 @@ package models import ( + "github.com/astaxie/beego/logs" "time" - "github.com/astaxie/beego" "github.com/astaxie/beego/orm" "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"` ModifyAt int `orm:"column(modify_at);type(int)" json:"-"` 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 { @@ -127,22 +127,22 @@ func (m *DocumentHistory) InsertOrUpdate() (history *DocumentHistory, err error) } else { _, err = o.Insert(m) if err == nil { - if doc,e := NewDocument().Find(m.DocumentId);e == nil { - if book,e := NewBook().Find(doc.BookId);e == nil && book.HistoryCount > 0 { + if doc, e := NewDocument().Find(m.DocumentId); e == nil { + 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) - beego.Info("需要删除的历史文档数量:" ,count) + logs.Info("需要删除的历史文档数量:", count) 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 { - for _,d := range lists { + 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 { o.Delete(&d) } } - }else{ - beego.Info(book.HistoryCount) + } else { + logs.Info(book.HistoryCount) } } } diff --git a/models/DocumentModel.go b/models/DocumentModel.go index 5e5e4474..356c8a8f 100644 --- a/models/DocumentModel.go +++ b/models/DocumentModel.go @@ -1,6 +1,7 @@ package models import ( + "github.com/astaxie/beego/logs" "time" "fmt" @@ -142,7 +143,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) if err != nil { - beego.Error("RecursiveDocument => ", err) + logs.Error("RecursiveDocument => ", err) return err } @@ -164,11 +165,11 @@ func (item *Document) PutToCache() { if m.Identify == "" { 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 { 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 +191,7 @@ func (item *Document) RemoveCache() { func (item *Document) FromCacheById(id int) (*Document, error) { 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 } @@ -211,7 +212,7 @@ func (item *Document) FromCacheByIdentify(identify string, bookId int) (*Documen key := fmt.Sprintf("Document.BookId.%d.Identify.%s", bookId, identify) if err := cache.Get(key, item); err == nil && item.DocumentId > 0 { - beego.Info("从缓存中获取文档信息成功 ->", key) + logs.Info("从缓存中获取文档信息成功 ->", key) return item, nil } @@ -247,14 +248,14 @@ func (item *Document) ReleaseContent() error { err := item.Processor().InsertOrUpdate("release") if err != nil { - beego.Error(fmt.Sprintf("发布失败 -> %+v", item), err) + logs.Error(fmt.Sprintf("发布失败 -> %+v", item), err) return err } //当文档发布后,需要清除已缓存的转换文档和文档缓存 item.RemoveCache() 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 } @@ -360,7 +361,7 @@ func (item *Document) Processor() *Document { selection.SetAttr("href", "#") return } - val = strings.Replace(strings.ToLower(val), " ", "",-1) + val = strings.Replace(strings.ToLower(val), " ", "", -1) //移除危险脚本链接 if strings.HasPrefix(val, "data:text/html") || strings.HasPrefix(val, "vbscript:") || diff --git a/models/DocumentSearchResult.go b/models/DocumentSearchResult.go index 44dcfd2d..f8559b20 100644 --- a/models/DocumentSearchResult.go +++ b/models/DocumentSearchResult.go @@ -1,10 +1,10 @@ package models import ( + "github.com/astaxie/beego/logs" "time" "github.com/astaxie/beego/orm" - "github.com/astaxie/beego" "strings" ) @@ -33,7 +33,7 @@ func (m *DocumentSearchResult) FindToPager(keyword string, pageIndex, pageSize, offset := (pageIndex - 1) * pageSize - keyword = "%" + strings.Replace(keyword," ","%",-1) + "%" + keyword = "%" + strings.Replace(keyword, " ", "%", -1) + "%" if memberId <= 0 { sql1 := `SELECT count(doc.document_id) as total_count FROM md_documents AS doc @@ -99,7 +99,7 @@ LIMIT ?, ?;` err = o.Raw(sql1, keyword, keyword).QueryRow(&totalCount) if err != nil { - beego.Error("查询搜索结果失败 -> ",err) + logs.Error("查询搜索结果失败 -> ", err) return } sql3 := ` SELECT @@ -110,7 +110,7 @@ LIMIT ?, ?;` c := 0 err = o.Raw(sql3, keyword, keyword).QueryRow(&c) if err != nil { - beego.Error("查询搜索结果失败 -> ",err) + logs.Error("查询搜索结果失败 -> ", err) return } @@ -121,15 +121,15 @@ WHERE book.privately_owned = 0 AND (book.book_name LIKE ? OR book.description LI err = o.Raw(sql4, keyword, keyword).QueryRow(&c) if err != nil { - beego.Error("查询搜索结果失败 -> ",err) + logs.Error("查询搜索结果失败 -> ", err) return } 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 { - beego.Error("查询搜索结果失败 -> ",err) + logs.Error("查询搜索结果失败 -> ", err) return } } else { @@ -236,9 +236,9 @@ LIMIT ?, ?;` (blog.blog_release LIKE ? OR blog.blog_title LIKE ?);` c := 0 - err = o.Raw(sql3,memberId, keyword, keyword).QueryRow(&c) + err = o.Raw(sql3, memberId, keyword, keyword).QueryRow(&c) if err != nil { - beego.Error("查询搜索结果失败 -> ",err) + logs.Error("查询搜索结果失败 -> ", err) return } @@ -253,15 +253,15 @@ LIMIT ?, ?;` 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 ?);` - err = o.Raw(sql4,memberId, memberId,keyword, keyword).QueryRow(&c) + err = o.Raw(sql4, memberId, memberId, keyword, keyword).QueryRow(&c) if err != nil { - beego.Error("查询搜索结果失败 -> ",err) + logs.Error("查询搜索结果失败 -> ", err) return } 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 { return } diff --git a/models/Itemsets.go b/models/Itemsets.go index 0cd5038b..6852fe95 100644 --- a/models/Itemsets.go +++ b/models/Itemsets.go @@ -2,10 +2,10 @@ package models import ( "errors" + "github.com/astaxie/beego/logs" "strings" "time" - "github.com/astaxie/beego" "github.com/astaxie/beego/orm" "github.com/mindoc-org/mindoc/conf" "github.com/mindoc-org/mindoc/utils" @@ -55,7 +55,7 @@ func (item *Itemsets) First(itemId int) (*Itemsets, error) { } err := item.QueryTable().Filter("item_id", itemId).One(item) if err != nil { - beego.Error("查询项目空间失败 -> item_id=", itemId, err) + logs.Error("查询项目空间失败 -> item_id=", itemId, err) } else { item.Include() } @@ -65,7 +65,7 @@ func (item *Itemsets) First(itemId int) (*Itemsets, error) { func (item *Itemsets) FindFirst(itemKey string) (*Itemsets, error) { err := item.QueryTable().Filter("item_key", itemKey).One(item) if err != nil { - beego.Error("查询项目空间失败 -> itemKey=", itemKey, err) + logs.Error("查询项目空间失败 -> itemKey=", itemKey, err) } else { item.Include() } @@ -114,17 +114,17 @@ func (item *Itemsets) Delete(itemId int) (err error) { } o := orm.NewOrm() if err := o.Begin(); err != nil { - beego.Error("开启事物失败 ->", err) + logs.Error("开启事物失败 ->", err) return err } _, err = o.QueryTable(item.TableNameWithPrefix()).Filter("item_id", itemId).Delete() if err != nil { - beego.Error("删除项目空间失败 -> item_id=", itemId, err) + logs.Error("删除项目空间失败 -> item_id=", itemId, err) o.Rollback() } _, err = o.Raw("update md_books set item_id=1 where item_id=?;", itemId).Exec() if err != nil { - beego.Error("删除项目空间失败 -> item_id=", itemId, err) + logs.Error("删除项目空间失败 -> item_id=", itemId, err) o.Rollback() } @@ -190,7 +190,7 @@ func (item *Itemsets) FindItemsetsByName(name string, limit int) (*SelectMemberR _, err = item.QueryTable().Filter("item_name__icontains", name).Limit(limit).All(&itemsets) } if err != nil { - beego.Error("查询项目空间失败 ->", err) + logs.Error("查询项目空间失败 ->", err) return &result, err } @@ -214,7 +214,7 @@ func (item *Itemsets) FindItemsetsByItemKey(key string, pageIndex, pageSize, mem err = item.QueryTable().Filter("item_key", key).One(item) if err != nil { - beego.Error("查询项目空间时出错 ->", key, err) + logs.Error("查询项目空间时出错 ->", key, err) return nil, 0, err } offset := (pageIndex - 1) * pageSize @@ -232,7 +232,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) if err != nil { - beego.Error("查询项目空间时出错 ->", key, err) + logs.Error("查询项目空间时出错 ->", key, err) return } sql2 := `SELECT book.*,rel1.*,member.account AS create_name FROM md_books AS book diff --git a/models/LabelModel.go b/models/LabelModel.go index 772e7fa1..088c4f45 100644 --- a/models/LabelModel.go +++ b/models/LabelModel.go @@ -1,9 +1,9 @@ package models import ( + "github.com/astaxie/beego/logs" "strings" - "github.com/astaxie/beego" "github.com/astaxie/beego/orm" "github.com/mindoc-org/mindoc/conf" ) @@ -74,10 +74,11 @@ func (m *Label) InsertOrUpdateMulti(labels string) { } } } + //删除标签 func (m *Label) Delete() error { 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 { 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) if err == orm.ErrNoRows { - beego.Info("没有查询到标签 ->",err) + logs.Info("没有查询到标签 ->", err) err = nil return } return } - - - - diff --git a/models/Member.go b/models/Member.go index cf08c923..3d50006b 100644 --- a/models/Member.go +++ b/models/Member.go @@ -124,13 +124,13 @@ func (m *Member) ldapLogin(account string, password string) (*Member, error) { var err error lc, err := ldap.Dial("tcp", fmt.Sprintf("%s:%d", beego.AppConfig.String("ldap_host"), beego.AppConfig.DefaultInt("ldap_port", 3268))) if err != nil { - beego.Error("绑定 LDAP 用户失败 ->", err) + logs.Error("绑定 LDAP 用户失败 ->", err) return m, ErrLDAPConnect } defer lc.Close() err = lc.Bind(beego.AppConfig.String("ldap_user"), beego.AppConfig.String("ldap_password")) if err != nil { - beego.Error("绑定 LDAP 用户失败 ->", err) + logs.Error("绑定 LDAP 用户失败 ->", err) return m, ErrLDAPFirstBind } searchRequest := ldap.NewSearchRequest( @@ -143,7 +143,7 @@ func (m *Member) ldapLogin(account string, password string) (*Member, error) { ) searchResult, err := lc.Search(searchRequest) if err != nil { - beego.Error("绑定 LDAP 用户失败 ->", err) + logs.Error("绑定 LDAP 用户失败 ->", err) return m, ErrLDAPSearch } if len(searchResult.Entries) != 1 { @@ -152,7 +152,7 @@ func (m *Member) ldapLogin(account string, password string) (*Member, error) { userdn := searchResult.Entries[0].DN err = lc.Bind(userdn, password) if err != nil { - beego.Error("绑定 LDAP 用户失败 ->", err) + logs.Error("绑定 LDAP 用户失败 ->", err) return m, ErrorMemberPasswordError } if m.MemberId <= 0 { @@ -165,7 +165,7 @@ func (m *Member) ldapLogin(account string, password string) (*Member, error) { err = m.Add() if err != nil { - beego.Error("自动注册LDAP用户错误", err) + logs.Error("自动注册LDAP用户错误", err) return m, ErrorMemberPasswordError } m.ResolveRoleName() @@ -191,22 +191,22 @@ func (m *Member) httpLogin(account, password string) (*Member, error) { resp, err := http.PostForm(urlStr, val) if err != nil { - beego.Error("通过接口登录失败 -> ", urlStr, account, err) + logs.Error("通过接口登录失败 -> ", urlStr, account, err) return nil, ErrHTTPServerFail } defer resp.Body.Close() body, err := ioutil.ReadAll(resp.Body) if err != nil { - beego.Error("读取接口返回值失败 -> ", urlStr, account, err) + logs.Error("读取接口返回值失败 -> ", urlStr, account, err) return nil, ErrHTTPServerFail } - beego.Info("HTTP 登录接口返回数据 ->", string(body)) + logs.Info("HTTP 登录接口返回数据 ->", string(body)) var result map[string]interface{} if err := json.Unmarshal(body, &result); err != nil { - beego.Error("解析接口返回值失败 -> ", urlStr, account, string(body)) + logs.Error("解析接口返回值失败 -> ", urlStr, account, string(body)) return nil, ErrHTTPServerFail } @@ -240,7 +240,7 @@ func (m *Member) httpLogin(account, password string) (*Member, error) { member.Role = conf.SystemRole(beego.AppConfig.DefaultInt("ldap_user_role", 2)) member.CreateTime = time.Now() if err := member.Add(); err != nil { - beego.Error("自动注册用户错误", err) + logs.Error("自动注册用户错误", err) return m, ErrorMemberPasswordError } member.ResolveRoleName() @@ -274,7 +274,7 @@ func (m *Member) Add() error { hash, err := utils.PasswordHash(m.Password) if err != nil { - beego.Error("加密用户密码失败 =>", err) + logs.Error("加密用户密码失败 =>", err) return errors.New("加密用户密码失败") } @@ -285,7 +285,7 @@ func (m *Member) Add() error { _, err = o.Insert(m) if err != nil { - beego.Error("保存用户数据到数据时失败 =>", err) + logs.Error("保存用户数据到数据时失败 =>", err) return errors.New("保存用户失败") } m.ResolveRoleName() @@ -303,7 +303,7 @@ func (m *Member) Update(cols ...string) error { return errors.New("邮箱已被使用") } if _, err := o.Update(m, cols...); err != nil { - beego.Error("保存用户信息失败=>", err) + logs.Error("保存用户信息失败=>", err) return errors.New("保存用户信息失败") } return nil @@ -552,18 +552,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) if err == nil { if _, err := o.Delete(relationship); err != nil { - beego.Error(err) + logs.Error(err) } relationship.RelationshipId = rel.RelationshipId } relationship.MemberId = newId relationship.RoleId = 0 if _, err := o.Update(relationship); err != nil { - beego.Error(err) + logs.Error(err) } } else { if _, err := o.Delete(relationship); err != nil { - beego.Error(err) + logs.Error(err) } } } diff --git a/models/Team.go b/models/Team.go index cc9a5fa0..8458adfe 100644 --- a/models/Team.go +++ b/models/Team.go @@ -2,9 +2,9 @@ package models import ( "errors" + "github.com/astaxie/beego/logs" "time" - "github.com/astaxie/beego" "github.com/astaxie/beego/orm" "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...) if err != nil { - beego.Error("查询团队失败 ->",id, err) - return nil,err + logs.Error("查询团队失败 ->", id, err) + return nil, err } t.Include() return t, err @@ -64,29 +64,29 @@ func (t *Team) Delete(id int) (err error) { err = o.Begin() if err != nil { - beego.Error("开启事物时出错 ->",err) + logs.Error("开启事物时出错 ->", err) return } - _,err = o.QueryTable(t.TableNameWithPrefix()).Filter("team_id",id).Delete() + _, err = o.QueryTable(t.TableNameWithPrefix()).Filter("team_id", id).Delete() if err != nil { - beego.Error("删除团队时出错 ->", err) + logs.Error("删除团队时出错 ->", err) o.Rollback() 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 { - beego.Error("删除团队成员时出错 ->", err) + logs.Error("删除团队成员时出错 ->", err) o.Rollback() 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 { - beego.Error("删除团队项目时出错 ->", err) + logs.Error("删除团队项目时出错 ->", err) o.Rollback() return err } @@ -113,7 +113,7 @@ func (t *Team) FindToPager(pageIndex, pageSize int) (list []*Team, totalCount in } totalCount = int(c) - for _,item := range list { + for _, item := range list { item.Include() } return @@ -123,23 +123,23 @@ func (t *Team) Include() { 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 != "" { t.MemberName = member.RealName } else { 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) } - 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) } } //更新或添加一个团队. -func (t *Team) Save(cols ... string) (err error) { +func (t *Team) Save(cols ...string) (err error) { if t.TeamName == "" { return NewError(5001, "团队名称不能为空") } @@ -155,7 +155,7 @@ func (t *Team) Save(cols ... string) (err error) { _, err = o.Update(t, cols...) } if err != nil { - beego.Error("在保存团队时出错 ->", err) + logs.Error("在保存团队时出错 ->", err) } return } diff --git a/models/TeamMember.go b/models/TeamMember.go index f6f08b95..64ca4207 100644 --- a/models/TeamMember.go +++ b/models/TeamMember.go @@ -2,8 +2,8 @@ package models import ( "errors" + "github.com/astaxie/beego/logs" - "github.com/astaxie/beego" "github.com/astaxie/beego/orm" "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...) if err != nil && err != orm.ErrNoRows { - beego.Error("查询团队成员错误 ->", err) + logs.Error("查询团队成员错误 ->", 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) if err != nil { - beego.Error("查询团队用户时失败 ->", err) + logs.Error("查询团队用户时失败 ->", err) return m, err } 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) if err != nil { - beego.Error("查询团队用户失败 ->", err) + logs.Error("查询团队用户失败 ->", err) return nil, err } return m.Include(), nil @@ -127,7 +127,7 @@ func (m *TeamMember) Save(cols ...string) (err error) { _, err = o.Update(m, cols...) } if err != nil { - beego.Error("在保存团队时出错 ->", err) + logs.Error("在保存团队时出错 ->", err) } 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() if err != nil { - beego.Error("删除团队用户时出错 ->", err) + logs.Error("删除团队用户时出错 ->", err) } return } @@ -160,7 +160,7 @@ func (m *TeamMember) FindToPager(teamId, pageIndex, pageSize int) (list []*TeamM if err != nil { if err != orm.ErrNoRows { - beego.Error("查询团队成员失败 ->", err) + logs.Error("查询团队成员失败 ->", err) } return } @@ -217,7 +217,7 @@ limit ?;` _, err := o.Raw(sql, teamId, "%"+account+"%", "%"+account+"%", limit).QueryRows(&members) if err != nil { - beego.Error("查询团队用户时出错 ->", err) + logs.Error("查询团队用户时出错 ->", 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) if err != nil { - beego.Error("查询用户项目所在团队失败 ->bookId=", bookId, " memberId=", memberId, err) + logs.Error("查询用户项目所在团队失败 ->bookId=", bookId, " memberId=", memberId, err) return nil, err } return m, nil diff --git a/models/TeamRelationship.go b/models/TeamRelationship.go index 4b6fd6db..1d30fd23 100644 --- a/models/TeamRelationship.go +++ b/models/TeamRelationship.go @@ -2,9 +2,9 @@ package models import ( "errors" + "github.com/astaxie/beego/logs" "time" - "github.com/astaxie/beego" "github.com/astaxie/beego/orm" "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...) if err != nil { - beego.Error("查询项目团队失败 ->", err) + logs.Error("查询项目团队失败 ->", 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) if err != nil { - beego.Error("查询项目团队失败 ->", err) + logs.Error("查询项目团队失败 ->", 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 { err := m.QueryTable().Filter("team_id", teamId).Filter("book_id", bookId).One(m) if err != nil { - beego.Error("查询项目团队失败 ->", err) + logs.Error("查询项目团队失败 ->", err) return err } m.Include() @@ -95,7 +95,7 @@ func (m *TeamRelationship) Save(cols ...string) (err error) { _, err = orm.NewOrm().Insert(m) } if err != nil { - beego.Error("保存团队项目时出错 ->", err) + logs.Error("保存团队项目时出错 ->", err) } return } @@ -107,7 +107,7 @@ func (m *TeamRelationship) Delete(teamRelId int) (err error) { _, err = m.QueryTable().Filter("team_relationship_id", teamRelId).Delete() if err != nil { - beego.Error("删除团队项目失败 ->", err) + logs.Error("删除团队项目失败 ->", err) } 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) if err != nil { - beego.Error("查询团队项目时出错 ->", err) + logs.Error("查询团队项目时出错 ->", err) return } count, err := m.QueryTable().Filter("team_id", teamId).Count() if err != nil { - beego.Error("查询团队项目时出错 ->", err) + logs.Error("查询团队项目时出错 ->", err) return } totalCount = int(count) @@ -162,8 +162,8 @@ func (m *TeamRelationship) Include() (*TeamRelationship, error) { } } } - if m.TeamId > 0{ - team ,err := NewTeam().First(m.TeamId) + if m.TeamId > 0 { + team, err := NewTeam().First(m.TeamId) if err == nil { m.TeamName = team.TeamName 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) if err != nil { - beego.Error("查询团队项目时出错 ->", err) + logs.Error("查询团队项目时出错 ->", err) return nil, err } @@ -224,7 +224,7 @@ order by team.team_id desc limit ?;` _, err := o.Raw(sql, bookId, "%"+teamName+"%", limit).QueryRows(&teams) if err != nil { - beego.Error("查询团队项目时出错 ->", err) + logs.Error("查询团队项目时出错 ->", 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) if err != nil { - beego.Error("查询团队项目时出错 ->", err) + logs.Error("查询团队项目时出错 ->", err) return } count, err := m.QueryTable().Filter("book_id", bookId).Count() if err != nil { - beego.Error("查询团队项目时出错 ->", err) + logs.Error("查询团队项目时出错 ->", err) return } totalCount = int(count) diff --git a/models/Template.go b/models/Template.go index 48625f0e..a5b61059 100644 --- a/models/Template.go +++ b/models/Template.go @@ -4,27 +4,26 @@ import ( "errors" "time" - "github.com/astaxie/beego" "github.com/astaxie/beego/logs" "github.com/astaxie/beego/orm" "github.com/mindoc-org/mindoc/conf" ) type Template struct { - TemplateId int `orm:"column(template_id);pk;auto;unique;" json:"template_id"` - TemplateName string `orm:"column(template_name);size(500);" json:"template_name"` - MemberId int `orm:"column(member_id);index" json:"member_id"` - BookId int `orm:"column(book_id);index" json:"book_id"` - BookName string `orm:"-" json:"book_name"` + TemplateId int `orm:"column(template_id);pk;auto;unique;" json:"template_id"` + TemplateName string `orm:"column(template_name);size(500);" json:"template_name"` + MemberId int `orm:"column(member_id);index" json:"member_id"` + BookId int `orm:"column(book_id);index" json:"book_id"` + BookName string `orm:"-" json:"book_name"` //是否是全局模板:0 否/1 是; 全局模板在所有项目中都可以使用;否则只能在创建模板的项目中使用 - IsGlobal int `orm:"column(is_global);default(0)" json:"is_global"` - 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"` - CreateName string `orm:"-" json:"create_name"` - ModifyTime time.Time `orm:"column(modify_time);type(datetime);auto_now" json:"modify_time"` - ModifyAt int `orm:"column(modify_at);type(int)" json:"-"` - ModifyName string `orm:"-" json:"modify_name"` - Version int64 `orm:"type(bigint);column(version)" json:"version"` + IsGlobal int `orm:"column(is_global);default(0)" json:"is_global"` + 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"` + CreateName string `orm:"-" json:"create_name"` + ModifyTime time.Time `orm:"column(modify_time);type(datetime);auto_now" json:"modify_time"` + ModifyAt int `orm:"column(modify_at);type(int)" json:"-"` + ModifyName string `orm:"-" json:"modify_name"` + Version int64 `orm:"type(bigint);column(version)" json:"version"` } // TableName 获取对应数据库表名. @@ -41,82 +40,83 @@ func (m *Template) TableNameWithPrefix() string { return conf.GetDatabasePrefix() + m.TableName() } -func NewTemplate() *Template { +func NewTemplate() *Template { return &Template{} } //查询指定ID的模板 -func (t *Template) Find(templateId int) (*Template,error) { +func (t *Template) Find(templateId int) (*Template, error) { if templateId <= 0 { return t, ErrInvalidParameter } 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 { - 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 { - return nil,ErrInvalidParameter + return nil, ErrInvalidParameter } o := orm.NewOrm() 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 { - 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 { - return nil,ErrInvalidParameter + return nil, ErrInvalidParameter } o := orm.NewOrm() 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()) var templateList []*Template - _,err := qs.SetCond(cond1).OrderBy("-template_id").All(&templateList) + _, err := qs.SetCond(cond1).OrderBy("-template_id").All(&templateList) 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 { return ErrInvalidParameter } o := orm.NewOrm() - qs := o.QueryTable(t.TableNameWithPrefix()).Filter("template_id",templateId) + qs := o.QueryTable(t.TableNameWithPrefix()).Filter("template_id", templateId) if memberId > 0 { - qs = qs.Filter("member_id",memberId) + qs = qs.Filter("member_id", memberId) } - _,err := qs.Delete() + _, err := qs.Delete() if err != nil { - beego.Error("删除模板失败 ->",err) + logs.Error("删除模板失败 ->", err) } return err } @@ -129,20 +129,20 @@ func (t *Template) Save(cols ...string) (err error) { } 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("项目不存在") } - 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("用户已被禁用") } t.Version = time.Now().Unix() if t.TemplateId > 0 { t.ModifyTime = time.Now() - _,err = o.Update(t,cols...) - }else{ + _, err = o.Update(t, cols...) + } else { t.CreateTime = time.Now() - _,err = o.Insert(t) + _, err = o.Insert(t) } return @@ -152,36 +152,31 @@ func (t *Template) Save(cols ...string) (err error) { func (t *Template) Preload() *Template { if t != nil { 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 m.RealName != "" { t.CreateName = m.RealName - }else{ + } else { t.CreateName = m.Account } - }else{ - beego.Error("加载模板所有者失败 ->",err) + } else { + logs.Error("加载模板所有者失败 ->", err) } } 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 != "" { t.ModifyName = m.RealName - }else{ + } else { t.ModifyName = m.Account } } } 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 } } } return t } - - - - - diff --git a/utils/ldap.go b/utils/ldap.go index b5af6605..e4a11db4 100644 --- a/utils/ldap.go +++ b/utils/ldap.go @@ -3,7 +3,7 @@ package utils import ( "errors" "fmt" - "github.com/astaxie/beego" + "github.com/astaxie/beego/logs" "gopkg.in/ldap.v2" ) @@ -24,14 +24,14 @@ func ValidLDAPLogin(password string) (result bool, err error) { err = nil lc, err := ldap.Dial("tcp", fmt.Sprintf("%s:%d", "192.168.3.104", 389)) if err != nil { - beego.Error("Dial => ", err) + logs.Error("Dial => ", err) return } defer lc.Close() err = lc.Bind("cn=admin,dc=minho,dc=com", "123456") if err != nil { - beego.Error("Bind => ", err) + logs.Error("Bind => ", err) return } searchRequest := ldap.NewSearchRequest( @@ -43,7 +43,7 @@ func ValidLDAPLogin(password string) (result bool, err error) { ) searchResult, err := lc.Search(searchRequest) if err != nil { - beego.Error("Search => ", err) + logs.Error("Search => ", err) return } if len(searchResult.Entries) != 1 { @@ -58,7 +58,7 @@ func ValidLDAPLogin(password string) (result bool, err error) { if err == nil { result = true } else { - beego.Error("Bind2 => ", err) + logs.Error("Bind2 => ", err) err = nil } return @@ -67,7 +67,7 @@ func ValidLDAPLogin(password string) (result bool, err error) { func AddMember(account, password string) error { lc, err := ldap.Dial("tcp", fmt.Sprintf("%s:%d", "192.168.3.104", 389)) if err != nil { - beego.Error("Dial => ", err) + logs.Error("Dial => ", err) return err } @@ -84,33 +84,33 @@ func AddMember(account, password string) error { err = lc.Bind(user, "") if err != nil { - beego.Error("Bind => ", err) + logs.Error("Bind => ", err) return err } passwordModifyRequest := ldap.NewPasswordModifyRequest(user, "", "1q2w3e__ABC") _, err = lc.PasswordModify(passwordModifyRequest) if err != nil { - beego.Error("PasswordModify => ", err) + logs.Error("PasswordModify => ", err) return err } return nil } - beego.Error("Add => ", err) + logs.Error("Add => ", err) return err } func ModifyPassword(account, old_password, new_password string) error { l, err := ldap.Dial("tcp", fmt.Sprintf("%s:%d", "192.168.3.104", 389)) if err != nil { - beego.Error("Dial => ", err) + logs.Error("Dial => ", err) } defer l.Close() user := fmt.Sprintf("cn=%s,dc=minho,dc=com", account) err = l.Bind(user, old_password) if err != nil { - beego.Error("Bind => ", err) + logs.Error("Bind => ", err) return err } @@ -118,7 +118,7 @@ func ModifyPassword(account, old_password, new_password string) error { _, err = l.PasswordModify(passwordModifyRequest) 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 nil From 1239620f756cee655b3cd184bc4587f037ee8cde Mon Sep 17 00:00:00 2001 From: shiqstone Date: Tue, 30 Mar 2021 16:18:02 +0800 Subject: [PATCH 08/32] refactor and add i18n, to be continue --- commands/command.go | 24 +++--- conf/lang/en-us.ini | 54 ++++++++++++- conf/lang/zh-cn.ini | 50 ++++++++++++ controllers/AccountController.go | 111 ++++++++++++-------------- controllers/BaseController.go | 48 +++++++---- views/account/find_password_setp1.tpl | 20 ++--- views/account/find_password_setp2.tpl | 28 +++---- views/account/login.tpl | 32 ++++---- views/widgets/footer.tpl | 8 +- 9 files changed, 240 insertions(+), 135 deletions(-) diff --git a/commands/command.go b/commands/command.go index e03649ab..dae5c1a3 100644 --- a/commands/command.go +++ b/commands/command.go @@ -163,40 +163,40 @@ func RegisterLogger(log string) { if level := beego.AppConfig.DefaultString("log_level", "Trace"); level != "" { switch level { case "Emergency": - config["level"] = beego.LevelEmergency + config["level"] = logs.LevelEmergency break case "Alert": - config["level"] = beego.LevelAlert + config["level"] = logs.LevelAlert break case "Critical": - config["level"] = beego.LevelCritical + config["level"] = logs.LevelCritical break case "Error": - config["level"] = beego.LevelError + config["level"] = logs.LevelError break case "Warning": - config["level"] = beego.LevelWarning + config["level"] = logs.LevelWarning break case "Notice": - config["level"] = beego.LevelNotice + config["level"] = logs.LevelNotice break case "Informational": - config["level"] = beego.LevelInformational + config["level"] = logs.LevelInformational break case "Debug": - config["level"] = beego.LevelDebug + config["level"] = logs.LevelDebug break } } b, err := json.Marshal(config) if err != nil { logs.Error("初始化文件日志时出错 ->", err) - _ = beego.SetLogger("file", `{"filename":"`+logPath+`"}`) + _ = logs.SetLogger("file", `{"filename":"`+logPath+`"}`) } else { - _ = beego.SetLogger(logs.AdapterFile, string(b)) + _ = logs.SetLogger(logs.AdapterFile, string(b)) } - beego.SetLogFuncCall(true) + logs.SetLogFuncCall(true) } // RunCommand 注册orm命令行工具 @@ -454,7 +454,7 @@ func RegisterCache() { } else { cache.Init(&cache.NullCache{}) - beego.Warn("不支持的缓存管道,缓存将禁用 ->", cacheProvider) + logs.Warn("不支持的缓存管道,缓存将禁用 ->", cacheProvider) return } logs.Info("缓存初始化完成.") diff --git a/conf/lang/en-us.ini b/conf/lang/en-us.ini index 8474fdc6..77eda9b8 100644 --- a/conf/lang/en-us.ini +++ b/conf/lang/en-us.ini @@ -7,8 +7,58 @@ person_center = Persona Center my_project = My Project my_blog = My Article manage = Management -login = Login -logout = Logout +login = Log In +logout = Log Out +official_website = Official Website +feedback = Feedback +source_code = Source Code +manual = Manual +username = Username +email = Email +password = Password +captcha = Captcha +keep_login = Stay signed in +forgot_password = Forgot password? +register = Create New Account +dingtalk_login = DingTalk QrCode login +account_recovery = Account recovery +new_password = New password +confirm_password = Confirm password [message] keyword_placeholder = input keyword please... +wrong_account_password = Incorrect username or password +click_to_change = Click to change one +logging_in = logging in... +return_account_login = Return account password login +no_account_yet = No account yet? +account_empty = Account cannot be empty +email_empty = Email cannot be empty +password_empty = Password cannot be empty +captcha_empty = Captcha cannot be empty +system_error = System error +processing = Processing... +email_sent = The email is sent successfully, please log in to check it. +password_empty = Confirm password cannot be empty +incorrect_confirm_password = Incorrect confirm password +illegal_request = Illegal request +account_or_password_empty = Account or Password cannot be empty +captcha_wrong = Incorrect captcha +password_length_invalid = The password cannot be empty and must be between 6-50 characters +mail_expired = Mail has expired +captcha_expired = The verification code has expired, please try again. +user_not_existed = User does not exist +email_not_exist = Email does not exist +failed_save_password = Failed to save password +mail_service_not_enable = Mail service is not enabled +account_disable = Account has been disabled +failed_send_mail = Failed to send mail +sent_too_many_times = Send too many times, please try again later +account_not_support_retrieval = The current user does not support password retrieval +username_invalid_format = The account number can only be composed of English alphanumerics and 3-50 characters +email_invalid_format = Email format is incorrect +account_existed = Username already existed +failed_register = Registration failed, please contact the system administrator +failed_obtain_user_info = Failed to obtain identity information +dingtalk_auto_login_not_enable = DingTalk automatic login function is not enabled +failed_auto_login = Automatic login failed \ No newline at end of file diff --git a/conf/lang/zh-cn.ini b/conf/lang/zh-cn.ini index fbc45fe9..b4161a2d 100644 --- a/conf/lang/zh-cn.ini +++ b/conf/lang/zh-cn.ini @@ -9,6 +9,56 @@ my_blog = 我的文章 manage = 管理后台 login = 登录 logout = 退出登录 +official_website = 官方网站 +feedback = 意见反馈 +source_code = 项目源码 +manual = 使用手册 +username = 用户名 +email = 邮箱 +password = 密码 +captcha = 验证码 +keep_login = 保持登录 +forgot_password = 忘记密码? +register = 立即注册 +dingtalk_login = 扫码登录 +account_recovery = 找回密码 +new_password = 新密码 +confirm_password = 确认密码 [message] keyword_placeholder = 请输入关键词... +wrong_account_password = 账号或密码错误 +click_to_change = 点击换一张 +logging_in = 正在登录... +return_account_login = 返回账号密码登录 +no_account_yet = 还没有账号? +account_empty = 账号不能为空 +email_empty = 邮箱不能为空 +password_empty = 密码不能为空 +captcha_empty = 验证码不能为空 +system_error = 系统错误 +processing = 正在处理... +email_sent = 邮件发送成功,请登录邮箱查看。 +confirm_password_empty = 确认密码不能为空 +incorrect_confirm_password = 确认密码输入不正确 +illegal_request = 非法请求 +account_or_password_empty = 账号或密码不能为空 +captcha_wrong = 验证码不正确 +password_length_invalid = 密码不能为空且必须在6-50个字符之间 +mail_expired = 邮件已失效 +captcha_expired = 验证码已过期,请重新操作。 +user_not_existed = 用户不存在 +email_not_exist = 邮箱不存在 +failed_save_password = 保存密码失败 +mail_service_not_enable = 未启用邮件服务 +account_disable = 账号已被禁用 +failed_send_mail = 发送邮件失败 +sent_too_many_times = 发送次数太多,请稍候再试 +account_not_support_retrieval = 当前用户不支持找回密码 +username_invalid_format = 账号只能由英文字母数字组成,且在3-50个字符 +email_invalid_format = 邮箱格式不正确 +account_existed = 账号已存在 +failed_register = 注册失败,请联系管理员 +failed_obtain_user_info = 获取身份信息失败 +dingtalk_auto_login_not_enable = 未开启钉钉自动登录功能 +failed_auto_login = 自动登录失败 \ No newline at end of file diff --git a/controllers/AccountController.go b/controllers/AccountController.go index 69858e5d..b0e975d7 100644 --- a/controllers/AccountController.go +++ b/controllers/AccountController.go @@ -54,17 +54,17 @@ func (c *AccountController) Prepare() { } if token == "" { if c.IsAjax() { - c.JsonResult(403, "非法请求") + c.JsonResult(403, i18n.Tr(c.Lang, "message.illegal_request")) } else { - c.ShowErrorPage(403, "非法请求") + c.ShowErrorPage(403, i18n.Tr(c.Lang, "message.illegal_request")) } } xsrfToken := c.XSRFToken() if xsrfToken != token { if c.IsAjax() { - c.JsonResult(403, "非法请求") + c.JsonResult(403, i18n.Tr(c.Lang, "message.illegal_request")) } else { - c.ShowErrorPage(403, "非法请求") + c.ShowErrorPage(403, i18n.Tr(c.Lang, "message.illegal_request")) } } } @@ -108,12 +108,12 @@ func (c *AccountController) Login() { if v, ok := c.Option["ENABLED_CAPTCHA"]; ok && strings.EqualFold(v, "true") { v, ok := c.GetSession(conf.CaptchaSessionName).(string) if !ok || !strings.EqualFold(v, captcha) { - c.JsonResult(6001, "验证码不正确") + c.JsonResult(6001, i18n.Tr(c.Lang, "message.captcha_wrong")) } } if account == "" || password == "" { - c.JsonResult(6002, "账号或密码不能为空") + c.JsonResult(6002, i18n.Tr(c.Lang, "message.account_or_password_empty")) } member, err := models.NewMember().Login(account, password) @@ -149,7 +149,7 @@ func (c *AccountController) DingTalkLogin() { code := c.GetString("dingtalk_code") if code == "" { - c.JsonResult(500, "获取身份信息失败", nil) + c.JsonResult(500, i18n.Tr(c.Lang, "message.failed_obtain_user_info"), nil) } appKey := beego.AppConfig.String("dingtalk_app_key") @@ -157,29 +157,29 @@ func (c *AccountController) DingTalkLogin() { tmpReader := beego.AppConfig.String("dingtalk_tmp_reader") if appKey == "" || appSecret == "" || tmpReader == "" { - c.JsonResult(500, "未开启钉钉自动登录功能", nil) + c.JsonResult(500, i18n.Tr(c.Lang, "message.dingtalk_auto_login_not_enable"), nil) c.StopRun() } dingtalkAgent := dingtalk.NewDingTalkAgent(appSecret, appKey) err := dingtalkAgent.GetAccesstoken() if err != nil { - beego.Warn("获取钉钉临时Token失败 ->", err) - c.JsonResult(500, "自动登录失败", nil) + logs.Warn("获取钉钉临时Token失败 ->", err) + c.JsonResult(500, i18n.Tr(c.Lang, "message.failed_auto_login"), nil) c.StopRun() } userid, err := dingtalkAgent.GetUserIDByCode(code) if err != nil { - beego.Warn("获取钉钉用户ID失败 ->", err) - c.JsonResult(500, "自动登录失败", nil) + logs.Warn("获取钉钉用户ID失败 ->", err) + c.JsonResult(500, i18n.Tr(c.Lang, "message.failed_auto_login"), nil) c.StopRun() } username, avatar, err := dingtalkAgent.GetUserNameAndAvatarByUserID(userid) if err != nil { - beego.Warn("获取钉钉用户信息失败 ->", err) - c.JsonResult(500, "自动登录失败", nil) + logs.Warn("获取钉钉用户信息失败 ->", err) + c.JsonResult(500, i18n.Tr(c.Lang, "message.failed_auto_login"), nil) c.StopRun() } @@ -218,7 +218,7 @@ func (c *AccountController) QRLogin() { qrDingtalk := dingtalk.NewDingtalkQRLogin(appSecret, appKey) unionID, err := qrDingtalk.GetUnionIDByCode(code) if err != nil { - beego.Warn("获取钉钉临时UnionID失败 ->", err) + logs.Warn("获取钉钉临时UnionID失败 ->", err) c.Redirect(conf.URLFor("AccountController.Login"), 302) c.StopRun() } @@ -230,21 +230,21 @@ func (c *AccountController) QRLogin() { dingtalkAgent := dingtalk.NewDingTalkAgent(appSecret, appKey) err = dingtalkAgent.GetAccesstoken() if err != nil { - beego.Warn("获取钉钉临时Token失败 ->", err) + logs.Warn("获取钉钉临时Token失败 ->", err) c.Redirect(conf.URLFor("AccountController.Login"), 302) c.StopRun() } userid, err := dingtalkAgent.GetUserIDByUnionID(unionID) if err != nil { - beego.Warn("获取钉钉用户ID失败 ->", err) + logs.Warn("获取钉钉用户ID失败 ->", err) c.Redirect(conf.URLFor("AccountController.Login"), 302) c.StopRun() } username, avatar, err := dingtalkAgent.GetUserNameAndAvatarByUserID(userid) if err != nil { - beego.Warn("获取钉钉用户信息失败 ->", err) + logs.Warn("获取钉钉用户信息失败 ->", err) c.Redirect(conf.URLFor("AccountController.Login"), 302) c.StopRun() } @@ -308,29 +308,29 @@ func (c *AccountController) Register() { captcha := c.GetString("code") if ok, err := regexp.MatchString(conf.RegexpAccount, account); account == "" || !ok || err != nil { - c.JsonResult(6001, "账号只能由英文字母数字组成,且在3-50个字符") + c.JsonResult(6001, i18n.Tr(c.Lang, "message.username_invalid_format")) } if l := strings.Count(password1, ""); password1 == "" || l > 50 || l < 6 { - c.JsonResult(6002, "密码必须在6-50个字符之间") + c.JsonResult(6002, i18n.Tr(c.Lang, "message.password_length_invalid")) } if password1 != password2 { - c.JsonResult(6003, "确认密码不正确") + c.JsonResult(6003, i18n.Tr(c.Lang, "message.incorrect_confirm_password")) } if ok, err := regexp.MatchString(conf.RegexpEmail, email); !ok || err != nil || email == "" { - c.JsonResult(6004, "邮箱格式不正确") + c.JsonResult(6004, i18n.Tr(c.Lang, "message.email_invalid_format")) } // 如果开启了验证码 if v, ok := c.Option["ENABLED_CAPTCHA"]; ok && strings.EqualFold(v, "true") { v, ok := c.GetSession(conf.CaptchaSessionName).(string) if !ok || !strings.EqualFold(v, captcha) { - c.JsonResult(6001, "验证码不正确") + c.JsonResult(6001, i18n.Tr(c.Lang, "message.captcha_wrong")) } } member := models.NewMember() if _, err := member.FindByAccount(account); err == nil && member.MemberId > 0 { - c.JsonResult(6005, "账号已存在") + c.JsonResult(6005, i18n.Tr(c.Lang, "message.account_existed")) } member.Account = account @@ -341,7 +341,7 @@ func (c *AccountController) Register() { member.Email = email member.Status = 0 if err := member.Add(); err != nil { - c.JsonResult(6006, "注册失败,请联系系统管理员处理") + c.JsonResult(6006, i18n.Tr(c.Lang, "message.failed_register")) } c.JsonResult(0, "ok", member) @@ -359,39 +359,39 @@ func (c *AccountController) FindPassword() { captcha := c.GetString("code") if email == "" { - c.JsonResult(6005, "邮箱地址不能为空") + c.JsonResult(6005, i18n.Tr(c.Lang, "message.email_empty")) } if !mailConf.EnableMail { - c.JsonResult(6004, "未启用邮件服务") + c.JsonResult(6004, i18n.Tr(c.Lang, "message.mail_service_not_enable")) } // 如果开启了验证码 if v, ok := c.Option["ENABLED_CAPTCHA"]; ok && strings.EqualFold(v, "true") { v, ok := c.GetSession(conf.CaptchaSessionName).(string) if !ok || !strings.EqualFold(v, captcha) { - c.JsonResult(6001, "验证码不正确") + c.JsonResult(6001, i18n.Tr(c.Lang, "message.captcha_wrong")) } } member, err := models.NewMember().FindByFieldFirst("email", email) if err != nil { - c.JsonResult(6006, "邮箱不存在") + c.JsonResult(6006, i18n.Tr(c.Lang, "message.email_not_exist")) } - if member.Status != 0 { - c.JsonResult(6007, "账号已被禁用") + if member == nil || member.Status != 0 { + c.JsonResult(6007, i18n.Tr(c.Lang, "message.account_disable")) } - if member.AuthMethod == conf.AuthMethodLDAP { - c.JsonResult(6011, "当前用户不支持找回密码") + if member == nil || member.AuthMethod == conf.AuthMethodLDAP { + c.JsonResult(6011, i18n.Tr(c.Lang, "message.account_not_support_retrieval")) } count, err := models.NewMemberToken().FindSendCount(email, time.Now().Add(-1*time.Hour), time.Now()) if err != nil { logs.Error(err) - c.JsonResult(6008, "发送邮件失败") + c.JsonResult(6008, i18n.Tr(c.Lang, "message.failed_send_mail")) } if count > mailConf.MailNumber { - c.JsonResult(6008, "发送次数太多,请稍候再试") + c.JsonResult(6008, i18n.Tr(c.Lang, "message.sent_too_many_times")) } memberToken := models.NewMemberToken() @@ -401,7 +401,7 @@ func (c *AccountController) FindPassword() { memberToken.MemberId = member.MemberId memberToken.IsValid = false if _, err := memberToken.InsertOrUpdate(); err != nil { - c.JsonResult(6009, "邮件发送失败") + c.JsonResult(6009, i18n.Tr(c.Lang, "message.failed_send_mail")) } data := map[string]interface{}{ @@ -413,7 +413,7 @@ func (c *AccountController) FindPassword() { body, err := c.ExecuteViewPathTemplate("account/mail_template.tpl", data) if err != nil { logs.Error(err) - c.JsonResult(6003, "邮件发送失败") + c.JsonResult(6003, i18n.Tr(c.Lang, "message.failed_send_mail")) } go func(mailConf *conf.SmtpConf, email string, body string) { @@ -472,17 +472,16 @@ func (c *AccountController) FindPassword() { if token != "" && email != "" { memberToken, err := models.NewMemberToken().FindByFieldFirst("token", token) - if err != nil { logs.Error(err) - c.Data["ErrorMessage"] = "邮件已失效" + c.Data["ErrorMessage"] = i18n.Tr(c.Lang, "message.mail_expired") c.TplName = "errors/error.tpl" return } subTime := memberToken.SendTime.Sub(time.Now()) if !strings.EqualFold(memberToken.Email, email) || subTime.Minutes() > float64(mailConf.MailExpired) || !memberToken.ValidTime.IsZero() { - c.Data["ErrorMessage"] = "验证码已过期,请重新操作。" + c.Data["ErrorMessage"] = i18n.Tr(c.Lang, "message.captcha_expired") c.TplName = "errors/error.tpl" return } @@ -503,48 +502,46 @@ func (c *AccountController) ValidEmail() { email := c.GetString("mail") if password1 == "" { - c.JsonResult(6001, "密码不能为空") + c.JsonResult(6001, i18n.Tr(c.Lang, "message.password_empty")) } if l := strings.Count(password1, ""); l < 6 || l > 50 { - c.JsonResult(6001, "密码不能为空且必须在6-50个字符之间") + c.JsonResult(6001, i18n.Tr(c.Lang, "message.password_length_invalid")) } if password2 == "" { - c.JsonResult(6002, "确认密码不能为空") + c.JsonResult(6002, i18n.Tr(c.Lang, "message.confirm_password_empty")) } if password1 != password2 { - c.JsonResult(6003, "确认密码输入不正确") + c.JsonResult(6003, i18n.Tr(c.Lang, "message.incorrect_confirm_password")) } if captcha == "" { - c.JsonResult(6004, "验证码不能为空") + c.JsonResult(6004, i18n.Tr(c.Lang, "message.captcha_empty")) } v, ok := c.GetSession(conf.CaptchaSessionName).(string) if !ok || !strings.EqualFold(v, captcha) { - c.JsonResult(6001, "验证码不正确") + c.JsonResult(6001, i18n.Tr(c.Lang, "message.captcha_wrong")) } mailConf := conf.GetMailConfig() memberToken, err := models.NewMemberToken().FindByFieldFirst("token", token) - if err != nil { logs.Error(err) - c.JsonResult(6007, "邮件已失效") + c.JsonResult(6007, i18n.Tr(c.Lang, "message.mail_expired")) } subTime := memberToken.SendTime.Sub(time.Now()) if !strings.EqualFold(memberToken.Email, email) || subTime.Minutes() > float64(mailConf.MailExpired) || !memberToken.ValidTime.IsZero() { - c.JsonResult(6008, "验证码已过期,请重新操作。") + c.JsonResult(6008, i18n.Tr(c.Lang, "message.captcha_expired")) } member, err := models.NewMember().Find(memberToken.MemberId) if err != nil { logs.Error(err) - c.JsonResult(6005, "用户不存在") + c.JsonResult(6005, i18n.Tr(c.Lang, "message.user_not_existed")) } hash, err := utils.PasswordHash(password1) - if err != nil { logs.Error(err) - c.JsonResult(6006, "保存密码失败") + c.JsonResult(6006, i18n.Tr(c.Lang, "message.failed_save_password")) } member.Password = hash @@ -556,7 +553,7 @@ func (c *AccountController) ValidEmail() { if err != nil { logs.Error(err) - c.JsonResult(6006, "保存密码失败") + c.JsonResult(6006, i18n.Tr(c.Lang, "message.failed_save_password")) } c.JsonResult(0, "ok", conf.URLFor("AccountController.Login")) } @@ -564,11 +561,8 @@ func (c *AccountController) ValidEmail() { // Logout 退出登录 func (c *AccountController) Logout() { c.SetMember(models.Member{}) - c.SetSecureCookie(conf.GetAppKey(), "login", "", -3600) - u := c.Ctx.Request.Header.Get("Referer") - c.Redirect(conf.URLFor("AccountController.Login", "url", u), 302) } @@ -578,11 +572,6 @@ func (c *AccountController) Captcha() { captchaImage := gocaptcha.NewCaptchaImage(140, 40, gocaptcha.RandLightColor()) - //if err != nil { - // logs.Error(err) - // c.Abort("500") - //} - captchaImage.DrawNoise(gocaptcha.CaptchaComplexLower) // captchaImage.DrawTextNoise(gocaptcha.CaptchaComplexHigh) diff --git a/controllers/BaseController.go b/controllers/BaseController.go index e1cfb4f4..82ae8332 100644 --- a/controllers/BaseController.go +++ b/controllers/BaseController.go @@ -2,9 +2,9 @@ package controllers import ( "bytes" - "github.com/beego/i18n" - "encoding/json" + "github.com/astaxie/beego/logs" + "github.com/beego/i18n" "io" "strings" "time" @@ -24,6 +24,7 @@ type BaseController struct { Option map[string]string EnableAnonymous bool EnableDocumentHistory bool + Lang string } type CookieRemember struct { @@ -45,7 +46,6 @@ func (c *BaseController) Prepare() { c.EnableDocumentHistory = false if member, ok := c.GetSession(conf.LoginSessionName).(models.Member); ok && member.MemberId > 0 { - c.Member = &member c.Data["Member"] = c.Member } else { @@ -78,13 +78,8 @@ func (c *BaseController) Prepare() { if b, err := ioutil.ReadFile(filepath.Join(beego.BConfig.WebConfig.ViewsPath, "widgets", "scripts.tpl")); err == nil { c.Data["Scripts"] = template.HTML(string(b)) } - lang := c.Input().Get("lang") - if len(lang) == 0 || - !i18n.IsExist(lang) { - lang = "zh-cn" - } - c.Data["Lang"] = lang + c.SetLang() } //判断用户是否登录. @@ -117,14 +112,16 @@ func (c *BaseController) JsonResult(errCode int, errMsg string, data ...interfac } returnJSON, err := json.Marshal(jsonData) - 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("Cache-Control", "no-cache, no-store") - io.WriteString(c.Ctx.ResponseWriter, string(returnJSON)) + _, err = io.WriteString(c.Ctx.ResponseWriter, string(returnJSON)) + if err != nil { + logs.Error(err) + } c.StopRun() } @@ -141,14 +138,16 @@ func (c *BaseController) CheckJsonError(code int, err error) { jsonData["message"] = err.Error() returnJSON, err := json.Marshal(jsonData) - 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("Cache-Control", "no-cache, no-store") - io.WriteString(c.Ctx.ResponseWriter, string(returnJSON)) + _, err = io.WriteString(c.Ctx.ResponseWriter, string(returnJSON)) + if err != nil { + logs.Error(err) + } c.StopRun() } @@ -201,9 +200,26 @@ func (c *BaseController) ShowErrorPage(errCode int, errMsg string) { } } - func (c *BaseController) CheckErrorResult(code int, err error) { if err != nil { c.ShowErrorPage(code, err.Error()) } } + +func (c *BaseController) SetLang() { + hasCookie := false + lang := c.Input().Get("lang") + if len(lang) == 0 { + lang = c.Ctx.GetCookie("lang") + hasCookie = true + } + if len(lang) == 0 || + !i18n.IsExist(lang) { + lang = beego.AppConfig.String("default_lang") + } + if !hasCookie { + c.Ctx.SetCookie("lang", lang, 1<<31-1, "/") + } + c.Data["Lang"] = lang + c.Lang = lang +} diff --git a/views/account/find_password_setp1.tpl b/views/account/find_password_setp1.tpl index 3771e89d..bd723ff4 100644 --- a/views/account/find_password_setp1.tpl +++ b/views/account/find_password_setp1.tpl @@ -7,7 +7,7 @@ - 找回密码 - Powered by MinDoc + {{i18n .Lang "common.account_recovery"}} - Powered by MinDoc @@ -35,13 +35,13 @@
    - +
    @@ -88,7 +88,7 @@ var email = $.trim($("#email").val()); if(email === ""){ - $("#email").tooltip({placement:"auto",title : "邮箱不能为空",trigger : 'manual'}) + $("#email").tooltip({placement:"auto",title : "{{i18n .Lang "message.email_empty"}}",trigger : 'manual'}) .tooltip('show') .parents('.form-group').addClass('has-error'); $btn.button('reset'); @@ -97,7 +97,7 @@ } var code = $.trim($("#code").val()); if(code === ""){ - $("#code").tooltip({title : '验证码不能为空',trigger : 'manual'}) + $("#code").tooltip({title : '{{i18n .Lang "message.captcha_empty"}}',trigger : 'manual'}) .tooltip('show') .parents('.form-group').addClass('has-error'); $btn.button('reset'); @@ -113,14 +113,14 @@ layer.msg(res.message); $("#btnSendMail").button('reset'); }else{ - alert("邮件发送成功,请登录邮箱查看。") + alert("{{i18n .Lang "message.email_sent"}}") window.location = res.data; } }, error :function () { $("#captcha-img").click(); $("#code").val(''); - layer.msg('系统错误'); + layer.msg('{{i18n .Lang "message.system_error"}}'); $("#btnSendMail").button('reset'); } }); diff --git a/views/account/find_password_setp2.tpl b/views/account/find_password_setp2.tpl index b57e3876..16d78e56 100644 --- a/views/account/find_password_setp2.tpl +++ b/views/account/find_password_setp2.tpl @@ -6,8 +6,8 @@ - - 找回密码 - Powered by MinDoc + + {{i18n .Lang "common.account_recovery"}} - Powered by MinDoc @@ -37,14 +37,14 @@ {{ .xsrfdata }} -

    找回密码

    +

    {{i18n .Lang "common.account_recovery"}}

    - - + +
    - - + +
    @@ -52,13 +52,13 @@
    -   +  
    - +
    @@ -92,26 +92,26 @@ var code = $.trim($("#code").val()); if(newPassword === ""){ - $("#newPassword").tooltip({placement:"auto",title : "密码不能为空",trigger : 'manual'}) + $("#newPassword").tooltip({placement:"auto",title : "{{i18n .Lang "message.password_empty"}}",trigger : 'manual'}) .tooltip('show') .parents('.form-group').addClass('has-error'); return false; }else if(confirmPassword === ""){ - $("#confirmPassword").tooltip({placement:"auto",title : "确认密码不能为空",trigger : 'manual'}) + $("#confirmPassword").tooltip({placement:"auto",title : "{{i18n .Lang "message.confirm_password_empty"}}",trigger : 'manual'}) .tooltip('show') .parents('.form-group').addClass('has-error'); return false; }else if(newPassword !== confirmPassword) { - $("#confirmPassword").tooltip({placement:"auto",title : "确认密码输入不正确",trigger : 'manual'}) + $("#confirmPassword").tooltip({placement:"auto",title : "{{i18n .Lang "message.incorrect_confirm_password"}}",trigger : 'manual'}) .tooltip('show') .parents('.form-group').addClass('has-error'); return false; }else if(code === ""){ - $("#code").tooltip({title : '验证码不能为空',trigger : 'manual'}) + $("#code").tooltip({title : '{{i18n .Lang "message.captcha_empty"}}',trigger : 'manual'}) .tooltip('show') .parents('.form-group').addClass('has-error'); @@ -134,7 +134,7 @@ error :function () { $("#captcha-img").click(); $("#code").val(''); - layer.msg('系统错误'); + layer.msg('{{i18n .Lang "message.system_error"}}'); $("#btnSendMail").button('reset'); } }); diff --git a/views/account/login.tpl b/views/account/login.tpl index 0a34c379..405f81d0 100644 --- a/views/account/login.tpl +++ b/views/account/login.tpl @@ -7,7 +7,7 @@ - 用户登录 - Powered by MinDoc + {{i18n .Lang "common.login"}} - Powered by MinDoc @@ -30,13 +30,13 @@ {{if .ENABLED_CAPTCHA }} @@ -54,38 +54,38 @@
    -   +   - +
    {{end}} {{end}}
    - 忘记密码? + {{i18n .Lang "common.forgot_password"}}
    - +
    {{if .ENABLE_QR_DINGTALK}} {{end}} {{if .ENABLED_REGISTER}} {{if ne .ENABLED_REGISTER "false"}}
    - 还没有账号?立即注册 + {{i18n .Lang "message.no_account_yet"}}{{i18n .Lang "common.register"}}
    {{end}} {{end}} @@ -196,19 +196,19 @@ var code = $("#code").val(); if (account === "") { - $("#account").tooltip({ placement: "auto", title: "账号不能为空", trigger: 'manual' }) + $("#account").tooltip({ placement: "auto", title: "{{i18n .Lang "message.account_empty"}}", trigger: 'manual' }) .tooltip('show') .parents('.form-group').addClass('has-error'); $btn.button('reset'); return false; } else if (password === "") { - $("#password").tooltip({ title: '密码不能为空', trigger: 'manual' }) + $("#password").tooltip({ title: '{{i18n .Lang "message.password_empty"}}', trigger: 'manual' }) .tooltip('show') .parents('.form-group').addClass('has-error'); $btn.button('reset'); return false; } else if (code !== undefined && code === "") { - $("#code").tooltip({ title: '验证码不能为空', trigger: 'manual' }) + $("#code").tooltip({ title: '{{i18n .Lang "message.captcha_empty"}}', trigger: 'manual' }) .tooltip('show') .parents('.form-group').addClass('has-error'); $btn.button('reset'); @@ -236,7 +236,7 @@ error: function () { $("#captcha-img").click(); $("#code").val(''); - layer.msg('系统错误'); + layer.msg('{{i18n .Lang "message.system_error"}}'); $btn.button('reset'); } }); diff --git a/views/widgets/footer.tpl b/views/widgets/footer.tpl index 6c638b73..54991e83 100644 --- a/views/widgets/footer.tpl +++ b/views/widgets/footer.tpl @@ -1,13 +1,13 @@
    - +
    {{if ne .ENABLED_REGISTER "false"}}
    - 已有账号?立即登录 + {{i18n .Lang "message.has_account"}} {{i18n .Lang "common.login"}}
    {{end}} @@ -117,28 +117,28 @@ var email = $.trim($("#email").val()); if(account === ""){ - $("#account").focus().tooltip({placement:"auto",title : "账号不能为空",trigger : 'manual'}) + $("#account").focus().tooltip({placement:"auto",title : "{{i18n .Lang "message.account_empty"}}",trigger : 'manual'}) .tooltip('show') .parents('.form-group').addClass('has-error'); return false; }else if(password === ""){ - $("#password").focus().tooltip({title : '密码不能为空',trigger : 'manual'}) + $("#password").focus().tooltip({title : '{{i18n .Lang "message.password_empty"}}',trigger : 'manual'}) .tooltip('show') .parents('.form-group').addClass('has-error'); return false; }else if(confirmPassword !== password){ - $("#confirm_password").focus().tooltip({title : '确认密码不正确',trigger : 'manual'}) + $("#confirm_password").focus().tooltip({title : '{{i18n .Lang "message.confirm_password_empty"}}',trigger : 'manual'}) .tooltip('show') .parents('.form-group').addClass('has-error'); return false; }else if(email === ""){ - $("#email").focus().tooltip({title : '邮箱不能为空',trigger : 'manual'}) + $("#email").focus().tooltip({title : '{{i18n .Lang "message.email_empty"}}',trigger : 'manual'}) .tooltip('show') .parents('.form-group').addClass('has-error'); return false; }else if(code !== undefined && code === ""){ - $("#code").focus().tooltip({title : '验证码不能为空',trigger : 'manual'}) + $("#code").focus().tooltip({title : '{{i18n .Lang "message.captcha_empty"}}',trigger : 'manual'}) .tooltip('show') .parents('.form-group').addClass('has-error'); return false; From ec2888940e0cb540e01ab313448825316b191752 Mon Sep 17 00:00:00 2001 From: Ben Stone Date: Tue, 30 Mar 2021 19:08:50 +0800 Subject: [PATCH 10/32] refactor and add i18n, to be continue --- conf/lang/en-us.ini | 6 +++++- conf/lang/zh-cn.ini | 6 +++++- controllers/HomeController.go | 4 ---- views/home/index.tpl | 4 ++-- 4 files changed, 12 insertions(+), 8 deletions(-) diff --git a/conf/lang/en-us.ini b/conf/lang/en-us.ini index da7b302f..d432887f 100644 --- a/conf/lang/en-us.ini +++ b/conf/lang/en-us.ini @@ -63,4 +63,8 @@ account_existed = Username already existed failed_register = Registration failed, please contact the system administrator failed_obtain_user_info = Failed to obtain identity information dingtalk_auto_login_not_enable = DingTalk automatic login function is not enabled -failed_auto_login = Automatic login failed \ No newline at end of file +failed_auto_login = Automatic login failed +no_project = No Project + +[blog] +author = author \ No newline at end of file diff --git a/conf/lang/zh-cn.ini b/conf/lang/zh-cn.ini index 25b2832b..31c15257 100644 --- a/conf/lang/zh-cn.ini +++ b/conf/lang/zh-cn.ini @@ -63,4 +63,8 @@ account_existed = 账号已存在 failed_register = 注册失败,请联系管理员 failed_obtain_user_info = 获取身份信息失败 dingtalk_auto_login_not_enable = 未开启钉钉自动登录功能 -failed_auto_login = 自动登录失败 \ No newline at end of file +failed_auto_login = 自动登录失败 +no_project = 暂无项目 + +[blog] +author = 作者 \ No newline at end of file diff --git a/controllers/HomeController.go b/controllers/HomeController.go index e4c6f145..00521a67 100644 --- a/controllers/HomeController.go +++ b/controllers/HomeController.go @@ -28,14 +28,11 @@ func (c *HomeController) Index() { pageIndex, _ := c.GetInt("page", 1) pageSize := 18 - memberId := 0 - if c.Member != nil { memberId = c.Member.MemberId } books, totalCount, err := models.NewBook().FindForHomeToPager(pageIndex, pageSize, memberId) - if err != nil { logs.Error(err) c.Abort("500") @@ -47,6 +44,5 @@ func (c *HomeController) Index() { c.Data["PageHtml"] = "" } c.Data["TotalPages"] = int(math.Ceil(float64(totalCount) / float64(pageSize))) - c.Data["Lists"] = books } diff --git a/views/home/index.tpl b/views/home/index.tpl index 9b634493..982b6d7a 100644 --- a/views/home/index.tpl +++ b/views/home/index.tpl @@ -35,7 +35,7 @@
    - 作者 + {{i18n $.Lang "blog.author"}} - {{if eq $item.RealName "" }}{{$item.CreateName}}{{else}}{{$item.RealName}}{{end}} @@ -43,7 +43,7 @@ {{else}} -
    暂无项目
    +
    {{i18n $.Lang "message.no_project"}}
    {{end}}
    From f5518d73f798d0fe78a02b8dc793fd650a531716 Mon Sep 17 00:00:00 2001 From: Ben Stone Date: Wed, 31 Mar 2021 12:00:10 +0800 Subject: [PATCH 11/32] Update app.conf.example i18n, add default locale conf --- conf/app.conf.example | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/conf/app.conf.example b/conf/app.conf.example index b7ce3b31..4db80aa2 100644 --- a/conf/app.conf.example +++ b/conf/app.conf.example @@ -230,6 +230,7 @@ dingtalk_qr_key="${MINDOC_DINGTALK_QRKEY}" # 钉钉扫码登录Secret dingtalk_qr_secret="${MINDOC_DINGTALK_QRSECRET}" - +# i18n config +default_lang="zh-cn" From fa6643ae52b925657fd38d6c440c928fee7f37f1 Mon Sep 17 00:00:00 2001 From: Ben Stone Date: Wed, 31 Mar 2021 17:10:23 +0800 Subject: [PATCH 12/32] Update en-us.ini refactor and update i18n, to be continue --- conf/lang/en-us.ini | 52 +++++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 50 insertions(+), 2 deletions(-) diff --git a/conf/lang/en-us.ini b/conf/lang/en-us.ini index d432887f..23a5df21 100644 --- a/conf/lang/en-us.ini +++ b/conf/lang/en-us.ini @@ -25,6 +25,11 @@ account_recovery = Account recovery new_password = New password confirm_password = Confirm password new_account = Create New Account +setting = Setting +save = Save +cancel = Cancel +create = Create +confirm_delete = Confirm Delete [message] keyword_placeholder = input keyword please... @@ -41,7 +46,7 @@ captcha_empty = Captcha cannot be empty system_error = System error processing = Processing... email_sent = The email is sent successfully, please log in to check it. -password_empty = Confirm password cannot be empty +confirm_password_empty = Confirm password cannot be empty incorrect_confirm_password = Incorrect confirm password illegal_request = Illegal request account_or_password_empty = Account or Password cannot be empty @@ -65,6 +70,49 @@ failed_obtain_user_info = Failed to obtain identity information dingtalk_auto_login_not_enable = DingTalk automatic login function is not enabled failed_auto_login = Automatic login failed no_project = No Project +item_not_exist = Item does not exist or has been deleted +doc_not_exist = Document does not exist or has been deleted +unknown_exception = Unknown Exception +no_data = No Data +project_must_belong_space = Project must belong to a project space, and the super administrator can manage and maintain it +project_title_placeholder = Title (limit in 30 words) +project_title_tips = Project name cannot exceed 100 characters +project_id_placeholder = Project ID(limit in 30 characters) +project_id_tips = The document logo can only contain lowercase letters, numbers, and "-", "." and "_" symbols. +project_decs_placeholder = Project description cannot exceed 500 characters +project_public_desc = (Anyone can access) +project_private_desc = (Only participants or use tokens can access) +project_cover_desc = The project cover can be modified in the project settings +confirm_delete_project = Are you sure you want to delete the project? +warning_delete_project = Remove items will not be retrieved. +project_space_empty = Please select project space +project_title_empty = Project title cannot be empty +project_id_empty = Project ID cannot be empty +project_id_length = Project ID must be less than 50 characters +import_file_empty = Please select the file to upload +file_type_placeholder = Please select a Zip file [blog] -author = author \ No newline at end of file +author = author +project_list = Project List +add_project = Add Project +import_project = Import Project +delete_project = Delete Project +project_summary = Project summary +read = Read +edit = Edit +delete = Delete +copy = Copy +view = View +edit_doc = Edit Document +default_cover = Default Cover +create_time = Create Time +creator = Creator +doc_amount = Document Amount +project_role = Project Role +last_edit = Last Edited +project_title = Project Title +project_id = Project ID +project_desc = Project description +public = Public +private = Private From 581d902cd88408f66e4146784103b301301b7078 Mon Sep 17 00:00:00 2001 From: Ben Stone Date: Wed, 31 Mar 2021 17:13:05 +0800 Subject: [PATCH 13/32] refactor and update i18n, to be continue --- conf/lang/en-us.ini | 6 ++ conf/lang/zh-cn.ini | 56 +++++++++++- utils/pagination/pagination.go | 39 ++++++--- views/book/index.tpl | 154 ++++++++++++++++----------------- 4 files changed, 167 insertions(+), 88 deletions(-) diff --git a/conf/lang/en-us.ini b/conf/lang/en-us.ini index 23a5df21..597c6640 100644 --- a/conf/lang/en-us.ini +++ b/conf/lang/en-us.ini @@ -116,3 +116,9 @@ project_id = Project ID project_desc = Project description public = Public private = Private + +[page] +first = first +last = last +prev = prev +next = next \ No newline at end of file diff --git a/conf/lang/zh-cn.ini b/conf/lang/zh-cn.ini index 31c15257..4e1bdc42 100644 --- a/conf/lang/zh-cn.ini +++ b/conf/lang/zh-cn.ini @@ -25,6 +25,11 @@ account_recovery = 找回密码 new_password = 新密码 confirm_password = 确认密码 new_account = 用户注册 +setting = 设置 +save = 保存 +cancel = 取消 +create = 创建 +confirm_delete = 确定删除 [message] keyword_placeholder = 请输入关键词... @@ -65,6 +70,55 @@ failed_obtain_user_info = 获取身份信息失败 dingtalk_auto_login_not_enable = 未开启钉钉自动登录功能 failed_auto_login = 自动登录失败 no_project = 暂无项目 +item_not_exist = 项目不存在或已删除 +doc_not_exist = 文档不存在或已删除 +unknown_exception = 未知异常 +no_data = 暂无数据 +project_must_belong_space = 每个项目必须归属一个项目空间,超级管理员可在后台管理和维护 +project_title_placeholder = 项目标题(不超过100字) +project_title_tips = 项目标题不能超过100字符 +project_id_placeholder = 项目唯一标识(不超过50字) +project_id_tips = 文档标识只能包含小写字母、数字,以及“-”、“.”和“_”符号. +project_desc_placeholder = 描述信息不超过500个字符 +project_public_desc = (任何人都可以访问) +project_private_desc = (只有参与者或使用令牌才能访问) +project_cover_desc = 项目图片可在项目设置中修改 +confirm_delete_project = 确定删除项目吗? +warning_delete_project = 删除项目后将无法找回。 +project_space_empty = 请选择项目空间 +project_title_empty = 项目标题不能为空 +project_id_empty = 项目标识不能为空 +project_id_length = 项目标识必须小于50字符 +import_file_empty = 请选择需要上传的文件 +file_type_placeholder = 请选择Zip文件 [blog] -author = 作者 \ No newline at end of file +author = 作者 +project_list = 项目列表 +add_project = 添加项目 +import_project = 导入项目 +delete_project = 删除项目 +project_summary = 项目概要 +read = 阅读 +edit = 编辑 +delete = 删除 +copy = 复制 +view = 查看文档 +edit_doc = 编辑文档 +default_cover = 默认封面 +create_time = 创建时间 +creator = 创建者 +doc_amount = 文档数量 +project_role = 项目角色 +last_edit = 最后编辑 +project_title = 项目标题 +project_id = 项目标识 +project_desc = 项目描述 +public = 公开 +private = 私有 + +[page] +first = 首页 +last = 末页 +prev = 上一页 +next = 下一页 \ No newline at end of file diff --git a/utils/pagination/pagination.go b/utils/pagination/pagination.go index f6dcec43..df25d91a 100644 --- a/utils/pagination/pagination.go +++ b/utils/pagination/pagination.go @@ -2,12 +2,14 @@ package pagination import ( "fmt" + "github.com/astaxie/beego" + "github.com/beego/i18n" + "html/template" "math" "net/http" "net/url" "strconv" "strings" - "html/template" ) //Pagination 分页器 @@ -19,7 +21,7 @@ type Pagination struct { } //NewPagination 新建分页器 -func NewPagination(req *http.Request, total int, pernum int,baseUrl string) *Pagination { +func NewPagination(req *http.Request, total int, pernum int, baseUrl string) *Pagination { return &Pagination{ Request: req, Total: total, @@ -49,6 +51,8 @@ func (p *Pagination) Pages() string { //计算总页数 var totalPageNum = int(math.Ceil(float64(p.Total) / float64(p.Pernum))) + lang := p.getLang() + //首页链接 var firstLink string //上一页链接 @@ -62,20 +66,20 @@ func (p *Pagination) Pages() string { //首页和上一页链接 if pagenum > 1 { - firstLink = fmt.Sprintf(`
  • 首页
  • `, p.pageURL("1")) - prevLink = fmt.Sprintf(`
  • 上一页
  • `, p.pageURL(strconv.Itoa(pagenum-1))) + firstLink = fmt.Sprintf(`
  • %s
  • `, p.pageURL("1"), i18n.Tr(lang, "page.first")) + prevLink = fmt.Sprintf(`
  • %s
  • `, p.pageURL(strconv.Itoa(pagenum-1)), i18n.Tr(lang, "page.prev")) } else { - firstLink = `
  • 首页
  • ` - prevLink = `
  • 上一页
  • ` + firstLink = fmt.Sprintf(`
  • %s
  • `, i18n.Tr(lang, "page.first")) + prevLink = fmt.Sprintf(`
  • %s
  • `, i18n.Tr(lang, "page.prev")) } //末页和下一页 if pagenum < totalPageNum { - lastLink = fmt.Sprintf(`
  • 末页
  • `, p.pageURL(strconv.Itoa(totalPageNum))) - nextLink = fmt.Sprintf(`
  • 下一页
  • `, p.pageURL(strconv.Itoa(pagenum+1))) + lastLink = fmt.Sprintf(`
  • %s
  • `, p.pageURL(strconv.Itoa(totalPageNum)), i18n.Tr(lang, "page.last")) + nextLink = fmt.Sprintf(`
  • %s
  • `, p.pageURL(strconv.Itoa(pagenum+1)), i18n.Tr(lang, "page.next")) } else { - lastLink = `
  • 末页
  • ` - nextLink = `
  • 下一页
  • ` + lastLink = fmt.Sprintf(`
  • %s
  • `, i18n.Tr(lang, "page.last")) + nextLink = fmt.Sprintf(`
  • %s
  • `, i18n.Tr(lang, "page.next")) } //生成中间页码链接 @@ -112,3 +116,18 @@ func (p *Pagination) pageURL(page string) string { return u.String() } +func (p *Pagination) getLang() string { + lang := beego.AppConfig.String("default_lang") + ulang := p.Request.FormValue("lang") + if len(ulang) == 0 { + clang, err := p.Request.Cookie("lang") + if err != nil { + return lang + } + ulang = clang.Value + } + if !i18n.IsExist(ulang) { + return lang + } + return ulang +} diff --git a/views/book/index.tpl b/views/book/index.tpl index ab8dec46..234a0151 100644 --- a/views/book/index.tpl +++ b/views/book/index.tpl @@ -5,7 +5,7 @@ - 我的项目 - Powered by MinDoc + {{i18n $.Lang "common.my_project"}} - Powered by MinDoc @@ -28,30 +28,30 @@
    - 项目列表 + {{i18n $.Lang "blog.project_list"}}   - - + +
    - + ${(new Date(item.create_time)).format("yyyy-MM-dd hh:mm:ss")} - ${item.create_name} - ${item.doc_count} - ${item.role_name} + ${item.create_name} + ${item.doc_count} + ${item.role_name}
    @@ -133,49 +133,49 @@