Passed
Push — master ( 7f7da9...d308f4 )
by Viktor
01:34
created

bot.*DBWorker.UpdateAlbionPlayerLast   A

Complexity

Conditions 2

Size

Total Lines 7
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 7
nop 2
dl 0
loc 7
rs 10
c 0
b 0
f 0
1
package bot
2
3
import (
4
	"fmt"
5
	"github.com/bwmarrin/discordgo"
6
	"github.com/globalsign/mgo"
7
	"github.com/globalsign/mgo/bson"
8
	"os"
9
	"time"
10
)
11
12
// DBWorker MongoDB instance
13
type DBWorker struct {
14
	DBSession *mgo.Session
15
	DBName    string
16
}
17
18
type dbLog struct {
19
	Date   time.Time
20
	Text   string
21
	Module string
22
	Guild  string
23
}
24
25
// GuildData contains data about guild settings
26
type GuildData struct {
27
	ID          string
28
	WeatherCity string
29
	NewsCounty  string
30
	Language    string
31
	Timezone    int
32
	EmbedColor  int
33
	VoiceVolume float32
34
	Greeting    string
35
}
36
37
// GuildsMap contains guilds settings
38
type GuildsMap struct {
39
	Guilds map[string]*GuildData
40
}
41
42
// RadioStation contains info about radio station
43
type RadioStation struct {
44
	Name     string
45
	URL      string
46
	Key      string
47
	Category string
48
}
49
50
// NewDBSession creates new MongoDB instance
51
func NewDBSession(dbname string) *DBWorker {
52
	session, err := mgo.Dial(os.Getenv("MONGO_CONN"))
53
	if err != nil {
54
		fmt.Printf("Mongo connection error: %v", err)
55
	}
56
	count, err := session.DB("dtbot").C("logs").Count()
57
	if err != nil {
58
		fmt.Println("DB_ERR: ", err)
59
	}
60
	fmt.Printf("Mongo connected\nLogs in base: %v\n", count)
61
	return &DBWorker{DBSession: session, DBName: dbname}
62
}
63
64
// InitGuilds initialize guilds in database
65
func (db *DBWorker) InitGuilds(sess *discordgo.Session, conf *Config) *GuildsMap {
66
	var data = &GuildsMap{Guilds: make(map[string]*GuildData)}
67
	var loaded, initialized = 0, 0
68
	for _, guild := range sess.State.Guilds {
69
		count, err := db.DBSession.DB(db.DBName).C("guilds").Find(bson.M{"id": guild.ID}).Count()
70
		if err != nil {
71
			fmt.Println("Mongo: ", err)
72
		}
73
		if count == 0 {
74
			newData := &GuildData{
75
				ID:          guild.ID,
76
				WeatherCity: conf.Weather.City,
77
				NewsCounty:  conf.News.Country,
78
				Language:    conf.General.Language,
79
				Timezone:    conf.General.Timezone,
80
				EmbedColor:  conf.General.EmbedColor,
81
				VoiceVolume: conf.Voice.Volume,
82
				Greeting:    "",
83
			}
84
			_ = db.DBSession.DB(db.DBName).C("guilds").Insert(newData)
85
			data.Guilds[guild.ID] = newData
86
			initialized++
87
		} else {
88
			var newData = &GuildData{}
89
			_ = db.DBSession.DB(db.DBName).C("guilds").Find(bson.M{"id": guild.ID}).One(newData)
90
			if err != nil {
91
				fmt.Println("Mongo: ", err)
92
				continue
93
			}
94
			data.Guilds[guild.ID] = newData
95
			loaded++
96
		}
97
	}
98
	fmt.Printf("Guilds loaded [%v], initialized [%v]\n", loaded, initialized)
99
	return data
100
}
101
102
// InitNewGuild creates new guild in database
103
func (db *DBWorker) InitNewGuild(guildID string, conf *Config, data *GuildsMap) {
104
	newData := &GuildData{
105
		ID:          guildID,
106
		WeatherCity: conf.Weather.City,
107
		NewsCounty:  conf.News.Country,
108
		Language:    conf.General.Language,
109
		Timezone:    conf.General.Timezone,
110
		EmbedColor:  conf.General.EmbedColor,
111
		VoiceVolume: conf.Voice.Volume,
112
		Greeting:    "",
113
	}
114
	_ = db.DBSession.DB(db.DBName).C("guilds").Insert(newData)
115
	data.Guilds[guildID] = newData
116
}
117
118
// Log saves log in database
119
func (db *DBWorker) Log(module, guildID, text string) {
120
	_ = db.DBSession.DB(db.DBName).C("logs").Insert(dbLog{Date: time.Now(), Text: text, Module: module, Guild: guildID})
121
}
122
123
// LogGet returns last N log rows
124
func (db *DBWorker) LogGet(count int) []dbLog {
0 ignored issues
show
introduced by
exported method LogGet returns unexported type []bot.dbLog, which can be annoying to use
Loading history...
125
	var log = make([]dbLog, count)
126
	_ = db.DBSession.DB(db.DBName).C("logs").Find(nil).Sort("-$natural").Limit(count).All(&log)
127
	return log
128
}
129
130
// Guilds returns guilds collection from mongodb
131
func (db *DBWorker) Guilds() *mgo.Collection {
132
	return db.DBSession.DB(db.DBName).C("guilds")
133
}
134
135
// GetTwitchStreams returns twitch streams from mongodb
136
func (db *DBWorker) GetTwitchStreams(guildID string) map[string]*TwitchStream {
137
	streams := []TwitchStream{}
138
	err := db.DBSession.DB(db.DBName).C("streams").Find(bson.M{"guild": guildID}).All(&streams)
139
	if err != nil {
140
		fmt.Println("Mongo: ", err)
141
	}
142
	var newMap = make(map[string]*TwitchStream)
143
	for i, s := range streams {
144
		newMap[s.Login] = &streams[i]
145
	}
146
	return newMap
147
}
148
149
// UpdateStream updates stream in mongodb
150
func (db *DBWorker) UpdateStream(stream *TwitchStream) {
151
	err := db.DBSession.DB(db.DBName).C("streams").
152
		Update(
153
			bson.M{"guild": stream.Guild, "login": stream.Login},
154
			bson.M{"$set": bson.M{"isonline": stream.IsOnline}})
155
	if err != nil {
156
		fmt.Println(err.Error())
157
	}
158
}
159
160
// AddStream adds stream in mongodb
161
func (db *DBWorker) AddStream(stream *TwitchStream) {
162
	_ = db.DBSession.DB(db.DBName).C("streams").Insert(stream)
163
}
164
165
// RemoveStream removes stream from mongodb
166
func (db *DBWorker) RemoveStream(stream *TwitchStream) {
167
	_ = db.DBSession.DB(db.DBName).C("streams").Remove(bson.M{"login": stream.Login, "guild": stream.Guild})
168
}
169
170
// GetRadioStations gets stations from database and returns slice of them
171
func (db *DBWorker) GetRadioStations(category string) []RadioStation {
172
	stations := []RadioStation{}
173
	var request = bson.M{}
174
	if category != "" {
175
		request = bson.M{"category": category}
176
	}
177
	err := db.DBSession.DB(db.DBName).C("stations").Find(request).All(&stations)
178
	if err != nil {
179
		fmt.Println("Mongo: ", err)
180
	}
181
	return stations
182
}
183
184
// GetRadioStationByKey returns one station by key
185
func (db *DBWorker) GetRadioStationByKey(key string) (*RadioStation, error) {
186
	station := RadioStation{}
187
	err := db.DBSession.DB(db.DBName).C("stations").Find(bson.M{"key": key}).One(&station)
188
	if err != nil {
189
		fmt.Println("Mongo: ", err)
190
		return nil, fmt.Errorf("station not found")
191
	}
192
	return &station, nil
193
}
194
195
// RemoveRadioStation removes radio station by key
196
func (db *DBWorker) RemoveRadioStation(key string) error {
197
	err := db.DBSession.DB(db.DBName).C("stations").Remove(bson.M{"key": key})
198
	return err
199
}
200
201
// AddRadioStation adds new radio station
202
func (db *DBWorker) AddRadioStation(name, url, key, category string) error {
203
	station := RadioStation{Name: name, URL: url, Key: key, Category: category}
204
	err := db.DBSession.DB(db.DBName).C("stations").Insert(&station)
205
	return err
206
}
207
208
func (db *DBWorker) GetAlbionPlayers() []AlbionPlayerUpdater {
0 ignored issues
show
introduced by
exported method DBWorker.GetAlbionPlayers should have comment or be unexported
Loading history...
209
	var kills []AlbionPlayerUpdater
210
	_ = db.DBSession.DB(db.DBName).C("albion").Find(nil).All(&kills)
211
	return kills
212
}
213
214
func (db *DBWorker) AddAlbionPlayer(player *AlbionPlayerUpdater) {
0 ignored issues
show
introduced by
exported method DBWorker.AddAlbionPlayer should have comment or be unexported
Loading history...
215
	err := db.DBSession.DB(db.DBName).C("albion").Insert(&player)
216
	if err != nil {
217
		fmt.Println("Error adding Albion player: ", err.Error())
218
	}
219
}
220
221
func (db *DBWorker) RemoveAlbionPlayer(id string) {
0 ignored issues
show
introduced by
exported method DBWorker.RemoveAlbionPlayer should have comment or be unexported
Loading history...
222
	err := db.DBSession.DB(db.DBName).C("albion").Remove(bson.M{"userid": id})
223
	if err != nil {
224
		fmt.Println("Error removing Albion player: ", err.Error())
225
	}
226
}
227
228
func (db *DBWorker) UpdateAlbionPlayerLast(userID string, lastKill int64) {
0 ignored issues
show
introduced by
exported method DBWorker.UpdateAlbionPlayerLast should have comment or be unexported
Loading history...
229
	err := db.DBSession.DB(db.DBName).C("albion").
230
		Update(
231
			bson.M{"userid": userID},
232
			bson.M{"$set": bson.M{"lastkill": lastKill}})
233
	if err != nil {
234
		fmt.Println(err.Error())
235
	}
236
}
237