aboutsummaryrefslogtreecommitdiff
path: root/user/member.go
blob: 91327ad1ab6cf11ccd8a290d989d38e7a65f0345 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
package user

import (
	"fmt"
	"github.com/anhgelus/gokord"
	"github.com/anhgelus/gokord/utils"
	"gorm.io/gorm"
)

type Copaing struct {
	gorm.Model
	DiscordID string `gorm:"not null"`
	//XP        []CopaingXP
	XP      uint   `gorm:"default:0"`
	GuildID string `gorm:"not null"`
}

type leftCopaing struct {
	ID         uint
	StopDelete chan<- interface{}
}

//type CopaingXP struct {
//	gorm.Model
//	XP        uint `gorm:"default:0"`
//	CopaingID uint
//}

var (
	leftCopaingsMap = map[string]*leftCopaing{}
)

const (
	LastEvent      = "last_event"
	AlreadyRemoved = "already_removed"
)

func GetCopaing(discordID string, guildID string) *Copaing {
	c := Copaing{DiscordID: discordID, GuildID: guildID}
	if err := c.Load(); err != nil {
		utils.SendAlert(
			"user/member.go - Loading user",
			err.Error(),
			"discord_id",
			discordID,
			"guild_id",
			guildID,
		)
		return nil
	}
	return &c
}

func (c *Copaing) Load() error {
	// check if user left in the past 48 hours
	k := c.GuildID + ":" + c.DiscordID
	l, ok := leftCopaingsMap[k]
	if !ok || l == nil {
		// if not, common first or create
		return gokord.DB.Where("discord_id = ? and guild_id = ?", c.DiscordID, c.GuildID).FirstOrCreate(c).Error
	}
	// else, getting last data
	tmp := Copaing{
		Model: gorm.Model{
			ID: c.ID,
		},
		DiscordID: c.DiscordID,
		GuildID:   c.GuildID,
	}
	if err := gokord.DB.Unscoped().Find(&tmp).Error; err != nil {
		// if error, avoid getting old data and use new one
		utils.SendAlert(
			"user/member.go - Getting user in soft delete", err.Error(),
			"discord_id", c.DiscordID,
			"guild_id", c.DiscordID,
			"last_id", l.ID,
		)
		return gokord.DB.Where("discord_id = ? and guild_id = ?", c.DiscordID, c.GuildID).FirstOrCreate(c).Error
	}
	// resetting internal data
	tmp.Model = gorm.Model{}
	l.StopDelete <- true
	leftCopaingsMap[k] = nil
	// creating new data
	err := gokord.DB.Create(&tmp).Error
	if err != nil {
		return err
	}
	// delete old data
	if err = gokord.DB.Unscoped().Delete(&tmp).Error; err != nil {
		utils.SendAlert(
			"user/member.go - Deleting user in soft delete", err.Error(),
			"discord_id", c.DiscordID,
			"guild_id", c.DiscordID,
			"last_id", l.ID,
		)
	}
	return nil
}

func (c *Copaing) Save() error {
	return gokord.DB.Save(c).Error
}

func (c *Copaing) GenKey(key string) string {
	return fmt.Sprintf("%s:%s:%s", c.GuildID, c.DiscordID, key)
}