// create a time limit code // code format: 12 length date time string + 6 minutes string + 40 sha1 encoded string func CreateTimeLimitCode(data string, minutes int, startInf interface{}) string { format := "YmdHi" var start, end time.Time var startStr, endStr string if startInf == nil { // Use now time create code start = time.Now() startStr = beego.Date(start, format) } else { // use start string create code startStr = startInf.(string) start, _ = beego.DateParse(startStr, format) startStr = beego.Date(start, format) } end = start.Add(time.Minute * time.Duration(minutes)) endStr = beego.Date(end, format) // create sha1 encode string sh := sha1.New() sh.Write([]byte(data + setting.SecretKey + startStr + endStr + ToStr(minutes))) encoded := hex.EncodeToString(sh.Sum(nil)) code := fmt.Sprintf("%s%06d%s", startStr, minutes, encoded) return code }
//insert or update point func (m *Point) InsertOrUpdate() error { o := orm.NewOrm() q := Point{Id: m.Id} err := o.Read(&q) if nil != err { // not exit, insert m.CreateTime = beego.Date(time.Now(), "Y-m-d H:i:s") m.Status = 10 if _, err := o.Insert(m); err != nil { return err } } else { // update _, err := o.QueryTable(new(Point)).Filter("Id", m.Id).Update(orm.Params{ "Id": m.Id, "Name": m.Name, "Type": m.Type, "Hours": m.Hours, "Stars": m.Stars, "Points": m.Points, //"StartTime": m.StartTime, //"EndTime": m.EndTime, "UpdateTime": beego.Date(time.Now(), "Y-m-d H:i:s"), }) if nil != err { return err } } return nil }
//get specify week points. //@ w param specify how many weeks data to get (not include this week) func (this *Point) GetWeekPoints(w int) ([]string, interface{}) { var points []orm.Params o := orm.NewOrm() index_keys := []string{} result := make(map[string]interface{}) t := time.Now() sunday_str := this.GetSunday(t) t, _ = beego.DateParse(sunday_str, "Y-m-d") for i := w; i >= 0; i-- { last_sunday := t.AddDate(0, 0, -7*i) last_monday := last_sunday.AddDate(0, 0, -6) last_sunday = last_sunday.Add(time.Hour*time.Duration(23) + time.Minute*time.Duration(59) + time.Second*time.Duration(59)) end_time := beego.Date(last_sunday, "Y-m-d H:i:s") end_date := beego.Date(last_sunday, "Y-m-d") start_time := beego.Date(last_monday, "Y-m-d") data := make(map[string]interface{}) data["start_time"] = start_time data["end_date"] = end_date data["end_time"] = end_time data["time_str"] = start_time + "_" + end_time o.QueryTable(new(Point)).Filter("start_time__gte", start_time).Filter("end_time__lte", end_time).Filter("status", 10).Values(&points) data["point"] = points result[end_time] = data // index_keys[w-i] = end_time index_keys = append(index_keys, end_time) } return index_keys, result }
// 任务列表 func (this *TaskController) List() { page, _ := this.GetInt("page") if page < 1 { page = 1 } groupId, _ := this.GetInt("groupid") filters := make([]interface{}, 0) if groupId > 0 { filters = append(filters, "group_id", groupId) } result, count := models.TaskGetList(page, this.pageSize, filters...) list := make([]map[string]interface{}, len(result)) for k, v := range result { row := make(map[string]interface{}) row["id"] = v.Id row["name"] = v.TaskName row["cron_spec"] = v.CronSpec row["status"] = v.Status row["description"] = v.Description e := jobs.GetEntryById(v.Id) if e != nil { row["next_time"] = beego.Date(e.Next, "Y-m-d H:i:s") row["prev_time"] = "-" if e.Prev.Unix() > 0 { row["prev_time"] = beego.Date(e.Prev, "Y-m-d H:i:s") } else if v.PrevTime > 0 { row["prev_time"] = beego.Date(time.Unix(v.PrevTime, 0), "Y-m-d H:i:s") } row["running"] = 1 } else { row["next_time"] = "-" if v.PrevTime > 0 { row["prev_time"] = beego.Date(time.Unix(v.PrevTime, 0), "Y-m-d H:i:s") } else { row["prev_time"] = "-" } row["running"] = 0 } list[k] = row } // 分组列表 groups, _ := models.TaskGroupGetList(1, 100) this.Data["pageTitle"] = "任务列表" this.Data["list"] = list this.Data["groups"] = groups this.Data["groupid"] = groupId this.Data["pageBar"] = libs.NewPager(page, int(count), this.pageSize, beego.URLFor("TaskController.List", "groupid", groupId), true).ToString() this.display() }
func (this *LoginController) Post() { this.TplNames = "login.tpl" this.Ctx.Request.ParseForm() username := this.Ctx.Request.Form.Get("username") password := this.Ctx.Request.Form.Get("password") md5Password := md5.New() io.WriteString(md5Password, password) buffer := bytes.NewBuffer(nil) fmt.Fprintf(buffer, "%x", md5Password.Sum(nil)) newPass := buffer.String() now := beego.Date(time.Now(), "Y-m-d H:i:s") userInfo := models.GetUserInfo(username) if userInfo.Password == newPass { var users models.User users.Last_logintime = now models.UpdateUserInfo(users) //登录成功设置session sess := this.StartSession() sess.Set("uid", userInfo.Id) sess.Set("uname", userInfo.Username) this.Ctx.Redirect(302, "/") } this.Ctx.Redirect(302, "/") }
// 任务执行日志列表 func (this *TaskController) Logs() { taskId, _ := this.GetInt("id") page, _ := this.GetInt("page") if page < 1 { page = 1 } task, err := models.TaskGetById(taskId) if err != nil { this.showMsg(err.Error()) } result, count := models.TaskLogGetList(page, this.pageSize, "task_id", task.Id) list := make([]map[string]interface{}, len(result)) for k, v := range result { row := make(map[string]interface{}) row["id"] = v.Id row["start_time"] = beego.Date(time.Unix(v.CreateTime, 0), "Y-m-d H:i:s") row["process_time"] = float64(v.ProcessTime) / 1000 row["ouput_size"] = libs.SizeFormat(float64(len(v.Output))) row["status"] = v.Status list[k] = row } this.Data["pageTitle"] = "任务执行日志" this.Data["list"] = list this.Data["task"] = task this.Data["pageBar"] = libs.NewPager(page, int(count), this.pageSize, beego.URLFor("TaskController.Logs", "id", taskId), true).ToString() this.display() }
// 查看日志详情 func (this *TaskController) ViewLog() { id, _ := this.GetInt("id") taskLog, err := models.TaskLogGetById(id) if err != nil { this.showMsg(err.Error()) } task, err := models.TaskGetById(taskLog.TaskId) if err != nil { this.showMsg(err.Error()) } data := make(map[string]interface{}) data["id"] = taskLog.Id data["output"] = taskLog.Output data["error"] = taskLog.Error data["start_time"] = beego.Date(time.Unix(taskLog.CreateTime, 0), "Y-m-d H:i:s") data["process_time"] = float64(taskLog.ProcessTime) / 1000 data["ouput_size"] = libs.SizeFormat(float64(len(taskLog.Output))) data["status"] = taskLog.Status this.Data["task"] = task this.Data["data"] = data this.Data["pageTitle"] = "查看日志" this.display() }
// 首页 func (this *MainController) Index() { this.Data["pageTitle"] = "系统概况" // 即将执行的任务 entries := jobs.GetEntries(30) jobList := make([]map[string]interface{}, len(entries)) for k, v := range entries { row := make(map[string]interface{}) job := v.Job.(*jobs.Job) row["task_id"] = job.GetId() row["task_name"] = job.GetName() row["next_time"] = beego.Date(v.Next, "Y-m-d H:i:s") jobList[k] = row } // 最近执行的日志 logs, _ := models.TaskLogGetList(1, 20) recentLogs := make([]map[string]interface{}, len(logs)) for k, v := range logs { task, err := models.TaskGetById(v.TaskId) taskName := "" if err == nil { taskName = task.TaskName } row := make(map[string]interface{}) row["task_name"] = taskName row["id"] = v.Id row["start_time"] = beego.Date(time.Unix(v.CreateTime, 0), "Y-m-d H:i:s") row["process_time"] = float64(v.ProcessTime) / 1000 row["ouput_size"] = libs.SizeFormat(float64(len(v.Output))) row["output"] = beego.Substr(v.Output, 0, 100) row["status"] = v.Status recentLogs[k] = row } this.Data["recentLogs"] = recentLogs this.Data["jobs"] = jobList this.Data["cpuNum"] = runtime.NumCPU() this.display() }
// Prepare implemented Prepare method for baseRouter. func (this *baseRouter) Prepare() { if utils.IsProMode { } else { utils.AppJsVer = beego.Date(time.Now(), "YmdHis") utils.AppCssVer = beego.Date(time.Now(), "YmdHis") } // Setting properties. this.Data["AppDescription"] = utils.AppDescription this.Data["AppKeywords"] = utils.AppKeywords this.Data["AppName"] = utils.AppName this.Data["AppVer"] = utils.AppVer this.Data["AppUrl"] = utils.AppUrl this.Data["AppJsVer"] = utils.AppJsVer this.Data["AppCssVer"] = utils.AppCssVer this.Data["IsProMode"] = utils.IsProMode this.Data["IsBeta"] = utils.IsBeta // Setting language version. if len(langTypes) == 0 { // Initialize languages. langs := strings.Split(utils.Cfg.MustValue("lang", "types"), "|") names := strings.Split(utils.Cfg.MustValue("lang", "names"), "|") langTypes = make([]*langType, 0, len(langs)) for i, v := range langs { langTypes = append(langTypes, &langType{ Lang: v, Name: names[i], }) } } isNeedRedir, langVer := setLangVer(this.Ctx, this.Input(), this.Data) this.Locale.CurrentLocale = langVer // Redirect to make URL clean. if isNeedRedir { i := strings.Index(this.Ctx.Request.RequestURI, "?") this.Redirect(this.Ctx.Request.RequestURI[:i], 302) } }
//获取日历json数据 func (this *IndexModel) GetIndexJsonStr(uid int) (j []TaskJson) { var work []Memberwork //var json_str, fuhao string db.Raw("select * from "+this.tableName+" where admin_uid=? order by start desc limit 50", uid).QueryRows(&work) var jsonData []TaskJson //fmt.Println(times) for _, v := range work { jsons := TaskJson{} jsons.Color = this.GetTaskColor(v.Task_type) jsons.Id = v.Id jsons.Title = v.Title times := beego.Date(time.Unix(v.Start, 0), "Y-m-d H:i:s") jsons.Start = times if v.End > 0 { timee := beego.Date(time.Unix(v.End, 0), "Y-m-d H:i:s") jsons.End = timee } jsonData = append(jsonData, jsons) } return jsonData }
func (this *AddBlogController) Post() { this.Ctx.Request.ParseForm() title := this.Ctx.Request.Form.Get("title") content := this.Ctx.Request.Form.Get("content") //打印生成日志 defer utils.Info("addblog: ", "title:"+title, "content:"+content) var data models.Blogs data.Title = title data.Content = content //获取系统当前时间 now := beego.Date(time.Now(), "Y-m-d H:i:s") data.Created = now models.InsertBlogs(data) this.Ctx.Redirect(302, "/admin/index") }
func timesince(lang string, t time.Time) string { now := time.Now() seconds := int(now.Sub(t).Seconds()) if seconds < 60 { return i18n.Tr(lang, "seconds_ago", seconds) } else if seconds < 60*60 { return i18n.Tr(lang, "minutes_ago", seconds/60) } else if seconds < 60*60*24 { return i18n.Tr(lang, "hours_ago", seconds/(60*60)) } else if seconds < 60*60*24*100 { return i18n.Tr(lang, "days_ago", seconds/(60*60*24)) } else { return beego.Date(t, DateFormat) } }
func timesince(lang string, t time.Time) string { seconds := int(time.Since(t).Seconds()) switch { case seconds < 60: return i18n.Tr(lang, "seconds_ago", seconds) case seconds < 60*60: return i18n.Tr(lang, "minutes_ago", seconds/60) case seconds < 60*60*24: return i18n.Tr(lang, "hours_ago", seconds/(60*60)) case seconds < 60*60*24*100: return i18n.Tr(lang, "days_ago", seconds/(60*60*24)) default: return beego.Date(t, setting.DateFormat) } }
func (this *RegController) Post() { this.TplNames = "reg.tpl" this.Ctx.Request.ParseForm() username := this.Ctx.Request.Form.Get("username") password := this.Ctx.Request.Form.Get("password") usererr := checkUsername(username) fmt.Println(usererr) if usererr == false { this.Data["UsernameErr"] = "Username error, Please to again" return } passerr := checkPassword(password) if passerr == false { this.Data["PasswordErr"] = "Password error, Please to again" return } md5Password := md5.New() io.WriteString(md5Password, password) buffer := bytes.NewBuffer(nil) fmt.Fprintf(buffer, "%x", md5Password.Sum(nil)) newPass := buffer.String() now := beego.Date(time.Now(), "Y-m-d H:i:s") userInfo := models.GetUserInfo(username) if userInfo.Username == "" { var users models.User users.Username = username users.Password = newPass users.Created = now users.Last_logintime = now models.AddUser(users) //登录成功设置session sess := this.StartSession() sess.Set("uid", userInfo.Id) sess.Set("uname", userInfo.Username) this.Ctx.Redirect(302, "/") } else { this.Data["UsernameErr"] = "User already exists" } }
func (this *EditBlogController) Post() { this.Ctx.Request.ParseForm() id_str := this.Ctx.Request.Form.Get("id") id, _ := strconv.Atoi(id_str) blogInfo := models.GetBlogInfoById(id) title := this.Ctx.Request.Form.Get("title") content := this.Ctx.Request.Form.Get("content") blogInfo.Title = title blogInfo.Content = content //打印生成日志 defer utils.Info("editBlog: ", "id:"+id_str, "title:"+title, "content:"+content) //获取系统当前时间 now := beego.Date(time.Now(), "Y-m-d H:i:s") blogInfo.Created = now models.UpdateBlogInfo(blogInfo) this.Ctx.Redirect(302, "/admin/index") }
func (self *AvatarController) Post() { result := make([]interface{}, 2) result[0] = 1 result[1] = "" defer func() { self.Data["json"] = &result self.ServeJson() }() // f, h, err := self.GetFile("avatar") if err != nil { fmt.Println("getfile err ", err) } fmt.Println("filename:", h.Filename) defer f.Close() // ext := h.Filename[strings.LastIndex(h.Filename, ".")+1:] path := "upload/avatar/" + beego.Date(time.Now(), "y/m/d/h/") os.MkdirAll(path, 0744) tofile := path + strconv.Itoa(int(self.Uid)) + "." + ext tf, err := os.OpenFile(tofile, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0644) if err != nil { fmt.Println("write failed:", err) return } defer tf.Close() io.Copy(tf, f) if self.U.Avatar != "" && self.U.Avatar != setting.Default_Avatar { os.Remove(self.U.Avatar[1:]) } self.U.Avatar = "/" + tofile self.U.Update("Avatar") self.SetSession("useravatar", self.U.Avatar) // result[0] = 0 result[1] = self.U.Avatar }
func (this *Point) GetSunday(t time.Time) string { //t := time.Now() week := t.Weekday().String() var monday string switch week { case "Sunday": case "Monday": t = t.AddDate(0, 0, 6) case "Tuesday": t = t.AddDate(0, 0, 5) case "Wednesday": t = t.AddDate(0, 0, 4) case "Thursday": t = t.AddDate(0, 0, 3) case "Friday": t = t.AddDate(0, 0, 2) case "Saturday": t = t.AddDate(0, 0, 1) } //monday = t.Format(t_layout) monday = beego.Date(t, "Y-m-d") return monday }
func datetime(t time.Time) string { return beego.Date(t, DateTimeFormat) }
func (j *Job) Run() { defer func() { if err := recover(); err != nil { beego.Error(err, "\n", string(debug.Stack())) } }() t := time.Now() if j.Concurrent { j.running.Lock() defer j.running.Unlock() } if workPool != nil { workPool <- true defer func() { <-workPool }() } j.status = 1 defer func() { j.status = 0 }() bout, berr, err := j.runFunc() ut := time.Now().Sub(t) / time.Millisecond // 插入日志 log := new(models.TaskLog) log.TaskId = j.id log.Output = string(bout) log.Error = string(berr) log.ProcessTime = int(ut) log.CreateTime = t.Unix() if err != nil { log.Status = -1 log.Error = err.Error() + ":" + string(berr) } models.TaskLogAdd(log) // 更新上次执行时间 j.task.PrevTime = t.Unix() j.task.ExecuteTimes++ j.task.Update() // 发送邮件通知 if (j.task.Notify == 1 && err != nil) || j.task.Notify == 2 { user, uerr := models.UserGetById(j.task.UserId) if uerr != nil { return } title := "" if err != nil { title = fmt.Sprintf("任务执行结果通知 #%d: %s", j.task.Id, "失败") } else { title = fmt.Sprintf("任务执行结果通知 #%d: %s", j.task.Id, "成功") } data := make(map[string]interface{}) data["task_id"] = j.task.Id data["username"] = user.UserName data["task_name"] = j.task.TaskName data["start_time"] = beego.Date(t, "Y-m-d H:i:s") data["process_time"] = float64(ut) / 1000 if err != nil { data["status"] = "失败(" + err.Error() + ")" data["output"] = string(berr) } else { data["status"] = "成功" data["output"] = string(bout) } content := new(bytes.Buffer) mailTpl.Execute(content, data) ccList := make([]string, 0) if j.task.NotifyEmail != "" { ccList = strings.Split(j.task.NotifyEmail, "\n") } if !mail.SendMail(user.Email, user.UserName, title, content.String(), ccList) { beego.Error("发送邮件超时:", user.Email) } } }
func datetimes(t time.Time) string { return beego.Date(t, setting.DateTimeShortFormat) }
func date(t time.Time) string { return beego.Date(t, setting.DateFormat) }
// create formSets for generate label/field html code func NewFormSets(form interface{}, errs map[string]*validation.ValidationError, locale FormLocaler) *FormSets { fSets := new(FormSets) fSets.Fields = make(map[string]*FieldSet) if locale != nil { fSets.Locale = locale } else { fSets.Locale = fakeLocaler } val := reflect.ValueOf(form) panicAssertStructPtr(val) elm := val.Elem() var helps map[string]string var labels map[string]string var places map[string]string // get custom field helo messages if f, ok := form.(FormHelper); ok { hlps := f.Helps() if hlps != nil { helps = hlps } } // ge custom field labels if f, ok := form.(FormLabeler); ok { lbls := f.Labels() if lbls != nil { labels = lbls } } // ge custom field placeholders if f, ok := form.(FormPlaceholder); ok { phs := f.Placeholders() if phs != nil { places = phs } } outFor: for i := 0; i < elm.NumField(); i++ { f := elm.Field(i) fT := elm.Type().Field(i) name := fT.Name value := f.Interface() fTyp := "text" switch f.Kind() { case reflect.Bool: fTyp = "checkbox" default: switch value.(type) { case time.Time: fTyp = "datetime" } } fName := name var attrm map[string]string // parse struct tag settings for _, v := range strings.Split(fT.Tag.Get("form"), ";") { v = strings.TrimSpace(v) if v == "-" { continue outFor } else if i := strings.Index(v, "("); i > 0 && strings.Index(v, ")") == len(v)-1 { tN := v[:i] v = strings.TrimSpace(v[i+1 : len(v)-1]) switch tN { case "type": fTyp = v case "name": fName = v case "attr": if attrm == nil { attrm = make(map[string]string) } parts := strings.SplitN(v, ",", 2) if len(parts) > 1 { attrm[parts[0]] = parts[1] } else { attrm[v] = v } } } } var attrs string if attrm != nil { for k, v := range attrm { attrs += fmt.Sprintf(` %s="%s"`, k, v) } } // set field id fId := elm.Type().Name() + "-" + fName var fSet FieldSet fSet.Id = fId fSet.Name = fName fSet.Value = value fSet.Type = fTyp fSet.Attrs = attrs // get field label text fSet.LabelText = fName if labels != nil { if _, ok := labels[name]; ok { fSet.LabelText = labels[name] } } fSet.LabelText = locale.Tr(fSet.LabelText) // get field help if helps != nil { if _, ok := helps[name]; ok { fSet.Help = helps[name] } } fSet.Help = locale.Tr(helps[name]) if places != nil { if _, ok := places[name]; ok { fSet.Placeholder = places[name] } } fSet.Placeholder = locale.Tr(fSet.Placeholder) placeholders := "" if len(fSet.Placeholder) > 0 { placeholders = fmt.Sprintf(` placeholder="%s"`, fSet.Placeholder) } // create error string if errs != nil { if err, ok := errs[name]; ok { fSet.Error = locale.Tr(err.Tmpl, err.LimitValue) } } if creater, ok := customCreaters[fTyp]; ok { // use custome creater generate label/input html creater(&fSet) } else { // create field html switch fTyp { case "text", "tel", "email": fSet.Field = template.HTML(fmt.Sprintf( `<div class="controls"><input id="%s" name="%s" type="%s" value="%v" class="form-control"%s%s></div>`, fId, fName, fTyp, value, placeholders, attrs)) case "textarea": fSet.Field = template.HTML(fmt.Sprintf( `<div class="controls"><textarea id="%s" name="%s" rows="5" class="form-control"%s%s>%v</textarea></div>`, fId, fName, placeholders, attrs, value)) case "password": fSet.Field = template.HTML(fmt.Sprintf( `<div class="controls"><input id="%s" name="%s" type="password" value="%v" class="form-control"%s%s></div>`, fId, fName, value, placeholders, attrs)) case "select": var options string str := fmt.Sprintf( `<div class="controls"><select id="%s" name="%s" class="form-control"%s%s>%s</select></div>`, fId, fName, placeholders, attrs) fun := elm.Addr().MethodByName(name + "SelectData") if fun.IsValid() { results := fun.Call([]reflect.Value{}) if len(results) > 0 { v := results[0] if v.CanInterface() { if vu, ok := v.Interface().([][]string); ok { var vs []string val := reflect.ValueOf(value) if val.Kind() == reflect.Slice { vs = make([]string, 0, val.Len()) for i := 0; i < val.Len(); i++ { vs = append(vs, ToStr(val.Index(i).Interface())) } } isMulti := len(vs) > 0 for _, parts := range vu { var n, v string switch { case len(parts) > 1: n, v = locale.Tr(parts[0]), parts[1] case len(parts) == 1: n, v = locale.Tr(parts[0]), parts[0] } var selected string if isMulti { for _, e := range vs { if e == v { selected = ` selected="selected"` break } } } else if ToStr(value) == v { selected = ` selected="selected"` } options += fmt.Sprintf(`<option value="%s"%s>%s</option>`, v, selected, n) } } } } } if len(options) == 0 { options = fmt.Sprintf(`<option value="%v">%v</option>`, value, value) } str = fmt.Sprintf(str, options) fSet.Field = template.HTML(str) case "hidden": fSet.Field = template.HTML(fmt.Sprintf( `<div class="controls"><input id="%s" name="%s" type="hidden" value="%v"%s></div>`, fId, fName, value, attrs)) case "date", "datetime": t := value.(time.Time) tval := beego.Date(t, DateTimeFormat) if tval == "0001-01-01 00:00:00" { t = time.Now() } if fTyp == "date" { tval = beego.Date(t, DateFormat) } fSet.Field = template.HTML(fmt.Sprintf( `<div class="controls"><input id="%s" name="%s" type="%s" value="%s" class="form-control"%s%s></div>`, fId, fName, fTyp, tval, placeholders, attrs)) case "checkbox": var checked string if b, ok := value.(bool); ok && b { checked = "checked" } fSet.Field = template.HTML(fmt.Sprintf( `<div class="controls"><label for="%s" class="checkbox">%s<input id="%s" name="%s" type="checkbox" %s></label></div>`, fId, fSet.LabelText, fId, fName, checked)) } // create label html switch fTyp { case "checkbox", "hidden": default: fSet.Label = template.HTML(fmt.Sprintf(` <label class="control-label" for="%s">%s</label>`, fId, fSet.LabelText)) } if filter, ok := customFilters[fTyp]; ok { // use custome filter replace label/input html filter(&fSet) } } fSets.FieldList = append(fSets.FieldList, &fSet) fSets.Fields[name] = &fSet } return fSets }
//我的面板 func (this *IndexController) Index() { var ts, ActType string this.NeedLogin() //需要登录 this.GetUrlAuthorith() //URL访问权限控制 Data := this.Input() IndexModel := models.NewIndexModel() ts = Data.Get("ts") this.Data["ts"] = ts if ts == "add" { ActType = Data.Get("type") //添加模板输出 if ActType == "2" { this.Data["start"] = Data.Get("start") this.Data["end"] = Data.Get("end") this.Data["TaskType"] = IndexModel.GetTaskHtml(0) this.TplNames = "index/add.html" } else if ActType == "3" { //添加数据处理 var s_time, e_time int64 title := Data.Get("title") if title == "" { this.SendError("请输入事件内容", 1) } else { task_type := 0 //初始 task_input := Data.Get("task_type") task, _ := strconv.Atoi(task_input) if task > 0 { task_type = task } start := Data.Get("start") end := Data.Get("end") s_time = IndexModel.GetTimeVal(start) e_time = IndexModel.GetTimeVal(end) uid := this.GetSessUid() if IndexModel.AddOneTask(s_time, e_time, title, task_type, uid) == true { this.SendOk("添加成功", 1) } else { this.SendError("添加失败", 1) } } } else { //输出请求异常 this.SendError("参数有误", 1) } } else if ts == "delete" { //删除 id := this.GetInt1("id") if id > 0 { if IndexModel.DelOneTask(id) == true { this.SendOk("删除成功", 1) } else { this.SendError("删除失败.", 1) } } else { this.SendError("参数有误.", 1) } } else if ts == "edit" { ActType = Data.Get("type") if ActType == "3" { //修改人物内容 id := 0 //初始 id_input := Data.Get("id") id_in, _ := strconv.Atoi(id_input) if id_in > 0 { id = id_in } else { this.SendError("参数有误.", 1) } title := Data.Get("title") if title == "" { this.SendError("请输入事件内容", 1) } else { task_type := 0 //初始 task_input := Data.Get("task_type") task, _ := strconv.Atoi(task_input) if task > 0 { task_type = task } if IndexModel.EditOneTask(title, task_type, id) == true { this.SendOk("修改成功", 1) } else { this.SendError("修改失败", 1) } } //this.Ctx.WriteString("hahahaha") } else if ActType == "2" { //修改任务模板显示 taskId := Data.Get("id") if taskId != "" { id, _ := strconv.Atoi(taskId) taskData := IndexModel.GetOneTaskData(id) this.Data["TaskType"] = IndexModel.GetTaskHtml(taskData.Task_type) this.Data["Info"] = taskData this.TplNames = "index/add.html" } else { this.Ctx.WriteString("参数有误") } } else if ActType == "1" { //任务拖动 var s_time, e_time int64 taskId := Data.Get("id") if taskId != "" { id, _ := strconv.Atoi(taskId) start := Data.Get("start") end := Data.Get("end") if end == "" { end = start } s_time = IndexModel.GetTimeVal(start) e_time = IndexModel.GetTimeVal(end) if e_time < 1 { e_time = s_time } if IndexModel.EditOneTaskForTime(s_time, e_time, id) == true { this.SendOk("修改成功", 1) } else { this.SendError("修改失败", 1) } } else { this.SendError("参数有误.", 1) } } else { //输出请求异常 this.SendError("参数有误", 1) } //this.Ctx.WriteString("hahahaha") } else { this.init() //实例化控制器 Uid := this.GetSessUid() json_str := IndexModel.GetIndexJsonStr(Uid) this.Data["Json_str"] = json_str this.Data["day"] = beego.Date(time.Now(), "Y-m-d") this.Data["Title"] = "我的面板" this.TplNames = "index/index.html" } }
func datetimes(t time.Time) string { return beego.Date(t, "Y-m-d H:i") }
func (m *Image) GetToken() string { number := beego.Date(m.Created, "ymds") + utils.ToStr(m.Id) return utils.NumberEncode(number, setting.ImageLinkAlphabets) }
func date(t time.Time) string { return beego.Date(t, "Y-m-d") }
func initCommonField() { RegisterFieldCreater("text", func(fSet *FieldSet) { fSet.Field = func() template.HTML { return template.HTML(fmt.Sprintf( `<input id="%s" name="%s" type="text" value="%v" class="form-control"%s%s>`, fSet.Id, fSet.Name, fSet.Value, fSet.Placeholder, fSet.Attrs)) } }) RegisterFieldCreater("textarea", func(fSet *FieldSet) { fSet.Field = func() template.HTML { return template.HTML(fmt.Sprintf( `<textarea id="%s" name="%s" rows="5" class="form-control"%s%s>%v</textarea>`, fSet.Id, fSet.Name, fSet.Placeholder, fSet.Attrs, fSet.Value)) } }) RegisterFieldCreater("password", func(fSet *FieldSet) { fSet.Field = func() template.HTML { return template.HTML(fmt.Sprintf( `<input id="%s" name="%s" type="password" value="%v" class="form-control"%s%s>`, fSet.Id, fSet.Name, fSet.Value, fSet.Placeholder, fSet.Attrs)) } }) RegisterFieldCreater("hidden", func(fSet *FieldSet) { fSet.Field = func() template.HTML { return template.HTML(fmt.Sprintf( `<input id="%s" name="%s" type="hidden" value="%v"%s>`, fSet.Id, fSet.Name, fSet.Value, fSet.Attrs)) } }) datetimeFunc := func(fSet *FieldSet) { fSet.Field = func() template.HTML { t := fSet.Value.(time.Time) tval := beego.Date(t, setting.DateTimeFormat) if tval == "0001-01-01 00:00:00" { t = time.Now() } if fSet.Type == "date" { tval = beego.Date(t, setting.DateFormat) } return template.HTML(fmt.Sprintf( `<input id="%s" name="%s" type="%s" value="%s" class="form-control"%s%s>`, fSet.Id, fSet.Name, fSet.Type, tval, fSet.Placeholder, fSet.Attrs)) } } RegisterFieldCreater("date", datetimeFunc) RegisterFieldCreater("datetime", datetimeFunc) RegisterFieldCreater("checkbox", func(fSet *FieldSet) { fSet.Field = func() template.HTML { var checked string if b, ok := fSet.Value.(bool); ok && b { checked = "checked" } return template.HTML(fmt.Sprintf( `<label for="%s" class="checkbox">%s<input id="%s" name="%s" type="checkbox" %s></label>`, fSet.Id, fSet.LabelText, fSet.Id, fSet.Name, checked)) } }) RegisterFieldCreater("select", func(fSet *FieldSet) { fSet.Field = func() template.HTML { var options string str := fmt.Sprintf(`<select id="%s" name="%s" class="form-control"%s%s>%s</select>`, fSet.Id, fSet.Name, fSet.Placeholder, fSet.Attrs) fun := fSet.FormElm.Addr().MethodByName(fSet.Name + "SelectData") if fun.IsValid() { results := fun.Call([]reflect.Value{}) if len(results) > 0 { v := results[0] if v.CanInterface() { if vu, ok := v.Interface().([][]string); ok { var vs []string val := reflect.ValueOf(fSet.Value) if val.Kind() == reflect.Slice { vs = make([]string, 0, val.Len()) for i := 0; i < val.Len(); i++ { vs = append(vs, ToStr(val.Index(i).Interface())) } } isMulti := len(vs) > 0 for _, parts := range vu { var n, v string switch { case len(parts) > 1: n, v = fSet.Locale.Tr(parts[0]), parts[1] case len(parts) == 1: n, v = fSet.Locale.Tr(parts[0]), parts[0] } var selected string if isMulti { for _, e := range vs { if e == v { selected = ` selected="selected"` break } } } else if ToStr(fSet.Value) == v { selected = ` selected="selected"` } options += fmt.Sprintf(`<option value="%s"%s>%s</option>`, v, selected, n) } } } } } if len(options) == 0 { options = fmt.Sprintf(`<option value="%v">%v</option>`, fSet.Value, fSet.Value) } return template.HTML(fmt.Sprintf(str, options)) } }) }
func GenImagePath(img *models.Image) string { return "upload/img/" + beego.Date(img.Created, "y/m/d/s/") + utils.ToStr(img.Id) + "/" }