Skip to content

Commit

Permalink
1.add fav item in flutter app
Browse files Browse the repository at this point in the history
2.fix backend share error
  • Loading branch information
ghjkg546 committed Nov 14, 2024
1 parent 231c902 commit a7d3a1c
Show file tree
Hide file tree
Showing 284 changed files with 5,657 additions and 647 deletions.
1 change: 1 addition & 0 deletions app/common/request/resource.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package request
type BatchSave struct {
Content string `form:"content" json:"content"`
CategoryId uint `form:"category_id" json:"category_id"`
DiskTypeId int `form:"disk_type_id" json:"disk_type_id"`
}

type Crawl struct {
Expand Down
4 changes: 4 additions & 0 deletions app/common/request/user.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,10 @@ type Login struct {
Password string `form:"password" json:"password"`
}

type Fav struct {
Id int `form:"id" json:"id"`
}

type PostComment struct {
Content string `form:"content" json:"content"`
ResItemId int32 `form:"resource_item_id" json:"resource_item_id"`
Expand Down
16 changes: 16 additions & 0 deletions app/constant/constants.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
package constants

import (
"fmt"
"github.com/jassue/jassue-gin/global"
)

// 定义 Redis 收藏键的格式
const (
FavKeyPattern = "%s:user:%s:fav" // %s 占位符将替换为 AppName 和 userID
)

// 获取 Redis 收藏键
func GetFavKey(userID string) string {
return fmt.Sprintf(FavKeyPattern, global.App.Config.App.AppName, userID)
}
86 changes: 71 additions & 15 deletions app/controllers/adminapi/resource.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import (
"github.com/jassue/jassue-gin/global"
"github.com/jassue/jassue-gin/utils"
client "github.com/zinclabs/sdk-go-zincsearch"
"gorm.io/gorm"
"io"
"io/ioutil"
"math"
Expand All @@ -30,6 +31,7 @@ func (uc *ResourceController) GetList(c *gin.Context) {
pageStr := c.DefaultQuery("pageNum", "1")
pageSizeStr := c.DefaultQuery("pageSize", "10")
keyword := c.DefaultQuery("keyword", "")
diskTypeId := c.DefaultQuery("disk_type_id", "")

page, err := strconv.Atoi(pageStr)
if err != nil || page < 1 {
Expand All @@ -48,7 +50,10 @@ func (uc *ResourceController) GetList(c *gin.Context) {

query := db.Model(models.ResourceItem{})
if keyword != "" {
query.Where("mobile LIKE ?", "%"+keyword+"%").Or("name LIKE ?", "%"+keyword+"%")
query.Where("title LIKE ?", "%"+keyword+"%")
}
if diskTypeId != "" {
query.Where("title LIKE ?", "%"+keyword+"%")
}

query.Count(&totalUsers).Limit(limit).Offset(offset).Order("id desc").Find(&users)
Expand Down Expand Up @@ -182,36 +187,87 @@ func (uc *ResourceController) BatchCreate(c *gin.Context) {
}
lines := strings.Split(input.Content, "\n")
for _, line := range lines {
fmt.Println("line")
parts := strings.Split(line, ">>>")

var items []models.NetDiskItem

// Create a new NetDiskItem
newItem := models.NetDiskItem{
Type: 2,
Type: input.DiskTypeId,
Url: parts[1],
}

// Append the new item to the slice
items = append(items, newItem)
//&models.ResourceItem{Views: 0, Title: parts[0], DiskItems: string(jsonData), CategoryId: input.CategoryId, Status: 1, CoverImg: ""}
err1 := CreateOrUpdateResourceItem(models.ResourceItem{Views: 0, Title: parts[0], DiskItems: "",
CategoryId: input.CategoryId, Status: 1, CoverImg: ""}, newItem, db)
if err1 != nil {
response.Fail(c, 500, err1.Error())
fmt.Println("操作失败:", err1)
} else {
fmt.Println("操作成功")
}

}

response.Success(c, nil)
}

func CreateOrUpdateResourceItem(input models.ResourceItem, newItem models.NetDiskItem, db *gorm.DB) error {
// 去掉 title 前后空格
trimmedTitle := strings.TrimSpace(input.Title)

// Convert the slice to JSON
// 先尝试根据 title 查找记录
var existingItem models.ResourceItem
db.Where("title = ?", trimmedTitle).First(&existingItem)
var items []models.NetDiskItem
fmt.Println(existingItem.GetUid())
if existingItem.GetUid() == "0" {
// Create a new NetDiskItem
items = append(items, newItem)
jsonData, err := json.MarshalIndent(items, "", " ")
fmt.Println(jsonData)
//if errors.Is(err, gorm.ErrRecordNotFound) {
// 如果未找到记录,则创建新记录
err = db.Create(&models.ResourceItem{
Views: 0,
Title: trimmedTitle,
DiskItems: string(jsonData),
CategoryId: input.CategoryId,
Status: 1,
CoverImg: "",
}).Error
if err != nil {
continue

return fmt.Errorf("创建记录失败: %v", err)
}
err1 := db.Create(&models.ResourceItem{Views: 0, Title: parts[0], DiskItems: string(jsonData), CategoryId: input.CategoryId, Status: 1, CoverImg: ""})
fmt.Println("创建新记录成功")
//} else {
// return fmt.Errorf("查找记录失败: %v", err)
//}
} else {
// 如果找到记录,则更新
err1 := json.Unmarshal([]byte(existingItem.DiskItems), &items)
if err1 != nil {
fmt.Println("Error decoding JSON:", err1)
return nil
}
items = append(items, newItem)
jsonData, err := json.MarshalIndent(items, "", " ")
if err != nil {
return fmt.Errorf("update时json_encode失败: %v", err)

if err1.Error != nil {
response.Fail(c, 500, err1.Error.Error())
return
}
fmt.Println(string(jsonData))
err = db.Model(&existingItem).Updates(models.ResourceItem{
Views: existingItem.Views + 1, // 示例更新逻辑
DiskItems: string(jsonData),

Status: 1,
}).Error
if err != nil {
return fmt.Errorf("更新记录失败: %v", err)
}
fmt.Println("更新记录成功")
}

response.Success(c, nil)
return nil
}

// Update handles PUT requests to update a user
Expand Down
98 changes: 90 additions & 8 deletions app/controllers/app/index.go
Original file line number Diff line number Diff line change
Expand Up @@ -118,16 +118,92 @@ func DoShare(c *gin.Context) {
response.Success(c, res)
}

func GetFavList(c *gin.Context) {
//keyword := c.DefaultQuery("keyword", "")
categoryId := c.DefaultQuery("category_id", "0")
pageSizeStr := c.DefaultQuery("pageSize", "50")

pageStr := c.DefaultQuery("page", "1")
page, err1 := strconv.Atoi(pageStr)
if err1 != nil {
page = 1
}
pageSize, err3 := strconv.Atoi(pageSizeStr)
if err3 != nil {
pageSize = 10
}
cid := 0
cid, err2 := strconv.Atoi(categoryId)
if err2 != nil {
cid = 0
}
fmt.Println(cid)
itemIDs, _ := services.AppUserService.GetFavIds(c)
fmt.Println(itemIDs)
totalCount := len(itemIDs)
// 计算分页
start := (page - 1) * pageSize
end := int(math.Min(float64(start+pageSize), float64(totalCount)))
if start >= totalCount {
var res = gin.H{
"list": []models.ResourceItem{},
"total": totalCount,
}
response.Success(c, res)
return
}

// 分页获取 itemID
pagedItemIDs := itemIDs[start:end]

// 从数据库中查询收藏的物品
var items []models.ResourceItem
if err := global.App.DB.Where("id IN ?", pagedItemIDs).Find(&items).Error; err != nil {
response.BusinessFail(c, err.Error())
return
}
var res = gin.H{
"list": items,
"total": totalCount,
}
response.Success(c, res)
return
//err, data, total := services.ResourceItemService.GetResList(page, pageSize, int32(cid), keyword)
//if err != nil {
// response.BusinessFail(c, err.Error())
// return
//}

//for i := range data {
// res := &data[i]
// tm1 := time.Unix(res.CreatedAt, 0)
// tm2 := time.Unix(res.UpdatedAt, 0)
// //res.Description = ""
// res.CreateTimeStr = tm1.Format("2006-01-02 15:04:05")
// res.UpdateTimeStr = tm2.Format("2006-01-02 15:04:05")
//}
//
//var res = gin.H{
// "list": data,
// "total": total,
//}
//response.Success(c, res)
}

func GetResList(c *gin.Context) {
keyword := c.DefaultQuery("keyword", "")
categoryId := c.DefaultQuery("category_id", "0")
pageSizeStr := c.DefaultQuery("pageSize", "50")

pageSize := 10 // Number of items per page
pageStr := c.DefaultQuery("page", "1")
page, err1 := strconv.Atoi(pageStr)
if err1 != nil {
page = 1
}
pageSize, err3 := strconv.Atoi(pageSizeStr)
if err3 != nil {
pageSize = 10
}
cid := 0
cid, err2 := strconv.Atoi(categoryId)
if err2 != nil {
Expand Down Expand Up @@ -297,7 +373,6 @@ func (bc *ResController) GetBlogDetail(c *gin.Context) {
c.String(400, "Invalid ID")
return
}
fmt.Println(intId)
err, data := services.ResourceItemService.GetResInfo(intId)
if err != nil {
response.BusinessFail(c, err.Error())
Expand All @@ -312,18 +387,25 @@ func (bc *ResController) GetBlogDetail(c *gin.Context) {
var comments []models.Comment
err1 := global.App.DB.Preload("User").Where("resource_item_id=?", intId).Order("id desc").Limit(20).Find(&comments)
if err1 != nil {
fmt.Println(err1.Error)
data.IsFavorite = false
}
global.App.DB.Model(&models.ResourceItem{}).Where("id = ?", intId).UpdateColumn("views", gorm.Expr("views + ?", 1))

data.IsFavorite, _ = services.AppUserService.IsFavorite(c, id)
tm1 := time.Unix(data.CreatedAt, 0)

data.CreateTimeStr = tm1.Format("2006-01-02 15:04:05")
//response.Success(c, gin.H{"info": data, "comments": comments})
buttonTextMap := map[int]string{
1: "百度网盘",
2: "夸克网盘",
3: "阿里网盘",
4: "移动彩云",
}
c.HTML(http.StatusOK, "detail.html", gin.H{
"Content": template.HTML(data.Description),
"blogItem": data,
"Cates": cates,
"Content": template.HTML(data.Description),
"ButtonTextMap": buttonTextMap,
"blogItem": data,
"Cates": cates,
})

c.AbortWithStatus(http.StatusNotFound)
Expand Down Expand Up @@ -434,7 +516,7 @@ func Info(c *gin.Context) {
global.App.DB.Model(&models.ResourceItem{}).Where("id = ?", intId).UpdateColumn("views", gorm.Expr("views + ?", 1))

tm1 := time.Unix(data.CreatedAt, 0)

data.IsFavorite, _ = services.AppUserService.IsFavorite(c, c.Query("id"))
data.CreateTimeStr = tm1.Format("2006-01-02 15:04:05")
response.Success(c, gin.H{"info": data, "comments": comments})
}
Expand Down
58 changes: 58 additions & 0 deletions app/controllers/app/user.go
Original file line number Diff line number Diff line change
@@ -1,8 +1,12 @@
package app

import (
"context"
"fmt"
"github.com/gin-gonic/gin"
"github.com/go-redis/redis/v8"
"github.com/golang-jwt/jwt/v4"
"github.com/jassue/jassue-gin/app/common/request"
"github.com/jassue/jassue-gin/app/common/response"
"github.com/jassue/jassue-gin/app/models"
"github.com/jassue/jassue-gin/app/services"
Expand Down Expand Up @@ -55,3 +59,57 @@ func getTokenFromHeader(c *gin.Context) string {

return splitToken[1]
}

func Fav(c *gin.Context) {
var form request.Fav
if err := c.ShouldBindJSON(&form); err != nil {
response.BusinessFail(c, "参数格式有误222")
return
}
uid := services.AppUserService.GetUserId(c)
if uid == "" {
response.BusinessFail(c, "未登录或登录过期")
return
}
res, _ := AddToFavorites(services.AppUserService.GetUserId(c), form.Id)
response.Success(c, res)
}

// 添加商品到用户收藏
func AddToFavorites(userID string, itemID int) (bool, error) {
key := fmt.Sprintf(global.App.Config.App.AppName+":user:%s:fav", userID)
ctx := context.Background()

// 检查 itemID 是否已经存在于集合中
isMember, _ := global.App.Redis.SIsMember(ctx, key, itemID).Result()

if isMember {
// 如果已存在,则移除,并返回 false(取消收藏)
err := global.App.Redis.SRem(ctx, key, itemID).Err()
if err != nil {
return false, err
}
return false, nil
} else {
// 如果不存在,则添加,并返回 true(已收藏)
err := global.App.Redis.SAdd(ctx, key, itemID).Err()
if err != nil {
return false, err
}
return true, nil
}
//key := fmt.Sprintf(global.App.Config.App.AppName+":user:%s:fav", userID)
//return global.App.Redis.SAdd(context.Background(), key, itemID).Err()
}

// 检查商品是否被用户收藏
func IsFavorite(userID, itemID string) (bool, error) {
key := fmt.Sprintf(global.App.Config.App.AppName+":user:%s:fav", userID)
return global.App.Redis.SIsMember(context.Background(), key, itemID).Result()
}

// 获取用户的所有收藏商品
func GetFavoriteItems(redisClient *redis.Client, userID string) ([]string, error) {
key := fmt.Sprintf(global.App.Config.App.AppName+":user:%s:fav", userID)
return redisClient.SMembers(context.Background(), key).Result()
}
1 change: 1 addition & 0 deletions app/models/resource_item.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ type ResourceItem struct {
CreateTimeStr string `gorm:"-" json:"create_time_str"`
UpdateTimeStr string `gorm:"-" json:"update_time_str"`
Url string `gorm:"-" json:"url"`
IsFavorite bool `gorm:"-" json:"is_favorite"`
}

func (res ResourceItem) GetUid() string {
Expand Down
Loading

0 comments on commit a7d3a1c

Please sign in to comment.