模块化上传驱动,使用泛型优化工具库降低冗余

This commit is contained in:
孟帅
2023-06-02 20:29:08 +08:00
parent fdc48b9335
commit 62ecbb7f26
96 changed files with 1276 additions and 1483 deletions

View File

@@ -223,8 +223,8 @@ func (s *sAdminDept) List(ctx context.Context, in adminin.DeptListInp) (res *adm
}
if len(ids) > 0 {
ids = convert.UniqueSliceInt64(ids)
pids = convert.UniqueSliceInt64(pids)
ids = convert.UniqueSlice(ids)
pids = convert.UniqueSlice(pids)
mod = mod.Wheref(`id in (?) or pid in (?)`, ids, pids)
}

View File

@@ -307,6 +307,6 @@ func (s *sAdminMenu) LoginPermissions(ctx context.Context, memberId int64) (list
}
}
lists = convert.UniqueSliceString(lists)
lists = convert.UniqueSlice(lists)
return
}

View File

@@ -124,7 +124,7 @@ func (s *sAdminNotice) Status(ctx context.Context, in adminin.NoticeStatusInp) (
return
}
if !validate.InSliceInt(consts.StatusSlice, in.Status) {
if !validate.InSlice(consts.StatusSlice, in.Status) {
err = gerror.New("状态不正确")
return
}
@@ -322,16 +322,14 @@ func (s *sAdminNotice) UnreadCount(ctx context.Context, in adminin.NoticeUnreadC
// messageIds 获取我的消息所有的消息ID
func (s *sAdminNotice) messageIds(ctx context.Context, memberId int64) (ids []int64, err error) {
mod := s.Model(ctx, &handler.Option{FilterAuth: false}).
array, err := s.Model(ctx, &handler.Option{FilterAuth: false}).
Fields("id").
Where("status", consts.StatusEnabled).
Where("(`type` IN(?) OR (`type` = ? and JSON_CONTAINS(`receiver`,'"+gconv.String(memberId)+"')))",
[]int{consts.NoticeTypeNotify, consts.NoticeTypeNotice}, consts.NoticeTypeLetter,
)
array, err := mod.Array()
).Array()
if err != nil {
return nil, err
return
}
for _, v := range array {
@@ -351,14 +349,15 @@ func (s *sAdminNotice) UpRead(ctx context.Context, in adminin.NoticeUpReadInp) (
err = gerror.New("获取用户信息失败!")
return
}
if err = dao.AdminNotice.Ctx(ctx).Where("id", in.Id).Scan(&data); err != nil {
err = gerror.Wrap(err, consts.ErrorORM)
return err
return
}
if data == nil {
return gerror.New("公告不存在")
}
return s.updatedReadClicks(ctx, in.Id, memberId)
}
@@ -408,13 +407,12 @@ func (s *sAdminNotice) ReadAll(ctx context.Context, in adminin.NoticeReadAllInp)
}
for _, messageId := range messageIds {
if !validate.InSliceInt64(readIds, messageId) {
if !validate.InSlice(readIds, messageId) {
if err = s.updatedReadClicks(ctx, messageId, memberId); err != nil {
return
}
}
}
return
}
@@ -435,7 +433,7 @@ func (s *sAdminNotice) updatedReadClicks(ctx context.Context, noticeId, memberId
_, err = dao.AdminNoticeRead.Ctx(ctx).Data(entity.AdminNoticeRead{NoticeId: noticeId, MemberId: memberId}).Insert()
return
}
_, err = dao.AdminNoticeRead.Ctx(ctx).Where(dao.AdminNoticeRead.Columns().Id, models.Id).Increment("clicks", 1)
_, err = dao.AdminNoticeRead.Ctx(ctx).Where(dao.AdminNoticeRead.Columns().Id, models.Id).Increment(dao.AdminNoticeRead.Columns().Clicks, 1)
return
}

View File

@@ -382,7 +382,7 @@ func (s *sAdminOrder) Status(ctx context.Context, in adminin.OrderStatusInp) (er
return
}
if !validate.InSliceInt(consts.StatusSlice, in.Status) {
if !validate.InSlice(consts.StatusSlice, in.Status) {
err = gerror.New("状态不正确")
return
}

View File

@@ -203,7 +203,7 @@ func (s *sAdminPost) Status(ctx context.Context, in adminin.PostStatusInp) (err
return
}
if !validate.InSliceInt(consts.StatusSlice, in.Status) {
if !validate.InSlice(consts.StatusSlice, in.Status) {
err = gerror.New("状态不正确")
return
}

View File

@@ -57,7 +57,6 @@ func (s *sAdminRole) Verify(ctx context.Context, path, method string) bool {
g.Log().Infof(ctx, "admin Verify Enforce err:%+v", err)
return false
}
return ok
}
@@ -102,7 +101,6 @@ func (s *sAdminRole) GetName(ctx context.Context, id int64) (name string, err er
err = gerror.Wrap(err, consts.ErrorORM)
return
}
return r.String(), nil
}
@@ -148,7 +146,7 @@ func (s *sAdminRole) UpdatePermissions(ctx context.Context, in adminin.UpdatePer
}
// 去重
in.MenuIds = convert.UniqueSliceInt64(in.MenuIds)
in.MenuIds = convert.UniqueSlice(in.MenuIds)
list := make(g.List, 0, len(in.MenuIds))
for _, v := range in.MenuIds {
@@ -169,7 +167,6 @@ func (s *sAdminRole) UpdatePermissions(ctx context.Context, in adminin.UpdatePer
if err != nil {
return
}
return casbin.Refresh(ctx)
}
@@ -296,19 +293,18 @@ func (s *sAdminRole) DataScopeEdit(ctx context.Context, in *adminin.DataScopeEdi
return gerror.New("超管角色拥有全部权限,无需修改!")
}
if in.DataScope == consts.RoleDataDeptCustom && len(convert.UniqueSliceInt64(in.CustomDept)) == 0 {
if in.DataScope == consts.RoleDataDeptCustom && len(convert.UniqueSlice(in.CustomDept)) == 0 {
return gerror.New("自定义权限必须配置自定义部门!")
}
models.DataScope = in.DataScope
models.CustomDept = gjson.New(convert.UniqueSliceInt64(in.CustomDept))
models.CustomDept = gjson.New(convert.UniqueSlice(in.CustomDept))
_, err = dao.AdminRole.Ctx(ctx).
Fields(dao.AdminRole.Columns().DataScope, dao.AdminRole.Columns().CustomDept).
Where("id", in.Id).
Data(models).
Update()
return
}

View File

@@ -7,33 +7,12 @@ package common
import (
"context"
"github.com/aliyun/aliyun-oss-go-sdk/oss"
"github.com/gogf/gf/v2/errors/gerror"
"github.com/gogf/gf/v2/frame/g"
"github.com/gogf/gf/v2/net/ghttp"
"github.com/gogf/gf/v2/os/gfile"
"github.com/gogf/gf/v2/os/gtime"
"github.com/gogf/gf/v2/util/gconv"
"github.com/gogf/gf/v2/util/grand"
"github.com/qiniu/go-sdk/v7/auth/qbox"
"github.com/qiniu/go-sdk/v7/storage"
"github.com/tencentyun/cos-go-sdk-v5"
ufile "github.com/ufilesdk-dev/ufile-gosdk"
"hotgo/internal/consts"
"hotgo/internal/dao"
"hotgo/internal/model"
"hotgo/internal/library/storager"
"hotgo/internal/model/input/sysin"
"hotgo/internal/service"
"hotgo/utility/encrypt"
f "hotgo/utility/file"
"hotgo/utility/format"
utilityurl "hotgo/utility/url"
"hotgo/utility/validate"
"net/http"
"net/url"
"strconv"
"strings"
"time"
)
type sCommonUpload struct{}
@@ -47,391 +26,31 @@ func init() {
}
// UploadFile 上传文件
func (s *sCommonUpload) UploadFile(ctx context.Context, file *ghttp.UploadFile) (result *sysin.AttachmentListModel, err error) {
if file == nil {
err = gerror.New("文件必须!")
return
}
meta, err := s.fileMeta(file)
func (s *sCommonUpload) UploadFile(ctx context.Context, file *ghttp.UploadFile) (res *sysin.AttachmentListModel, err error) {
attachment, err := storager.DoUpload(ctx, file, consts.UploadTypeFile)
if err != nil {
return
}
if _, err = f.GetFileType(meta.Ext); err != nil {
return
}
result, err = s.HasFile(ctx, meta.Md5)
if err != nil {
return
}
if result != nil {
return
}
conf, err := service.SysConfig().GetUpload(ctx)
if err != nil {
return
}
switch conf.Drive {
case consts.UploadDriveLocal:
return s.UploadLocal(ctx, conf, file, meta)
case consts.UploadDriveUCloud:
return s.UploadUCloud(ctx, conf, file, meta)
case consts.UploadDriveCos:
return s.UploadCOS(ctx, conf, file, meta)
case consts.UploadDriveOss:
return s.UploadOSS(ctx, conf, file, meta)
case consts.UploadDriveQiNiu:
return s.UploadQiNiu(ctx, conf, file, meta)
default:
return nil, gerror.Newf("暂不支持上传驱动:%v", conf.Drive)
attachment.FileUrl = storager.LastUrl(ctx, attachment.FileUrl, attachment.Drive)
res = &sysin.AttachmentListModel{
SysAttachment: *attachment,
SizeFormat: format.FileSize(attachment.Size),
}
return
}
// UploadImage 上传图片
func (s *sCommonUpload) UploadImage(ctx context.Context, file *ghttp.UploadFile) (result *sysin.AttachmentListModel, err error) {
if file == nil {
err = gerror.New("文件必须!")
return
}
meta, err := s.fileMeta(file)
func (s *sCommonUpload) UploadImage(ctx context.Context, file *ghttp.UploadFile) (res *sysin.AttachmentListModel, err error) {
attachment, err := storager.DoUpload(ctx, file, consts.UploadTypeImage)
if err != nil {
return
}
if !f.IsImgType(meta.Ext) {
err = gerror.New("上传的文件不是图片")
return
}
if meta.Size > 2*1024*1024 {
err = gerror.New("图片大小不能超过2MB")
return
}
result, err = s.HasFile(ctx, meta.Md5)
if err != nil {
return
}
if result != nil {
return
}
conf, err := service.SysConfig().GetUpload(ctx)
if err != nil {
return
}
switch conf.Drive {
case consts.UploadDriveLocal:
return s.UploadLocal(ctx, conf, file, meta)
case consts.UploadDriveUCloud:
return s.UploadUCloud(ctx, conf, file, meta)
case consts.UploadDriveCos:
return s.UploadCOS(ctx, conf, file, meta)
case consts.UploadDriveOss:
return s.UploadOSS(ctx, conf, file, meta)
case consts.UploadDriveQiNiu:
return s.UploadQiNiu(ctx, conf, file, meta)
default:
err = gerror.Newf("暂不支持上传驱动:%v", conf.Drive)
return
}
}
// UploadLocal 上传本地
func (s *sCommonUpload) UploadLocal(ctx context.Context, conf *model.UploadConfig, file *ghttp.UploadFile, meta *sysin.UploadFileMeta) (result *sysin.AttachmentListModel, err error) {
var (
value = g.Cfg().MustGet(ctx, "server.serverRoot")
nowDate = time.Now().Format("2006-01-02")
)
if value.IsEmpty() {
err = gerror.New("本地上传驱动必须配置静态路径!")
return
}
if conf.LocalPath == "" {
err = gerror.New("本地上传驱动必须配置本地存储路径!")
return
}
// 包含静态文件夹的路径
fullDirPath := strings.Trim(value.String(), "/") + "/" + conf.LocalPath + nowDate
fileName, err := file.Save(fullDirPath, true)
if err != nil {
return
}
// 不含静态文件夹的路径
fullPath := conf.LocalPath + nowDate + "/" + fileName
attachment, err := service.SysAttachment().Add(ctx, meta, fullPath, consts.UploadDriveLocal)
if err != nil {
return
}
attachment.FileUrl = s.LastUrl(ctx, conf, attachment.FileUrl, attachment.Drive)
result = &sysin.AttachmentListModel{
attachment.FileUrl = storager.LastUrl(ctx, attachment.FileUrl, attachment.Drive)
res = &sysin.AttachmentListModel{
SysAttachment: *attachment,
SizeFormat: format.FileSize(attachment.Size),
}
return
}
// UploadUCloud 上传UCloud对象存储
func (s *sCommonUpload) UploadUCloud(ctx context.Context, conf *model.UploadConfig, file *ghttp.UploadFile, meta *sysin.UploadFileMeta) (result *sysin.AttachmentListModel, err error) {
if conf.UCloudPath == "" {
err = gerror.New("UCloud存储驱动必须配置存储路径!")
return
}
nowDate := time.Now().Format("2006-01-02")
fileName := strings.ToLower(strconv.FormatInt(gtime.TimestampNano(), 36) + grand.S(6))
fileName = fileName + gfile.Ext(file.Filename)
fullPath := conf.UCloudPath + nowDate + "/" + fileName
config := &ufile.Config{
PublicKey: conf.UCloudPublicKey,
PrivateKey: conf.UCloudPrivateKey,
BucketHost: conf.UCloudBucketHost,
BucketName: conf.UCloudBucketName,
FileHost: conf.UCloudFileHost,
Endpoint: conf.UCloudEndpoint,
VerifyUploadMD5: false,
}
req, err := ufile.NewFileRequest(config, nil)
if err != nil {
return
}
// 流式上传本地小文件
f2, err := file.Open()
defer func() { _ = f2.Close() }()
if err != nil {
return
}
if err = req.IOPut(f2, fullPath, ""); err != nil {
return
}
attachment, err := service.SysAttachment().Add(ctx, meta, fullPath, consts.UploadDriveUCloud)
if err != nil {
return
}
attachment.FileUrl = s.LastUrl(ctx, conf, attachment.FileUrl, attachment.Drive)
result = &sysin.AttachmentListModel{
SysAttachment: *attachment,
SizeFormat: format.FileSize(attachment.Size),
}
return
}
// UploadCOS 上传腾讯云对象存储
func (s *sCommonUpload) UploadCOS(ctx context.Context, conf *model.UploadConfig, file *ghttp.UploadFile, meta *sysin.UploadFileMeta) (result *sysin.AttachmentListModel, err error) {
if conf.CosPath == "" {
err = gerror.New("COS存储驱动必须配置存储路径!")
return
}
nowDate := time.Now().Format("2006-01-02")
fileName := strings.ToLower(strconv.FormatInt(gtime.TimestampNano(), 36) + grand.S(6))
fileName = fileName + gfile.Ext(file.Filename)
fullPath := conf.CosPath + nowDate + "/" + fileName
// 流式上传本地小文件
f2, err := file.Open()
defer func() { _ = f2.Close() }()
if err != nil {
return
}
u, _ := url.Parse(conf.CosBucketURL)
b := &cos.BaseURL{BucketURL: u}
c := cos.NewClient(b, &http.Client{
Transport: &cos.AuthorizationTransport{
SecretID: conf.CosSecretId,
SecretKey: conf.CosSecretKey,
},
})
if _, err = c.Object.Put(ctx, fullPath, f2, nil); err != nil {
return
}
attachment, err := service.SysAttachment().Add(ctx, meta, fullPath, consts.UploadDriveCos)
if err != nil {
return
}
attachment.FileUrl = s.LastUrl(ctx, conf, attachment.FileUrl, attachment.Drive)
result = &sysin.AttachmentListModel{
SysAttachment: *attachment,
SizeFormat: format.FileSize(attachment.Size),
}
return
}
// UploadOSS 上传阿里云云对象存储
func (s *sCommonUpload) UploadOSS(ctx context.Context, conf *model.UploadConfig, file *ghttp.UploadFile, meta *sysin.UploadFileMeta) (result *sysin.AttachmentListModel, err error) {
if conf.OssPath == "" {
err = gerror.New("OSS存储驱动必须配置存储路径!")
return
}
nowDate := time.Now().Format("2006-01-02")
fileName := strings.ToLower(strconv.FormatInt(gtime.TimestampNano(), 36) + grand.S(6))
fileName = fileName + gfile.Ext(file.Filename)
fullPath := conf.OssPath + nowDate + "/" + fileName
// 流式上传本地小文件
f2, err := file.Open()
defer func() { _ = f2.Close() }()
if err != nil {
return
}
client, err := oss.New(conf.OssEndpoint, conf.OssSecretId, conf.OssSecretKey)
if err != nil {
return
}
bucket, err := client.Bucket(conf.OssBucket)
if err != nil {
return
}
if err = bucket.PutObject(fullPath, f2); err != nil {
return
}
attachment, err := service.SysAttachment().Add(ctx, meta, fullPath, consts.UploadDriveOss)
if err != nil {
return
}
attachment.FileUrl = s.LastUrl(ctx, conf, attachment.FileUrl, attachment.Drive)
result = &sysin.AttachmentListModel{
SysAttachment: *attachment,
SizeFormat: format.FileSize(attachment.Size),
}
return
}
// UploadQiNiu 上传七牛云对象存储
func (s *sCommonUpload) UploadQiNiu(ctx context.Context, conf *model.UploadConfig, file *ghttp.UploadFile, meta *sysin.UploadFileMeta) (result *sysin.AttachmentListModel, err error) {
if conf.QiNiuPath == "" {
err = gerror.New("七牛云存储驱动必须配置存储路径!")
return
}
nowDate := time.Now().Format("2006-01-02")
fileName := strings.ToLower(strconv.FormatInt(gtime.TimestampNano(), 36) + grand.S(6))
fileName = fileName + gfile.Ext(file.Filename)
fullPath := conf.QiNiuPath + nowDate + "/" + fileName
// 流式上传本地小文件
f2, err := file.Open()
defer func() { _ = f2.Close() }()
if err != nil {
return
}
putPolicy := storage.PutPolicy{
Scope: conf.QiNiuBucket,
}
token := putPolicy.UploadToken(qbox.NewMac(conf.QiNiuAccessKey, conf.QiNiuSecretKey))
cfg := storage.Config{}
// 是否使用https域名
cfg.UseHTTPS = true
// 上传是否使用CDN上传加速
cfg.UseCdnDomains = false
// 空间对应的机房
cfg.Region, err = storage.GetRegion(conf.QiNiuAccessKey, conf.QiNiuBucket)
if err != nil {
return
}
if err = storage.NewFormUploader(&cfg).Put(ctx, &storage.PutRet{}, token, fullPath, f2, file.Size, &storage.PutExtra{}); err != nil {
return
}
attachment, err := service.SysAttachment().Add(ctx, meta, fullPath, consts.UploadDriveQiNiu)
if err != nil {
return
}
attachment.FileUrl = s.LastUrl(ctx, conf, attachment.FileUrl, attachment.Drive)
result = &sysin.AttachmentListModel{
SysAttachment: *attachment,
SizeFormat: format.FileSize(attachment.Size),
}
return
}
// LastUrl 根据驱动获取最终文件访问地址
func (s *sCommonUpload) LastUrl(ctx context.Context, conf *model.UploadConfig, fullPath, drive string) string {
if validate.IsURL(fullPath) {
return fullPath
}
switch drive {
case consts.UploadDriveLocal:
return utilityurl.GetAddr(ctx) + "/" + fullPath
case consts.UploadDriveUCloud:
return conf.UCloudEndpoint + "/" + fullPath
case consts.UploadDriveCos:
return conf.CosBucketURL + "/" + fullPath
case consts.UploadDriveOss:
return conf.OssBucketURL + "/" + fullPath
case consts.UploadDriveQiNiu:
return conf.QiNiuDomain + "/" + fullPath
default:
return fullPath
}
}
// HasFile 文件是否存在
func (s *sCommonUpload) HasFile(ctx context.Context, md5 string) (res *sysin.AttachmentListModel, err error) {
res, err = dao.SysAttachment.GetMd5File(ctx, md5)
return
}
// fileMeta 上传文件元数据
func (s *sCommonUpload) fileMeta(file *ghttp.UploadFile) (meta *sysin.UploadFileMeta, err error) {
meta = new(sysin.UploadFileMeta)
meta.Filename = file.Filename
meta.Size = file.Size
meta.Ext = f.Ext(file.Filename)
meta.Kind = f.GetFileKind(meta.Ext)
meta.MetaType, err = f.GetFileType(meta.Ext)
if err != nil {
return
}
// 兼容naiveUI
naiveType := "text/plain"
if f.IsImgType(f.Ext(file.Filename)) {
naiveType = ""
}
meta.NaiveType = naiveType
// 文件hash
b, err := f.UploadFileByte(file)
if err != nil {
return
}
meta.Md5 = encrypt.Md5ToString(gconv.String(encrypt.Hash32(b)))
return
}

View File

@@ -32,7 +32,6 @@ func (s *sMiddleware) AdminAuth(r *ghttp.Request) {
// 将用户信息传递到上下文中
if err := deliverUserContext(r); err != nil {
g.Log().Warningf(ctx, "deliverUserContext err:%+v", err)
response.JsonExit(r, gcode.CodeNotAuthorized.Code(), err.Error())
return
}

View File

@@ -138,7 +138,7 @@ func (s *sPay) Status(ctx context.Context, in payin.PayStatusInp) (err error) {
return
}
if !validate.InSliceInt(consts.StatusSlice, in.Status) {
if !validate.InSlice(consts.StatusSlice, in.Status) {
err = gerror.New("状态不正确")
return
}

View File

@@ -90,7 +90,6 @@ func (s *sSysAddons) List(ctx context.Context, in sysin.AddonsListInp) (list []*
}
totalCount = len(sks)
return
}
@@ -129,7 +128,6 @@ func (s *sSysAddons) Build(ctx context.Context, in sysin.AddonsBuildInp) (err er
err = gerror.New("没有找到有效的生成或插件配置,请检查配置文件是否正常")
return
}
return addons.Build(ctx, in.Skeleton, genConfig.Addon)
}

View File

@@ -54,8 +54,8 @@ func (s *sSysAddonsConfig) GetConfigByGroup(ctx context.Context, in sysin.GetAdd
Scan(&models); err != nil {
return nil, err
}
isDemo := g.Cfg().MustGet(ctx, "hotgo.isDemo", false)
isDemo := g.Cfg().MustGet(ctx, "hotgo.isDemo", false)
if len(models) > 0 {
res = new(sysin.GetAddonsConfigModel)
res.List = make(g.Map, len(models))
@@ -71,7 +71,6 @@ func (s *sSysAddonsConfig) GetConfigByGroup(ctx context.Context, in sysin.GetAdd
}
}
}
return
}
@@ -105,10 +104,10 @@ func (s *sSysAddonsConfig) UpdateConfigByGroup(ctx context.Context, in sysin.Upd
Where("addon_name", in.AddonName).
Where("group", in.Group).
Scan(&models); err != nil {
return err
return
}
err = dao.SysAddonsConfig.Transaction(ctx, func(ctx context.Context, tx gdb.TX) error {
err = dao.SysAddonsConfig.Transaction(ctx, func(ctx context.Context, tx gdb.TX) (err error) {
for k, v := range in.List {
row := s.getConfigByKey(k, models)
// 新增
@@ -130,20 +129,15 @@ func (s *sSysAddonsConfig) UpdateConfigByGroup(ctx context.Context, in sysin.Upd
}
// 更新
_, err = dao.SysAddonsConfig.Ctx(ctx).Where("id", row.Id).Data(g.Map{"value": v, "updated_at": gtime.Now()}).Update()
if err != nil {
if _, err = dao.SysAddonsConfig.Ctx(ctx).Where("id", row.Id).Data(g.Map{"value": v, "updated_at": gtime.Now()}).Update(); err != nil {
err = gerror.Wrap(err, consts.ErrorORM)
return err
return
}
}
return nil
return
})
if err != nil {
return err
}
return nil
return
}
func (s *sSysAddonsConfig) getConfigByKey(key string, models []*entity.SysAddonsConfig) *entity.SysAddonsConfig {
@@ -156,6 +150,5 @@ func (s *sSysAddonsConfig) getConfigByKey(key string, models []*entity.SysAddons
return v
}
}
return nil
}

View File

@@ -9,17 +9,12 @@ import (
"context"
"github.com/gogf/gf/v2/database/gdb"
"github.com/gogf/gf/v2/errors/gerror"
"github.com/gogf/gf/v2/os/gtime"
"hotgo/internal/consts"
"hotgo/internal/dao"
"hotgo/internal/library/contexts"
"hotgo/internal/library/hgorm/handler"
"hotgo/internal/model/entity"
"hotgo/internal/model/input/form"
"hotgo/internal/library/storager"
"hotgo/internal/model/input/sysin"
"hotgo/internal/service"
"hotgo/utility/format"
"hotgo/utility/validate"
)
type sSysAttachment struct{}
@@ -37,92 +32,41 @@ func (s *sSysAttachment) Model(ctx context.Context, option ...*handler.Option) *
return handler.Model(dao.SysAttachment.Ctx(ctx), option...)
}
// Delete 删除
// Delete 删除附件
func (s *sSysAttachment) Delete(ctx context.Context, in sysin.AttachmentDeleteInp) (err error) {
_, err = s.Model(ctx).Where("id", in.Id).Delete()
if _, err = s.Model(ctx).WherePri(in.Id).Delete(); err != nil {
err = gerror.Wrap(err, "删除附件失败,请稍后重试!")
}
return
}
// Edit 修改/新增
func (s *sSysAttachment) Edit(ctx context.Context, in sysin.AttachmentEditInp) (err error) {
if in.Name == "" {
err = gerror.New("标题不能为空")
return
}
// 修改
if in.Id > 0 {
_, err = s.Model(ctx).Where("id", in.Id).Data(in).Update()
return
}
// 新增
_, err = dao.SysAttachment.Ctx(ctx).Data(in).Insert()
return
}
// Status 更新部门状态
func (s *sSysAttachment) Status(ctx context.Context, in sysin.AttachmentStatusInp) (err error) {
if in.Id <= 0 {
err = gerror.New("ID不能为空")
return
}
if in.Status <= 0 {
err = gerror.New("状态不能为空")
return
}
if !validate.InSliceInt(consts.StatusSlice, in.Status) {
err = gerror.New("状态不正确")
return
}
// 修改
_, err = s.Model(ctx).Where("id", in.Id).Data("status", in.Status).Update()
return
}
// MaxSort 最大排序
func (s *sSysAttachment) MaxSort(ctx context.Context, in sysin.AttachmentMaxSortInp) (res *sysin.AttachmentMaxSortModel, err error) {
if in.Id > 0 {
if err = s.Model(ctx).Where("id", in.Id).Order("sort desc").Scan(&res); err != nil {
return
}
}
if res == nil {
res = new(sysin.AttachmentMaxSortModel)
}
res.Sort = form.DefaultMaxSort(ctx, res.Sort)
return
}
// View 获取指定字典类型信息
// View 获取附件信息
func (s *sSysAttachment) View(ctx context.Context, in sysin.AttachmentViewInp) (res *sysin.AttachmentViewModel, err error) {
err = s.Model(ctx).Where("id", in.Id).Scan(&res)
if err = s.Model(ctx).WherePri(in.Id).Scan(&res); err != nil {
err = gerror.Wrap(err, "获取附件信息失败,请稍后重试!")
}
return
}
// List 获取列表
// List 获取附件列表
func (s *sSysAttachment) List(ctx context.Context, in sysin.AttachmentListInp) (list []*sysin.AttachmentListModel, totalCount int, err error) {
mod := s.Model(ctx)
if in.MemberId > 0 {
mod = mod.Where("member_id", in.MemberId)
mod = mod.Where(dao.SysAttachment.Columns().MemberId, in.MemberId)
}
if in.Drive != "" {
mod = mod.Where("drive", in.Drive)
mod = mod.Where(dao.SysAttachment.Columns().Drive, in.Drive)
}
if in.Status > 0 {
mod = mod.Where("status", in.Status)
mod = mod.Where(dao.SysAttachment.Columns().Status, in.Status)
}
totalCount, err = mod.Count()
if err != nil {
err = gerror.Wrap(err, consts.ErrorORM)
err = gerror.Wrap(err, "获取附件数据行失败!")
return
}
@@ -130,58 +74,14 @@ func (s *sSysAttachment) List(ctx context.Context, in sysin.AttachmentListInp) (
return
}
if err = mod.Page(in.Page, in.PerPage).Order("updated_at desc").Scan(&list); err != nil {
err = gerror.Wrap(err, consts.ErrorORM)
return
}
conf, err := service.SysConfig().GetUpload(ctx)
if err != nil {
if err = mod.Page(in.Page, in.PerPage).OrderDesc(dao.SysAttachment.Columns().UpdatedAt).Scan(&list); err != nil {
err = gerror.Wrap(err, "获取附件列表失败!")
return
}
for _, v := range list {
v.SizeFormat = format.FileSize(v.Size)
v.FileUrl = service.CommonUpload().LastUrl(ctx, conf, v.FileUrl, v.Drive)
v.FileUrl = storager.LastUrl(ctx, v.FileUrl, v.Drive)
}
return
}
// Add 新增附件
func (s *sSysAttachment) Add(ctx context.Context, meta *sysin.UploadFileMeta, fullPath, drive string) (models *entity.SysAttachment, err error) {
var (
c = contexts.Get(ctx)
user = c.User
memberId int64 = 0
)
if user != nil {
memberId = user.Id
}
models = &entity.SysAttachment{
Id: 0,
AppId: c.Module,
MemberId: memberId,
Drive: drive,
Size: meta.Size,
Path: fullPath,
FileUrl: fullPath,
Name: meta.Filename,
Kind: meta.Kind,
MetaType: meta.MetaType,
NaiveType: meta.NaiveType,
Ext: meta.Ext,
Md5: meta.Md5,
Status: consts.StatusEnabled,
CreatedAt: gtime.Now(),
UpdatedAt: gtime.Now(),
}
id, err := dao.SysAttachment.Ctx(ctx).Data(models).InsertAndGetId()
if err != nil {
return
}
models.Id = id
return
}

View File

@@ -71,7 +71,7 @@ func (s *sSysBlacklist) Status(ctx context.Context, in sysin.BlacklistStatusInp)
return
}
if !validate.InSliceInt(consts.StatusSlice, in.Status) {
if !validate.InSlice(consts.StatusSlice, in.Status) {
err = gerror.New("状态不正确")
return
}

View File

@@ -16,6 +16,7 @@ import (
"hotgo/internal/consts"
"hotgo/internal/dao"
"hotgo/internal/library/payment"
"hotgo/internal/library/storager"
"hotgo/internal/library/token"
"hotgo/internal/library/wechat"
"hotgo/internal/model"
@@ -35,6 +36,7 @@ func init() {
service.RegisterSysConfig(NewSysConfig())
}
// InitConfig 初始化一些系统启动就需要用到的配置
func (s *sSysConfig) InitConfig(ctx context.Context) {
wx, err := s.GetWechat(ctx)
if err != nil {
@@ -48,12 +50,17 @@ func (s *sSysConfig) InitConfig(ctx context.Context) {
}
payment.SetConfig(pay)
upload, err := s.GetUpload(ctx)
if err != nil {
g.Log().Fatalf(ctx, "init upload conifg fail%+v", err)
}
storager.SetConfig(upload)
tk, err := s.GetLoadToken(ctx)
if err != nil {
g.Log().Fatalf(ctx, "init token conifg fail%+v", err)
}
token.SetConfig(tk)
}
// GetLogin 获取登录配置
@@ -267,7 +274,6 @@ func (s *sSysConfig) UpdateConfigByGroup(ctx context.Context, in sysin.UpdateCon
return s.syncUpdate(ctx, in)
})
return
}
@@ -281,7 +287,6 @@ func (s *sSysConfig) getConfigByKey(key string, models []*entity.SysConfig) *ent
return v
}
}
return nil
}
@@ -298,6 +303,11 @@ func (s *sSysConfig) syncUpdate(ctx context.Context, in sysin.UpdateConfigInp) (
if err == nil {
payment.SetConfig(pay)
}
case "upload":
upload, err := s.GetUpload(ctx)
if err == nil {
storager.SetConfig(upload)
}
}
if err != nil {

View File

@@ -106,7 +106,7 @@ func (s *sSysCron) Status(ctx context.Context, in sysin.CronStatusInp) (err erro
return
}
if !validate.InSliceInt(consts.StatusSlice, in.Status) {
if !validate.InSlice(consts.StatusSlice, in.Status) {
err = gerror.New("状态不正确")
return
}

View File

@@ -46,7 +46,6 @@ func (s *sSysCronGroup) Edit(ctx context.Context, in sysin.CronGroupEditInp) (er
if _, err = dao.SysCronGroup.Ctx(ctx).Fields(sysin.CronGroupInsertFields{}).Data(in).Insert(); err != nil {
err = gerror.Wrap(err, consts.ErrorORM)
}
return
}

View File

@@ -198,7 +198,7 @@ func (s *sSysCurdDemo) Switch(ctx context.Context, in sysin.CurdDemoSwitchInp) (
// ...
}
if !validate.InSliceString(fields, in.Key) {
if !validate.InSlice(fields, in.Key) {
err = gerror.New("开关键名不在白名单")
return
}

View File

@@ -44,7 +44,6 @@ func (s *sSysDictData) Edit(ctx context.Context, in sysin.DictDataEditInp) (err
err = gerror.Wrap(err, consts.ErrorORM)
return err
}
return nil
}

View File

@@ -76,7 +76,7 @@ func (s *sSysEmsLog) Status(ctx context.Context, in sysin.EmsLogStatusInp) (err
return
}
if !validate.InSliceInt(consts.StatusSlice, in.Status) {
if !validate.InSlice(consts.StatusSlice, in.Status) {
err = gerror.New("状态不正确")
return
}

View File

@@ -110,7 +110,7 @@ func (s *sSysGenCodes) Status(ctx context.Context, in sysin.GenCodesStatusInp) (
return
}
if !validate.InSliceInt(consts.StatusSlice, in.Status) {
if !validate.InSlice(consts.StatusSlice, in.Status) {
err = gerror.New("状态不正确")
return
}
@@ -274,7 +274,6 @@ func (s *sSysGenCodes) ColumnSelect(ctx context.Context, in sysin.GenCodesColumn
res[k].Name = fmt.Sprintf("%s (%s)", v.Value, v.Label)
res[k].Label = res[k].Name
}
return
}
@@ -306,6 +305,5 @@ func (s *sSysGenCodes) Build(ctx context.Context, in sysin.GenCodesBuildInp) (er
_ = s.Status(ctx, sysin.GenCodesStatusInp{Id: in.Id, Status: consts.GenCodesStatusFail})
return err
}
return
}

View File

@@ -230,7 +230,6 @@ func (s *sSysLog) AnalysisLog(ctx context.Context) entity.SysLog {
Status: consts.StatusEnabled,
TakeUpTime: takeUpTime,
}
return data
}
@@ -241,8 +240,7 @@ func (s *sSysLog) View(ctx context.Context, in sysin.LogViewInp) (res *sysin.Log
return
}
isDemo := g.Cfg().MustGet(ctx, "hotgo.isDemo", false)
if isDemo.Bool() {
if g.Cfg().MustGet(ctx, "hotgo.isDemo", false).Bool() {
res.HeaderData = gjson.New(`{
"none": [
"` + consts.DemoTips + `"
@@ -364,6 +362,5 @@ func (s *sSysLog) List(ctx context.Context, in sysin.LogListInp) (list []*sysin.
}
}
return
}

View File

@@ -107,7 +107,6 @@ func (s *sSysLoginLog) List(ctx context.Context, in sysin.LoginLogListInp) (list
v.Os = useragent.GetOs(v.SysLogUserAgent)
v.Browser = useragent.GetBrowser(v.SysLogUserAgent)
}
return
}

View File

@@ -71,7 +71,7 @@ func (s *sSysSmsLog) Status(ctx context.Context, in sysin.SmsLogStatusInp) (err
return
}
if !validate.InSliceInt(consts.StatusSlice, in.Status) {
if !validate.InSlice(consts.StatusSlice, in.Status) {
err = gerror.New("状态不正确")
return
}

View File

@@ -3,11 +3,9 @@
// @Copyright Copyright (c) 2023 HotGo CLI
// @Author Ms <133814250@qq.com>
// @License https://github.com/bufanyun/hotgo/blob/master/LICENSE
//
package view
import (
"fmt"
"hotgo/internal/consts"
"github.com/gogf/gf/v2/net/ghttp"
@@ -44,41 +42,6 @@ func (s *viewBuildIn) UrlPath() string {
return s.httpRequest.URL.Path
}
// FormatTime 格式化时间
func (s *viewBuildIn) FormatTime(gt *gtime.Time) string {
if gt == nil {
return ""
}
n := gtime.Now().Timestamp()
t := gt.Timestamp()
var ys int64 = 31536000
var ds int64 = 86400
var hs int64 = 3600
var ms int64 = 60
var ss int64 = 1
var rs string
d := n - t
switch {
case d > ys:
rs = fmt.Sprintf("%d年前", int(d/ys))
case d > ds:
rs = fmt.Sprintf("%d天前", int(d/ds))
case d > hs:
rs = fmt.Sprintf("%d小时前", int(d/hs))
case d > ms:
rs = fmt.Sprintf("%d分钟前", int(d/ms))
case d > ss:
rs = fmt.Sprintf("%d秒前", int(d/ss))
default:
rs = "刚刚"
}
return rs
}
// Version 随机数 开发环境时间戳,线上为前端版本号
func (s *viewBuildIn) Version() string {
var rand string