Passed
Push — master ( 6b3f48...e7383a )
by Viktor
01:41
created

bot.*DBWorker.InitNewGuild   A

Complexity

Conditions 1

Size

Total Lines 13
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 12
nop 3
dl 0
loc 13
rs 9.8
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
// NewDBSession creates new MongoDB instance
43
func NewDBSession(dbname string) *DBWorker {
44
	session, err := mgo.Dial(os.Getenv("MONGO_CONN"))
45
	if err != nil {
46
		fmt.Printf("Mongo connection error: %v", err)
47
	}
48
	count, err := session.DB("dtbot").C("logs").Count()
49
	if err != nil {
50
		fmt.Println("DB_ERR: ", err)
51
	}
52
	fmt.Printf("Mongo connected\nLogs in base: %v\n", count)
53
	return &DBWorker{DBSession: session, DBName: dbname}
54
}
55
56
// InitGuilds initialize guilds in database
57
func (db *DBWorker) InitGuilds(sess *discordgo.Session, conf *Config) *GuildsMap {
58
	var data = &GuildsMap{Guilds: make(map[string]*GuildData)}
59
	var loaded, initialized = 0, 0
60
	for _, guild := range sess.State.Guilds {
61
		count, err := db.DBSession.DB(db.DBName).C("guilds").Find(bson.M{"id": guild.ID}).Count()
62
		if err != nil {
63
			fmt.Println("Mongo: ", err)
64
		}
65
		if count == 0 {
66
			newData := &GuildData{
67
				ID:          guild.ID,
68
				WeatherCity: conf.Weather.City,
69
				NewsCounty:  conf.News.Country,
70
				Language:    conf.General.Language,
71
				Timezone:    conf.General.Timezone,
72
				EmbedColor:  conf.General.EmbedColor,
73
				VoiceVolume: conf.Voice.Volume,
74
				Greeting:    "",
75
			}
76
			_ = db.DBSession.DB(db.DBName).C("guilds").Insert(newData)
77
			data.Guilds[guild.ID] = newData
78
			initialized++
79
		} else {
80
			var newData = &GuildData{}
81
			_ = db.DBSession.DB(db.DBName).C("guilds").Find(bson.M{"id": guild.ID}).One(newData)
82
			if err != nil {
83
				fmt.Println("Mongo: ", err)
84
				continue
85
			}
86
			data.Guilds[guild.ID] = newData
87
			loaded++
88
		}
89
	}
90
	fmt.Printf("Guilds loaded [%v], initialized [%v]\n", loaded, initialized)
91
	return data
92
}
93
94
func (db *DBWorker) InitNewGuild(guildID string, conf *Config, data *GuildsMap) {
0 ignored issues
show
introduced by
exported method DBWorker.InitNewGuild should have comment or be unexported
Loading history...
95
	newData := &GuildData{
96
		ID:          guildID,
97
		WeatherCity: conf.Weather.City,
98
		NewsCounty:  conf.News.Country,
99
		Language:    conf.General.Language,
100
		Timezone:    conf.General.Timezone,
101
		EmbedColor:  conf.General.EmbedColor,
102
		VoiceVolume: conf.Voice.Volume,
103
		Greeting:    "",
104
	}
105
	_ = db.DBSession.DB(db.DBName).C("guilds").Insert(newData)
106
	data.Guilds[guildID] = newData
107
}
108
109
// Log saves log in database
110
func (db *DBWorker) Log(module, guildID, text string) {
111
	_ = db.DBSession.DB(db.DBName).C("logs").Insert(dbLog{Date: time.Now(), Text: text, Module: module, Guild: guildID})
112
}
113
114
// LogGet returns last N log rows
115
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...
116
	var log = make([]dbLog, count)
117
	_ = db.DBSession.DB(db.DBName).C("logs").Find(nil).Sort("-$natural").Limit(count).All(&log)
118
	return log
119
}
120
121
// Guilds returns guilds collection from mongodb
122
func (db *DBWorker) Guilds() *mgo.Collection {
123
	return db.DBSession.DB(db.DBName).C("guilds")
124
}
125
126
// GetTwitchStreams returns twitch streams from mongodb
127
func (db *DBWorker) GetTwitchStreams(guildID string) map[string]*TwitchStream {
128
	streams := []TwitchStream{}
129
	err := db.DBSession.DB(db.DBName).C("streams").Find(bson.M{"guild": guildID}).All(&streams)
130
	if err != nil {
131
		fmt.Println("Mongo: ", err)
132
	}
133
	var newMap = make(map[string]*TwitchStream)
134
	for i, s := range streams {
135
		newMap[s.Login] = &streams[i]
136
	}
137
	return newMap
138
}
139
140
// UpdateStream updates stream in mongodb
141
func (db *DBWorker) UpdateStream(stream *TwitchStream) {
142
	err := db.DBSession.DB(db.DBName).C("streams").
143
		Update(
144
			bson.M{"guild": stream.Guild, "login": stream.Login},
145
			bson.M{"$set": bson.M{"isonline": stream.IsOnline}})
146
	if err != nil {
147
		fmt.Println(err.Error())
148
	}
149
}
150
151
// AddStream adds stream in mongodb
152
func (db *DBWorker) AddStream(stream *TwitchStream) {
153
	_ = db.DBSession.DB(db.DBName).C("streams").Insert(stream)
154
}
155
156
// RemoveStream removes stream from mongodb
157
func (db *DBWorker) RemoveStream(stream *TwitchStream) {
158
	_ = db.DBSession.DB(db.DBName).C("streams").Remove(bson.M{"login": stream.Login, "guild": stream.Guild})
159
}
160