resource/backend/server/server.go

200 lines
4.5 KiB
Go

package server
import (
"crypto/md5"
"encoding/hex"
"fmt"
"net/http"
"os"
"path"
"strconv"
"strings"
"time"
"github.com/gin-gonic/gin"
"gorm.io/gorm"
"sketchlib.bing89.com/backend/api"
"sketchlib.bing89.com/backend/utils/reader"
)
const (
SUCCESS = "success"
)
type Server struct{
sketchReader reader.SlmReader
tokenMap map[string]string
fileDir string
database *gorm.DB
}
type Response struct {
Code int `json:"code"`
Message string `json:"message"`
Data interface{} `json:"data"`
}
func NewServer(dir string, db *gorm.DB)*Server{
return &Server{
sketchReader: &reader.Sketch{},
tokenMap: make(map[string]string),
fileDir: dir,
database: db,
}
}
func (s *Server)HandleLogin(c *gin.Context){
user := api.User{}
err := c.ShouldBind(&user)
if err != nil {
s.ResponseError(c, 1000, err)
return
}
token := s.GenToken(&user)
s.ResponseSuccess(c, SUCCESS, token)
}
func (s *Server)GenToken(user *api.User)string{
return s.md5(fmt.Sprintf("%d-%s-%s", user.ID, user.Name, user.Phone))
}
func (s *Server)md5(str string)string{
m := md5.New()
m.Write([]byte(str))
res := hex.EncodeToString(m.Sum(nil))
fmt.Println("md5:", string(res))
return string(res)
}
func (s *Server)ResponseSuccess(c *gin.Context, msg string, data interface{}){
c.JSON(http.StatusOK, Response{Code: 0, Message: msg, Data: data})
}
func (s *Server)ResponseError(c *gin.Context, code int, err error){
c.JSON(http.StatusOK, Response{Code: code, Message: err.Error(), Data: err})
}
func (s *Server)Upload(c *gin.Context){
file, err := c.FormFile("file")
if err != nil {
s.ResponseError(c, 1001, err)
return
}
fileExt:=strings.ToLower(path.Ext(file.Filename))
if fileExt!=".sketch" && fileExt!=".xk"{
s.ResponseError(c, 1002, fmt.Errorf("only support sketch file"))
return
}
// fileName:=s.md5(fmt.Sprintf("%s%s",file.Filename, time.Now().String()))
fildDir := path.Join(fmt.Sprintf("%d", time.Now().Year()),fmt.Sprintf("%d", time.Now().Month()))
err = s.checkDir(fildDir)
if err != nil {
s.ResponseError(c, 1002, err)
return
}
filepath := path.Join(fildDir,file.Filename)
err = c.SaveUploadedFile(file, path.Join(s.fileDir, filepath))
if err != nil {
s.ResponseError(c, 1003, err)
return
}
go s.sketchReader.SavePreview(path.Join(s.fileDir, filepath))
doc := api.Doc{
Name: file.Filename,
File: filepath,
Preview: filepath+".png",
Permission: -1,
State: 1,
Owner: 0,
Size: file.Size,
}
err = s.database.Save(&doc).Error
if err != nil {
s.ResponseError(c, 1100, err)
return
}
s.ResponseSuccess(c,SUCCESS, doc)
}
func (s *Server)UploadBatch(c *gin.Context){
file, err := c.FormFile("file")
if err != nil {
s.ResponseError(c, 1001, err)
return
}
fileExt:=strings.ToLower(path.Ext(file.Filename))
if fileExt!=".sketch" && fileExt!=".xk"{
s.ResponseError(c, 1002, fmt.Errorf("only support sketch file"))
return
}
fileName:=s.md5(fmt.Sprintf("%s%s",file.Filename, time.Now().String()))
fildDir := path.Join(fmt.Sprintf("%d", time.Now().Year()),fmt.Sprintf("%d", time.Now().Month()))
err = s.checkDir(fildDir)
if err != nil {
s.ResponseError(c, 1002, err)
return
}
filepath := path.Join(fildDir,fileName + fileExt)
err = c.SaveUploadedFile(file, path.Join(s.fileDir, filepath))
if err != nil {
s.ResponseError(c, 1003, err)
return
}
go s.sketchReader.SavePreview(path.Join(s.fileDir, filepath))
doc := api.Doc{
Name: file.Filename,
File: filepath,
Preview: filepath+".png",
Permission: -1,
State: 1,
Owner: 0,
}
err = s.database.Save(&doc).Error
if err != nil {
s.ResponseError(c, 1100, err)
return
}
s.ResponseSuccess(c,SUCCESS, doc)
}
func (s *Server)List(c *gin.Context){
limit := -1
offset := -1
if n, err := strconv.Atoi(c.Query("limit")); err == nil && n >0 {
limit = n
}
if n, err := strconv.Atoi(c.Query("offset")); err == nil && n >0 {
offset = n
}
size := 0
if n, err := strconv.Atoi(c.Query("size")); err == nil{
size = n
}
db := s.database.Limit(limit).Offset(offset).Where("size > ?", size)
name := c.Query("name")
if name != "" {
db = db.Where(" name like '%"+ name+"%' ")
}
docs := []api.Doc{}
err := db.Find(&docs).Error
if err != nil {
s.ResponseError(c, 1102, err)
return
}
s.ResponseSuccess(c, SUCCESS, docs)
}
func (s *Server)checkDir(dir string)error{
if _, err := os.Stat(dir); !os.IsNotExist(err) {
return err
}
return os.MkdirAll(dir, os.ModePerm)
}
func (s *Server)Run(addr string)error{
engine := gin.Default()
apiGroup := engine.Group("/api/v1")
apiGroup.POST("/upload", s.Upload)
apiGroup.GET("/docs", s.List)
return engine.Run(addr)
}