func (l *BinLog) flushIndex() error { data := strings.Join(l.logNames, "\n") bakName := fmt.Sprintf("%s.bak", l.indexName) f, err := os.OpenFile(bakName, os.O_WRONLY|os.O_CREATE, 0666) if err != nil { log.Error("create binlog bak index error %s", err.Error()) return err } if _, err := f.WriteString(data); err != nil { log.Error("write binlog index error %s", err.Error()) f.Close() return err } f.Close() if err := os.Rename(bakName, l.indexName); err != nil { log.Error("rename binlog bak index error %s", err.Error()) return err } return nil }
func (this *NewPost) Post() error { if this.CheckActiveRedirect() { return nil } var err error form := post.PostForm{Locale: this.Locale} topicSlug := this.GetString("topic") if len(topicSlug) > 0 { topic, err := models.GetTopicBySlug(topicSlug) if err == nil { form.Category = topic.CategoryId form.Topic = topic.Id this.Data["Topic"] = topic } else { log.Error("Can not find topic by slug:", topicSlug) } } else { topicId, err := this.GetInt("Topic") if err == nil { topic, err := models.GetTopicById(topicId) if err == nil { form.Category = topic.CategoryId form.Topic = topic.Id this.Data["Topic"] = topic } else { log.Error("Can not find topic by id:", topicId) } } else { log.Error("Parse param Topic from request failed", err) } } if categorySlug := this.GetString("category"); categorySlug != "" { log.Debug("Find category slug:", categorySlug) category, err := models.GetCategoryBySlug(categorySlug) if err != nil { log.Error("Get category error", err) } this.Data["Category"] = &category } err = models.FindTopics(&form.Topics) if err != nil { return err } if !this.ValidFormSets(&form) { this.Redirect("/new") return nil } var post models.Post if err := form.SavePost(&post, &this.User); err == nil { this.JsStorage("deleteKey", "post/new") this.Redirect(post.Link()) return nil } return this.Render("post/new.html", this.Data) }
func (l *BinLog) loadIndex() error { l.indexName = path.Join(l.path, fmt.Sprintf("ledis-bin.index")) if _, err := os.Stat(l.indexName); os.IsNotExist(err) { //no index file, nothing to do } else { indexData, err := ioutil.ReadFile(l.indexName) if err != nil { return err } lines := strings.Split(string(indexData), "\n") for _, line := range lines { line = strings.Trim(line, "\r\n ") if len(line) == 0 { continue } if _, err := os.Stat(path.Join(l.path, line)); err != nil { log.Error("load index line %s error %s", line, err.Error()) return err } else { l.logNames = append(l.logNames, line) } } } if l.cfg.MaxFileNum > 0 && len(l.logNames) > l.cfg.MaxFileNum { //remove oldest logfile if err := l.Purge(len(l.logNames) - l.cfg.MaxFileNum); err != nil { return err } } var err error if len(l.logNames) == 0 { l.lastLogIndex = 1 } else { lastName := l.logNames[len(l.logNames)-1] if l.lastLogIndex, err = strconv.ParseInt(path.Ext(lastName)[1:], 10, 64); err != nil { log.Error("invalid logfile name %s", err.Error()) return err } //like mysql, if server restart, a new binlog will create l.lastLogIndex++ } return nil }
func configWatcher() { watcher, err := fsnotify.NewWatcher() if err != nil { panic("Failed start app watcher: " + err.Error()) } go func() { for { select { case event := <-watcher.Event: switch filepath.Ext(event.Name) { case ".ini": if checkEventTime(event.Name) { continue } log.Info(event) if err := Cfg.Reload(); err != nil { log.Error("Conf Reload: ", err) } if err := i18n.ReloadLangs(); err != nil { log.Error("Conf Reload: ", err) } reloadConfig() log.Info("Config Reloaded") case ".json": if checkEventTime(event.Name) { continue } if event.Name == CompressConfPath { settingCompress() log.Info("Compress Reloaded") } } } } }() if err := watcher.WatchFlags("conf", fsnotify.FSN_MODIFY); err != nil { log.Error(err) } if err := watcher.WatchFlags("conf/global", fsnotify.FSN_MODIFY); err != nil { log.Error(err) } }
func (this *BulletinAdminEdit) Post() { form := bulletin.BulletinAdminForm{Id: int(this.object.Id)} if this.ValidFormSets(&form) == false { return } // get changed field names changes := utils.FormChanges(&this.object, &form) url := fmt.Sprintf("/admin/bulletin/%d", this.object.Id) // update changed fields only if len(changes) > 0 { form.SetToBulletin(&this.object) if err := models.UpdateById(this.object.Id, this.object, models.Obj2Table(changes)...); err == nil { this.FlashRedirect(url, 302, "UpdateSuccess") return } else { log.Error(err) this.Data["Error"] = err } } else { this.Redirect(url, 302) } }
// query object and set to template func (this *ModelAdminRouter) QueryObject() bool { id, _ := utils.StrTo(this.Params().Get(":id")).Int() if id <= 0 { this.NotFound() return false } var app ModelFinder if a, ok := this.Ctx.Action().(ModelFinder); ok { app = a } else { panic("ModelAdmin AppController need implement ModelFinder") } object := app.Object() // query object if err := models.GetById(int64(id), object); err != nil { this.NotFound() if err != models.ErrNotExist { log.Error("SetObject: ", err) } return false } else { this.Data["Object"] = object } return true }
// view for update object func (this *PostAdminEdit) Post() { form := this.GetForm(false) if this.ValidFormSets(&form) == false { return } // get changed field names changes := utils.FormChanges(&this.object, &form) url := fmt.Sprintf("/admin/post/%d", this.object.Id) // update changed fields only if len(changes) > 0 { //fix the bug of category not updated changes = append(changes, "Category") form.SetToPost(&this.object) if err := models.UpdateById(this.object.Id, this.object, models.Obj2Table(changes)...); err == nil { this.FlashRedirect(url, 302, "UpdateSuccess") return } else { log.Error(err) this.Data["Error"] = err } } else { this.Redirect(url, 302) } }
// Reset implemented user password reset. func (this *ResetRouter) Post() { code := this.GetString(":code") this.Data["Code"] = code var user models.User if auth.VerifyUserResetPwdCode(&user, code) { this.Data["Success"] = true form := auth.ResetPwdForm{} if this.ValidFormSets(&form) == false { return } user.IsActive = true user.Rands = models.GetUserSalt() if err := auth.SaveNewPassword(&user, form.Password); err != nil { log.Error("ResetPost Save New Password: "******"/login", 302, "ResetSuccess") } else { this.Data["Success"] = false } this.Render("auth/reset.html", this.Data) }
// Active implemented check Email actice code. func (this *RegisterActive) Get() { // no need active if this.CheckActiveRedirect(false) { return } code := this.Params().Get(":code") var user models.User if auth.VerifyUserActiveCode(&user, code) { user.IsActive = true user.Rands = models.GetUserSalt() if err := models.UpdateById(user.Id, user, models.Obj2Table([]string{"IsActive", "Rands", "Updated"})...); err != nil { log.Error("Active: user Update ", err) } if this.IsLogin { this.User = user } this.Redirect("/active/success", 302) } else { this.Data["Success"] = false } this.Render("auth/active.html", this.Data) }
func (l *BinLog) openNewLogFile() error { var err error lastName := l.getLogFile() logPath := path.Join(l.path, lastName) if l.logFile, err = os.OpenFile(logPath, os.O_CREATE|os.O_WRONLY, 0666); err != nil { log.Error("open new logfile error %s", err.Error()) return err } if l.cfg.MaxFileNum > 0 && len(l.logNames) == l.cfg.MaxFileNum { l.purge(1) } l.logNames = append(l.logNames, lastName) if l.logWb == nil { l.logWb = bufio.NewWriterSize(l.logFile, 1024) } else { l.logWb.Reset(l.logFile) } if err = l.flushIndex(); err != nil { return err } return nil }
func (this *BulletinAdminList) Get() { var bulletins []models.Bulletin sess := models.ORM().Asc("type") if err := this.SetObjects(sess, &bulletins); err != nil { this.Data["Error"] = err log.Error(err) } }
// view for list model data func (this *TopicAdminList) Get() { var topics []models.Topic sess := models.ORM().Desc("category_id") if err := this.SetObjects(sess, &topics); err != nil { this.Data["Error"] = err log.Error(err) } }
// getFileModTime retuens unix timestamp of `os.File.ModTime` by given path. func getFileModTime(path string) int64 { path = strings.Replace(path, "\\", "/", -1) f, err := os.Open(path) if err != nil { log.Error("Fail to open file[ %s ]\n", err) return time.Now().Unix() } defer f.Close() fi, err := f.Stat() if err != nil { log.Error("Fail to get file information[ %s ]\n", err) return time.Now().Unix() } return fi.ModTime().Unix() }
// view for list model data func (this *PageAdminList) Get() { var pages []models.Page sess := models.ORM().NewSession() defer sess.Close() if err := this.SetObjects(sess, &pages); err != nil { this.Data["Error"] = err log.Error(err) } }
func (l *Nodb) FlushAll() error { for index, db := range l.dbs { if _, err := db.FlushAll(); err != nil { log.Error("flush db %d error %s", index, err.Error()) } } return nil }
func (this *PostRouter) loadComments(post *models.Post, comments *[]*models.Comment) { err := models.GetCommentsByPostId(comments, post.Id) if err == nil { this.Data["Comments"] = *comments this.Data["CommentsNum"] = len(*comments) } else { log.Error("loadComments error:", err) } }
// view for list model data func (this *CommentAdminList) Get() { var comments []models.Comment sess := models.ORM().NewSession() defer sess.Close() if err := this.SetObjects(sess, &comments); err != nil { this.Data["Error"] = err log.Error(err) } }
func (o *OAuthAccess) Get() { redirect, _, err := setting.SocialAuth.OAuthAccess(o.Context, &o.Session) if err != nil { log.Error("OAuthAccess", err) } if len(redirect) > 0 { o.Context.Redirect(redirect) } }
func PostReplysCount(post *models.Post) { cnt, err := models.CountCommentsByPostId(post.Id) if err == nil { post.Replys = int(cnt) //disable post editable post.CanEdit = false err = models.UpdateById(post.Id, post, "replys", "can_edit") } if err != nil { log.Error("PostReplysCount ", err) } }
// view for delete object func (this *CommentAdminDelete) Post() { if this.FormOnceNotMatch() { return } // delete object if err := models.DeleteById(this.object.Id, this.object); err == nil { this.FlashRedirect("/admin/comment", 302, "DeleteSuccess") return } else { log.Error(err) this.Data["Error"] = err } }
// Async Send mail message func SendAsync(msg Message) { // TODO may be need pools limit concurrent nums go func() { if num, err := Send(msg); err != nil { tos := strings.Join(msg.To, "; ") info := "" if len(msg.Info) > 0 { info = ", info: " + msg.Info } // log failed log.Error(fmt.Sprintf("Async send email %d succeed, not send emails: %s%s err: %s", num, tos, info, err)) } }() }
// view for list model data func (this *UserAdminList) Get() { var q = this.GetString("q") var users []models.User sess := models.ORM().NewSession() defer sess.Close() if q != "" { sess.Where("email = ?", q).Or("user_name = ?", q) } this.Data["q"] = q if err := this.SetObjects(sess, &users); err != nil { this.Data["Error"] = err log.Error(err) } }
// view for new object save func (this *TopicAdminNew) Post() { form := post.TopicAdminForm{Create: true} if this.ValidFormSets(&form) == false { return } var topic models.Topic form.SetToTopic(&topic) if err := models.Insert(&topic); err == nil { this.FlashRedirect(fmt.Sprintf("/admin/topic/%d", topic.Id), 302, "CreateSuccess") return } else { log.Error(err) this.Data["Error"] = err } }
func (this *BulletinAdminNew) Post() { form := bulletin.BulletinAdminForm{Create: true} if this.ValidFormSets(&form) == false { return } var bulletin models.Bulletin form.SetToBulletin(&bulletin) if err := models.Insert(&bulletin); err == nil { this.FlashRedirect(fmt.Sprintf("/admin/bulletin/%d", bulletin.Id), 302, "CreateSuccess") return } else { log.Error(err) this.Data["Error"] = err } }
// view for new object save func (this *CommentAdminNew) Post() { form := post.CommentAdminForm{Create: true} if this.ValidFormSets(&form) == false { return } var comment models.Comment form.SetToComment(&comment) if err := models.Insert(&comment); err == nil { this.FlashRedirect(fmt.Sprintf("/admin/comment/%d", comment.Id), 302, "CreateSuccess") return } else { log.Error(err) this.Data["Error"] = err } }
// view for new object save func (this *UserAdminNew) Post() { form := auth.UserAdminForm{Create: true} if this.ValidFormSets(&form) == false { return } var user models.User form.SetToUser(&user) if err := models.Insert(&user); err == nil { this.FlashRedirect(fmt.Sprintf("/admin/user/%d", user.Id), 302, "CreateSuccess") return } else { log.Error(err) this.Data["Error"] = err } }
func settingCompress() { setting, err := compress.LoadJsonConf(CompressConfPath, IsProMode, AppUrl) if err != nil { log.Error(err) return } setting.RunCommand() if IsProMode { setting.RunCompress(true, false, true) } Funcs["compress_js"] = setting.Js.CompressJs Funcs["compress_css"] = setting.Css.CompressCss }
// view for new object save func (this *PostAdminNew) Post() { form := this.GetForm(true) if !this.ValidFormSets(&form) { return } var post models.Post form.SetToPost(&post) if err := models.Insert(&post); err == nil { this.FlashRedirect(fmt.Sprintf("/admin/post/%d", post.Id), 302, "CreateSuccess") return } else { log.Error(err) this.Data["Error"] = err } }
// view for new object save func (this *PageAdminNew) Post() { form := page.PageAdminForm{Create: true} if !this.ValidFormSets(&form) { return } var a models.Page form.SetToPage(&a) if err := models.Insert(&a); err == nil { this.FlashRedirect(fmt.Sprintf("/admin/page/%d", a.Id), 302, "CreateSuccess") return } else { log.Error(err) this.Data["Error"] = err } }
func (this *BulletinAdminDelete) Post() { if this.FormOnceNotMatch() { return } cnt, _ := models.Count(&models.Bulletin{Id: this.object.Id}) if cnt > 0 { // delete object if err := models.DeleteById(this.object.Id, new(models.Bulletin)); err == nil { this.FlashRedirect("/admin/bulletin", 302, "DeleteSuccess") return } else { log.Error(err) this.Data["Error"] = err } } }