diff --git a/commands/command.go b/commands/command.go
index c13582c2..2fcbc4b8 100644
--- a/commands/command.go
+++ b/commands/command.go
@@ -6,11 +6,12 @@ import (
"net/url"
"os"
"time"
-
+ "log"
"flag"
"path/filepath"
"strings"
+ "encoding/json"
"github.com/astaxie/beego"
"github.com/astaxie/beego/logs"
"github.com/astaxie/beego/orm"
@@ -19,14 +20,6 @@ import (
"github.com/lifei6671/mindoc/conf"
"github.com/lifei6671/mindoc/models"
"github.com/lifei6671/mindoc/utils"
- "log"
- "encoding/json"
-)
-
-var (
- ConfigurationFile = "./conf/app.conf"
- WorkingDirectory = "./"
- LogFile = "./logs"
)
// RegisterDataBase 注册数据库
@@ -54,8 +47,8 @@ func RegisterDataBase() {
}
} else if adapter == "sqlite3" {
database := beego.AppConfig.String("db_database")
- if strings.HasPrefix(database,"./") {
- database = filepath.Join(WorkingDirectory,string(database[1:]))
+ if strings.HasPrefix(database, "./") {
+ database = filepath.Join(conf.WorkingDirectory, string(database[1:]))
}
dbPath := filepath.Dir(database)
@@ -99,11 +92,11 @@ func RegisterLogger(log string) {
if f, err := os.Create(logPath); err == nil {
f.Close()
- config := make(map[string]interface{},1)
+ config := make(map[string]interface{}, 1)
config["filename"] = logPath
- b,_ := json.Marshal(config)
+ b, _ := json.Marshal(config)
beego.SetLogger("file", string(b))
}
@@ -133,7 +126,7 @@ func RegisterFunction() {
beego.AddFuncMap("cdn", func(p string) string {
cdn := beego.AppConfig.DefaultString("cdn", "")
- if strings.HasPrefix(p,"http://") || strings.HasPrefix(p,"https://") {
+ if strings.HasPrefix(p, "http://") || strings.HasPrefix(p, "https://") {
return p
}
if strings.HasPrefix(p, "/") && strings.HasSuffix(cdn, "/") {
@@ -147,7 +140,7 @@ func RegisterFunction() {
beego.AddFuncMap("cdnjs", func(p string) string {
cdn := beego.AppConfig.DefaultString("cdnjs", "")
- if strings.HasPrefix(p,"http://") || strings.HasPrefix(p,"https://") {
+ if strings.HasPrefix(p, "http://") || strings.HasPrefix(p, "https://") {
return p
}
if strings.HasPrefix(p, "/") && strings.HasSuffix(cdn, "/") {
@@ -160,7 +153,7 @@ func RegisterFunction() {
})
beego.AddFuncMap("cdncss", func(p string) string {
cdn := beego.AppConfig.DefaultString("cdncss", "")
- if strings.HasPrefix(p,"http://") || strings.HasPrefix(p,"https://") {
+ if strings.HasPrefix(p, "http://") || strings.HasPrefix(p, "https://") {
return p
}
if strings.HasPrefix(p, "/") && strings.HasSuffix(cdn, "/") {
@@ -172,7 +165,7 @@ func RegisterFunction() {
return cdn + p
})
beego.AddFuncMap("cdnimg", func(p string) string {
- if strings.HasPrefix(p,"http://") || strings.HasPrefix(p,"https://") {
+ if strings.HasPrefix(p, "http://") || strings.HasPrefix(p, "https://") {
return p
}
cdn := beego.AppConfig.DefaultString("cdnimg", "")
@@ -188,62 +181,64 @@ func RegisterFunction() {
func ResolveCommand(args []string) {
flagSet := flag.NewFlagSet("MinDoc command: ", flag.ExitOnError)
- flagSet.StringVar(&ConfigurationFile, "config", "", "MinDoc configuration file.")
- flagSet.StringVar(&WorkingDirectory, "dir", "", "MinDoc working directory.")
- flagSet.StringVar(&LogFile, "log", "", "MinDoc log file path.")
+ flagSet.StringVar(&conf.ConfigurationFile, "config", "", "MinDoc configuration file.")
+ flagSet.StringVar(&conf.WorkingDirectory, "dir", "", "MinDoc working directory.")
+ flagSet.StringVar(&conf.LogFile, "log", "", "MinDoc log file path.")
flagSet.Parse(args)
-
- if WorkingDirectory == "" {
+ if conf.WorkingDirectory == "" {
if p, err := filepath.Abs(os.Args[0]); err == nil {
- WorkingDirectory = filepath.Dir(p)
+ conf.WorkingDirectory = filepath.Dir(p)
}
}
- if LogFile == "" {
- LogFile = filepath.Join(WorkingDirectory,"logs")
+ if conf.LogFile == "" {
+ conf.LogFile = filepath.Join(conf.WorkingDirectory, "logs")
}
- if ConfigurationFile == "" {
- ConfigurationFile = filepath.Join(WorkingDirectory,"conf","app.conf")
- config := filepath.Join(WorkingDirectory,"conf","app.conf.example")
- if !utils.FileExists(ConfigurationFile) && utils.FileExists(config){
- utils.CopyFile(ConfigurationFile,config)
+ if conf.ConfigurationFile == "" {
+ conf.ConfigurationFile = filepath.Join(conf.WorkingDirectory, "conf", "app.conf")
+ config := filepath.Join(conf.WorkingDirectory, "conf", "app.conf.example")
+ if !utils.FileExists(conf.ConfigurationFile) && utils.FileExists(config) {
+ utils.CopyFile(conf.ConfigurationFile, config)
}
}
- gocaptcha.ReadFonts(filepath.Join(WorkingDirectory,"static","fonts"), ".ttf")
+ gocaptcha.ReadFonts(filepath.Join(conf.WorkingDirectory, "static", "fonts"), ".ttf")
- err := beego.LoadAppConfig("ini", ConfigurationFile)
+ err := beego.LoadAppConfig("ini", conf.ConfigurationFile)
if err != nil {
log.Println("An error occurred:", err)
os.Exit(1)
}
- uploads := filepath.Join(WorkingDirectory, "uploads")
+ uploads := filepath.Join(conf.WorkingDirectory, "uploads")
- os.MkdirAll(uploads,0666)
+ os.MkdirAll(uploads, 0666)
- beego.BConfig.WebConfig.StaticDir["/static"] = filepath.Join(WorkingDirectory, "static")
+ beego.BConfig.WebConfig.StaticDir["/static"] = filepath.Join(conf.WorkingDirectory, "static")
beego.BConfig.WebConfig.StaticDir["/uploads"] = uploads
- beego.BConfig.WebConfig.ViewsPath = filepath.Join(WorkingDirectory, "views")
+ beego.BConfig.WebConfig.ViewsPath = filepath.Join(conf.WorkingDirectory, "views")
- fonts := filepath.Join(WorkingDirectory, "static", "fonts")
+ fonts := filepath.Join(conf.WorkingDirectory, "static", "fonts")
if !utils.FileExists(fonts) {
log.Fatal("Font path not exist.")
}
- gocaptcha.ReadFonts(filepath.Join(WorkingDirectory, "static", "fonts"), ".ttf")
+ gocaptcha.ReadFonts(filepath.Join(conf.WorkingDirectory, "static", "fonts"), ".ttf")
RegisterDataBase()
RegisterModel()
- RegisterLogger(LogFile)
+ RegisterLogger(conf.LogFile)
}
func init() {
+ if configPath ,err := filepath.Abs(conf.ConfigurationFile); err == nil {
+ conf.ConfigurationFile = configPath
+ }
gocaptcha.ReadFonts("./static/fonts", ".ttf")
gob.Register(models.Member{})
- if p,err := filepath.Abs(os.Args[0]);err == nil{
- WorkingDirectory = filepath.Dir(p)
+ if p, err := filepath.Abs(os.Args[0]); err == nil {
+ conf.WorkingDirectory = filepath.Dir(p)
}
}
diff --git a/commands/daemon/daemon.go b/commands/daemon/daemon.go
index 5245ab65..69bfc7cf 100644
--- a/commands/daemon/daemon.go
+++ b/commands/daemon/daemon.go
@@ -19,10 +19,10 @@ type Daemon struct {
func NewDaemon() *Daemon {
config := &service.Config{
- Name: "mindocd", //服务显示名称
+ Name: "mindocd", //服务显示名称
DisplayName: "MinDoc service", //服务名称
Description: "A document online management program.", //服务描述
- WorkingDirectory: commands.WorkingDirectory,
+ WorkingDirectory: conf.WorkingDirectory,
Arguments: os.Args[1:],
}
diff --git a/commands/migrate/migrate.go b/commands/migrate/migrate.go
index e0f46856..2cd0f960 100644
--- a/commands/migrate/migrate.go
+++ b/commands/migrate/migrate.go
@@ -16,19 +16,18 @@ package migrate
import (
"os"
- "log"
- "github.com/lifei6671/mindoc/models"
"container/list"
"fmt"
"github.com/astaxie/beego"
"github.com/astaxie/beego/orm"
+ "github.com/lifei6671/mindoc/models"
+ "log"
)
var (
- migrationList = &migrationCache{ }
+ migrationList = &migrationCache{}
)
-
type MigrationDatabase interface {
//获取当前的版本
Version() int64
@@ -58,7 +57,7 @@ func RunMigration() {
if len(os.Args) >= 2 && os.Args[1] == "migrate" {
- migrate,err := models.NewMigration().FindFirst()
+ migrate, err := models.NewMigration().FindFirst()
if err != nil {
//log.Fatalf("migrations table %s", err)
@@ -66,10 +65,10 @@ func RunMigration() {
}
fmt.Println("Start migration databae... ")
- for el := migrationList.items.Front(); el != nil ; el = el.Next() {
+ for el := migrationList.items.Front(); el != nil; el = el.Next() {
//如果存在比当前版本大的版本,则依次升级
- if item,ok := el.Value.(MigrationDatabase); ok && item.Version() > migrate.Version {
+ if item, ok := el.Value.(MigrationDatabase); ok && item.Version() > migrate.Version {
err := item.ValidUpdate(migrate.Version)
if err != nil {
log.Fatal(err)
@@ -112,51 +111,53 @@ func RunMigration() {
}
//导出数据库的表结构
-func ExportDatabaseTable() ([]string,error) {
+func ExportDatabaseTable() ([]string, error) {
db_adapter := beego.AppConfig.String("db_adapter")
db_database := beego.AppConfig.String("db_database")
- tables := make([]string,0)
+ tables := make([]string, 0)
o := orm.NewOrm()
switch db_adapter {
- case "mysql":{
- var lists []orm.Params
+ case "mysql":
+ {
+ var lists []orm.Params
- _,err := o.Raw(fmt.Sprintf("SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = '%s'",db_database)).Values(&lists)
- if err != nil {
- return tables,err
- }
- for _,table := range lists {
- var results []orm.Params
-
- _,err = o.Raw(fmt.Sprintf("show create table %s",table["TABLE_NAME"])).Values(&results)
+ _, err := o.Raw(fmt.Sprintf("SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = '%s'", db_database)).Values(&lists)
if err != nil {
- return tables,err
+ return tables, err
}
- tables = append(tables,results[0]["Create Table"].(string))
- }
- break;
- }
- case "sqlite3": {
- var results []orm.Params
- _,err := o.Raw("SELECT sql FROM sqlite_master WHERE sql IS NOT NULL ORDER BY rootpage ASC").Values(&results)
- if err != nil {
- return tables,err
- }
- for _,item := range results {
- if sql,ok := item["sql"]; ok {
- tables = append(tables,sql.(string))
+ for _, table := range lists {
+ var results []orm.Params
+
+ _, err = o.Raw(fmt.Sprintf("show create table %s", table["TABLE_NAME"])).Values(&results)
+ if err != nil {
+ return tables, err
+ }
+ tables = append(tables, results[0]["Create Table"].(string))
}
+ break
+ }
+ case "sqlite3":
+ {
+ var results []orm.Params
+ _, err := o.Raw("SELECT sql FROM sqlite_master WHERE sql IS NOT NULL ORDER BY rootpage ASC").Values(&results)
+ if err != nil {
+ return tables, err
+ }
+ for _, item := range results {
+ if sql, ok := item["sql"]; ok {
+ tables = append(tables, sql.(string))
+ }
+ }
+ break
}
- break
- }
}
- return tables,nil
+ return tables, nil
}
-func RegisterMigration() {
+func RegisterMigration() {
migrationList.items = list.New()
- migrationList.items.PushBack(NewMigrationVersion03())
-}
\ No newline at end of file
+ migrationList.items.PushBack(NewMigrationVersion03())
+}
diff --git a/commands/migrate/migrate_v03.go b/commands/migrate/migrate_v03.go
index 6088f702..d73e9e78 100644
--- a/commands/migrate/migrate_v03.go
+++ b/commands/migrate/migrate_v03.go
@@ -2,21 +2,20 @@ package migrate
import (
"errors"
+ "fmt"
"github.com/astaxie/beego/orm"
"github.com/lifei6671/mindoc/models"
- "time"
- "fmt"
"strings"
+ "time"
)
type MigrationVersion03 struct {
isValid bool
- tables []string
-
+ tables []string
}
func NewMigrationVersion03() *MigrationVersion03 {
- return &MigrationVersion03{ isValid: false, tables: make([]string,0)}
+ return &MigrationVersion03{isValid: false, tables: make([]string, 0)}
}
func (m *MigrationVersion03) Version() int64 {
@@ -37,8 +36,7 @@ func (m *MigrationVersion03) ValidForBackupTableSchema() error {
return errors.New("The current version failed to verify.")
}
var err error
- m.tables,err = ExportDatabaseTable()
-
+ m.tables, err = ExportDatabaseTable()
return err
}
@@ -72,11 +70,11 @@ func (m *MigrationVersion03) MigrationNewTableData() error {
}
o := orm.NewOrm()
- _,err := o.Raw("UPDATE md_members SET auth_method = 'local'").Exec()
+ _, err := o.Raw("UPDATE md_members SET auth_method = 'local'").Exec()
if err != nil {
return err
}
- _,err = o.Raw("INSERT INTO md_options (option_title, option_name, option_value) SELECT '是否启用文档历史','ENABLE_DOCUMENT_HISTORY','true' WHERE NOT exists(SELECT * FROM md_options WHERE option_name = 'ENABLE_DOCUMENT_HISTORY');").Exec()
+ _, err = o.Raw("INSERT INTO md_options (option_title, option_name, option_value) SELECT '是否启用文档历史','ENABLE_DOCUMENT_HISTORY','true' WHERE NOT exists(SELECT * FROM md_options WHERE option_name = 'ENABLE_DOCUMENT_HISTORY');").Exec()
if err != nil {
return err
}
@@ -85,24 +83,24 @@ func (m *MigrationVersion03) MigrationNewTableData() error {
func (m *MigrationVersion03) AddMigrationRecord(version int64) error {
o := orm.NewOrm()
- tables,err := ExportDatabaseTable()
+ tables, err := ExportDatabaseTable()
if err != nil {
- return err
+ return err
}
migration := models.NewMigration()
migration.Version = version
migration.Status = "update"
migration.CreateTime = time.Now()
- migration.Name = fmt.Sprintf("update_%d",version)
- migration.Statements = strings.Join(tables,"\r\n")
+ migration.Name = fmt.Sprintf("update_%d", version)
+ migration.Statements = strings.Join(tables, "\r\n")
_, err = o.Insert(migration)
return err
}
-func (m *MigrationVersion03) MigrationCleanup() error {
+func (m *MigrationVersion03) MigrationCleanup() error {
return nil
}
@@ -112,16 +110,16 @@ func (m *MigrationVersion03) RollbackMigration() error {
return errors.New("The current version failed to verify.")
}
o := orm.NewOrm()
- _,err := o.Raw("ALTER TABLE md_members DROP COLUMN auth_method").Exec()
+ _, err := o.Raw("ALTER TABLE md_members DROP COLUMN auth_method").Exec()
if err != nil {
return err
}
- _,err = o.Raw("DROP TABLE md_document_history").Exec()
+ _, err = o.Raw("DROP TABLE md_document_history").Exec()
if err != nil {
return err
}
- _,err = o.Raw("DELETE md_options WHERE option_name = 'ENABLE_DOCUMENT_HISTORY'").Exec()
+ _, err = o.Raw("DELETE md_options WHERE option_name = 'ENABLE_DOCUMENT_HISTORY'").Exec()
if err != nil {
return err
@@ -129,11 +127,3 @@ func (m *MigrationVersion03) RollbackMigration() error {
return nil
}
-
-
-
-
-
-
-
-
diff --git a/conf/enumerate.go b/conf/enumerate.go
index 5053241a..5ce602ca 100644
--- a/conf/enumerate.go
+++ b/conf/enumerate.go
@@ -20,7 +20,7 @@ const RegexpEmail = "^[a-zA-Z0-9.!#$%&'*+\\/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-
const RegexpAccount = `^[a-zA-Z][a-zA-z0-9\.]{2,50}$`
// PageSize 默认分页条数.
-const PageSize = 15
+const PageSize = 10
// 用户权限
const (
@@ -44,23 +44,31 @@ const (
)
const (
- LoggerOperate = "operate"
- LoggerSystem = "system"
+ LoggerOperate = "operate"
+ LoggerSystem = "system"
LoggerException = "exception"
- LoggerDocument = "document"
+ LoggerDocument = "document"
)
const (
//本地账户校验
AuthMethodLocal = "local"
//LDAP用户校验
- AuthMethodLDAP = "ldap"
+ AuthMethodLDAP = "ldap"
)
+
var (
VERSION string
BUILD_TIME string
GO_VERSION string
)
+var (
+ ConfigurationFile = "./conf/app.conf"
+ WorkingDirectory = "./"
+ LogFile = "./logs"
+ BaseUrl = ""
+)
+
// app_key
func GetAppKey() string {
return beego.AppConfig.DefaultString("app_key", "godoc")
@@ -102,29 +110,30 @@ func GetUploadFileExt() []string {
}
return exts
}
+
// 获取上传文件允许的最大值
func GetUploadFileSize() int64 {
- size := beego.AppConfig.DefaultString("upload_file_size","0")
+ size := beego.AppConfig.DefaultString("upload_file_size", "0")
- if strings.HasSuffix(size,"MB") {
- if s,e := strconv.ParseInt(size[0:len(size) - 2], 10, 64);e == nil {
+ if strings.HasSuffix(size, "MB") {
+ if s, e := strconv.ParseInt(size[0:len(size)-2], 10, 64); e == nil {
return s * 1024 * 1024
}
}
- if strings.HasSuffix(size,"GB") {
- if s,e := strconv.ParseInt(size[0:len(size) - 2], 10, 64);e == nil {
+ if strings.HasSuffix(size, "GB") {
+ if s, e := strconv.ParseInt(size[0:len(size)-2], 10, 64); e == nil {
return s * 1024 * 1024 * 1024
}
}
- if strings.HasSuffix(size,"KB") {
- if s,e := strconv.ParseInt(size[0:len(size) - 2], 10, 64);e == nil {
+ if strings.HasSuffix(size, "KB") {
+ if s, e := strconv.ParseInt(size[0:len(size)-2], 10, 64); e == nil {
return s * 1024
}
}
- if s,e := strconv.ParseInt(size, 10, 64);e == nil {
+ if s, e := strconv.ParseInt(size, 10, 64); e == nil {
return s * 1024
}
- return 0
+ return 0
}
//判断是否是允许商城的文件类型.
diff --git a/conf/mail.go b/conf/mail.go
index 69304f03..162ceb1d 100644
--- a/conf/mail.go
+++ b/conf/mail.go
@@ -6,33 +6,33 @@ import (
)
type SmtpConf struct {
- EnableMail bool
- MailNumber int
+ EnableMail bool
+ MailNumber int
SmtpUserName string
- SmtpHost string
+ SmtpHost string
SmtpPassword string
- SmtpPort int
+ SmtpPort int
FormUserName string
- MailExpired int
+ MailExpired int
}
func GetMailConfig() *SmtpConf {
user_name := beego.AppConfig.String("smtp_user_name")
password := beego.AppConfig.String("smtp_password")
smtp_host := beego.AppConfig.String("smtp_host")
- smtp_port := beego.AppConfig.DefaultInt("smtp_port",25)
+ smtp_port := beego.AppConfig.DefaultInt("smtp_port", 25)
form_user_name := beego.AppConfig.String("form_user_name")
enable_mail := beego.AppConfig.String("enable_mail")
- mail_number := beego.AppConfig.DefaultInt("mail_number",5)
+ mail_number := beego.AppConfig.DefaultInt("mail_number", 5)
c := &SmtpConf{
- EnableMail : strings.EqualFold(enable_mail,"true"),
- MailNumber: mail_number,
- SmtpUserName:user_name,
- SmtpHost:smtp_host,
- SmtpPassword:password,
- FormUserName:form_user_name,
- SmtpPort:smtp_port,
+ EnableMail: strings.EqualFold(enable_mail, "true"),
+ MailNumber: mail_number,
+ SmtpUserName: user_name,
+ SmtpHost: smtp_host,
+ SmtpPassword: password,
+ FormUserName: form_user_name,
+ SmtpPort: smtp_port,
}
return c
-}
\ No newline at end of file
+}
diff --git a/controllers/account.go b/controllers/account.go
index 5ee2175e..9033eeec 100644
--- a/controllers/account.go
+++ b/controllers/account.go
@@ -14,6 +14,7 @@ import (
"github.com/lifei6671/mindoc/conf"
"github.com/lifei6671/mindoc/models"
"github.com/lifei6671/mindoc/utils"
+ "net/url"
)
// AccountController 用户登录与注册
@@ -32,14 +33,17 @@ func (c *AccountController) Login() {
Time time.Time
}
- // 显式指定的 URL 参数优先;为了统一处理,将之更新到 Session 中
- turl := c.GetString("turl", "")
- if turl != "" {
- c.SetSession("turl", turl)
+ if member, ok := c.GetSession(conf.LoginSessionName).(models.Member); ok && member.MemberId > 0 {
+ u := c.GetString("url")
+ if u == "" {
+ u = c.Ctx.Request.Header.Get("Referer")
+ }
+ if u == "" {
+ u = beego.URLFor("HomeController.Index")
+ }
+ c.Redirect(u,302)
}
- beego.Info("AccountController.Login(): turl is: " + turl)
-
// 如果 Cookie 中存在登录信息
if cookie, ok := c.GetSecureCookie(conf.GetAppKey(), "login"); ok {
if err := utils.Decode(cookie, &remember); err == nil {
@@ -81,26 +85,35 @@ func (c *AccountController) Login() {
c.SetSecureCookie(conf.GetAppKey(), "login", v)
}
}
+ u,_ := url.PathUnescape(c.GetString("url"))
+ if u == "" {
+ u = c.Ctx.Request.Header.Get("Referer")
+ }
+ if u == "" {
+ u = beego.URLFor("HomeController.Index")
+ }
- data := c.LoggedIn(true)
- c.JsonResult(0, "ok", data)
+ c.JsonResult(0, "ok", u)
} else {
logs.Error("用户登录 =>", err)
c.JsonResult(500, "账号或密码错误", nil)
}
+ }else{
+ u,_ := url.PathUnescape(c.GetString("url"))
+ if u == "" {
+ u = c.Ctx.Request.Header.Get("Referer")
+ }
+ if u == "" {
+ u = beego.URLFor("HomeController.Index")
+ }
+ c.Data["url"] = url.PathEscape(u)
}
}
// 登录成功后的操作,如重定向到原始请求页面
func (c *AccountController) LoggedIn(isPost bool) interface{} {
- turl := ""
- value := c.GetSession("turl")
- if value != nil {
- turl = value.(string)
- }
- c.DelSession("turl")
- beego.Info("AccountController.LoggedIn(): turl is: " + turl)
+ turl := c.GetString("url")
if !isPost {
// 检查是否存在 turl 参数,如果有则重定向至 turl 处,否则进入 Home 页面
@@ -111,7 +124,7 @@ func (c *AccountController) LoggedIn(isPost bool) interface{} {
return nil
} else {
var data struct {
- TURL string `json:"turl"`
+ TURL string `json:"url"`
}
data.TURL = turl
return data
@@ -369,7 +382,9 @@ func (c *AccountController) Logout() {
c.SetSecureCookie(conf.GetAppKey(), "login", "", -3600)
- c.Redirect(beego.URLFor("AccountController.Login"), 302)
+ u := c.Ctx.Request.Header.Get("Referer")
+
+ c.Redirect(beego.URLFor("AccountController.Login","url",u), 302)
}
// 验证码
diff --git a/controllers/base.go b/controllers/base.go
index ca116a67..21a6e1cf 100644
--- a/controllers/base.go
+++ b/controllers/base.go
@@ -1,53 +1,52 @@
package controllers
import (
-
"bytes"
- "github.com/lifei6671/mindoc/models"
- "github.com/lifei6671/mindoc/conf"
- "github.com/astaxie/beego"
- "strings"
"encoding/json"
+ "github.com/astaxie/beego"
+ "github.com/lifei6671/mindoc/conf"
+ "github.com/lifei6671/mindoc/models"
"io"
+ "strings"
)
-
type BaseController struct {
beego.Controller
- Member *models.Member
- Option map[string]string
- EnableAnonymous bool
+ Member *models.Member
+ Option map[string]string
+ EnableAnonymous bool
EnableDocumentHistory bool
}
// Prepare 预处理.
-func (c *BaseController) Prepare (){
+func (c *BaseController) Prepare() {
c.Data["SiteName"] = "MinDoc"
c.Data["Member"] = models.Member{}
c.EnableAnonymous = false
c.EnableDocumentHistory = false
- if member,ok := c.GetSession(conf.LoginSessionName).(models.Member); ok && member.MemberId > 0{
+ if member, ok := c.GetSession(conf.LoginSessionName).(models.Member); ok && member.MemberId > 0 {
c.Member = &member
c.Data["Member"] = c.Member
- }else{
+ } else {
//c.Member = models.NewMember()
//c.Member.Find(1)
//c.Data["Member"] = *c.Member
}
- c.Data["BaseUrl"] = c.Ctx.Input.Scheme() + "://" + c.Ctx.Request.Host
+ conf.BaseUrl = c.BaseUrl()
+ c.Data["BaseUrl"] = c.BaseUrl()
- if options,err := models.NewOption().All();err == nil {
- c.Option = make(map[string]string,len(options))
- for _,item := range options {
+ if options, err := models.NewOption().All(); err == nil {
+ c.Option = make(map[string]string, len(options))
+ for _, item := range options {
c.Data[item.OptionName] = item.OptionValue
c.Option[item.OptionName] = item.OptionValue
- if strings.EqualFold(item.OptionName,"ENABLE_ANONYMOUS") && item.OptionValue == "true" {
+ if strings.EqualFold(item.OptionName, "ENABLE_ANONYMOUS") && item.OptionValue == "true" {
c.EnableAnonymous = true
}
- if strings.EqualFold(item.OptionName,"ENABLE_DOCUMENT_HISTORY") && item.OptionValue == "true" {
+ if strings.EqualFold(item.OptionName, "ENABLE_DOCUMENT_HISTORY") && item.OptionValue == "true" {
c.EnableDocumentHistory = true
}
}
@@ -68,13 +67,13 @@ func (c *BaseController) SetMember(member models.Member) {
}
// JsonResult 响应 json 结果
-func (c *BaseController) JsonResult(errCode int,errMsg string,data ...interface{}){
- jsonData := make(map[string]interface{},3)
+func (c *BaseController) JsonResult(errCode int, errMsg string, data ...interface{}) {
+ jsonData := make(map[string]interface{}, 3)
jsonData["errcode"] = errCode
jsonData["message"] = errMsg
- if len(data) > 0 && data[0] != nil{
+ if len(data) > 0 && data[0] != nil {
jsonData["data"] = data[0]
}
@@ -86,13 +85,13 @@ func (c *BaseController) JsonResult(errCode int,errMsg string,data ...interface{
c.Ctx.ResponseWriter.Header().Set("Content-Type", "application/json; charset=utf-8")
- io.WriteString(c.Ctx.ResponseWriter,string(returnJSON))
+ io.WriteString(c.Ctx.ResponseWriter, string(returnJSON))
c.StopRun()
}
// ExecuteViewPathTemplate 执行指定的模板并返回执行结果.
-func (c *BaseController) ExecuteViewPathTemplate(tplName string,data interface{}) (string,error){
+func (c *BaseController) ExecuteViewPathTemplate(tplName string, data interface{}) (string, error) {
var buf bytes.Buffer
viewPath := c.ViewPath
@@ -102,28 +101,28 @@ func (c *BaseController) ExecuteViewPathTemplate(tplName string,data interface{}
}
- if err := beego.ExecuteViewPathTemplate(&buf,tplName,viewPath,data); err != nil {
- return "",err
+ if err := beego.ExecuteViewPathTemplate(&buf, tplName, viewPath, data); err != nil {
+ return "", err
}
- return buf.String(),nil
+ return buf.String(), nil
}
func (c *BaseController) BaseUrl() string {
- baseUrl := beego.AppConfig.DefaultString("baseurl","")
+ baseUrl := beego.AppConfig.DefaultString("baseurl", "")
if baseUrl != "" {
- if strings.HasSuffix(baseUrl,"/"){
- baseUrl = strings.TrimSuffix(baseUrl,"/")
+ if strings.HasSuffix(baseUrl, "/") {
+ baseUrl = strings.TrimSuffix(baseUrl, "/")
}
- }else{
+ } else {
baseUrl = c.Ctx.Input.Scheme() + "://" + c.Ctx.Request.Host
}
return baseUrl
}
//显示错误信息页面.
-func (c *BaseController) ShowErrorPage(errCode int,errMsg string) {
+func (c *BaseController) ShowErrorPage(errCode int, errMsg string) {
c.TplName = "errors/error.tpl"
c.Data["ErrorMessage"] = errMsg
c.Data["ErrorCode"] = errCode
c.StopRun()
-}
\ No newline at end of file
+}
diff --git a/controllers/book.go b/controllers/book.go
index d5884041..35904831 100644
--- a/controllers/book.go
+++ b/controllers/book.go
@@ -1,25 +1,24 @@
package controllers
import (
- "strings"
- "regexp"
- "strconv"
- "time"
"encoding/json"
- "html/template"
"errors"
"fmt"
- "path/filepath"
+ "html/template"
"os"
+ "path/filepath"
+ "regexp"
+ "strconv"
+ "strings"
+ "time"
- "github.com/lifei6671/mindoc/models"
- "github.com/lifei6671/mindoc/utils"
"github.com/astaxie/beego"
- "github.com/astaxie/beego/orm"
"github.com/astaxie/beego/logs"
+ "github.com/astaxie/beego/orm"
"github.com/lifei6671/mindoc/conf"
"github.com/lifei6671/mindoc/graphics"
- "github.com/lifei6671/mindoc/commands"
+ "github.com/lifei6671/mindoc/models"
+ "github.com/lifei6671/mindoc/utils"
)
type BookController struct {
@@ -32,10 +31,10 @@ func (c *BookController) Index() {
pageIndex, _ := c.GetInt("page", 1)
- books,totalCount,err := models.NewBook().FindToPager(pageIndex,conf.PageSize,c.Member.MemberId)
+ books, totalCount, err := models.NewBook().FindToPager(pageIndex, conf.PageSize, c.Member.MemberId)
if err != nil {
- logs.Error("BookController.Index => ",err)
+ logs.Error("BookController.Index => ", err)
c.Abort("500")
}
@@ -43,14 +42,14 @@ func (c *BookController) Index() {
html := utils.GetPagerHtml(c.Ctx.Request.RequestURI, pageIndex, conf.PageSize, totalCount)
c.Data["PageHtml"] = html
- }else {
+ } else {
c.Data["PageHtml"] = ""
}
- b,err := json.Marshal(books)
+ b, err := json.Marshal(books)
- if err != nil || len(books) <= 0{
+ if err != nil || len(books) <= 0 {
c.Data["Result"] = template.JS("[]")
- }else{
+ } else {
c.Data["Result"] = template.JS(string(b))
}
}
@@ -62,11 +61,11 @@ func (c *BookController) Dashboard() {
key := c.Ctx.Input.Param(":key")
- if key == ""{
+ if key == "" {
c.Abort("404")
}
- book,err := models.NewBookResult().FindByIdentify(key,c.Member.MemberId)
+ book, err := models.NewBookResult().FindByIdentify(key, c.Member.MemberId)
if err != nil {
if err == models.ErrPermissionDenied {
c.Abort("403")
@@ -79,17 +78,17 @@ func (c *BookController) Dashboard() {
}
// Setting 项目设置 .
-func (c *BookController) Setting() {
+func (c *BookController) Setting() {
c.Prepare()
c.TplName = "book/setting.tpl"
key := c.Ctx.Input.Param(":key")
- if key == ""{
+ if key == "" {
c.Abort("404")
}
- book,err := models.NewBookResult().FindByIdentify(key,c.Member.MemberId)
+ book, err := models.NewBookResult().FindByIdentify(key, c.Member.MemberId)
if err != nil {
if err == orm.ErrNoRows {
c.Abort("404")
@@ -104,225 +103,224 @@ func (c *BookController) Setting() {
c.Abort("403")
}
if book.PrivateToken != "" {
- book.PrivateToken = c.BaseUrl() + beego.URLFor("DocumentController.Index",":key",book.Identify,"token",book.PrivateToken)
+ book.PrivateToken = c.BaseUrl() + beego.URLFor("DocumentController.Index", ":key", book.Identify, "token", book.PrivateToken)
}
c.Data["Model"] = book
}
//保存项目信息
-func (c *BookController) SaveBook() {
- bookResult,err := c.IsPermission()
+func (c *BookController) SaveBook() {
+ bookResult, err := c.IsPermission()
if err != nil {
- c.JsonResult(6001,err.Error())
+ c.JsonResult(6001, err.Error())
}
- book,err := models.NewBook().Find(bookResult.BookId)
+ book, err := models.NewBook().Find(bookResult.BookId)
if err != nil {
- logs.Error("SaveBook => ",err)
- c.JsonResult(6002,err.Error())
+ logs.Error("SaveBook => ", err)
+ c.JsonResult(6002, err.Error())
}
book_name := strings.TrimSpace(c.GetString("book_name"))
- description := strings.TrimSpace(c.GetString("description",""))
+ description := strings.TrimSpace(c.GetString("description", ""))
comment_status := c.GetString("comment_status")
tag := strings.TrimSpace(c.GetString("label"))
editor := strings.TrimSpace(c.GetString("editor"))
auto_release := strings.TrimSpace(c.GetString("auto_release")) == "on"
- if strings.Count(description,"") > 500 {
- c.JsonResult(6004,"项目描述不能大于500字")
+ if strings.Count(description, "") > 500 {
+ c.JsonResult(6004, "项目描述不能大于500字")
}
if comment_status != "open" && comment_status != "closed" && comment_status != "group_only" && comment_status != "registered_only" {
comment_status = "closed"
}
- if tag != ""{
- tags := strings.Split(tag,",")
+ if tag != "" {
+ tags := strings.Split(tag, ",")
if len(tags) > 10 {
- c.JsonResult(6005,"最多允许添加10个标签")
+ c.JsonResult(6005, "最多允许添加10个标签")
}
}
if editor != "markdown" && editor != "html" {
editor = "markdown"
}
- book.BookName = book_name
- book.Description = description
- book.CommentStatus = comment_status
- book.Label = tag
- book.Editor = editor
+ book.BookName = book_name
+ book.Description = description
+ book.CommentStatus = comment_status
+ book.Label = tag
+ book.Editor = editor
if auto_release {
book.AutoRelease = 1
- }else{
+ } else {
book.AutoRelease = 0
}
-
- if err := book.Update();err != nil {
- c.JsonResult(6006,"保存失败")
+ if err := book.Update(); err != nil {
+ c.JsonResult(6006, "保存失败")
}
bookResult.BookName = book_name
bookResult.Description = description
bookResult.CommentStatus = comment_status
bookResult.Label = tag
- c.JsonResult(0,"ok",bookResult)
+ c.JsonResult(0, "ok", bookResult)
}
//设置项目私有状态.
-func (c *BookController) PrivatelyOwned() {
+func (c *BookController) PrivatelyOwned() {
status := c.GetString("status")
if status != "open" && status != "close" {
- c.JsonResult(6003,"参数错误")
+ c.JsonResult(6003, "参数错误")
}
state := 0
if status == "open" {
state = 0
- }else{
+ } else {
state = 1
}
- bookResult,err := c.IsPermission()
+ bookResult, err := c.IsPermission()
if err != nil {
- c.JsonResult(6001,err.Error())
+ c.JsonResult(6001, err.Error())
}
//只有创始人才能变更私有状态
if bookResult.RoleId != conf.BookFounder {
- c.JsonResult(6002,"权限不足")
+ c.JsonResult(6002, "权限不足")
}
- book,err := models.NewBook().Find(bookResult.BookId)
+ book, err := models.NewBook().Find(bookResult.BookId)
if err != nil {
- c.JsonResult(6005,"项目不存在")
+ c.JsonResult(6005, "项目不存在")
}
book.PrivatelyOwned = state
err = book.Update()
if err != nil {
- logs.Error("PrivatelyOwned => ",err)
- c.JsonResult(6004,"保存失败")
+ logs.Error("PrivatelyOwned => ", err)
+ c.JsonResult(6004, "保存失败")
}
- c.JsonResult(0,"ok")
+ c.JsonResult(0, "ok")
}
// Transfer 转让项目.
-func (c *BookController) Transfer() {
+func (c *BookController) Transfer() {
c.Prepare()
account := c.GetString("account")
if account == "" {
- c.JsonResult(6004,"接受者账号不能为空")
+ c.JsonResult(6004, "接受者账号不能为空")
}
- member,err := models.NewMember().FindByAccount(account)
+ member, err := models.NewMember().FindByAccount(account)
if err != nil {
- logs.Error("FindByAccount => ",err)
- c.JsonResult(6005,"接受用户不存在")
+ logs.Error("FindByAccount => ", err)
+ c.JsonResult(6005, "接受用户不存在")
}
if member.Status != 0 {
- c.JsonResult(6006,"接受用户已被禁用")
+ c.JsonResult(6006, "接受用户已被禁用")
}
if member.MemberId == c.Member.MemberId {
- c.JsonResult(6007,"不能转让给自己")
+ c.JsonResult(6007, "不能转让给自己")
}
- bookResult,err := c.IsPermission()
+ bookResult, err := c.IsPermission()
if err != nil {
- c.JsonResult(6001,err.Error())
+ c.JsonResult(6001, err.Error())
}
- err = models.NewRelationship().Transfer(bookResult.BookId,c.Member.MemberId,member.MemberId)
+ err = models.NewRelationship().Transfer(bookResult.BookId, c.Member.MemberId, member.MemberId)
if err != nil {
- logs.Error("Transfer => ",err)
- c.JsonResult(6008,err.Error())
+ logs.Error("Transfer => ", err)
+ c.JsonResult(6008, err.Error())
}
- c.JsonResult(0,"ok")
+ c.JsonResult(0, "ok")
}
+
//上传项目封面.
-func (c *BookController) UploadCover() {
+func (c *BookController) UploadCover() {
- bookResult,err := c.IsPermission()
+ bookResult, err := c.IsPermission()
if err != nil {
- c.JsonResult(6001,err.Error())
+ c.JsonResult(6001, err.Error())
}
- book,err := models.NewBook().Find(bookResult.BookId)
+ book, err := models.NewBook().Find(bookResult.BookId)
if err != nil {
- logs.Error("SaveBook => ",err)
- c.JsonResult(6002,err.Error())
+ logs.Error("SaveBook => ", err)
+ c.JsonResult(6002, err.Error())
}
- file,moreFile,err := c.GetFile("image-file")
+ file, moreFile, err := c.GetFile("image-file")
defer file.Close()
if err != nil {
- logs.Error("",err.Error())
- c.JsonResult(500,"读取文件异常")
+ logs.Error("", err.Error())
+ c.JsonResult(500, "读取文件异常")
}
ext := filepath.Ext(moreFile.Filename)
- if !strings.EqualFold(ext,".png") && !strings.EqualFold(ext,".jpg") && !strings.EqualFold(ext,".gif") && !strings.EqualFold(ext,".jpeg") {
- c.JsonResult(500,"不支持的图片格式")
+ if !strings.EqualFold(ext, ".png") && !strings.EqualFold(ext, ".jpg") && !strings.EqualFold(ext, ".gif") && !strings.EqualFold(ext, ".jpeg") {
+ c.JsonResult(500, "不支持的图片格式")
}
-
- x1 ,_ := strconv.ParseFloat(c.GetString("x"),10)
- y1 ,_ := strconv.ParseFloat(c.GetString("y"),10)
- w1 ,_ := strconv.ParseFloat(c.GetString("width"),10)
- h1 ,_ := strconv.ParseFloat(c.GetString("height"),10)
+ x1, _ := strconv.ParseFloat(c.GetString("x"), 10)
+ y1, _ := strconv.ParseFloat(c.GetString("y"), 10)
+ w1, _ := strconv.ParseFloat(c.GetString("width"), 10)
+ h1, _ := strconv.ParseFloat(c.GetString("height"), 10)
x := int(x1)
y := int(y1)
width := int(w1)
height := int(h1)
- fileName := "cover_" + strconv.FormatInt(time.Now().UnixNano(), 16)
+ fileName := "cover_" + strconv.FormatInt(time.Now().UnixNano(), 16)
- filePath := filepath.Join("uploads",time.Now().Format("200601"),fileName + ext)
+ filePath := filepath.Join("uploads", time.Now().Format("200601"), fileName+ext)
path := filepath.Dir(filePath)
os.MkdirAll(path, os.ModePerm)
- err = c.SaveToFile("image-file",filePath)
+ err = c.SaveToFile("image-file", filePath)
if err != nil {
- logs.Error("",err)
- c.JsonResult(500,"图片保存失败")
+ logs.Error("", err)
+ c.JsonResult(500, "图片保存失败")
}
defer func(filePath string) {
os.Remove(filePath)
}(filePath)
//剪切图片
- subImg,err := graphics.ImageCopyFromFile(filePath,x,y,width,height)
-
- if err != nil{
- logs.Error("graphics.ImageCopyFromFile => ",err)
- c.JsonResult(500,"图片剪切")
- }
-
- filePath = filepath.Join(commands.WorkingDirectory,"uploads",time.Now().Format("200601"),fileName + "_small" + ext)
-
- //生成缩略图并保存到磁盘
- err = graphics.ImageResizeSaveFile(subImg,175,230,filePath)
+ subImg, err := graphics.ImageCopyFromFile(filePath, x, y, width, height)
if err != nil {
- logs.Error("ImageResizeSaveFile => ",err.Error())
- c.JsonResult(500,"保存图片失败")
+ logs.Error("graphics.ImageCopyFromFile => ", err)
+ c.JsonResult(500, "图片剪切")
}
- url := "/" + strings.Replace(strings.TrimPrefix(filePath,commands.WorkingDirectory),"\\","/",-1)
+ filePath = filepath.Join(conf.WorkingDirectory, "uploads", time.Now().Format("200601"), fileName+"_small"+ext)
- if strings.HasPrefix(url,"//") {
+ //生成缩略图并保存到磁盘
+ err = graphics.ImageResizeSaveFile(subImg, 175, 230, filePath)
+
+ if err != nil {
+ logs.Error("ImageResizeSaveFile => ", err.Error())
+ c.JsonResult(500, "保存图片失败")
+ }
+
+ url := "/" + strings.Replace(strings.TrimPrefix(filePath, conf.WorkingDirectory), "\\", "/", -1)
+
+ if strings.HasPrefix(url, "//") {
url = string(url[1:])
}
@@ -330,15 +328,15 @@ func (c *BookController) UploadCover() {
book.Cover = url
- if err := book.Update() ; err != nil {
- c.JsonResult(6001,"保存图片失败")
+ if err := book.Update(); err != nil {
+ c.JsonResult(6001, "保存图片失败")
}
//如果原封面不是默认封面则删除
if old_cover != conf.GetDefaultCover() {
os.Remove("." + old_cover)
}
- c.JsonResult(0,"ok",url)
+ c.JsonResult(0, "ok", url)
}
// Users 用户列表.
@@ -347,13 +345,13 @@ func (c *BookController) Users() {
c.TplName = "book/users.tpl"
key := c.Ctx.Input.Param(":key")
- pageIndex,_ := c.GetInt("page",1)
+ pageIndex, _ := c.GetInt("page", 1)
- if key == ""{
+ if key == "" {
c.Abort("404")
}
- book,err := models.NewBookResult().FindByIdentify(key,c.Member.MemberId)
+ book, err := models.NewBookResult().FindByIdentify(key, c.Member.MemberId)
if err != nil {
if err == models.ErrPermissionDenied {
c.Abort("403")
@@ -363,20 +361,20 @@ func (c *BookController) Users() {
c.Data["Model"] = *book
- members,totalCount,err := models.NewMemberRelationshipResult().FindForUsersByBookId(book.BookId,pageIndex,15)
+ members, totalCount, err := models.NewMemberRelationshipResult().FindForUsersByBookId(book.BookId, pageIndex, 15)
if totalCount > 0 {
html := utils.GetPagerHtml(c.Ctx.Request.RequestURI, pageIndex, 10, totalCount)
c.Data["PageHtml"] = html
- }else{
+ } else {
c.Data["PageHtml"] = ""
}
- b,err := json.Marshal(members)
+ b, err := json.Marshal(members)
if err != nil {
c.Data["Result"] = template.JS("[]")
- }else{
+ } else {
c.Data["Result"] = template.JS(string(b))
}
}
@@ -385,28 +383,28 @@ func (c *BookController) Users() {
func (c *BookController) Create() {
if c.Ctx.Input.IsPost() {
- book_name := strings.TrimSpace(c.GetString("book_name",""))
- identify := strings.TrimSpace(c.GetString("identify",""))
- description := strings.TrimSpace(c.GetString("description",""))
- privately_owned,_ := strconv.Atoi(c.GetString("privately_owned"))
+ book_name := strings.TrimSpace(c.GetString("book_name", ""))
+ identify := strings.TrimSpace(c.GetString("identify", ""))
+ description := strings.TrimSpace(c.GetString("description", ""))
+ privately_owned, _ := strconv.Atoi(c.GetString("privately_owned"))
comment_status := c.GetString("comment_status")
if book_name == "" {
- c.JsonResult(6001,"项目名称不能为空")
+ c.JsonResult(6001, "项目名称不能为空")
}
if identify == "" {
- c.JsonResult(6002,"项目标识不能为空")
+ c.JsonResult(6002, "项目标识不能为空")
}
- if ok,err := regexp.MatchString(`^[a-z]+[a-zA-Z0-9_\-]*$`,identify); !ok || err != nil {
- c.JsonResult(6003,"项目标识只能包含小写字母、数字,以及“-”和“_”符号,并且只能小写字母开头")
+ if ok, err := regexp.MatchString(`^[a-z]+[a-zA-Z0-9_\-]*$`, identify); !ok || err != nil {
+ c.JsonResult(6003, "项目标识只能包含小写字母、数字,以及“-”和“_”符号,并且只能小写字母开头")
}
- if strings.Count(identify,"") > 50 {
- c.JsonResult(6004,"文档标识不能超过50字")
+ if strings.Count(identify, "") > 50 {
+ c.JsonResult(6004, "文档标识不能超过50字")
}
- if strings.Count(description,"") > 500 {
- c.JsonResult(6004,"项目描述不能大于500字")
+ if strings.Count(description, "") > 500 {
+ c.JsonResult(6004, "项目描述不能大于500字")
}
- if privately_owned !=0 && privately_owned != 1 {
+ if privately_owned != 0 && privately_owned != 1 {
privately_owned = 1
}
if comment_status != "open" && comment_status != "closed" && comment_status != "group_only" && comment_status != "registered_only" {
@@ -415,39 +413,39 @@ func (c *BookController) Create() {
book := models.NewBook()
- if books,_ := book.FindByField("identify",identify); len(books) > 0 {
- c.JsonResult(6006,"项目标识已存在")
+ if books, _ := book.FindByField("identify", identify); len(books) > 0 {
+ c.JsonResult(6006, "项目标识已存在")
}
- book.BookName = book_name
+ book.BookName = book_name
book.Description = description
book.CommentCount = 0
book.PrivatelyOwned = privately_owned
book.CommentStatus = comment_status
- book.Identify = identify
- book.DocCount = 0
- book.MemberId = c.Member.MemberId
+ book.Identify = identify
+ book.DocCount = 0
+ book.MemberId = c.Member.MemberId
book.CommentCount = 0
- book.Version = time.Now().Unix()
- book.Cover = conf.GetDefaultCover()
- book.Editor = "markdown"
- book.Theme = "default"
+ book.Version = time.Now().Unix()
+ book.Cover = conf.GetDefaultCover()
+ book.Editor = "markdown"
+ book.Theme = "default"
err := book.Insert()
if err != nil {
- logs.Error("Insert => ",err)
- c.JsonResult(6005,"保存项目失败")
+ logs.Error("Insert => ", err)
+ c.JsonResult(6005, "保存项目失败")
}
- bookResult,err := models.NewBookResult().FindByIdentify(book.Identify,c.Member.MemberId)
+ bookResult, err := models.NewBookResult().FindByIdentify(book.Identify, c.Member.MemberId)
if err != nil {
beego.Error(err)
}
- c.JsonResult(0,"ok",bookResult)
+ c.JsonResult(0, "ok", bookResult)
}
- c.JsonResult(6001,"error")
+ c.JsonResult(6001, "error")
}
// CreateToken 创建访问来令牌.
@@ -455,22 +453,22 @@ func (c *BookController) CreateToken() {
action := c.GetString("action")
- bookResult ,err := c.IsPermission()
+ bookResult, err := c.IsPermission()
if err != nil {
if err == models.ErrPermissionDenied {
- c.JsonResult(403,"权限不足")
+ c.JsonResult(403, "权限不足")
}
if err == orm.ErrNoRows {
- c.JsonResult(404,"项目不存在")
+ c.JsonResult(404, "项目不存在")
}
- logs.Error("生成阅读令牌失败 =>",err)
- c.JsonResult(6002,err.Error())
+ logs.Error("生成阅读令牌失败 =>", err)
+ c.JsonResult(6002, err.Error())
}
book := models.NewBook()
- if _,err := book.Find(bookResult.BookId);err != nil {
- c.JsonResult(6001,"项目不存在")
+ if _, err := book.Find(bookResult.BookId); err != nil {
+ c.JsonResult(6001, "项目不存在")
}
if action == "create" {
if bookResult.PrivatelyOwned == 0 {
@@ -482,14 +480,14 @@ func (c *BookController) CreateToken() {
logs.Error("生成阅读令牌失败 => ", err)
c.JsonResult(6003, "生成阅读令牌失败")
}
- c.JsonResult(0, "ok", c.BaseUrl() + beego.URLFor("DocumentController.Index",":key",book.Identify,"token",book.PrivateToken))
- }else{
+ c.JsonResult(0, "ok", c.BaseUrl()+beego.URLFor("DocumentController.Index", ":key", book.Identify, "token", book.PrivateToken))
+ } else {
book.PrivateToken = ""
- if err := book.Update();err != nil {
- logs.Error("CreateToken => ",err)
- c.JsonResult(6004,"删除令牌失败")
+ if err := book.Update(); err != nil {
+ logs.Error("CreateToken => ", err)
+ c.JsonResult(6004, "删除令牌失败")
}
- c.JsonResult(0,"ok","")
+ c.JsonResult(0, "ok", "")
}
}
@@ -497,25 +495,25 @@ func (c *BookController) CreateToken() {
func (c *BookController) Delete() {
c.Prepare()
- bookResult ,err := c.IsPermission()
+ bookResult, err := c.IsPermission()
if err != nil {
- c.JsonResult(6001,err.Error())
+ c.JsonResult(6001, err.Error())
}
if bookResult.RoleId != conf.BookFounder {
- c.JsonResult(6002,"只有创始人才能删除项目")
+ c.JsonResult(6002, "只有创始人才能删除项目")
}
err = models.NewBook().ThoroughDeleteBook(bookResult.BookId)
if err == orm.ErrNoRows {
- c.JsonResult(6002,"项目不存在")
+ c.JsonResult(6002, "项目不存在")
}
if err != nil {
- logs.Error("删除项目 => ",err)
- c.JsonResult(6003,"删除失败")
+ logs.Error("删除项目 => ", err)
+ c.JsonResult(6003, "删除失败")
}
- c.JsonResult(0,"ok")
+ c.JsonResult(0, "ok")
}
//发布项目.
@@ -524,15 +522,15 @@ func (c *BookController) Release() {
identify := c.GetString("identify")
- book_id := 0
+ bookId := 0
if c.Member.IsAdministrator() {
- book,err := models.NewBook().FindByFieldFirst("identify",identify)
+ book, err := models.NewBook().FindByFieldFirst("identify", identify)
if err != nil {
}
- book_id = book.BookId
- }else {
+ bookId = book.BookId
+ } else {
book, err := models.NewBookResult().FindByIdentify(identify, c.Member.MemberId)
if err != nil {
@@ -548,15 +546,18 @@ func (c *BookController) Release() {
if book.RoleId != conf.BookAdmin && book.RoleId != conf.BookFounder && book.RoleId != conf.BookEditor {
c.JsonResult(6003, "权限不足")
}
- book_id = book.BookId
+ bookId = book.BookId
}
go func(identify string) {
- models.NewDocument().ReleaseContent(book_id)
+ models.NewDocument().ReleaseContent(bookId)
+ //当文档发布后,需要删除已缓存的转换项目
+ outputPath := filepath.Join(beego.AppConfig.DefaultString("book_output_path", "cache"), strconv.Itoa(bookId))
+ os.RemoveAll(outputPath)
}(identify)
- c.JsonResult(0,"发布任务已推送到任务队列,稍后将在后台执行。")
+ c.JsonResult(0, "发布任务已推送到任务队列,稍后将在后台执行。")
}
//文档排序.
@@ -570,94 +571,91 @@ func (c *BookController) SaveSort() {
book_id := 0
if c.Member.IsAdministrator() {
- book,err := models.NewBook().FindByFieldFirst("identify",identify)
+ book, err := models.NewBook().FindByFieldFirst("identify", identify)
if err != nil {
}
book_id = book.BookId
- }else{
- bookResult,err := models.NewBookResult().FindByIdentify(identify,c.Member.MemberId)
+ } else {
+ bookResult, err := models.NewBookResult().FindByIdentify(identify, c.Member.MemberId)
if err != nil {
- beego.Error("DocumentController.Edit => ",err)
+ beego.Error("DocumentController.Edit => ", err)
c.Abort("403")
}
if bookResult.RoleId == conf.BookObserver {
- c.JsonResult(6002,"项目不存在或权限不足")
+ c.JsonResult(6002, "项目不存在或权限不足")
}
book_id = bookResult.BookId
}
-
content := c.Ctx.Input.RequestBody
var docs []map[string]interface{}
- err := json.Unmarshal(content,&docs)
+ err := json.Unmarshal(content, &docs)
if err != nil {
beego.Error(err)
- c.JsonResult(6003,"数据错误")
+ c.JsonResult(6003, "数据错误")
}
- for _,item := range docs {
- if doc_id,ok := item["id"].(float64);ok {
- doc,err := models.NewDocument().Find(int(doc_id));
+ for _, item := range docs {
+ if doc_id, ok := item["id"].(float64); ok {
+ doc, err := models.NewDocument().Find(int(doc_id))
if err != nil {
beego.Error(err)
- continue;
- }
- if doc.BookId != book_id {
- logs.Info("%s","权限错误")
- continue;
- }
- sort,ok := item["sort"].(float64);
- if !ok {
- beego.Info("排序数字转换失败 => ",item)
continue
}
- parent_id,ok := item["parent"].(float64)
+ if doc.BookId != book_id {
+ logs.Info("%s", "权限错误")
+ continue
+ }
+ sort, ok := item["sort"].(float64)
if !ok {
- beego.Info("父分类转换失败 => ",item)
+ beego.Info("排序数字转换失败 => ", item)
+ continue
+ }
+ parent_id, ok := item["parent"].(float64)
+ if !ok {
+ beego.Info("父分类转换失败 => ", item)
continue
}
if parent_id > 0 {
- if parent,err := models.NewDocument().Find(int(parent_id)); err != nil || parent.BookId != book_id {
+ if parent, err := models.NewDocument().Find(int(parent_id)); err != nil || parent.BookId != book_id {
continue
}
}
doc.OrderSort = int(sort)
doc.ParentId = int(parent_id)
if err := doc.InsertOrUpdate(); err != nil {
- fmt.Printf("%s",err.Error())
+ fmt.Printf("%s", err.Error())
beego.Error(err)
}
- }else{
- fmt.Printf("文档ID转换失败 => %+v",item)
+ } else {
+ fmt.Printf("文档ID转换失败 => %+v", item)
}
}
- c.JsonResult(0,"ok")
+ c.JsonResult(0, "ok")
}
-
-func (c *BookController) IsPermission() (*models.BookResult,error) {
+func (c *BookController) IsPermission() (*models.BookResult, error) {
identify := c.GetString("identify")
- book ,err := models.NewBookResult().FindByIdentify(identify,c.Member.MemberId)
+ book, err := models.NewBookResult().FindByIdentify(identify, c.Member.MemberId)
if err != nil {
if err == models.ErrPermissionDenied {
- return book,errors.New("权限不足")
+ return book, errors.New("权限不足")
}
if err == orm.ErrNoRows {
- return book,errors.New("项目不存在")
+ return book, errors.New("项目不存在")
}
- return book,err
+ return book, err
}
if book.RoleId != conf.BookAdmin && book.RoleId != conf.BookFounder {
- return book,errors.New("权限不足")
+ return book, errors.New("权限不足")
}
- return book,nil
+ return book, nil
}
-
diff --git a/controllers/book_member.go b/controllers/book_member.go
index 1e61a2c3..70e9fcab 100644
--- a/controllers/book_member.go
+++ b/controllers/book_member.go
@@ -3,10 +3,10 @@ package controllers
import (
"errors"
- "github.com/lifei6671/mindoc/models"
- "github.com/astaxie/beego/orm"
"github.com/astaxie/beego/logs"
+ "github.com/astaxie/beego/orm"
"github.com/lifei6671/mindoc/conf"
+ "github.com/lifei6671/mindoc/models"
)
type BookMemberController struct {
@@ -14,31 +14,31 @@ type BookMemberController struct {
}
// AddMember 参加参与用户.
-func (c *BookMemberController) AddMember() {
+func (c *BookMemberController) AddMember() {
identify := c.GetString("identify")
account := c.GetString("account")
- role_id,_ := c.GetInt("role_id",3)
+ role_id, _ := c.GetInt("role_id", 3)
- if identify == "" || account == ""{
- c.JsonResult(6001,"参数错误")
+ if identify == "" || account == "" {
+ c.JsonResult(6001, "参数错误")
}
- book ,err := c.IsPermission()
+ book, err := c.IsPermission()
if err != nil {
- c.JsonResult(6001,err.Error())
+ c.JsonResult(6001, err.Error())
}
member := models.NewMember()
- if _,err := member.FindByAccount(account) ; err != nil {
- c.JsonResult(404,"用户不存在")
+ if _, err := member.FindByAccount(account); err != nil {
+ c.JsonResult(404, "用户不存在")
}
if member.Status == 1 {
- c.JsonResult(6003,"用户已被禁用")
+ c.JsonResult(6003, "用户已被禁用")
}
- if _,err := models.NewRelationship().FindForRoleId(book.BookId,member.MemberId);err == nil {
- c.JsonResult(6003,"用户已存在该项目中")
+ if _, err := models.NewRelationship().FindForRoleId(book.BookId, member.MemberId); err == nil {
+ c.JsonResult(6003, "用户已存在该项目中")
}
relationship := models.NewRelationship()
@@ -53,53 +53,52 @@ func (c *BookMemberController) AddMember() {
memberRelationshipResult.BookId = book.BookId
memberRelationshipResult.ResolveRoleName()
-
- c.JsonResult(0,"ok",memberRelationshipResult)
+ c.JsonResult(0, "ok", memberRelationshipResult)
}
- c.JsonResult(500,err.Error())
+ c.JsonResult(500, err.Error())
}
// 变更指定用户在指定项目中的权限
func (c *BookMemberController) ChangeRole() {
identify := c.GetString("identify")
- member_id,_ := c.GetInt("member_id",0)
- role,_ := c.GetInt("role_id",0)
+ member_id, _ := c.GetInt("member_id", 0)
+ role, _ := c.GetInt("role_id", 0)
- if identify == "" || member_id <=0 {
- c.JsonResult(6001,"参数错误")
+ if identify == "" || member_id <= 0 {
+ c.JsonResult(6001, "参数错误")
}
if member_id == c.Member.MemberId {
- c.JsonResult(6006,"不能变更自己的权限")
+ c.JsonResult(6006, "不能变更自己的权限")
}
- book ,err := models.NewBookResult().FindByIdentify(identify,c.Member.MemberId)
+ book, err := models.NewBookResult().FindByIdentify(identify, c.Member.MemberId)
if err != nil {
if err == models.ErrPermissionDenied {
- c.JsonResult(403,"权限不足")
+ c.JsonResult(403, "权限不足")
}
if err == orm.ErrNoRows {
- c.JsonResult(404,"项目不存在")
+ c.JsonResult(404, "项目不存在")
}
- c.JsonResult(6002,err.Error())
+ c.JsonResult(6002, err.Error())
}
if book.RoleId != 0 && book.RoleId != 1 {
- c.JsonResult(403,"权限不足")
+ c.JsonResult(403, "权限不足")
}
member := models.NewMember()
- if _,err := member.Find(member_id); err != nil {
- c.JsonResult(6003,"用户不存在")
+ if _, err := member.Find(member_id); err != nil {
+ c.JsonResult(6003, "用户不存在")
}
if member.Status == 1 {
- c.JsonResult(6004,"用户已被禁用")
+ c.JsonResult(6004, "用户已被禁用")
}
- relationship,err := models.NewRelationship().UpdateRoleId(book.BookId,member_id,role);
+ relationship, err := models.NewRelationship().UpdateRoleId(book.BookId, member_id, role)
if err != nil {
- logs.Error("变更用户在项目中的权限 => ",err)
- c.JsonResult(6005,err.Error())
+ logs.Error("变更用户在项目中的权限 => ", err)
+ c.JsonResult(6005, err.Error())
}
memberRelationshipResult := models.NewMemberRelationshipResult().FromMember(member)
@@ -108,58 +107,58 @@ func (c *BookMemberController) ChangeRole() {
memberRelationshipResult.BookId = book.BookId
memberRelationshipResult.ResolveRoleName()
- c.JsonResult(0,"ok",memberRelationshipResult)
+ c.JsonResult(0, "ok", memberRelationshipResult)
}
// 删除参与者.
-func (c *BookMemberController) RemoveMember() {
+func (c *BookMemberController) RemoveMember() {
identify := c.GetString("identify")
- member_id,_ := c.GetInt("member_id",0)
+ member_id, _ := c.GetInt("member_id", 0)
- if identify == "" || member_id <=0 {
- c.JsonResult(6001,"参数错误")
+ if identify == "" || member_id <= 0 {
+ c.JsonResult(6001, "参数错误")
}
if member_id == c.Member.MemberId {
- c.JsonResult(6006,"不能删除自己")
+ c.JsonResult(6006, "不能删除自己")
}
- book ,err := models.NewBookResult().FindByIdentify(identify,c.Member.MemberId)
+ book, err := models.NewBookResult().FindByIdentify(identify, c.Member.MemberId)
if err != nil {
if err == models.ErrPermissionDenied {
- c.JsonResult(403,"权限不足")
+ c.JsonResult(403, "权限不足")
}
if err == orm.ErrNoRows {
- c.JsonResult(404,"项目不存在")
+ c.JsonResult(404, "项目不存在")
}
- c.JsonResult(6002,err.Error())
+ c.JsonResult(6002, err.Error())
}
//如果不是创始人也不是管理员则不能操作
if book.RoleId != conf.BookFounder && book.RoleId != conf.BookAdmin {
- c.JsonResult(403,"权限不足")
+ c.JsonResult(403, "权限不足")
}
- err = models.NewRelationship().DeleteByBookIdAndMemberId(book.BookId,member_id)
+ err = models.NewRelationship().DeleteByBookIdAndMemberId(book.BookId, member_id)
if err != nil {
- c.JsonResult(6007,err.Error())
+ c.JsonResult(6007, err.Error())
}
- c.JsonResult(0,"ok")
+ c.JsonResult(0, "ok")
}
-func (c *BookMemberController) IsPermission() (*models.BookResult,error) {
+func (c *BookMemberController) IsPermission() (*models.BookResult, error) {
identify := c.GetString("identify")
- book ,err := models.NewBookResult().FindByIdentify(identify,c.Member.MemberId)
+ book, err := models.NewBookResult().FindByIdentify(identify, c.Member.MemberId)
if err != nil {
if err == models.ErrPermissionDenied {
- return book,errors.New("权限不足")
+ return book, errors.New("权限不足")
}
if err == orm.ErrNoRows {
- return book,errors.New("项目不存在")
+ return book, errors.New("项目不存在")
}
- return book,err
+ return book, err
}
if book.RoleId != conf.BookAdmin && book.RoleId != conf.BookFounder {
- return book,errors.New("权限不足")
+ return book, errors.New("权限不足")
}
- return book,nil
-}
\ No newline at end of file
+ return book, nil
+}
diff --git a/controllers/comment.go b/controllers/comment.go
index 1769dcb5..ff70e555 100644
--- a/controllers/comment.go
+++ b/controllers/comment.go
@@ -4,16 +4,16 @@ type CommentController struct {
BaseController
}
-func (c *CommentController) Lists() {
-
+func (c *CommentController) Lists() {
+
}
func (c *CommentController) Create() {
- c.JsonResult(0,"ok")
+ c.JsonResult(0, "ok")
}
-func (c *CommentController) Index() {
+func (c *CommentController) Index() {
c.Prepare()
c.TplName = "comment/index.tpl"
-}
\ No newline at end of file
+}
diff --git a/controllers/document.go b/controllers/document.go
index 693e3722..4fa5fc6c 100644
--- a/controllers/document.go
+++ b/controllers/document.go
@@ -11,7 +11,7 @@ import (
"strconv"
"strings"
"time"
-
+ "net/url"
"image/png"
"bytes"
@@ -21,7 +21,6 @@ import (
"github.com/astaxie/beego/orm"
"github.com/boombuler/barcode"
"github.com/boombuler/barcode/qr"
- "github.com/lifei6671/mindoc/commands"
"github.com/lifei6671/mindoc/conf"
"github.com/lifei6671/mindoc/models"
"github.com/lifei6671/mindoc/utils"
@@ -101,12 +100,10 @@ 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() + ").")
- c.SetSession("turl", c.Ctx.Request.URL.RequestURI())
-
if c.IsAjax() {
- c.JsonResult(6000, "需要[重]登录。")
+ c.JsonResult(6000, "请重新登录。")
} else {
- c.Redirect(beego.URLFor("AccountController.Login"), 302)
+ c.Redirect(beego.URLFor("AccountController.Login")+ "?url=" + url.PathEscape(conf.BaseUrl+ c.Ctx.Request.URL.RequestURI()), 302)
}
}
@@ -156,8 +153,7 @@ func (c *DocumentController) Read() {
token := c.GetString("token")
id := c.GetString(":id")
- c.Data["DocumentId"] = id // added by dandycheung, 2017-12-08, for exporting
- beego.Info("DocumentController.Read(): c.Data[\"DocumentId\"] = ", id, ", IsAjax = ", c.IsAjax())
+ c.Data["DocumentId"] = id
if identify == "" || id == "" {
c.Abort("404")
@@ -393,7 +389,6 @@ func (c *DocumentController) Create() {
document.Identify = doc_identify
-
document.Version = time.Now().Unix()
document.DocumentName = doc_name
document.ParentId = parent_id
@@ -438,11 +433,10 @@ func (c *DocumentController) Upload() {
}
beego.Info(conf.GetUploadFileSize())
beego.Info(moreFile.Size)
- if conf.GetUploadFileSize() > 0 && moreFile.Size > conf.GetUploadFileSize() {
- c.JsonResult(6009,"查过文件允许的上传最大值")
+ if conf.GetUploadFileSize() > 0 && moreFile.Size > conf.GetUploadFileSize() {
+ c.JsonResult(6009, "查过文件允许的上传最大值")
}
-
ext := filepath.Ext(moreFile.Filename)
if ext == "" {
@@ -498,7 +492,7 @@ func (c *DocumentController) Upload() {
}
fileName := "attach_" + strconv.FormatInt(time.Now().UnixNano(), 16)
- filePath := filepath.Join(commands.WorkingDirectory, "uploads", time.Now().Format("200601"), fileName+ext)
+ filePath := filepath.Join(conf.WorkingDirectory, "uploads", time.Now().Format("200601"), fileName+ext)
path := filepath.Dir(filePath)
os.MkdirAll(path, os.ModePerm)
@@ -515,7 +509,7 @@ func (c *DocumentController) Upload() {
attachment.FileName = moreFile.Filename
attachment.CreateAt = c.Member.MemberId
attachment.FileExt = ext
- attachment.FilePath = strings.TrimPrefix(filePath, commands.WorkingDirectory)
+ attachment.FilePath = strings.TrimPrefix(filePath, conf.WorkingDirectory)
attachment.DocumentId = doc_id
if fileInfo, err := os.Stat(filePath); err == nil {
@@ -527,7 +521,7 @@ func (c *DocumentController) Upload() {
}
if strings.EqualFold(ext, ".jpg") || strings.EqualFold(ext, ".jpeg") || strings.EqualFold(ext, ".png") || strings.EqualFold(ext, ".gif") {
- attachment.HttpPath = "/" + strings.Replace(strings.TrimPrefix(filePath, commands.WorkingDirectory), "\\", "/", -1)
+ attachment.HttpPath = "/" + strings.Replace(strings.TrimPrefix(filePath, conf.WorkingDirectory), "\\", "/", -1)
if strings.HasPrefix(attachment.HttpPath, "//") {
attachment.HttpPath = string(attachment.HttpPath[1:])
}
@@ -621,7 +615,7 @@ func (c *DocumentController) DownloadAttachment() {
c.Abort("404")
}
- c.Ctx.Output.Download(filepath.Join(commands.WorkingDirectory, attachment.FilePath), attachment.FileName)
+ c.Ctx.Output.Download(filepath.Join(conf.WorkingDirectory, attachment.FilePath), attachment.FileName)
c.StopRun()
}
@@ -666,7 +660,7 @@ func (c *DocumentController) RemoveAttachment() {
c.JsonResult(6005, "删除失败")
}
- os.Remove(filepath.Join(commands.WorkingDirectory, attach.FilePath))
+ os.Remove(filepath.Join(conf.WorkingDirectory, attach.FilePath))
c.JsonResult(0, "ok", attach)
}
@@ -819,15 +813,13 @@ func (c *DocumentController) Content() {
beego.Error("DocumentHistory InsertOrUpdate => ", err)
}
}
- if auto_release {
+ if auto_release {
go func(identify string) {
models.NewDocument().ReleaseContent(book_id)
-
}(identify)
}
-
c.JsonResult(0, "ok", doc)
}
@@ -844,7 +836,6 @@ func (c *DocumentController) Content() {
c.JsonResult(0, "ok", doc)
}
-
func (c *DocumentController) GetDocumentById(id string) (doc *models.Document, err error) {
doc = models.NewDocument()
if doc_id, err := strconv.Atoi(id); err == nil {
@@ -894,55 +885,33 @@ func (c *DocumentController) Export() {
bookResult = isReadable(identify, token, c)
}
- if bookResult.PrivatelyOwned == 0 {
- // TODO: 私有项目禁止导出
- }
-
- if !strings.HasPrefix(bookResult.Cover,"http:://") && !strings.HasPrefix(bookResult.Cover,"https:://"){
+ if !strings.HasPrefix(bookResult.Cover, "http:://") && !strings.HasPrefix(bookResult.Cover, "https:://") {
bookResult.Cover = c.BaseUrl() + bookResult.Cover
}
- eBookResult,err := bookResult.Converter(c.CruSession.SessionID())
+ eBookResult, err := bookResult.Converter(c.CruSession.SessionID())
if err != nil {
beego.Error("转换文档失败:" + bookResult.BookName + " -> " + err.Error())
c.Abort("500")
}
-
if output == "pdf" {
- c.Ctx.Output.Download(eBookResult.PDFPath, identify + ".pdf")
+ c.Ctx.Output.Download(eBookResult.PDFPath, bookResult.BookName+".pdf")
- //如果没有开启缓存,则10分钟后删除
- if !bookResult.IsCacheEBook {
- defer func(pdfpath string) {
- time.Sleep(time.Minute * 10)
- os.Remove(filepath.Dir(pdfpath))
- }(eBookResult.PDFPath)
- }
- c.StopRun()
- }else if output == "epub" {
- c.Ctx.Output.Download(eBookResult.PDFPath, identify + ".epub")
+ c.Abort("200")
+ } else if output == "epub" {
+ c.Ctx.Output.Download(eBookResult.EpubPath, bookResult.BookName+".epub")
- //如果没有开启缓存,则10分钟后删除
- if !bookResult.IsCacheEBook {
- defer func(pdfpath string) {
- time.Sleep(time.Minute * 10)
- os.Remove(filepath.Dir(pdfpath))
- }(eBookResult.EpubPath)
- }
- c.StopRun()
- }else if output == "mobi" {
- c.Ctx.Output.Download(eBookResult.PDFPath, identify + ".epub")
+ c.Abort("200")
+ } else if output == "mobi" {
+ c.Ctx.Output.Download(eBookResult.MobiPath, bookResult.BookName+".epub")
- //如果没有开启缓存,则10分钟后删除
- if !bookResult.IsCacheEBook {
- defer func(pdfpath string) {
- time.Sleep(time.Minute * 10)
- os.Remove(filepath.Dir(pdfpath))
- }(eBookResult.MobiPath)
- }
- c.StopRun()
+ c.Abort("200")
+ } else if output == "docx" {
+ c.Ctx.Output.Download(eBookResult.WordPath, bookResult.BookName+".epub")
+
+ c.Abort("200")
}
c.Abort("404")
diff --git a/controllers/home.go b/controllers/home.go
index 51f9a99f..b3fcfa70 100644
--- a/controllers/home.go
+++ b/controllers/home.go
@@ -1,10 +1,12 @@
package controllers
import (
+ "net/url"
"github.com/astaxie/beego"
"github.com/lifei6671/mindoc/models"
"github.com/lifei6671/mindoc/utils"
"math"
+ "github.com/lifei6671/mindoc/conf"
)
type HomeController struct {
@@ -16,9 +18,9 @@ func (c *HomeController) Index() {
c.TplName = "home/index.tpl"
//如果没有开启匿名访问,则跳转到登录页面
if !c.EnableAnonymous && c.Member == nil {
- c.Redirect(beego.URLFor("AccountController.Login"),302)
+ c.Redirect(beego.URLFor("AccountController.Login") + "?url=" + url.PathEscape(conf.BaseUrl + c.Ctx.Request.URL.RequestURI()), 302)
}
- pageIndex,_ := c.GetInt("page",1)
+ pageIndex, _ := c.GetInt("page", 1)
pageSize := 18
member_id := 0
@@ -26,7 +28,7 @@ func (c *HomeController) Index() {
if c.Member != nil {
member_id = c.Member.MemberId
}
- books,totalCount,err := models.NewBook().FindForHomeToPager(pageIndex,pageSize,member_id)
+ books, totalCount, err := models.NewBook().FindForHomeToPager(pageIndex, pageSize, member_id)
if err != nil {
beego.Error(err)
@@ -36,18 +38,18 @@ func (c *HomeController) Index() {
html := utils.GetPagerHtml(c.Ctx.Request.RequestURI, pageIndex, pageSize, totalCount)
c.Data["PageHtml"] = html
- }else {
+ } else {
c.Data["PageHtml"] = ""
}
c.Data["TotalPages"] = int(math.Ceil(float64(totalCount) / float64(pageSize)))
c.Data["Lists"] = books
- labels ,totalCount,err := models.NewLabel().FindToPager(1,10)
+ labels, totalCount, err := models.NewLabel().FindToPager(1, 10)
if err != nil {
- c.Data["Labels"] = make([]*models.Label,0)
- }else{
+ c.Data["Labels"] = make([]*models.Label, 0)
+ } else {
c.Data["Labels"] = labels
}
}
diff --git a/controllers/label.go b/controllers/label.go
index ca36fe66..98b7386c 100644
--- a/controllers/label.go
+++ b/controllers/label.go
@@ -1,10 +1,10 @@
package controllers
import (
- "github.com/lifei6671/mindoc/models"
- "github.com/astaxie/beego/orm"
"github.com/astaxie/beego"
+ "github.com/astaxie/beego/orm"
"github.com/lifei6671/mindoc/conf"
+ "github.com/lifei6671/mindoc/models"
"github.com/lifei6671/mindoc/utils"
"math"
)
@@ -18,7 +18,7 @@ func (c *LabelController) Prepare() {
//如果没有开启你们访问则跳转到登录
if !c.EnableAnonymous && c.Member == nil {
- c.Redirect(beego.URLFor("AccountController.Login"),302)
+ c.Redirect(beego.URLFor("AccountController.Login"), 302)
return
}
}
@@ -29,16 +29,16 @@ func (c *LabelController) Index() {
c.TplName = "label/index.tpl"
labelName := c.Ctx.Input.Param(":key")
- pageIndex,_ := c.GetInt("page",1)
+ pageIndex, _ := c.GetInt("page", 1)
if labelName == "" {
c.Abort("404")
}
- _,err := models.NewLabel().FindFirst("label_name",labelName)
+ _, err := models.NewLabel().FindFirst("label_name", labelName)
if err != nil {
if err == orm.ErrNoRows {
c.Abort("404")
- }else{
+ } else {
beego.Error(err)
c.Abort("500")
}
@@ -47,7 +47,7 @@ func (c *LabelController) Index() {
if c.Member != nil {
member_id = c.Member.MemberId
}
- search_result,totalCount,err := models.NewBook().FindForLabelToPager(labelName,pageIndex,conf.PageSize,member_id)
+ search_result, totalCount, err := models.NewBook().FindForLabelToPager(labelName, pageIndex, conf.PageSize, member_id)
if err != nil {
beego.Error(err)
@@ -57,7 +57,7 @@ func (c *LabelController) Index() {
html := utils.GetPagerHtml(c.Ctx.Request.RequestURI, pageIndex, conf.PageSize, totalCount)
c.Data["PageHtml"] = html
- }else {
+ } else {
c.Data["PageHtml"] = ""
}
c.Data["Lists"] = search_result
@@ -69,25 +69,22 @@ func (c *LabelController) List() {
c.Prepare()
c.TplName = "label/list.tpl"
- pageIndex,_ := c.GetInt("page",1)
+ pageIndex, _ := c.GetInt("page", 1)
pageSize := 200
- labels ,totalCount,err := models.NewLabel().FindToPager(pageIndex,pageSize)
+ labels, totalCount, err := models.NewLabel().FindToPager(pageIndex, pageSize)
if err != nil {
- c.ShowErrorPage(50001,err.Error())
+ c.ShowErrorPage(50001, err.Error())
}
if totalCount > 0 {
html := utils.GetPagerHtml(c.Ctx.Request.RequestURI, pageIndex, pageSize, totalCount)
c.Data["PageHtml"] = html
- }else {
+ } else {
c.Data["PageHtml"] = ""
}
c.Data["TotalPages"] = int(math.Ceil(float64(totalCount) / float64(pageSize)))
c.Data["Labels"] = labels
}
-
-
-
diff --git a/controllers/manager.go b/controllers/manager.go
index 17e4085b..6b1e7f8f 100644
--- a/controllers/manager.go
+++ b/controllers/manager.go
@@ -13,7 +13,6 @@ import (
"github.com/lifei6671/mindoc/models"
"github.com/lifei6671/mindoc/utils"
"path/filepath"
- "github.com/lifei6671/mindoc/commands"
"strconv"
)
@@ -21,7 +20,7 @@ type ManagerController struct {
BaseController
}
-func (c *ManagerController) Prepare (){
+func (c *ManagerController) Prepare() {
c.BaseController.Prepare()
if !c.Member.IsAdministrator() {
@@ -42,7 +41,7 @@ func (c *ManagerController) Users() {
pageIndex, _ := c.GetInt("page", 0)
- members, totalCount, err := models.NewMember().FindToPager(pageIndex, 15)
+ members, totalCount, err := models.NewMember().FindToPager(pageIndex, conf.PageSize)
if err != nil {
c.Data["ErrorMessage"] = err.Error()
@@ -50,7 +49,7 @@ func (c *ManagerController) Users() {
}
if totalCount > 0 {
- html := utils.GetPagerHtml(c.Ctx.Request.RequestURI, pageIndex, 10, int(totalCount))
+ html := utils.GetPagerHtml(c.Ctx.Request.RequestURI, pageIndex, conf.PageSize, int(totalCount))
c.Data["PageHtml"] = html
} else {
@@ -139,10 +138,10 @@ func (c *ManagerController) UpdateMemberStatus() {
c.JsonResult(6002, "用户不存在")
}
if member.MemberId == c.Member.MemberId {
- c.JsonResult(6004,"不能变更自己的状态")
+ c.JsonResult(6004, "不能变更自己的状态")
}
if member.Role == conf.MemberSuperRole {
- c.JsonResult(6005,"不能变更超级管理员的状态")
+ c.JsonResult(6005, "不能变更超级管理员的状态")
}
member.Status = status
@@ -171,10 +170,10 @@ func (c *ManagerController) ChangeMemberRole() {
c.JsonResult(6002, "用户不存在")
}
if member.MemberId == c.Member.MemberId {
- c.JsonResult(6004,"不能变更自己的权限")
+ c.JsonResult(6004, "不能变更自己的权限")
}
if member.Role == conf.MemberSuperRole {
- c.JsonResult(6005,"不能变更超级管理员的权限")
+ c.JsonResult(6005, "不能变更超级管理员的权限")
}
member.Role = role
@@ -191,13 +190,13 @@ func (c *ManagerController) EditMember() {
c.Prepare()
c.TplName = "manager/edit_users.tpl"
- member_id,_ := c.GetInt(":id",0)
+ member_id, _ := c.GetInt(":id", 0)
if member_id <= 0 {
c.Abort("404")
}
- member ,err := models.NewMember().Find(member_id)
+ member, err := models.NewMember().Find(member_id)
if err != nil {
beego.Error(err)
@@ -213,64 +212,64 @@ func (c *ManagerController) EditMember() {
member.Phone = phone
member.Description = description
if password1 != "" && password2 != password1 {
- c.JsonResult(6001,"确认密码不正确")
+ c.JsonResult(6001, "确认密码不正确")
}
- if password1 != "" && member.AuthMethod != conf.AuthMethodLDAP{
+ if password1 != "" && member.AuthMethod != conf.AuthMethodLDAP {
member.Password = password1
}
- if err := member.Valid(password1 == "");err != nil {
- c.JsonResult(6002,err.Error())
+ if err := member.Valid(password1 == ""); err != nil {
+ c.JsonResult(6002, err.Error())
}
if password1 != "" {
- password,err := utils.PasswordHash(password1)
+ password, err := utils.PasswordHash(password1)
if err != nil {
beego.Error(err)
- c.JsonResult(6003,"对用户密码加密时出错")
+ c.JsonResult(6003, "对用户密码加密时出错")
}
member.Password = password
}
- if err := member.Update();err != nil {
+ if err := member.Update(); err != nil {
beego.Error(err)
- c.JsonResult(6004,"保存失败")
+ c.JsonResult(6004, "保存失败")
}
- c.JsonResult(0,"ok")
+ c.JsonResult(0, "ok")
}
c.Data["Model"] = member
}
//删除一个用户,并将该用户的所有信息转移到超级管理员上.
-func (c *ManagerController) DeleteMember() {
+func (c *ManagerController) DeleteMember() {
c.Prepare()
- member_id,_ := c.GetInt("id",0)
+ member_id, _ := c.GetInt("id", 0)
if member_id <= 0 {
- c.JsonResult(404,"参数错误")
+ c.JsonResult(404, "参数错误")
}
- member ,err := models.NewMember().Find(member_id)
+ member, err := models.NewMember().Find(member_id)
if err != nil {
beego.Error(err)
- c.JsonResult(500,"用户不存在")
+ c.JsonResult(500, "用户不存在")
}
if member.Role == conf.MemberSuperRole {
- c.JsonResult(500,"不能删除超级管理员")
+ c.JsonResult(500, "不能删除超级管理员")
}
- superMember,err := models.NewMember().FindByFieldFirst("role",0)
+ superMember, err := models.NewMember().FindByFieldFirst("role", 0)
if err != nil {
beego.Error(err)
- c.JsonResult(5001,"未能找到超级管理员")
+ c.JsonResult(5001, "未能找到超级管理员")
}
- err = models.NewMember().Delete(member_id,superMember.MemberId)
+ err = models.NewMember().Delete(member_id, superMember.MemberId)
if err != nil {
beego.Error(err)
- c.JsonResult(5002,"删除失败")
+ c.JsonResult(5002, "删除失败")
}
- c.JsonResult(0,"ok")
+ c.JsonResult(0, "ok")
}
//项目列表.
@@ -572,9 +571,9 @@ func (c *ManagerController) AttachList() {
c.Data["PageHtml"] = ""
}
- for _,item := range attachList {
+ for _, item := range attachList {
- p := filepath.Join(commands.WorkingDirectory,item.FilePath)
+ p := filepath.Join(conf.WorkingDirectory, item.FilePath)
item.IsExist = utils.FileExists(p)
@@ -583,27 +582,27 @@ func (c *ManagerController) AttachList() {
}
//附件详情.
-func (c *ManagerController) AttachDetailed() {
+func (c *ManagerController) AttachDetailed() {
c.Prepare()
c.TplName = "manager/attach_detailed.tpl"
- attach_id,_ := strconv.Atoi(c.Ctx.Input.Param(":id"))
+ attach_id, _ := strconv.Atoi(c.Ctx.Input.Param(":id"))
if attach_id <= 0 {
c.Abort("404")
}
- attach,err := models.NewAttachmentResult().Find(attach_id)
+ attach, err := models.NewAttachmentResult().Find(attach_id)
if err != nil {
- beego.Error("AttachDetailed => ",err)
+ beego.Error("AttachDetailed => ", err)
if err == orm.ErrNoRows {
c.Abort("404")
- }else{
+ } else {
c.Abort("500")
}
}
- attach.FilePath = filepath.Join(commands.WorkingDirectory,attach.FilePath)
+ attach.FilePath = filepath.Join(conf.WorkingDirectory, attach.FilePath)
attach.HttpPath = c.BaseUrl() + attach.HttpPath
attach.IsExist = utils.FileExists(attach.FilePath)
@@ -612,43 +611,22 @@ func (c *ManagerController) AttachDetailed() {
}
//删除附件.
-func (c *ManagerController) AttachDelete() {
+func (c *ManagerController) AttachDelete() {
c.Prepare()
- attach_id,_ := c.GetInt("attach_id")
+ attach_id, _ := c.GetInt("attach_id")
if attach_id <= 0 {
c.Abort("404")
}
- attach,err := models.NewAttachment().Find(attach_id)
+ attach, err := models.NewAttachment().Find(attach_id)
if err != nil {
- beego.Error("AttachDelete => ",err)
- c.JsonResult(6001,err.Error())
+ beego.Error("AttachDelete => ", err)
+ c.JsonResult(6001, err.Error())
}
- if err := attach.Delete();err != nil {
- beego.Error("AttachDelete => ",err)
- c.JsonResult(6002,err.Error())
+ if err := attach.Delete(); err != nil {
+ beego.Error("AttachDelete => ", err)
+ c.JsonResult(6002, err.Error())
}
- c.JsonResult(0,"ok")
+ c.JsonResult(0, "ok")
}
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
diff --git a/controllers/search.go b/controllers/search.go
index 4681acae..9387aaf1 100644
--- a/controllers/search.go
+++ b/controllers/search.go
@@ -1,31 +1,31 @@
package controllers
import (
- "github.com/lifei6671/mindoc/models"
- "github.com/lifei6671/mindoc/conf"
- "github.com/lifei6671/mindoc/utils"
"github.com/astaxie/beego"
- "strings"
+ "github.com/lifei6671/mindoc/conf"
+ "github.com/lifei6671/mindoc/models"
+ "github.com/lifei6671/mindoc/utils"
"regexp"
"strconv"
+ "strings"
)
type SearchController struct {
BaseController
}
-func (c *SearchController) Index() {
+func (c *SearchController) Index() {
c.Prepare()
c.TplName = "search/index.tpl"
//如果没有开启你们访问则跳转到登录
if !c.EnableAnonymous && c.Member == nil {
- c.Redirect(beego.URLFor("AccountController.Login"),302)
+ c.Redirect(beego.URLFor("AccountController.Login"), 302)
return
}
keyword := c.GetString("keyword")
- pageIndex,_ := c.GetInt("page",1)
+ pageIndex, _ := c.GetInt("page", 1)
c.Data["BaseUrl"] = c.BaseUrl()
@@ -35,7 +35,7 @@ func (c *SearchController) Index() {
if c.Member != nil {
member_id = c.Member.MemberId
}
- search_result,totalCount,err := models.NewDocumentSearchResult().FindToPager(keyword,pageIndex,conf.PageSize,member_id)
+ search_result, totalCount, err := models.NewDocumentSearchResult().FindToPager(keyword, pageIndex, conf.PageSize, member_id)
if err != nil {
beego.Error(err)
@@ -45,12 +45,12 @@ func (c *SearchController) Index() {
html := utils.GetPagerHtml(c.Ctx.Request.RequestURI, pageIndex, conf.PageSize, totalCount)
c.Data["PageHtml"] = html
- }else {
+ } else {
c.Data["PageHtml"] = ""
}
if len(search_result) > 0 {
- for _,item := range search_result {
- item.DocumentName = strings.Replace(item.DocumentName,keyword,"" + keyword + "",-1)
+ for _, item := range search_result {
+ item.DocumentName = strings.Replace(item.DocumentName, keyword, ""+keyword+"", -1)
if item.Description != "" {
src := item.Description
@@ -79,13 +79,13 @@ func (c *SearchController) Index() {
if len(r) > 100 {
src = string(r[:100])
- }else{
+ } else {
src = string(r)
}
- item.Description = strings.Replace(src, keyword, "" + keyword + "", -1)
+ item.Description = strings.Replace(src, keyword, ""+keyword+"", -1)
}
- if item.Identify == ""{
+ if item.Identify == "" {
item.Identify = strconv.Itoa(item.DocumentId)
}
if item.ModifyTime.IsZero() {
diff --git a/controllers/setting.go b/controllers/setting.go
index 04852cf2..11e0b867 100644
--- a/controllers/setting.go
+++ b/controllers/setting.go
@@ -3,24 +3,23 @@ package controllers
import (
"fmt"
"os"
- "strings"
"path/filepath"
"strconv"
+ "strings"
"time"
"github.com/astaxie/beego/logs"
+ "github.com/lifei6671/mindoc/conf"
+ "github.com/lifei6671/mindoc/graphics"
"github.com/lifei6671/mindoc/models"
"github.com/lifei6671/mindoc/utils"
- "github.com/lifei6671/mindoc/graphics"
- "github.com/lifei6671/mindoc/conf"
- "github.com/lifei6671/mindoc/commands"
)
type SettingController struct {
BaseController
}
-func (c *SettingController) Index() {
+func (c *SettingController) Index() {
c.TplName = "setting/index.tpl"
if c.Ctx.Input.IsPost() {
@@ -43,131 +42,129 @@ func (c *SettingController) Index() {
}
}
-func (c *SettingController) Password() {
+func (c *SettingController) Password() {
c.TplName = "setting/password.tpl"
if c.Ctx.Input.IsPost() {
if c.Member.AuthMethod == conf.AuthMethodLDAP {
- c.JsonResult(6009,"当前用户不支持修改密码")
+ c.JsonResult(6009, "当前用户不支持修改密码")
}
password1 := c.GetString("password1")
password2 := c.GetString("password2")
password3 := c.GetString("password3")
if password1 == "" {
- c.JsonResult(6003,"原密码不能为空")
+ c.JsonResult(6003, "原密码不能为空")
}
if password2 == "" {
- c.JsonResult(6004,"新密码不能为空")
+ c.JsonResult(6004, "新密码不能为空")
}
- if count := strings.Count(password2,""); count < 6 || count > 18 {
- c.JsonResult(6009,"密码必须在6-18字之间")
+ if count := strings.Count(password2, ""); count < 6 || count > 18 {
+ c.JsonResult(6009, "密码必须在6-18字之间")
}
if password2 != password3 {
- c.JsonResult(6003,"确认密码不正确")
+ c.JsonResult(6003, "确认密码不正确")
}
- if ok,_ := utils.PasswordVerify(c.Member.Password,password1) ; !ok {
- c.JsonResult(6005,"原始密码不正确")
+ if ok, _ := utils.PasswordVerify(c.Member.Password, password1); !ok {
+ c.JsonResult(6005, "原始密码不正确")
}
if password1 == password2 {
- c.JsonResult(6006,"新密码不能和原始密码相同")
+ c.JsonResult(6006, "新密码不能和原始密码相同")
}
- pwd,err := utils.PasswordHash(password2)
+ pwd, err := utils.PasswordHash(password2)
if err != nil {
- c.JsonResult(6007,"密码加密失败")
+ c.JsonResult(6007, "密码加密失败")
}
c.Member.Password = pwd
- if err := c.Member.Update();err != nil {
- c.JsonResult(6008,err.Error())
+ if err := c.Member.Update(); err != nil {
+ c.JsonResult(6008, err.Error())
}
- c.JsonResult(0,"ok")
+ c.JsonResult(0, "ok")
}
}
// Upload 上传图片
func (c *SettingController) Upload() {
- file,moreFile,err := c.GetFile("image-file")
+ file, moreFile, err := c.GetFile("image-file")
defer file.Close()
if err != nil {
- logs.Error("",err.Error())
- c.JsonResult(500,"读取文件异常")
+ logs.Error("", err.Error())
+ c.JsonResult(500, "读取文件异常")
}
ext := filepath.Ext(moreFile.Filename)
- if !strings.EqualFold(ext,".png") && !strings.EqualFold(ext,".jpg") && !strings.EqualFold(ext,".gif") && !strings.EqualFold(ext,".jpeg") {
- c.JsonResult(500,"不支持的图片格式")
+ if !strings.EqualFold(ext, ".png") && !strings.EqualFold(ext, ".jpg") && !strings.EqualFold(ext, ".gif") && !strings.EqualFold(ext, ".jpeg") {
+ c.JsonResult(500, "不支持的图片格式")
}
-
- x1 ,_ := strconv.ParseFloat(c.GetString("x"),10)
- y1 ,_ := strconv.ParseFloat(c.GetString("y"),10)
- w1 ,_ := strconv.ParseFloat(c.GetString("width"),10)
- h1 ,_ := strconv.ParseFloat(c.GetString("height"),10)
+ x1, _ := strconv.ParseFloat(c.GetString("x"), 10)
+ y1, _ := strconv.ParseFloat(c.GetString("y"), 10)
+ w1, _ := strconv.ParseFloat(c.GetString("width"), 10)
+ h1, _ := strconv.ParseFloat(c.GetString("height"), 10)
x := int(x1)
y := int(y1)
width := int(w1)
height := int(h1)
- fmt.Println(x,x1,y,y1)
+ fmt.Println(x, x1, y, y1)
- fileName := "avatar_" + strconv.FormatInt(time.Now().UnixNano(), 16)
+ fileName := "avatar_" + strconv.FormatInt(time.Now().UnixNano(), 16)
- filePath := filepath.Join(commands.WorkingDirectory,"uploads" , time.Now().Format("200601") , fileName + ext)
+ filePath := filepath.Join(conf.WorkingDirectory, "uploads", time.Now().Format("200601"), fileName+ext)
path := filepath.Dir(filePath)
os.MkdirAll(path, os.ModePerm)
- err = c.SaveToFile("image-file",filePath)
+ err = c.SaveToFile("image-file", filePath)
if err != nil {
- logs.Error("",err)
- c.JsonResult(500,"图片保存失败")
+ logs.Error("", err)
+ c.JsonResult(500, "图片保存失败")
}
-
//剪切图片
- subImg,err := graphics.ImageCopyFromFile(filePath,x,y,width,height)
+ subImg, err := graphics.ImageCopyFromFile(filePath, x, y, width, height)
if err != nil {
- logs.Error("ImageCopyFromFile => ",err)
- c.JsonResult(6001,"头像剪切失败")
+ logs.Error("ImageCopyFromFile => ", err)
+ c.JsonResult(6001, "头像剪切失败")
}
os.Remove(filePath)
- filePath = filepath.Join(commands.WorkingDirectory,"uploads" , time.Now().Format("200601") , fileName + "_small" + ext)
+ filePath = filepath.Join(conf.WorkingDirectory, "uploads", time.Now().Format("200601"), fileName+"_small"+ext)
- err = graphics.ImageResizeSaveFile(subImg,120,120,filePath)
+ err = graphics.ImageResizeSaveFile(subImg, 120, 120, filePath)
//err = graphics.SaveImage(filePath,subImg)
if err != nil {
- logs.Error("保存文件失败 => ",err.Error())
- c.JsonResult(500,"保存文件失败")
+ logs.Error("保存文件失败 => ", err.Error())
+ c.JsonResult(500, "保存文件失败")
}
- url := "/" + strings.Replace(strings.TrimPrefix(filePath,commands.WorkingDirectory),"\\","/",-1)
- if strings.HasPrefix(url,"//") {
+ url := "/" + strings.Replace(strings.TrimPrefix(filePath, conf.WorkingDirectory), "\\", "/", -1)
+ if strings.HasPrefix(url, "//") {
url = string(url[1:])
}
- if member,err := models.NewMember().Find(c.Member.MemberId);err == nil {
+ if member, err := models.NewMember().Find(c.Member.MemberId); err == nil {
avater := member.Avatar
member.Avatar = url
- err := member.Update();
+ err := member.Update()
if err == nil {
- if strings.HasPrefix(avater,"/uploads/") {
- os.Remove(filepath.Join(commands.WorkingDirectory,avater))
+ if strings.HasPrefix(avater, "/uploads/") {
+ os.Remove(filepath.Join(conf.WorkingDirectory, avater))
}
c.SetMember(*member)
- }else{
- c.JsonResult(60001,"保存头像失败")
+ } else {
+ c.JsonResult(60001, "保存头像失败")
}
}
- c.JsonResult(0,"ok",url)
-}
\ No newline at end of file
+ c.JsonResult(0, "ok", url)
+}
diff --git a/converter/converter.go b/converter/converter.go
index 700caf72..020450f0 100644
--- a/converter/converter.go
+++ b/converter/converter.go
@@ -11,14 +11,12 @@ import (
"strings"
"time"
-
"os/exec"
-
"errors"
- "github.com/TruthHun/gotil/cryptil"
- "github.com/TruthHun/gotil/filetil"
- "github.com/TruthHun/gotil/ziptil"
+ "github.com/lifei6671/mindoc/utils/filetil"
+ "github.com/lifei6671/mindoc/utils/ziptil"
+ "github.com/lifei6671/mindoc/utils/cryptil"
)
type Converter struct {
@@ -67,6 +65,7 @@ var (
output = "output" //文档导出文件夹
ebookConvert = "ebook-convert"
)
+
// 接口文档 https://manual.calibre-ebook.com/generated/en/ebook-convert.html#table-of-contents
//根据json配置文件,创建文档转化对象
func NewConverter(configFile string, debug ...bool) (converter *Converter, err error) {
@@ -124,7 +123,8 @@ func (this *Converter) Convert() (err error) {
}
//将当前文件夹下的所有文件压缩成zip包,然后直接改名成content.epub
- f := this.BasePath + "/content.epub"
+ f := filepath.Join(this.BasePath, "content.epub")
+ fmt.Println("epub目录 " + f)
os.Remove(f) //如果原文件存在了,则删除;
if err = ziptil.Zip(f, this.BasePath); err == nil {
//创建导出文件夹
@@ -144,6 +144,12 @@ func (this *Converter) Convert() (err error) {
}
case "pdf":
if err = this.convertToPdf(); err != nil {
+ fmt.Println(err)
+ errs = append(errs, err.Error())
+ }
+ case "docx":
+ if err = this.convertToDocx(); err != nil {
+ fmt.Println(err)
errs = append(errs, err.Error())
}
}
@@ -157,6 +163,8 @@ func (this *Converter) Convert() (err error) {
fmt.Println(err)
}
}
+ } else {
+ fmt.Println("压缩目录出错" + err.Error())
}
return
}
@@ -164,13 +172,13 @@ func (this *Converter) Convert() (err error) {
//删除生成导出文档而创建的文件
func (this *Converter) converterDefer() {
//删除不必要的文件
- os.RemoveAll(this.BasePath + "/META-INF")
- os.RemoveAll(this.BasePath + "/content.epub")
- os.RemoveAll(this.BasePath + "/mimetype")
- os.RemoveAll(this.BasePath + "/toc.ncx")
- os.RemoveAll(this.BasePath + "/content.opf")
- os.RemoveAll(this.BasePath + "/titlepage.xhtml") //封面图片待优化
- os.RemoveAll(this.BasePath + "/summary.html") //文档目录
+ os.RemoveAll(filepath.Join(this.BasePath, "META-INF"))
+ os.RemoveAll(filepath.Join(this.BasePath, "content.epub"))
+ os.RemoveAll(filepath.Join(this.BasePath, "mimetype"))
+ os.RemoveAll(filepath.Join(this.BasePath, "toc.ncx"))
+ os.RemoveAll(filepath.Join(this.BasePath, "content.opf"))
+ os.RemoveAll(filepath.Join(this.BasePath, "titlepage.xhtml")) //封面图片待优化
+ os.RemoveAll(filepath.Join(this.BasePath, "summary.html")) //文档目录
}
//生成metainfo
@@ -182,15 +190,15 @@ func (this *Converter) generateMetaInfo() (err error) {
`
- folder := this.BasePath + "/META-INF"
+ folder := filepath.Join(this.BasePath, "META-INF")
os.MkdirAll(folder, os.ModePerm)
- err = ioutil.WriteFile(folder+"/container.xml", []byte(xml), os.ModePerm)
+ err = ioutil.WriteFile(filepath.Join(folder, "container.xml"), []byte(xml), os.ModePerm)
return
}
//形成mimetyppe
func (this *Converter) generateMimeType() (err error) {
- return ioutil.WriteFile(this.BasePath+"/mimetype", []byte("application/epub+zip"), os.ModePerm)
+ return ioutil.WriteFile(filepath.Join(this.BasePath, "mimetype"), []byte("application/epub+zip"), os.ModePerm)
}
//生成封面
@@ -216,7 +224,7 @@ func (this *Converter) generateTitlePage() (err error) {