Compare commits

..

2 Commits

Author SHA1 Message Date
659548a544 Result modifiers in check-in 2024-11-27 22:03:09 +08:00
c16019341f 🚚 Rename daily-sign to check-in 2024-11-27 21:57:10 +08:00
7 changed files with 69 additions and 43 deletions

10
.idea/workspace.xml generated
View File

@ -4,8 +4,10 @@
<option name="autoReloadType" value="ALL" /> <option name="autoReloadType" value="ALL" />
</component> </component>
<component name="ChangeListManager"> <component name="ChangeListManager">
<list default="true" id="3fefb2c4-b6f9-466b-a523-53352e8d6f95" name="更改" comment=":bug: Fix group permission didn't extend properly"> <list default="true" id="3fefb2c4-b6f9-466b-a523-53352e8d6f95" name="更改" comment=":truck: Rename daily-sign to check-in">
<change beforePath="$PROJECT_DIR$/.idea/workspace.xml" beforeDir="false" afterPath="$PROJECT_DIR$/.idea/workspace.xml" afterDir="false" /> <change beforePath="$PROJECT_DIR$/.idea/workspace.xml" beforeDir="false" afterPath="$PROJECT_DIR$/.idea/workspace.xml" afterDir="false" />
<change beforePath="$PROJECT_DIR$/pkg/authkit/models/check_in.go" beforeDir="false" afterPath="$PROJECT_DIR$/pkg/authkit/models/check_in.go" afterDir="false" />
<change beforePath="$PROJECT_DIR$/pkg/internal/services/check_in.go" beforeDir="false" afterPath="$PROJECT_DIR$/pkg/internal/services/check_in.go" afterDir="false" />
</list> </list>
<option name="SHOW_DIALOG" value="false" /> <option name="SHOW_DIALOG" value="false" />
<option name="HIGHLIGHT_CONFLICTS" value="true" /> <option name="HIGHLIGHT_CONFLICTS" value="true" />
@ -158,8 +160,6 @@
</component> </component>
<component name="VcsManagerConfiguration"> <component name="VcsManagerConfiguration">
<option name="CHECK_CODE_SMELLS_BEFORE_PROJECT_COMMIT" value="false" /> <option name="CHECK_CODE_SMELLS_BEFORE_PROJECT_COMMIT" value="false" />
<MESSAGE value="Revert &quot;:recycle: Move models.Account to sec.UserInfo&quot;&#10;&#10;This reverts commit 8fbb7960" />
<MESSAGE value=":rewind: Revert &quot;:recycle: Move models.Account to sec.UserInfo&quot; for a better solution&#10;&#10;This reverts commit 8fbb7960" />
<MESSAGE value=":truck: Update package name from Hypdrogen to Hypernet" /> <MESSAGE value=":truck: Update package name from Hypdrogen to Hypernet" />
<MESSAGE value=":sparkles: Support users related rpc calls" /> <MESSAGE value=":sparkles: Support users related rpc calls" />
<MESSAGE value=":technologist: Improve DX by extending authkit" /> <MESSAGE value=":technologist: Improve DX by extending authkit" />
@ -183,7 +183,9 @@
<MESSAGE value=":bug: Fix unable get user full perm node" /> <MESSAGE value=":bug: Fix unable get user full perm node" />
<MESSAGE value=":loud_sound: Add verbose permission logging" /> <MESSAGE value=":loud_sound: Add verbose permission logging" />
<MESSAGE value=":bug: Fix group permission didn't extend properly" /> <MESSAGE value=":bug: Fix group permission didn't extend properly" />
<option name="LAST_COMMIT_MESSAGE" value=":bug: Fix group permission didn't extend properly" /> <MESSAGE value=":mute: Remove authenticate result logging" />
<MESSAGE value=":truck: Rename daily-sign to check-in" />
<option name="LAST_COMMIT_MESSAGE" value=":truck: Rename daily-sign to check-in" />
<option name="GROUP_MULTIFILE_MERGE_BY_DIRECTORY" value="true" /> <option name="GROUP_MULTIFILE_MERGE_BY_DIRECTORY" value="true" />
</component> </component>
<component name="VgoProject"> <component name="VgoProject">

View File

@ -0,0 +1,19 @@
package models
import "gorm.io/datatypes"
type CheckInRecord struct {
BaseModel
ResultTier int `json:"result_tier"`
ResultExperience int `json:"result_experience"`
// The result modifiers are some random tips that will show up in the client;
// This field is to use to make sure the tips will be the same when the client is reloaded.
// For now, this modifier slice will contain four random numbers from 0 to 1024.
// Client should mod this modifier by the length of total available tips.
ResultModifiers datatypes.JSONSlice[int] `json:"result_modifiers"`
Account Account `json:"account"`
AccountID uint `json:"account_id"`
}

View File

@ -1,10 +0,0 @@
package models
type SignRecord struct {
BaseModel
ResultTier int `json:"result_tier"`
ResultExperience int `json:"result_experience"`
Account Account `json:"account"`
AccountID uint `json:"account_id"`
}

View File

@ -25,7 +25,7 @@ var AutoMaintainRange = []any{
&models.NotificationSubscriber{}, &models.NotificationSubscriber{},
&models.AuditRecord{}, &models.AuditRecord{},
&models.ApiKey{}, &models.ApiKey{},
&models.SignRecord{}, &models.CheckInRecord{},
&models.PreferenceNotification{}, &models.PreferenceNotification{},
&models.PreferenceAuth{}, &models.PreferenceAuth{},
&models.AbuseReport{}, &models.AbuseReport{},

View File

@ -9,7 +9,7 @@ import (
"strconv" "strconv"
) )
func listDailySignRecord(c *fiber.Ctx) error { func listCheckInRecord(c *fiber.Ctx) error {
take := c.QueryInt("take", 0) take := c.QueryInt("take", 0)
offset := c.QueryInt("offset", 0) offset := c.QueryInt("offset", 0)
@ -20,13 +20,13 @@ func listDailySignRecord(c *fiber.Ctx) error {
var count int64 var count int64
if err := database.C. if err := database.C.
Model(&models.SignRecord{}). Model(&models.CheckInRecord{}).
Where("account_id = ?", user.ID). Where("account_id = ?", user.ID).
Count(&count).Error; err != nil { Count(&count).Error; err != nil {
return fiber.NewError(fiber.StatusInternalServerError, err.Error()) return fiber.NewError(fiber.StatusInternalServerError, err.Error())
} }
var records []models.SignRecord var records []models.CheckInRecord
if err := database.C. if err := database.C.
Where("account_id = ?", user.ID). Where("account_id = ?", user.ID).
Limit(take).Offset(offset). Limit(take).Offset(offset).
@ -41,7 +41,7 @@ func listDailySignRecord(c *fiber.Ctx) error {
}) })
} }
func listOtherUserDailySignRecord(c *fiber.Ctx) error { func listOtherUserCheckInRecord(c *fiber.Ctx) error {
take := c.QueryInt("take", 0) take := c.QueryInt("take", 0)
offset := c.QueryInt("offset", 0) offset := c.QueryInt("offset", 0)
@ -56,13 +56,13 @@ func listOtherUserDailySignRecord(c *fiber.Ctx) error {
var count int64 var count int64
if err := database.C. if err := database.C.
Model(&models.SignRecord{}). Model(&models.CheckInRecord{}).
Where("account_id = ?", account.ID). Where("account_id = ?", account.ID).
Count(&count).Error; err != nil { Count(&count).Error; err != nil {
return fiber.NewError(fiber.StatusInternalServerError, err.Error()) return fiber.NewError(fiber.StatusInternalServerError, err.Error())
} }
var records []models.SignRecord var records []models.CheckInRecord
if err := database.C. if err := database.C.
Where("account_id = ?", account.ID). Where("account_id = ?", account.ID).
Limit(take).Offset(offset). Limit(take).Offset(offset).
@ -77,26 +77,26 @@ func listOtherUserDailySignRecord(c *fiber.Ctx) error {
}) })
} }
func getTodayDailySign(c *fiber.Ctx) error { func getTodayCheckIn(c *fiber.Ctx) error {
if err := exts.EnsureAuthenticated(c); err != nil { if err := exts.EnsureAuthenticated(c); err != nil {
return err return err
} }
user := c.Locals("user").(models.Account) user := c.Locals("user").(models.Account)
if record, err := services.GetTodayDailySign(user); err != nil { if record, err := services.GetTodayCheckIn(user); err != nil {
return fiber.NewError(fiber.StatusNotFound, err.Error()) return fiber.NewError(fiber.StatusNotFound, err.Error())
} else { } else {
return c.JSON(record) return c.JSON(record)
} }
} }
func doDailySign(c *fiber.Ctx) error { func doCheckIn(c *fiber.Ctx) error {
if err := exts.EnsureAuthenticated(c); err != nil { if err := exts.EnsureAuthenticated(c); err != nil {
return err return err
} }
user := c.Locals("user").(models.Account) user := c.Locals("user").(models.Account)
if record, err := services.DailySign(user); err != nil { if record, err := services.CheckIn(user); err != nil {
return fiber.NewError(fiber.StatusBadRequest, err.Error()) return fiber.NewError(fiber.StatusBadRequest, err.Error())
} else { } else {
services.AddEvent(user.ID, "dailySign", strconv.Itoa(int(record.ID)), c.IP(), c.Get(fiber.HeaderUserAgent)) services.AddEvent(user.ID, "dailySign", strconv.Itoa(int(record.ID)), c.IP(), c.Get(fiber.HeaderUserAgent))

View File

@ -10,11 +10,11 @@ func MapAPIs(app *fiber.App, baseURL string) {
api := app.Group(baseURL).Name("API") api := app.Group(baseURL).Name("API")
{ {
daily := api.Group("/daily").Name("Daily Sign API") checkIn := api.Group("/check-in").Name("Daily Check In API")
{ {
daily.Get("/", listDailySignRecord) checkIn.Get("/", listCheckInRecord)
daily.Get("/today", getTodayDailySign) checkIn.Get("/today", getTodayCheckIn)
daily.Post("/", doDailySign) checkIn.Post("/", doCheckIn)
} }
notify := api.Group("/notifications").Name("Notifications API") notify := api.Group("/notifications").Name("Notifications API")
@ -97,7 +97,7 @@ func MapAPIs(app *fiber.App, baseURL string) {
directory.Get("/", getOtherUserinfo) directory.Get("/", getOtherUserinfo)
directory.Get("/status", getStatus) directory.Get("/status", getStatus)
directory.Get("/daily", listOtherUserDailySignRecord) directory.Get("/check-in", listOtherUserCheckInRecord)
} }
api.Get("/users", getOtherUserinfoBatch) api.Get("/users", getOtherUserinfoBatch)

View File

@ -11,52 +11,67 @@ import (
"time" "time"
) )
func CheckDailyCanSign(user models.Account) error { func CheckCanCheckIn(user models.Account) error {
probe := time.Now().Format("2006-01-02") probe := time.Now().Format("2006-01-02")
var record models.SignRecord var record models.CheckInRecord
if err := database.C.Where("account_id = ? AND created_at::date = ?", user.ID, probe).First(&record).Error; err != nil { if err := database.C.Where("account_id = ? AND created_at::date = ?", user.ID, probe).First(&record).Error; err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) { if errors.Is(err, gorm.ErrRecordNotFound) {
return nil return nil
} }
return fmt.Errorf("unable check daliy sign record: %v", err) return fmt.Errorf("unable get check in record: %v", err)
} }
return fmt.Errorf("daliy sign record exists") return fmt.Errorf("today's check in record exists")
} }
func GetTodayDailySign(user models.Account) (models.SignRecord, error) { func GetTodayCheckIn(user models.Account) (models.CheckInRecord, error) {
probe := time.Now().Format("2006-01-02") probe := time.Now().Format("2006-01-02")
var record models.SignRecord var record models.CheckInRecord
if err := database.C.Where("account_id = ? AND created_at::date = ?", user.ID, probe).First(&record).Error; err != nil { if err := database.C.Where("account_id = ? AND created_at::date = ?", user.ID, probe).First(&record).Error; err != nil {
return record, fmt.Errorf("unable get daliy sign record: %v", err) return record, fmt.Errorf("unable get check in record: %v", err)
} }
return record, nil return record, nil
} }
func DailySign(user models.Account) (models.SignRecord, error) { const CheckInResultModifiersLength = 4
func CheckIn(user models.Account) (models.CheckInRecord, error) {
tier := rand.Intn(5) tier := rand.Intn(5)
record := models.SignRecord{ record := models.CheckInRecord{
ResultTier: tier, ResultTier: tier,
ResultExperience: rand.Intn(int(math.Max(float64(tier), 1)*100)+1-100) + 100, ResultExperience: rand.Intn(int(math.Max(float64(tier), 1)*100)+1-100) + 100,
AccountID: user.ID, AccountID: user.ID,
} }
if err := CheckDailyCanSign(user); err != nil { modifiers := make([]int, CheckInResultModifiersLength)
for i := 0; i < CheckInResultModifiersLength; i++ {
modifiers[i] = rand.Intn(1025) // from 0 to 1024 as the comment said
}
record.ResultModifiers = modifiers
if err := CheckCanCheckIn(user); err != nil {
return record, fmt.Errorf("today already signed") return record, fmt.Errorf("today already signed")
} }
tx := database.C.Begin()
var profile models.AccountProfile var profile models.AccountProfile
if err := database.C.Where("account_id = ?", user.ID).First(&profile).Error; err != nil { if err := database.C.Where("account_id = ?", user.ID).First(&profile).Error; err != nil {
return record, fmt.Errorf("unable get account profile: %v", err) return record, fmt.Errorf("unable get account profile: %v", err)
} else { } else {
profile.Experience += uint64(record.ResultExperience) profile.Experience += uint64(record.ResultExperience)
database.C.Save(&profile) if err := tx.Save(&profile).Error; err != nil {
tx.Rollback()
return record, fmt.Errorf("unable update account profile: %v", err)
}
} }
if err := database.C.Save(&record).Error; err != nil { if err := tx.Save(&record).Error; err != nil {
return record, fmt.Errorf("unable do daliy sign: %v", err) return record, fmt.Errorf("unable do check in: %v", err)
} }
tx.Commit()
return record, nil return record, nil
} }