Passed
Push — master ( ef97f9...04ca3a )
by Viktor
02:41
created

bot.*DBWorker.GetNewsCountry   A

Complexity

Conditions 2

Size

Total Lines 7
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 6
nop 1
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
	"log"
9
	"os"
10
	"time"
11
)
12
13
// DBWorker MongoDB instance
14
type DBWorker struct {
15
	DBSession *mgo.Session
16
	DBName    string
17
}
18
19
type dbLog struct {
20
	Date   time.Time
21
	Text   string
22
	Module string
23
	Guild  string
24
}
25
26
// GuildData contains data about guild settings
27
type GuildData struct {
28
	ID          string
29
	WeatherCity string
30
	NewsCounty  string
31
	Language    string
32
	Timezone    int
33
	EmbedColor  int
34
	VoiceVolume float32
35
	Greeting    string
36
}
37
38
// GuildsMap contains guilds settings
39
type GuildsMap struct {
40
	Guilds map[string]*GuildData
41
}
42
43
// RadioStation contains info about radio station
44
type RadioStation struct {
45
	Name     string
46
	URL      string
47
	Key      string
48
	Category string
49
}
50
51
type TwitchDBConfig struct {
0 ignored issues
show
introduced by
exported type TwitchDBConfig should have comment or be unexported
Loading history...
52
	Type   string
53
	Token  string
54
	Expire time.Time
55
}
56
57
type BlackListElement struct {
0 ignored issues
show
introduced by
exported type BlackListElement should have comment or be unexported
Loading history...
58
	ID string
59
}
60
61
// NewDBSession creates new MongoDB instance
62
func NewDBSession(dbname string) *DBWorker {
63
	session, err := mgo.Dial(os.Getenv("MONGO_CONN"))
64
	if err != nil {
65
		log.Printf("[Mongo] Mongo connection error: %v", err)
66
	}
67
	count, err := session.DB("dtbot").C("logs").Count()
68
	if err != nil {
69
		log.Printf("[Mongo] DB_ERR: ", err)
0 ignored issues
show
introduced by
no formatting directive in Printf call
Loading history...
70
	}
71
	log.Printf("[Mongo] connected\nLogs in base: %v\n", count)
72
	return &DBWorker{DBSession: session, DBName: dbname}
73
}
74
75
// InitGuilds initialize guilds in database
76
func (db *DBWorker) InitGuilds(sess *discordgo.Session, conf *Config) *GuildsMap {
77
	var data = &GuildsMap{Guilds: make(map[string]*GuildData)}
78
	var loaded, initialized = 0, 0
79
	for _, guild := range sess.State.Guilds {
80
		count, err := db.DBSession.DB(db.DBName).C("guilds").Find(bson.M{"id": guild.ID}).Count()
81
		if err != nil {
82
			log.Printf("[Mongo] guilds, DB: %s, Guild: %s, Error: %v\n", db.DBName, guild.ID, err)
83
		}
84
		if count == 0 {
85
			newData := &GuildData{
86
				ID:          guild.ID,
87
				WeatherCity: conf.Weather.City,
88
				NewsCounty:  conf.News.Country,
89
				Language:    conf.General.Language,
90
				Timezone:    conf.General.Timezone,
91
				EmbedColor:  conf.General.EmbedColor,
92
				VoiceVolume: conf.Voice.Volume,
93
				Greeting:    "",
94
			}
95
			_ = db.DBSession.DB(db.DBName).C("guilds").Insert(newData)
96
			data.Guilds[guild.ID] = newData
97
			initialized++
98
		} else {
99
			var newData = &GuildData{}
100
			_ = db.DBSession.DB(db.DBName).C("guilds").Find(bson.M{"id": guild.ID}).One(newData)
101
			if err != nil {
102
				log.Printf("[Mongo] guilds, DB: %s, Guild: %s, Error: %v\n", db.DBName, guild.ID, err)
103
				continue
104
			}
105
			data.Guilds[guild.ID] = newData
106
			loaded++
107
		}
108
	}
109
	log.Printf("[Mongo] Guilds loaded [%v], initialized [%v]\n", loaded, initialized)
110
	return data
111
}
112
113
// InitNewGuild creates new guild in database
114
func (db *DBWorker) InitNewGuild(guildID string, conf *Config, data *GuildsMap) {
115
	newData := &GuildData{
116
		ID:          guildID,
117
		WeatherCity: conf.Weather.City,
118
		NewsCounty:  conf.News.Country,
119
		Language:    conf.General.Language,
120
		Timezone:    conf.General.Timezone,
121
		EmbedColor:  conf.General.EmbedColor,
122
		VoiceVolume: conf.Voice.Volume,
123
		Greeting:    "",
124
	}
125
	_ = db.DBSession.DB(db.DBName).C("guilds").Insert(newData)
126
	data.Guilds[guildID] = newData
127
}
128
129
// Log saves log in database
130
func (db *DBWorker) Log(module, guildID, text string) {
131
	_ = db.DBSession.DB(db.DBName).C("logs").Insert(dbLog{Date: time.Now(), Text: text, Module: module, Guild: guildID})
132
}
133
134
// LogGet returns last N log rows
135
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...
136
	var log = make([]dbLog, count)
137
	_ = db.DBSession.DB(db.DBName).C("logs").Find(nil).Sort("-$natural").Limit(count).All(&log)
138
	return log
139
}
140
141
// Guilds returns guilds collection from mongodb
142
func (db *DBWorker) Guilds() *mgo.Collection {
143
	return db.DBSession.DB(db.DBName).C("guilds")
144
}
145
146
func (db *DBWorker) GetTwitchToken() *TwitchDBConfig {
0 ignored issues
show
introduced by
exported method DBWorker.GetTwitchToken should have comment or be unexported
Loading history...
147
	var token TwitchDBConfig
148
	err := db.DBSession.DB(db.DBName).C("config").Find(bson.M{"type": "twitch"}).One(&token)
149
	if err != nil {
150
		return &token
151
	}
152
	return &token
153
}
154
155
func (db *DBWorker) UpdateTwitchToken(token string, expire time.Time) {
0 ignored issues
show
introduced by
exported method DBWorker.UpdateTwitchToken should have comment or be unexported
Loading history...
156
	err := db.DBSession.DB(db.DBName).C("config").Update(bson.M{"type": "twitch"}, bson.M{"$set": bson.M{"token": token, "expire": expire}})
157
	if err != nil {
158
		log.Println("[Mongo] Update twitch token error: ", err)
159
		err = db.DBSession.DB(db.DBName).C("config").Insert(TwitchDBConfig{
160
			Type:   "twitch",
161
			Token:  token,
162
			Expire: expire,
163
		})
164
		if err != nil {
165
			log.Println("[Mongo] Update twitch token error: ", err)
166
		}
167
	}
168
}
169
170
// GetTwitchStreams returns twitch streams from mongodb
171
func (db *DBWorker) GetTwitchStreams(guildID string) map[string]*TwitchStream {
172
	streams := []TwitchStream{}
173
	err := db.DBSession.DB(db.DBName).C("streams").Find(bson.M{"guild": guildID}).All(&streams)
174
	if err != nil {
175
		log.Printf("[Mongo] streams, streams DB: %s, Guild: %s, Error: %v\n", db.DBName, guildID, err)
176
	}
177
	var newMap = make(map[string]*TwitchStream)
178
	for i, s := range streams {
179
		newMap[s.Login] = &streams[i]
180
	}
181
	return newMap
182
}
183
184
// UpdateStream updates stream in mongodb
185
func (db *DBWorker) UpdateStream(stream *TwitchStream) {
186
	err := db.DBSession.DB(db.DBName).C("streams").
187
		Update(
188
			bson.M{"guild": stream.Guild, "login": stream.Login},
189
			bson.M{"$set": bson.M{"isonline": stream.IsOnline}})
190
	if err != nil {
191
		log.Println("[Mongo] ", err)
192
	}
193
}
194
195
// AddStream adds stream in mongodb
196
func (db *DBWorker) AddStream(stream *TwitchStream) {
197
	_ = db.DBSession.DB(db.DBName).C("streams").Insert(stream)
198
}
199
200
// RemoveStream removes stream from mongodb
201
func (db *DBWorker) RemoveStream(stream *TwitchStream) {
202
	_ = db.DBSession.DB(db.DBName).C("streams").Remove(bson.M{"login": stream.Login, "guild": stream.Guild})
203
}
204
205
// GetRadioStations gets stations from database and returns slice of them
206
func (db *DBWorker) GetRadioStations(category string) []RadioStation {
207
	stations := []RadioStation{}
208
	var request = bson.M{}
209
	if category != "" {
210
		request = bson.M{"category": category}
211
	}
212
	err := db.DBSession.DB(db.DBName).C("stations").Find(request).All(&stations)
213
	if err != nil {
214
		log.Printf("[Mongo] stations, DB: %s, Error: %v\n", db.DBName, err)
215
216
	}
217
	return stations
218
}
219
220
// GetRadioStationByKey returns one station by key
221
func (db *DBWorker) GetRadioStationByKey(key string) (*RadioStation, error) {
222
	station := RadioStation{}
223
	err := db.DBSession.DB(db.DBName).C("stations").Find(bson.M{"key": key}).One(&station)
224
	if err != nil {
225
		log.Printf("[Mongo] stations, DB: %s, Key: %s, Error: %v\n", db.DBName, key, err)
226
		return nil, fmt.Errorf("station not found")
227
	}
228
	return &station, nil
229
}
230
231
// RemoveRadioStation removes radio station by key
232
func (db *DBWorker) RemoveRadioStation(key string) error {
233
	err := db.DBSession.DB(db.DBName).C("stations").Remove(bson.M{"key": key})
234
	return err
235
}
236
237
// AddRadioStation adds new radio station
238
func (db *DBWorker) AddRadioStation(name, url, key, category string) error {
239
	station := RadioStation{Name: name, URL: url, Key: key, Category: category}
240
	err := db.DBSession.DB(db.DBName).C("stations").Insert(&station)
241
	return err
242
}
243
244
// GetAlbionPlayers gets players from database
245
func (db *DBWorker) GetAlbionPlayers() []AlbionPlayerUpdater {
246
	var players []AlbionPlayerUpdater
247
	_ = db.DBSession.DB(db.DBName).C("albion").Find(nil).All(&players)
248
	fmt.Println(len(players))
249
	return players
250
}
251
252
// AddAlbionPlayer adds new player in database
253
func (db *DBWorker) AddAlbionPlayer(player *AlbionPlayerUpdater) {
254
	err := db.DBSession.DB(db.DBName).C("albion").Insert(player)
255
	if err != nil {
256
		log.Printf("[Mongo] Error adding Albion player: ", err.Error())
0 ignored issues
show
introduced by
no formatting directive in Printf call
Loading history...
257
	}
258
}
259
260
// RemoveAlbionPlayer removes player from database
261
func (db *DBWorker) RemoveAlbionPlayer(id string) {
262
	err := db.DBSession.DB(db.DBName).C("albion").Remove(bson.M{"userid": id})
263
	if err != nil {
264
		log.Printf("[Mongo] Error removing Albion player: ", err.Error())
0 ignored issues
show
introduced by
no formatting directive in Printf call
Loading history...
265
	}
266
}
267
268
// UpdateAlbionPlayerLast updates last kill of albion player
269
func (db *DBWorker) UpdateAlbionPlayerLast(userID string, lastKill int64) {
270
	err := db.DBSession.DB(db.DBName).C("albion").
271
		Update(
272
			bson.M{"userid": userID},
273
			bson.M{"$set": bson.M{"lastkill": lastKill}})
274
	if err != nil {
275
		log.Printf("[Mongo] ", err)
0 ignored issues
show
introduced by
no formatting directive in Printf call
Loading history...
276
	}
277
}
278
279
// GetBlackList gets blacklist from database
0 ignored issues
show
introduced by
comment on exported method DBWorker.GetBlacklist should be of the form "GetBlacklist ..."
Loading history...
280
func (db *DBWorker) GetBlacklist() *BlackListStruct {
281
	var (
282
		blacklist BlackListStruct
283
		Guilds    []BlackListElement
284
		Users     []BlackListElement
285
	)
286
	_ = db.DBSession.DB(db.DBName).C("blusers").Find(nil).All(&Users)
287
	_ = db.DBSession.DB(db.DBName).C("blguilds").Find(nil).All(&Guilds)
288
289
	for _, g := range Guilds {
290
		blacklist.Guilds = append(blacklist.Guilds, g.ID)
291
	}
292
	for _, u := range Users {
293
		blacklist.Users = append(blacklist.Users, u.ID)
294
	}
295
296
	return &blacklist
297
}
298
299
// AddBlacklistGuild adds guild in database blacklist
300
func (db *DBWorker) AddBlacklistGuild(id string) {
301
	err := db.DBSession.DB(db.DBName).C("blguilds").Insert(BlackListElement{ID: id})
302
	if err != nil {
303
		log.Printf("[Mongo] Error adding guild in blacklist: ", err.Error())
0 ignored issues
show
introduced by
no formatting directive in Printf call
Loading history...
304
	}
305
}
306
307
// AddBlacklistUser adds user in database blacklist
308
func (db *DBWorker) AddBlacklistUser(id string) {
309
	err := db.DBSession.DB(db.DBName).C("blusers").Insert(BlackListElement{ID: id})
310
	if err != nil {
311
		log.Printf("[Mongo] Error adding user in blacklist: ", err.Error())
0 ignored issues
show
introduced by
no formatting directive in Printf call
Loading history...
312
	}
313
}
314
315
// RemoveBlacklistGuild removes guild from database blacklist
316
func (db *DBWorker) RemoveBlacklistGuild(id string) {
317
	err := db.DBSession.DB(db.DBName).C("blguilds").Remove(bson.M{"id": id})
318
	if err != nil {
319
		log.Printf("[Mongo] Error removing guild from blacklist: ", err.Error())
0 ignored issues
show
introduced by
no formatting directive in Printf call
Loading history...
320
	}
321
}
322
323
// RemoveBlacklistUser removes user from database blacklist
324
func (db *DBWorker) RemoveBlacklistUser(id string) {
325
	err := db.DBSession.DB(db.DBName).C("blusers").Remove(bson.M{"id": id})
326
	if err != nil {
327
		log.Printf("[Mongo] Error removing user from blacklist: ", err.Error())
0 ignored issues
show
introduced by
no formatting directive in Printf call
Loading history...
328
	}
329
}
330
331
// GetNewsCountry returns news country string
332
func (db *DBWorker) GetNewsCountry(guild string) string {
333
	var dbGuild GuildData
334
	err := db.DBSession.DB(db.DBName).C("guilds").Find(bson.M{"id": guild}).One(&dbGuild)
335
	if err != nil {
336
		log.Printf("[Mongo] Error getting news country: ", err)
0 ignored issues
show
introduced by
no formatting directive in Printf call
Loading history...
337
	}
338
	return dbGuild.NewsCounty
339
}
340