-
Notifications
You must be signed in to change notification settings - Fork 13
/
Copy pathdbo.go
145 lines (121 loc) · 2.46 KB
/
dbo.go
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
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
package main
import (
"log"
"os"
"time"
"github.com/jinzhu/gorm"
_ "github.com/jinzhu/gorm/dialects/sqlite"
)
type (
channel struct {
gorm.Model
DiscordID string
Active bool
}
broadcastStamp struct {
BroadcastDate string
}
)
var db *gorm.DB
func initDb() {
err := touchFile("data.db")
if err != nil {
log.Panic(err)
}
db, err = gorm.Open("sqlite3", "data.db")
if err != nil {
log.Panic(err)
}
db.AutoMigrate(channel{})
db.AutoMigrate(broadcastStamp{})
}
func getSubs() (*[]channel, error) {
chList := []channel{}
err := db.Where(&channel{Active: true}).Find(&chList).Error
if err != nil {
return nil, err
}
return &chList, nil
}
func subscribe(channelID string) (bool, error) {
ch := channel{}
err := db.Where(channel{DiscordID: channelID}).First(&ch).Error
if err != nil && err != gorm.ErrRecordNotFound {
return false, err
}
if ch.ID == 0 {
ch = channel{
DiscordID: channelID,
Active: true,
}
err = db.Create(&ch).Error
if err != nil {
return false, err
}
return true, nil
}
if ch.Active {
return false, nil
}
ch.Active = true
err = db.Save(&ch).Error
if err != nil {
return false, err
}
return true, nil
}
func unsubscribe(channelID string) (bool, error) {
ch := channel{}
err := db.Where(channel{DiscordID: channelID}).First(&ch).Error
if err != nil {
return false, err
}
if ch.ID == 0 || !ch.Active {
return false, nil
}
ch.Active = false
err = db.Save(&ch).Error
if err != nil {
return false, err
}
return true, nil
}
func ubsubscribeBulk(chs []string) error {
err := db.Table("channels").Where("discord_id in (?)", chs).Updates(map[string]interface{}{"active": false}).Error
return err
}
func touchFile(name string) error {
file, err := os.OpenFile(name, os.O_RDONLY|os.O_CREATE, 0644)
if err != nil {
return err
}
file.Close()
return nil
}
func getTodayBroadcastStatus() (bool, error) {
now := time.Now()
now = time.Date(now.Year(), now.Month(), now.Day(), 0, 0, 0, 0, loc)
str := now.Format(time.RFC3339)
c := 0
err := db.Model(broadcastStamp{}).Where(&broadcastStamp{BroadcastDate: str}).Count(&c).Error
if err != nil {
return true, err
}
if c == 0 {
return false, nil
}
return true, nil
}
func stampBroadcastDate() error {
now := time.Now()
now = time.Date(now.Year(), now.Month(), now.Day(), 0, 0, 0, 0, loc)
str := now.Format(time.RFC3339)
b := broadcastStamp{
BroadcastDate: str,
}
err := db.Save(&b).Error
if err != nil {
return err
}
return nil
}