116 lines
2.2 KiB
Go
116 lines
2.2 KiB
Go
package way
|
|
|
|
import (
|
|
"io"
|
|
"log"
|
|
"mime/multipart"
|
|
"os"
|
|
"path"
|
|
"strings"
|
|
"time"
|
|
|
|
"gorm.io/gorm"
|
|
v1 "pkg.bing89.com/travebing/api/v1"
|
|
"pkg.bing89.com/travebing/config"
|
|
"pkg.bing89.com/travebing/controller/geo"
|
|
"pkg.bing89.com/travebing/tberror"
|
|
)
|
|
|
|
type Controller interface {
|
|
List() ([]v1.TravelWay, int, error)
|
|
Create(opt CreateOption) (*v1.TravelWay, int, error)
|
|
}
|
|
|
|
type way struct {
|
|
db *gorm.DB
|
|
cfg *config.Image
|
|
plan int
|
|
geoCtrl geo.Controller
|
|
}
|
|
|
|
func New(plan int, db *gorm.DB, cfg *config.Image, geoCtrl geo.Controller) Controller {
|
|
c := &way{
|
|
db: db,
|
|
cfg: cfg,
|
|
plan: plan,
|
|
geoCtrl: geoCtrl,
|
|
}
|
|
return c
|
|
}
|
|
|
|
func (c *way) List() ([]v1.TravelWay, int, error) {
|
|
ret := []v1.TravelWay{}
|
|
err := c.db.Where("plan = ?", c.plan).Find(&ret).Error
|
|
if err != nil {
|
|
return ret, tberror.CodeDatabase, err
|
|
}
|
|
ways := []v1.TravelWay{}
|
|
for _, w := range ret {
|
|
w.Image = w.ImageSrc()
|
|
ways = append(ways, w)
|
|
}
|
|
return ways, 0, nil
|
|
}
|
|
|
|
func (c *way) checkDir(file string) error {
|
|
dir := path.Dir(file)
|
|
_, err := os.ReadDir(dir)
|
|
if os.IsNotExist(err) {
|
|
return os.MkdirAll(dir, os.ModeDir|os.ModePerm)
|
|
}
|
|
return err
|
|
}
|
|
|
|
func (c *way) saveFile(file *multipart.FileHeader, dst string) error {
|
|
if file == nil {
|
|
return nil
|
|
}
|
|
if err := c.checkDir(dst); err != nil {
|
|
return err
|
|
}
|
|
src, err := file.Open()
|
|
if err != nil {
|
|
return err
|
|
}
|
|
defer src.Close()
|
|
|
|
out, err := os.Create(dst)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
defer out.Close()
|
|
_, err = io.Copy(out, src)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func (c *way) Create(opt CreateOption) (*v1.TravelWay, int, error) {
|
|
ret := &v1.TravelWay{
|
|
Plan: c.plan,
|
|
Lat: opt.Lat,
|
|
Lon: opt.Lon,
|
|
CreatedAt: time.Now().Unix(),
|
|
}
|
|
addr, err := c.geoCtrl.Address(opt.Lon, opt.Lat)
|
|
if err != nil {
|
|
log.Println("===>>>> get address failed:", err)
|
|
}
|
|
ret.Address = addr
|
|
if opt.File != nil {
|
|
fileExt := strings.ToLower(path.Ext(opt.File.Filename))
|
|
ret.Image = fileExt
|
|
}
|
|
err = c.db.Create(ret).Error
|
|
if err != nil {
|
|
return nil, tberror.CodeDatabase, err
|
|
}
|
|
err = c.saveFile(opt.File, ret.ImagePath(c.cfg.Dir))
|
|
if err != nil {
|
|
return ret, tberror.CodeFileSave, err
|
|
}
|
|
ret.Image = ret.ImageSrc()
|
|
return ret, 0, nil
|
|
}
|