Commit 0fb50ea9 authored by szh's avatar szh

delete unused

parent e1e84f48
/*
Navicat MySQL Data Transfer
Source Database : blog
Target Server Type : MYSQL
Target Server Version : 50639
File Encoding : 65001
Date: 2018-03-18 16:52:35
*/
SET FOREIGN_KEY_CHECKS=0;
-- ----------------------------
-- Table structure for blog_article
-- ----------------------------
DROP TABLE IF EXISTS `blog_article`;
CREATE TABLE `blog_article` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`tag_id` int(10) unsigned DEFAULT '0' COMMENT '标签ID',
`title` varchar(100) DEFAULT '' COMMENT '文章标题',
`desc` varchar(255) DEFAULT '' COMMENT '简述',
`content` text COMMENT '内容',
`cover_image_url` varchar(255) DEFAULT '' COMMENT '封面图片地址',
`created_on` int(10) unsigned DEFAULT '0' COMMENT '新建时间',
`created_by` varchar(100) DEFAULT '' COMMENT '创建人',
`modified_on` int(10) unsigned DEFAULT '0' COMMENT '修改时间',
`modified_by` varchar(255) DEFAULT '' COMMENT '修改人',
`deleted_on` int(10) unsigned DEFAULT '0',
`state` tinyint(3) unsigned DEFAULT '1' COMMENT '删除时间',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='文章管理';
-- ----------------------------
-- Table structure for blog_auth
-- ----------------------------
DROP TABLE IF EXISTS `blog_auth`;
CREATE TABLE `blog_auth` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`username` varchar(50) DEFAULT '' COMMENT '账号',
`password` varchar(50) DEFAULT '' COMMENT '密码',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;
INSERT INTO `blog_auth` (`id`, `username`, `password`) VALUES ('1', 'test', 'test123');
-- ----------------------------
-- Table structure for blog_tag
-- ----------------------------
DROP TABLE IF EXISTS `blog_tag`;
CREATE TABLE `blog_tag` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`name` varchar(100) DEFAULT '' COMMENT '标签名称',
`created_on` int(10) unsigned DEFAULT '0' COMMENT '创建时间',
`created_by` varchar(100) DEFAULT '' COMMENT '创建人',
`modified_on` int(10) unsigned DEFAULT '0' COMMENT '修改时间',
`modified_by` varchar(100) DEFAULT '' COMMENT '修改人',
`deleted_on` int(10) unsigned DEFAULT '0' COMMENT '删除时间',
`state` tinyint(3) unsigned DEFAULT '1' COMMENT '状态 0为禁用、1为启用',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='文章标签管理';
package models
import (
"github.com/jinzhu/gorm"
)
type Article struct {
Model
TagID int `json:"tag_id" gorm:"index"`
Tag Tag `json:"tag"`
Title string `json:"title"`
Desc string `json:"desc"`
Content string `json:"content"`
CoverImageUrl string `json:"cover_image_url"`
CreatedBy string `json:"created_by"`
ModifiedBy string `json:"modified_by"`
State int `json:"state"`
}
// ExistArticleByID checks if an article exists based on ID
func ExistArticleByID(id int) (bool, error) {
var article Article
err := db.Select("id").Where("id = ? AND deleted_on = ? ", id, 0).First(&article).Error
if err != nil && err != gorm.ErrRecordNotFound {
return false, err
}
if article.ID > 0 {
return true, nil
}
return false, nil
}
// GetArticleTotal gets the total number of articles based on the constraints
func GetArticleTotal(maps interface{}) (int, error) {
var count int
if err := db.Model(&Article{}).Where(maps).Count(&count).Error; err != nil {
return 0, err
}
return count, nil
}
// GetArticles gets a list of articles based on paging constraints
func GetArticles(pageNum int, pageSize int, maps interface{}) ([]*Article, error) {
var articles []*Article
err := db.Preload("Tag").Where(maps).Offset(pageNum).Limit(pageSize).Find(&articles).Error
if err != nil && err != gorm.ErrRecordNotFound {
return nil, err
}
return articles, nil
}
// GetArticle Get a single article based on ID
func GetArticle(id int) (*Article, error) {
var article Article
err := db.Where("id = ? AND deleted_on = ? ", id, 0).First(&article).Error
if err != nil && err != gorm.ErrRecordNotFound {
return nil, err
}
err = db.Model(&article).Related(&article.Tag).Error
if err != nil && err != gorm.ErrRecordNotFound {
return nil, err
}
return &article, nil
}
// EditArticle modify a single article
func EditArticle(id int, data interface{}) error {
if err := db.Model(&Article{}).Where("id = ? AND deleted_on = ? ", id, 0).Updates(data).Error; err != nil {
return err
}
return nil
}
// AddArticle add a single article
func AddArticle(data map[string]interface{}) error {
article := Article{
TagID: data["tag_id"].(int),
Title: data["title"].(string),
Desc: data["desc"].(string),
Content: data["content"].(string),
CreatedBy: data["created_by"].(string),
State: data["state"].(int),
CoverImageUrl: data["cover_image_url"].(string),
}
if err := db.Create(&article).Error; err != nil {
return err
}
return nil
}
// DeleteArticle delete a single article
func DeleteArticle(id int) error {
if err := db.Where("id = ?", id).Delete(Article{}).Error; err != nil {
return err
}
return nil
}
// CleanAllArticle clear all article
func CleanAllArticle() error {
if err := db.Unscoped().Where("deleted_on != ? ", 0).Delete(&Article{}).Error; err != nil {
return err
}
return nil
}
package models
import "github.com/jinzhu/gorm"
type Auth struct {
ID int `gorm:"primary_key" json:"id"`
Username string `json:"username"`
Password string `json:"password"`
}
// CheckAuth checks if authentication information exists
func CheckAuth(username, password string) (bool, error) {
var auth Auth
err := db.Select("id").Where(Auth{Username: username, Password: password}).First(&auth).Error
if err != nil && err != gorm.ErrRecordNotFound {
return false, err
}
if auth.ID > 0 {
return true, nil
}
return false, nil
}
package models
import (
"github.com/jinzhu/gorm"
)
type Tag struct {
Model
Name string `json:"name"`
CreatedBy string `json:"created_by"`
ModifiedBy string `json:"modified_by"`
State int `json:"state"`
}
// ExistTagByName checks if there is a tag with the same name
func ExistTagByName(name string) (bool, error) {
var tag Tag
err := db.Select("id").Where("name = ? AND deleted_on = ? ", name, 0).First(&tag).Error
if err != nil && err != gorm.ErrRecordNotFound {
return false, err
}
if tag.ID > 0 {
return true, nil
}
return false, nil
}
// AddTag Add a Tag
func AddTag(name string, state int, createdBy string) error {
tag := Tag{
Name: name,
State: state,
CreatedBy: createdBy,
}
if err := db.Create(&tag).Error; err != nil {
return err
}
return nil
}
// GetTags gets a list of tags based on paging and constraints
func GetTags(pageNum int, pageSize int, maps interface{}) ([]Tag, error) {
var (
tags []Tag
err error
)
if pageSize > 0 && pageNum > 0 {
err = db.Where(maps).Find(&tags).Offset(pageNum).Limit(pageSize).Error
} else {
err = db.Where(maps).Find(&tags).Error
}
if err != nil && err != gorm.ErrRecordNotFound {
return nil, err
}
return tags, nil
}
// GetTagTotal counts the total number of tags based on the constraint
func GetTagTotal(maps interface{}) (int, error) {
var count int
if err := db.Model(&Tag{}).Where(maps).Count(&count).Error; err != nil {
return 0, err
}
return count, nil
}
// ExistTagByID determines whether a Tag exists based on the ID
func ExistTagByID(id int) (bool, error) {
var tag Tag
err := db.Select("id").Where("id = ? AND deleted_on = ? ", id, 0).First(&tag).Error
if err != nil && err != gorm.ErrRecordNotFound {
return false, err
}
if tag.ID > 0 {
return true, nil
}
return false, nil
}
// DeleteTag delete a tag
func DeleteTag(id int) error {
if err := db.Where("id = ?", id).Delete(&Tag{}).Error; err != nil {
return err
}
return nil
}
// EditTag modify a single tag
func EditTag(id int, data interface{}) error {
if err := db.Model(&Tag{}).Where("id = ? AND deleted_on = ? ", id, 0).Updates(data).Error; err != nil {
return err
}
return nil
}
// CleanAllTag clear all tag
func CleanAllTag() (bool, error) {
if err := db.Unscoped().Where("deleted_on != ? ", 0).Delete(&Tag{}).Error; err != nil {
return false, err
}
return true, nil
}
package app package app
import ( import (
"bufio"
"bytes" "bytes"
"chain33-pai/pkg/setting" "chain33-pai/pkg/setting"
"errors" "errors"
...@@ -12,7 +11,6 @@ import ( ...@@ -12,7 +11,6 @@ import (
"os" "os"
"os/exec" "os/exec"
"path" "path"
"regexp"
"strings" "strings"
"time" "time"
"io/ioutil" "io/ioutil"
...@@ -180,58 +178,6 @@ func BityuanJob(ticker *time.Ticker){ ...@@ -180,58 +178,6 @@ func BityuanJob(ticker *time.Ticker){
} }
} }
func GetLatestVersion()string{
req, err := http.NewRequest("GET", setting.BityuanSetting.VersionPath, nil)
req.Close=true
req.Header.Add("Connection","close")
if err!=nil{
return ""
}
resp,err:= http.DefaultClient.Do(req)
if err!=nil{
fmt.Println(err)
return ""
}
defer resp.Body.Close()
rd:=bufio.NewReader(resp.Body)
for{
line,err:=rd.ReadString('\n')
if err==io.EOF{
break
}
if ok, _ := regexp.MatchString("version", line); ok {
return strings.Split( strings.Split(line, "=")[1], "\"")[1]
break
}
}
return ""
}
func DownLoadLatestVersion()error{
git:=exec.Command("git","clone",setting.BityuanSetting.GitPath,"./"+setting.BityuanSetting.Name)
sed:=exec.Command("sed", fmt.Sprintf("15,18 s/bityuan/%s/1",setting.BityuanSetting.Name) ,"Makefile")
makeb:=exec.Command("make")
git.Start()
err:=git.Wait()
if err!=nil{
tlog.Info("DownLoadLatestVersion","git err",err)
return errors.New("download latest version failed")
}
os.Chdir("./"+setting.BityuanSetting.Name)
sed.Start()
sed.Wait()
makeb.Start()
err=makeb.Wait()
if err!=nil {
tlog.Info("DownLoadLatestVersion","build err",err)
return errors.New("failed to compile latest version for some reason")
}
return nil
}
func Copy(src,dst string){ func Copy(src,dst string){
cp:=exec.Command("cp","-r",src,dst) cp:=exec.Command("cp","-r",src,dst)
cp.Start() cp.Start()
......
...@@ -255,11 +255,16 @@ func MakeSureBtyIsNotRun() bool { ...@@ -255,11 +255,16 @@ func MakeSureBtyIsNotRun() bool {
defer func() { defer func() {
tlog.Info("MakeSureBtyIsNotRun","cost",time.Since(s)) tlog.Info("MakeSureBtyIsNotRun","cost",time.Since(s))
}() }()
num := 0
for { for {
if num > 1000 {
break
}
info := getProcessInfo(setting.BityuanSetting.Name) info := getProcessInfo(setting.BityuanSetting.Name)
if info == "" { if info == "" {
return false return false
} }
num++
time.Sleep(time.Second*1) time.Sleep(time.Second*1)
} }
return true return true
......
package v1
import (
"net/http"
"github.com/unknwon/com"
"github.com/astaxie/beego/validation"
"github.com/boombuler/barcode/qr"
"github.com/gin-gonic/gin"
"chain33-pai/pkg/app"
"chain33-pai/pkg/e"
"chain33-pai/pkg/qrcode"
"chain33-pai/pkg/setting"
"chain33-pai/pkg/util"
"chain33-pai/service/article_service"
"chain33-pai/service/tag_service"
)
// @Summary Get a single article
// @Produce json
// @Param id path int true "ID"
// @Success 200 {object} app.Response
// @Failure 500 {object} app.Response
// @Router /api/v1/articles/{id} [get]
func GetArticle(c *gin.Context) {
appG := app.Gin{C: c}
id := com.StrTo(c.Param("id")).MustInt()
valid := validation.Validation{}
valid.Min(id, 1, "id")
if valid.HasErrors() {
app.MarkErrors(valid.Errors)
appG.Response(http.StatusBadRequest, e.INVALID_PARAMS, nil)
return
}
articleService := article_service.Article{ID: id}
exists, err := articleService.ExistByID()
if err != nil {
appG.Response(http.StatusInternalServerError, e.ERROR_CHECK_EXIST_ARTICLE_FAIL, nil)
return
}
if !exists {
appG.Response(http.StatusOK, e.ERROR_NOT_EXIST_ARTICLE, nil)
return
}
article, err := articleService.Get()
if err != nil {
appG.Response(http.StatusInternalServerError, e.ERROR_GET_ARTICLE_FAIL, nil)
return
}
appG.Response(http.StatusOK, e.SUCCESS, article)
}
// @Summary Get multiple articles
// @Produce json
// @Param tag_id body int false "TagID"
// @Param state body int false "State"
// @Param created_by body int false "CreatedBy"
// @Success 200 {object} app.Response
// @Failure 500 {object} app.Response
// @Router /api/v1/articles [get]
func GetArticles(c *gin.Context) {
appG := app.Gin{C: c}
valid := validation.Validation{}
state := -1
if arg := c.PostForm("state"); arg != "" {
state = com.StrTo(arg).MustInt()
valid.Range(state, 0, 1, "state")
}
tagId := -1
if arg := c.PostForm("tag_id"); arg != "" {
tagId = com.StrTo(arg).MustInt()
valid.Min(tagId, 1, "tag_id")
}
if valid.HasErrors() {
app.MarkErrors(valid.Errors)
appG.Response(http.StatusBadRequest, e.INVALID_PARAMS, nil)
return
}
articleService := article_service.Article{
TagID: tagId,
State: state,
PageNum: util.GetPage(c),
PageSize: setting.AppSetting.PageSize,
}
total, err := articleService.Count()
if err != nil {
appG.Response(http.StatusInternalServerError, e.ERROR_COUNT_ARTICLE_FAIL, nil)
return
}
articles, err := articleService.GetAll()
if err != nil {
appG.Response(http.StatusInternalServerError, e.ERROR_GET_ARTICLES_FAIL, nil)
return
}
data := make(map[string]interface{})
data["lists"] = articles
data["total"] = total
appG.Response(http.StatusOK, e.SUCCESS, data)
}
type AddArticleForm struct {
TagID int `form:"tag_id" valid:"Required;Min(1)"`
Title string `form:"title" valid:"Required;MaxSize(100)"`
Desc string `form:"desc" valid:"Required;MaxSize(255)"`
Content string `form:"content" valid:"Required;MaxSize(65535)"`
CreatedBy string `form:"created_by" valid:"Required;MaxSize(100)"`
CoverImageUrl string `form:"cover_image_url" valid:"Required;MaxSize(255)"`
State int `form:"state" valid:"Range(0,1)"`
}
// @Summary Add article
// @Produce json
// @Param tag_id body int true "TagID"
// @Param title body string true "Title"
// @Param desc body string true "Desc"
// @Param content body string true "Content"
// @Param created_by body string true "CreatedBy"
// @Param state body int true "State"
// @Success 200 {object} app.Response
// @Failure 500 {object} app.Response
// @Router /api/v1/articles [post]
func AddArticle(c *gin.Context) {
var (
appG = app.Gin{C: c}
form AddArticleForm
)
httpCode, errCode := app.BindAndValid(c, &form)
if errCode != e.SUCCESS {
appG.Response(httpCode, errCode, nil)
return
}
tagService := tag_service.Tag{ID: form.TagID}
exists, err := tagService.ExistByID()
if err != nil {
appG.Response(http.StatusInternalServerError, e.ERROR_EXIST_TAG_FAIL, nil)
return
}
if !exists {
appG.Response(http.StatusOK, e.ERROR_NOT_EXIST_TAG, nil)
return
}
articleService := article_service.Article{
TagID: form.TagID,
Title: form.Title,
Desc: form.Desc,
Content: form.Content,
CoverImageUrl: form.CoverImageUrl,
State: form.State,
}
if err := articleService.Add(); err != nil {
appG.Response(http.StatusInternalServerError, e.ERROR_ADD_ARTICLE_FAIL, nil)
return
}
appG.Response(http.StatusOK, e.SUCCESS, nil)
}
type EditArticleForm struct {
ID int `form:"id" valid:"Required;Min(1)"`
TagID int `form:"tag_id" valid:"Required;Min(1)"`
Title string `form:"title" valid:"Required;MaxSize(100)"`
Desc string `form:"desc" valid:"Required;MaxSize(255)"`
Content string `form:"content" valid:"Required;MaxSize(65535)"`
ModifiedBy string `form:"modified_by" valid:"Required;MaxSize(100)"`
CoverImageUrl string `form:"cover_image_url" valid:"Required;MaxSize(255)"`
State int `form:"state" valid:"Range(0,1)"`
}
// @Summary Update article
// @Produce json
// @Param id path int true "ID"
// @Param tag_id body string false "TagID"
// @Param title body string false "Title"
// @Param desc body string false "Desc"
// @Param content body string false "Content"
// @Param modified_by body string true "ModifiedBy"
// @Param state body int false "State"
// @Success 200 {object} app.Response
// @Failure 500 {object} app.Response
// @Router /api/v1/articles/{id} [put]
func EditArticle(c *gin.Context) {
var (
appG = app.Gin{C: c}
form = EditArticleForm{ID: com.StrTo(c.Param("id")).MustInt()}
)
httpCode, errCode := app.BindAndValid(c, &form)
if errCode != e.SUCCESS {
appG.Response(httpCode, errCode, nil)
return
}
articleService := article_service.Article{
ID: form.ID,
TagID: form.TagID,
Title: form.Title,
Desc: form.Desc,
Content: form.Content,
CoverImageUrl: form.CoverImageUrl,
ModifiedBy: form.ModifiedBy,
State: form.State,
}
exists, err := articleService.ExistByID()
if err != nil {
appG.Response(http.StatusInternalServerError, e.ERROR_CHECK_EXIST_ARTICLE_FAIL, nil)
return
}
if !exists {
appG.Response(http.StatusOK, e.ERROR_NOT_EXIST_ARTICLE, nil)
return
}
tagService := tag_service.Tag{ID: form.TagID}
exists, err = tagService.ExistByID()
if err != nil {
appG.Response(http.StatusInternalServerError, e.ERROR_EXIST_TAG_FAIL, nil)
return
}
if !exists {
appG.Response(http.StatusOK, e.ERROR_NOT_EXIST_TAG, nil)
return
}
err = articleService.Edit()
if err != nil {
appG.Response(http.StatusInternalServerError, e.ERROR_EDIT_ARTICLE_FAIL, nil)
return
}
appG.Response(http.StatusOK, e.SUCCESS, nil)
}
// @Summary Delete article
// @Produce json
// @Param id path int true "ID"
// @Success 200 {object} app.Response
// @Failure 500 {object} app.Response
// @Router /api/v1/articles/{id} [delete]
func DeleteArticle(c *gin.Context) {
appG := app.Gin{C: c}
valid := validation.Validation{}
id := com.StrTo(c.Param("id")).MustInt()
valid.Min(id, 1, "id").Message("ID必须大于0")
if valid.HasErrors() {
app.MarkErrors(valid.Errors)
appG.Response(http.StatusOK, e.INVALID_PARAMS, nil)
return
}
articleService := article_service.Article{ID: id}
exists, err := articleService.ExistByID()
if err != nil {
appG.Response(http.StatusInternalServerError, e.ERROR_CHECK_EXIST_ARTICLE_FAIL, nil)
return
}
if !exists {
appG.Response(http.StatusOK, e.ERROR_NOT_EXIST_ARTICLE, nil)
return
}
err = articleService.Delete()
if err != nil {
appG.Response(http.StatusInternalServerError, e.ERROR_DELETE_ARTICLE_FAIL, nil)
return
}
appG.Response(http.StatusOK, e.SUCCESS, nil)
}
const (
QRCODE_URL = "https://github.com/EDDYCJY/blog#gin%E7%B3%BB%E5%88%97%E7%9B%AE%E5%BD%95"
)
func GenerateArticlePoster(c *gin.Context) {
appG := app.Gin{C: c}
article := &article_service.Article{}
qr := qrcode.NewQrCode(QRCODE_URL, 300, 300, qr.M, qr.Auto)
posterName := article_service.GetPosterFlag() + "-" + qrcode.GetQrCodeFileName(qr.URL) + qr.GetQrCodeExt()
articlePoster := article_service.NewArticlePoster(posterName, article, qr)
articlePosterBgService := article_service.NewArticlePosterBg(
"bg.jpg",
articlePoster,
&article_service.Rect{
X0: 0,
Y0: 0,
X1: 550,
Y1: 700,
},
&article_service.Pt{
X: 125,
Y: 298,
},
)
_, filePath, err := articlePosterBgService.Generate()
if err != nil {
appG.Response(http.StatusInternalServerError, e.ERROR_GEN_ARTICLE_POSTER_FAIL, nil)
return
}
appG.Response(http.StatusOK, e.SUCCESS, map[string]string{
"poster_url": qrcode.GetQrCodeFullUrl(posterName),
"poster_save_url": filePath + posterName,
})
}
package v1
import (
"net/http"
"github.com/unknwon/com"
"github.com/astaxie/beego/validation"
"github.com/gin-gonic/gin"
"chain33-pai/pkg/app"
"chain33-pai/pkg/e"
"chain33-pai/pkg/export"
"chain33-pai/pkg/logging"
"chain33-pai/pkg/setting"
"chain33-pai/pkg/util"
"chain33-pai/service/tag_service"
)
// @Summary Get multiple article tags
// @Produce json
// @Param name query string false "Name"
// @Param state query int false "State"
// @Success 200 {object} app.Response
// @Failure 500 {object} app.Response
// @Router /api/v1/tags [get]
func GetTags(c *gin.Context) {
appG := app.Gin{C: c}
name := c.Query("name")
state := -1
if arg := c.Query("state"); arg != "" {
state = com.StrTo(arg).MustInt()
}
tagService := tag_service.Tag{
Name: name,
State: state,
PageNum: util.GetPage(c),
PageSize: setting.AppSetting.PageSize,
}
tags, err := tagService.GetAll()
if err != nil {
appG.Response(http.StatusInternalServerError, e.ERROR_GET_TAGS_FAIL, nil)
return
}
count, err := tagService.Count()
if err != nil {
appG.Response(http.StatusInternalServerError, e.ERROR_COUNT_TAG_FAIL, nil)
return
}
appG.Response(http.StatusOK, e.SUCCESS, map[string]interface{}{
"lists": tags,
"total": count,
})
}
type AddTagForm struct {
Name string `form:"name" valid:"Required;MaxSize(100)"`
CreatedBy string `form:"created_by" valid:"Required;MaxSize(100)"`
State int `form:"state" valid:"Range(0,1)"`
}
// @Summary Add article tag
// @Produce json
// @Param name body string true "Name"
// @Param state body int false "State"
// @Param created_by body int false "CreatedBy"
// @Success 200 {object} app.Response
// @Failure 500 {object} app.Response
// @Router /api/v1/tags [post]
func AddTag(c *gin.Context) {
var (
appG = app.Gin{C: c}
form AddTagForm
)
httpCode, errCode := app.BindAndValid(c, &form)
if errCode != e.SUCCESS {
appG.Response(httpCode, errCode, nil)
return
}
tagService := tag_service.Tag{
Name: form.Name,
CreatedBy: form.CreatedBy,
State: form.State,
}
exists, err := tagService.ExistByName()
if err != nil {
appG.Response(http.StatusInternalServerError, e.ERROR_EXIST_TAG_FAIL, nil)
return
}
if exists {
appG.Response(http.StatusOK, e.ERROR_EXIST_TAG, nil)
return
}
err = tagService.Add()
if err != nil {
appG.Response(http.StatusInternalServerError, e.ERROR_ADD_TAG_FAIL, nil)
return
}
appG.Response(http.StatusOK, e.SUCCESS, nil)
}
type EditTagForm struct {
ID int `form:"id" valid:"Required;Min(1)"`
Name string `form:"name" valid:"Required;MaxSize(100)"`
ModifiedBy string `form:"modified_by" valid:"Required;MaxSize(100)"`
State int `form:"state" valid:"Range(0,1)"`
}
// @Summary Update article tag
// @Produce json
// @Param id path int true "ID"
// @Param name body string true "ID"
// @Param state body int false "State"
// @Param modified_by body string true "ModifiedBy"
// @Success 200 {object} app.Response
// @Failure 500 {object} app.Response
// @Router /api/v1/tags/{id} [put]
func EditTag(c *gin.Context) {
var (
appG = app.Gin{C: c}
form = EditTagForm{ID: com.StrTo(c.Param("id")).MustInt()}
)
httpCode, errCode := app.BindAndValid(c, &form)
if errCode != e.SUCCESS {
appG.Response(httpCode, errCode, nil)
return
}
tagService := tag_service.Tag{
ID: form.ID,
Name: form.Name,
ModifiedBy: form.ModifiedBy,
State: form.State,
}
exists, err := tagService.ExistByID()
if err != nil {
appG.Response(http.StatusInternalServerError, e.ERROR_EXIST_TAG_FAIL, nil)
return
}
if !exists {
appG.Response(http.StatusOK, e.ERROR_NOT_EXIST_TAG, nil)
return
}
err = tagService.Edit()
if err != nil {
appG.Response(http.StatusInternalServerError, e.ERROR_EDIT_TAG_FAIL, nil)
return
}
appG.Response(http.StatusOK, e.SUCCESS, nil)
}
// @Summary Delete article tag
// @Produce json
// @Param id path int true "ID"
// @Success 200 {object} app.Response
// @Failure 500 {object} app.Response
// @Router /api/v1/tags/{id} [delete]
func DeleteTag(c *gin.Context) {
appG := app.Gin{C: c}
valid := validation.Validation{}
id := com.StrTo(c.Param("id")).MustInt()
valid.Min(id, 1, "id").Message("ID必须大于0")
if valid.HasErrors() {
app.MarkErrors(valid.Errors)
appG.Response(http.StatusBadRequest, e.INVALID_PARAMS, nil)
}
tagService := tag_service.Tag{ID: id}
exists, err := tagService.ExistByID()
if err != nil {
appG.Response(http.StatusInternalServerError, e.ERROR_EXIST_TAG_FAIL, nil)
return
}
if !exists {
appG.Response(http.StatusOK, e.ERROR_NOT_EXIST_TAG, nil)
return
}
if err := tagService.Delete(); err != nil {
appG.Response(http.StatusInternalServerError, e.ERROR_DELETE_TAG_FAIL, nil)
return
}
appG.Response(http.StatusOK, e.SUCCESS, nil)
}
// @Summary Export article tag
// @Produce json
// @Param name body string false "Name"
// @Param state body int false "State"
// @Success 200 {object} app.Response
// @Failure 500 {object} app.Response
// @Router /api/v1/tags/export [post]
func ExportTag(c *gin.Context) {
appG := app.Gin{C: c}
name := c.PostForm("name")
state := -1
if arg := c.PostForm("state"); arg != "" {
state = com.StrTo(arg).MustInt()
}
tagService := tag_service.Tag{
Name: name,
State: state,
}
filename, err := tagService.Export()
if err != nil {
appG.Response(http.StatusInternalServerError, e.ERROR_EXPORT_TAG_FAIL, nil)
return
}
appG.Response(http.StatusOK, e.SUCCESS, map[string]string{
"export_url": export.GetExcelFullUrl(filename),
"export_save_url": export.GetExcelPath() + filename,
})
}
// @Summary Import article tag
// @Produce json
// @Param file body file true "Excel File"
// @Success 200 {object} app.Response
// @Failure 500 {object} app.Response
// @Router /api/v1/tags/import [post]
func ImportTag(c *gin.Context) {
appG := app.Gin{C: c}
file, _, err := c.Request.FormFile("file")
if err != nil {
logging.Warn(err)
appG.Response(http.StatusInternalServerError, e.ERROR, nil)
return
}
tagService := tag_service.Tag{}
err = tagService.Import(file)
if err != nil {
logging.Warn(err)
appG.Response(http.StatusInternalServerError, e.ERROR_IMPORT_TAG_FAIL, nil)
return
}
appG.Response(http.StatusOK, e.SUCCESS, nil)
}
package article_service
import (
"encoding/json"
"chain33-pai/models"
"chain33-pai/pkg/gredis"
"chain33-pai/pkg/logging"
"chain33-pai/service/cache_service"
)
type Article struct {
ID int
TagID int
Title string
Desc string
Content string
CoverImageUrl string
State int
CreatedBy string
ModifiedBy string
PageNum int
PageSize int
}
func (a *Article) Add() error {
article := map[string]interface{}{
"tag_id": a.TagID,
"title": a.Title,
"desc": a.Desc,
"content": a.Content,
"created_by": a.CreatedBy,
"cover_image_url": a.CoverImageUrl,
"state": a.State,
}
if err := models.AddArticle(article); err != nil {
return err
}
return nil
}
func (a *Article) Edit() error {
return models.EditArticle(a.ID, map[string]interface{}{
"tag_id": a.TagID,
"title": a.Title,
"desc": a.Desc,
"content": a.Content,
"cover_image_url": a.CoverImageUrl,
"state": a.State,
"modified_by": a.ModifiedBy,
})
}
func (a *Article) Get() (*models.Article, error) {
var cacheArticle *models.Article
cache := cache_service.Article{ID: a.ID}
key := cache.GetArticleKey()
if gredis.Exists(key) {
data, err := gredis.Get(key)
if err != nil {
logging.Info(err)
} else {
json.Unmarshal(data, &cacheArticle)
return cacheArticle, nil
}
}
article, err := models.GetArticle(a.ID)
if err != nil {
return nil, err
}
gredis.Set(key, article, 3600)
return article, nil
}
func (a *Article) GetAll() ([]*models.Article, error) {
var (
articles, cacheArticles []*models.Article
)
cache := cache_service.Article{
TagID: a.TagID,
State: a.State,
PageNum: a.PageNum,
PageSize: a.PageSize,
}
key := cache.GetArticlesKey()
if gredis.Exists(key) {
data, err := gredis.Get(key)
if err != nil {
logging.Info(err)
} else {
json.Unmarshal(data, &cacheArticles)
return cacheArticles, nil
}
}
articles, err := models.GetArticles(a.PageNum, a.PageSize, a.getMaps())
if err != nil {
return nil, err
}
gredis.Set(key, articles, 3600)
return articles, nil
}
func (a *Article) Delete() error {
return models.DeleteArticle(a.ID)
}
func (a *Article) ExistByID() (bool, error) {
return models.ExistArticleByID(a.ID)
}
func (a *Article) Count() (int, error) {
return models.GetArticleTotal(a.getMaps())
}
func (a *Article) getMaps() map[string]interface{} {
maps := make(map[string]interface{})
maps["deleted_on"] = 0
if a.State != -1 {
maps["state"] = a.State
}
if a.TagID != -1 {
maps["tag_id"] = a.TagID
}
return maps
}
package article_service
import (
"image"
"image/draw"
"image/jpeg"
"io/ioutil"
"os"
"github.com/golang/freetype"
"chain33-pai/pkg/file"
"chain33-pai/pkg/qrcode"
"chain33-pai/pkg/setting"
)
type ArticlePoster struct {
PosterName string
*Article
Qr *qrcode.QrCode
}
func NewArticlePoster(posterName string, article *Article, qr *qrcode.QrCode) *ArticlePoster {
return &ArticlePoster{
PosterName: posterName,
Article: article,
Qr: qr,
}
}
func GetPosterFlag() string {
return "poster"
}
func (a *ArticlePoster) CheckMergedImage(path string) bool {
if file.CheckNotExist(path+a.PosterName) == true {
return false
}
return true
}
func (a *ArticlePoster) OpenMergedImage(path string) (*os.File, error) {
f, err := file.MustOpen(a.PosterName, path)
if err != nil {
return nil, err
}
return f, nil
}
type ArticlePosterBg struct {
Name string
*ArticlePoster
*Rect
*Pt
}
type Rect struct {
Name string
X0 int
Y0 int
X1 int
Y1 int
}
type Pt struct {
X int
Y int
}
func NewArticlePosterBg(name string, ap *ArticlePoster, rect *Rect, pt *Pt) *ArticlePosterBg {
return &ArticlePosterBg{
Name: name,
ArticlePoster: ap,
Rect: rect,
Pt: pt,
}
}
type DrawText struct {
JPG draw.Image
Merged *os.File
Title string
X0 int
Y0 int
Size0 float64
SubTitle string
X1 int
Y1 int
Size1 float64
}
func (a *ArticlePosterBg) DrawPoster(d *DrawText, fontName string) error {
fontSource := setting.AppSetting.RuntimeRootPath + setting.AppSetting.FontSavePath + fontName
fontSourceBytes, err := ioutil.ReadFile(fontSource)
if err != nil {
return err
}
trueTypeFont, err := freetype.ParseFont(fontSourceBytes)
if err != nil {
return err
}
fc := freetype.NewContext()
fc.SetDPI(72)
fc.SetFont(trueTypeFont)
fc.SetFontSize(d.Size0)
fc.SetClip(d.JPG.Bounds())
fc.SetDst(d.JPG)
fc.SetSrc(image.Black)
pt := freetype.Pt(d.X0, d.Y0)
_, err = fc.DrawString(d.Title, pt)
if err != nil {
return err
}
fc.SetFontSize(d.Size1)
_, err = fc.DrawString(d.SubTitle, freetype.Pt(d.X1, d.Y1))
if err != nil {
return err
}
err = jpeg.Encode(d.Merged, d.JPG, nil)
if err != nil {
return err
}
return nil
}
func (a *ArticlePosterBg) Generate() (string, string, error) {
fullPath := qrcode.GetQrCodeFullPath()
fileName, path, err := a.Qr.Encode(fullPath)
if err != nil {
return "", "", err
}
if !a.CheckMergedImage(path) {
mergedF, err := a.OpenMergedImage(path)
if err != nil {
return "", "", err
}
defer mergedF.Close()
bgF, err := file.MustOpen(a.Name, path)
if err != nil {
return "", "", err
}
defer bgF.Close()
qrF, err := file.MustOpen(fileName, path)
if err != nil {
return "", "", err
}
defer qrF.Close()
bgImage, err := jpeg.Decode(bgF)
if err != nil {
return "", "", err
}
qrImage, err := jpeg.Decode(qrF)
if err != nil {
return "", "", err
}
jpg := image.NewRGBA(image.Rect(a.Rect.X0, a.Rect.Y0, a.Rect.X1, a.Rect.Y1))
draw.Draw(jpg, jpg.Bounds(), bgImage, bgImage.Bounds().Min, draw.Over)
draw.Draw(jpg, jpg.Bounds(), qrImage, qrImage.Bounds().Min.Sub(image.Pt(a.Pt.X, a.Pt.Y)), draw.Over)
err = a.DrawPoster(&DrawText{
JPG: jpg,
Merged: mergedF,
Title: "Golang Gin 系列文章",
X0: 80,
Y0: 160,
Size0: 42,
SubTitle: "---煎鱼",
X1: 320,
Y1: 220,
Size1: 36,
}, "msyhbd.ttc")
if err != nil {
return "", "", err
}
}
return fileName, path, nil
}
package auth_service
import "chain33-pai/models"
type Auth struct {
Username string
Password string
}
func (a *Auth) Check() (bool, error) {
return models.CheckAuth(a.Username, a.Password)
}
package cache_service
import (
"strconv"
"strings"
"chain33-pai/pkg/e"
)
type Article struct {
ID int
TagID int
State int
PageNum int
PageSize int
}
func (a *Article) GetArticleKey() string {
return e.CACHE_ARTICLE + "_" + strconv.Itoa(a.ID)
}
func (a *Article) GetArticlesKey() string {
keys := []string{
e.CACHE_ARTICLE,
"LIST",
}
if a.ID > 0 {
keys = append(keys, strconv.Itoa(a.ID))
}
if a.TagID > 0 {
keys = append(keys, strconv.Itoa(a.TagID))
}
if a.State >= 0 {
keys = append(keys, strconv.Itoa(a.State))
}
if a.PageNum > 0 {
keys = append(keys, strconv.Itoa(a.PageNum))
}
if a.PageSize > 0 {
keys = append(keys, strconv.Itoa(a.PageSize))
}
return strings.Join(keys, "_")
}
package cache_service
import (
"strconv"
"strings"
"chain33-pai/pkg/e"
)
type Tag struct {
ID int
Name string
State int
PageNum int
PageSize int
}
func (t *Tag) GetTagsKey() string {
keys := []string{
e.CACHE_TAG,
"LIST",
}
if t.Name != "" {
keys = append(keys, t.Name)
}
if t.State >= 0 {
keys = append(keys, strconv.Itoa(t.State))
}
if t.PageNum > 0 {
keys = append(keys, strconv.Itoa(t.PageNum))
}
if t.PageSize > 0 {
keys = append(keys, strconv.Itoa(t.PageSize))
}
return strings.Join(keys, "_")
}
...@@ -16,6 +16,7 @@ import ( ...@@ -16,6 +16,7 @@ import (
"chain33-pai/pkg/pai" "chain33-pai/pkg/pai"
"os" "os"
"errors" "errors"
"strconv"
) )
var ( var (
...@@ -43,6 +44,7 @@ type Pai struct { ...@@ -43,6 +44,7 @@ type Pai struct {
ENum int64 `json:"e_num"` ENum int64 `json:"e_num"`
LocalLastHeight2 int64 `json:"local_last_height_2"` LocalLastHeight2 int64 `json:"local_last_height_2"`
ProLevel int64 `json:"pro_level"` ProLevel int64 `json:"pro_level"`
Temp int64 `json:"temp"`
} }
type ReqUpdatePai struct { type ReqUpdatePai struct {
...@@ -57,6 +59,7 @@ func (p *Pai) SetPai() error { ...@@ -57,6 +59,7 @@ func (p *Pai) SetPai() error {
p.SetPaiEnv() p.SetPaiEnv()
p.GetDiskUseage() p.GetDiskUseage()
p.CheckBackup() p.CheckBackup()
p.GetTemp()
return nil return nil
} }
...@@ -238,4 +241,20 @@ func (p *Pai) CheckBackup() error { ...@@ -238,4 +241,20 @@ func (p *Pai) CheckBackup() error {
} }
p.IsBackup = true p.IsBackup = true
return nil return nil
}
func (p *Pai) GetTemp() error {
var b bytes.Buffer
cmd := exec.Command("cat","/sys/class/thermal/thermal_zone0/temp")
cmd.Stdout = &b
err := cmd.Run()
if err != nil {
return err
}
list := strings.Split(b.String(),"\n")
if list[0] != "" {
temp,_ := strconv.Atoi(list[0])
p.Temp = int64(temp)
}
return nil
} }
\ No newline at end of file
package tag_service
import (
"encoding/json"
"io"
"strconv"
"time"
"github.com/360EntSecGroup-Skylar/excelize"
"github.com/tealeg/xlsx"
"chain33-pai/models"
"chain33-pai/pkg/export"
"chain33-pai/pkg/file"
"chain33-pai/pkg/gredis"
"chain33-pai/pkg/logging"
"chain33-pai/service/cache_service"
)
type Tag struct {
ID int
Name string
CreatedBy string
ModifiedBy string
State int
PageNum int
PageSize int
}
func (t *Tag) ExistByName() (bool, error) {
return models.ExistTagByName(t.Name)
}
func (t *Tag) ExistByID() (bool, error) {
return models.ExistTagByID(t.ID)
}
func (t *Tag) Add() error {
return models.AddTag(t.Name, t.State, t.CreatedBy)
}
func (t *Tag) Edit() error {
data := make(map[string]interface{})
data["modified_by"] = t.ModifiedBy
data["name"] = t.Name
if t.State >= 0 {
data["state"] = t.State
}
return models.EditTag(t.ID, data)
}
func (t *Tag) Delete() error {
return models.DeleteTag(t.ID)
}
func (t *Tag) Count() (int, error) {
return models.GetTagTotal(t.getMaps())
}
func (t *Tag) GetAll() ([]models.Tag, error) {
var (
tags, cacheTags []models.Tag
)
cache := cache_service.Tag{
State: t.State,
PageNum: t.PageNum,
PageSize: t.PageSize,
}
key := cache.GetTagsKey()
if gredis.Exists(key) {
data, err := gredis.Get(key)
if err != nil {
logging.Info(err)
} else {
json.Unmarshal(data, &cacheTags)
return cacheTags, nil
}
}
tags, err := models.GetTags(t.PageNum, t.PageSize, t.getMaps())
if err != nil {
return nil, err
}
gredis.Set(key, tags, 3600)
return tags, nil
}
func (t *Tag) Export() (string, error) {
tags, err := t.GetAll()
if err != nil {
return "", err
}
xlsFile := xlsx.NewFile()
sheet, err := xlsFile.AddSheet("标签信息")
if err != nil {
return "", err
}
titles := []string{"ID", "名称", "创建人", "创建时间", "修改人", "修改时间"}
row := sheet.AddRow()
var cell *xlsx.Cell
for _, title := range titles {
cell = row.AddCell()
cell.Value = title
}
for _, v := range tags {
values := []string{
strconv.Itoa(v.ID),
v.Name,
v.CreatedBy,
strconv.Itoa(v.CreatedOn),
v.ModifiedBy,
strconv.Itoa(v.ModifiedOn),
}
row = sheet.AddRow()
for _, value := range values {
cell = row.AddCell()
cell.Value = value
}
}
time := strconv.Itoa(int(time.Now().Unix()))
filename := "tags-" + time + export.EXT
dirFullPath := export.GetExcelFullPath()
err = file.IsNotExistMkDir(dirFullPath)
if err != nil {
return "", err
}
err = xlsFile.Save(dirFullPath + filename)
if err != nil {
return "", err
}
return filename, nil
}
func (t *Tag) Import(r io.Reader) error {
xlsx, err := excelize.OpenReader(r)
if err != nil {
return err
}
rows := xlsx.GetRows("标签信息")
for irow, row := range rows {
if irow > 0 {
var data []string
for _, cell := range row {
data = append(data, cell)
}
models.AddTag(data[1], 1, data[2])
}
}
return nil
}
func (t *Tag) getMaps() map[string]interface{} {
maps := make(map[string]interface{})
maps["deleted_on"] = 0
if t.Name != "" {
maps["name"] = t.Name
}
if t.State >= 0 {
maps["state"] = t.State
}
return maps
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment