From c9855116dabf8cac28585f29fe315ad8be3b2cb0 Mon Sep 17 00:00:00 2001 From: Vladimir Hodakov Date: Sat, 31 Mar 2018 08:34:27 +0400 Subject: [PATCH] Move rarely changed data to datamappings, fix profile updating As result of profile format change, introduced in game update yesterday we need to change profile regexp. As result of some refactoring, rarely changed data removed from database and added to sources of bot. --- Gopkg.lock | 15 +- Gopkg.toml | 6 +- .../datacacheinterface/datacacheinterface.go | 10 +- lib/datacache/elements.go | 48 ++-- lib/datacache/exported.go | 14 +- lib/datacache/leagues.go | 39 ++-- lib/datacache/locations.go | 31 +-- lib/datacache/pokememes.go | 13 +- lib/datacache/weapons.go | 39 ++-- lib/datamapping/elements.go | 12 + lib/datamapping/leagues.go | 11 + lib/datamapping/locations.go | 11 + lib/datamapping/weapons.go | 12 + lib/dbmapping/elements.go | 17 -- lib/dbmapping/leagues.go | 16 -- lib/dbmapping/locations.go | 16 -- lib/dbmapping/players.go | 3 +- lib/dbmapping/pokememes.go | 5 +- lib/dbmapping/weapons.go | 17 -- lib/forwarder/forwarder.go | 6 +- lib/migrations/33_delete_datamapped_tables.go | 220 ++++++++++++++++++ lib/migrations/5_create_locations.go | 36 +-- lib/migrations/6_create_elements.go | 72 +++--- lib/migrations/7_create_leagues.go | 18 +- lib/migrations/migrations.go | 1 + lib/users/parsers.go | 3 +- lib/users/responders.go | 6 +- 27 files changed, 460 insertions(+), 237 deletions(-) create mode 100644 lib/datamapping/elements.go create mode 100644 lib/datamapping/leagues.go create mode 100644 lib/datamapping/locations.go create mode 100644 lib/datamapping/weapons.go delete mode 100644 lib/dbmapping/elements.go delete mode 100644 lib/dbmapping/leagues.go delete mode 100644 lib/dbmapping/locations.go delete mode 100644 lib/dbmapping/weapons.go create mode 100644 lib/migrations/33_delete_datamapped_tables.go diff --git a/Gopkg.lock b/Gopkg.lock index 5ec0d02..cc2eb76 100644 --- a/Gopkg.lock +++ b/Gopkg.lock @@ -73,19 +73,6 @@ ] revision = "ff2a66f350cefa5c93a634eadb5d25bb60c85a9c" -[[projects]] - branch = "master" - name = "golang.org/x/text" - packages = [ - "internal/gen", - "internal/triegen", - "internal/ucd", - "transform", - "unicode/cldr", - "unicode/norm" - ] - revision = "e19ae1496984b1c655b8044a65c0300a3c878dd3" - [[projects]] branch = "v2" name = "gopkg.in/yaml.v2" @@ -95,6 +82,6 @@ [solve-meta] analyzer-name = "dep" analyzer-version = 1 - inputs-digest = "99811036e66782056cb66f37e4a2570ac81f0e3da2fe399c4d54d83acc5a368d" + inputs-digest = "1f9ca287338c3a5d515174b67ff79568a1e3be9df49bee694fac57d9de9802f9" solver-name = "gps-cdcl" solver-version = 1 diff --git a/Gopkg.toml b/Gopkg.toml index 3f7f980..9f1dbe2 100644 --- a/Gopkg.toml +++ b/Gopkg.toml @@ -11,7 +11,7 @@ # version = "1.0.0" # # [[constraint]] -# name = "github.com/user/project2" +# name = "github.com/user/project2" # branch = "dev" # source = "github.com/myfork/project2" # @@ -53,10 +53,6 @@ name = "github.com/robfig/cron" version = "1.0.0" -[[constraint]] - branch = "master" - name = "golang.org/x/text" - [[constraint]] branch = "v2" name = "gopkg.in/yaml.v2" diff --git a/lib/datacache/datacacheinterface/datacacheinterface.go b/lib/datacache/datacacheinterface/datacacheinterface.go index bbbc400..1cc5253 100644 --- a/lib/datacache/datacacheinterface/datacacheinterface.go +++ b/lib/datacache/datacacheinterface/datacacheinterface.go @@ -5,6 +5,7 @@ package datacacheinterface import ( "github.com/go-telegram-bot-api/telegram-bot-api" + "source.wtfteam.pro/i2_bot/i2_bot/lib/datamapping" "source.wtfteam.pro/i2_bot/i2_bot/lib/dbmapping" ) @@ -51,8 +52,11 @@ type DataCacheInterface interface { DeletePokememeByID(pokememeID int) error UpdatePokememe(pokememeData map[string]string, pokememeLocations map[string]string, pokememeElements map[string]string) (int, error) - GetLeagueBySymbol(symbol string) (*dbmapping.League, error) + GetElementByID(elementID int) (*datamapping.Element, error) - GetWeaponTypeByID(weaponID int) (*dbmapping.Weapon, error) - GetWeaponTypeByName(name string) (*dbmapping.Weapon, error) + GetLeagueByID(leagueID int) (*datamapping.League, error) + GetLeagueBySymbol(symbol string) (*datamapping.League, error) + + GetWeaponTypeByID(weaponID int) (*datamapping.Weapon, error) + GetWeaponTypeByName(name string) (*datamapping.Weapon, error) } diff --git a/lib/datacache/elements.go b/lib/datacache/elements.go index 836218b..0060071 100644 --- a/lib/datacache/elements.go +++ b/lib/datacache/elements.go @@ -5,41 +5,61 @@ package datacache import ( "errors" - "source.wtfteam.pro/i2_bot/i2_bot/lib/dbmapping" + "source.wtfteam.pro/i2_bot/i2_bot/lib/datamapping" "strconv" ) func (dc *DataCache) initElements() { c.Log.Info("Initializing Elements storage...") - dc.elements = make(map[int]*dbmapping.Element) + dc.elements = make(map[int]*datamapping.Element) } func (dc *DataCache) loadElements() { - c.Log.Info("Load current Elements data from database to DataCache...") - elements := []dbmapping.Element{} - err := c.Db.Select(&elements, "SELECT * FROM elements") - if err != nil { - // This is critical error and we need to stop immediately! - c.Log.Fatal(err.Error()) - } + c.Log.Info("Load current Elements data to DataCache...") + elements := dc.getElements() - dc.elementsMutex.Lock() for i := range elements { dc.elements[elements[i].ID] = &elements[i] } c.Log.Info("Loaded elements in DataCache: " + strconv.Itoa(len(dc.elements))) - dc.elementsMutex.Unlock() +} + +func (dc *DataCache) getElements() []datamapping.Element { + elements := []datamapping.Element{} + + elements = append(elements, datamapping.Element{1, "👊", "Боевой", 1}) + elements = append(elements, datamapping.Element{2, "🌀", "Летающий", 1}) + elements = append(elements, datamapping.Element{3, "💀", "Ядовитый", 1}) + elements = append(elements, datamapping.Element{4, "🗿", "Каменный", 1}) + elements = append(elements, datamapping.Element{5, "🔥", "Огненный", 2}) + elements = append(elements, datamapping.Element{6, "⚡", "Электрический", 2}) + elements = append(elements, datamapping.Element{7, "💧", "Водяной", 2}) + elements = append(elements, datamapping.Element{8, "🍀", "Травяной", 2}) + elements = append(elements, datamapping.Element{9, "💩", "Отважный", 3}) + elements = append(elements, datamapping.Element{10, "👁", "Психический", 3}) + elements = append(elements, datamapping.Element{11, "👿", "Тёмный", 3}) + elements = append(elements, datamapping.Element{12, "⌛", "Времени", 3}) + + return elements } func (dc *DataCache) findElementIDBySymbol(symbol string) (int, error) { - dc.elementsMutex.Lock() for i := range dc.elements { if dc.elements[i].Symbol == symbol { - dc.elementsMutex.Unlock() return i, nil } } - dc.elementsMutex.Unlock() return 0, errors.New("There is no element with symbol = " + symbol) } + +// External functions + +// GetElementByID returns element with given ID +func (dc *DataCache) GetElementByID(elementID int) (*datamapping.Element, error) { + if dc.elements[elementID] != nil { + return dc.elements[elementID], nil + } + + return nil, errors.New("There is no element with ID = " + strconv.Itoa(elementID)) +} diff --git a/lib/datacache/exported.go b/lib/datacache/exported.go index 4ea138a..140efc9 100644 --- a/lib/datacache/exported.go +++ b/lib/datacache/exported.go @@ -6,6 +6,7 @@ package datacache import ( "source.wtfteam.pro/i2_bot/i2_bot/lib/appcontext" "source.wtfteam.pro/i2_bot/i2_bot/lib/datacache/datacacheinterface" + "source.wtfteam.pro/i2_bot/i2_bot/lib/datamapping" "source.wtfteam.pro/i2_bot/i2_bot/lib/dbmapping" "sync" ) @@ -44,18 +45,15 @@ type DataCache struct { squadPlayers map[int]map[int]*dbmapping.SquadPlayerFull squadsMutex sync.Mutex + // Non-database data // Elements - elements map[int]*dbmapping.Element - elementsMutex sync.Mutex + elements map[int]*datamapping.Element // Leagues - leagues map[int]*dbmapping.League - leaguesMutex sync.Mutex + leagues map[int]*datamapping.League // Locations - locations map[int]*dbmapping.Location - locationsMutex sync.Mutex + locations map[int]*datamapping.Location // Weapons - weapons map[int]*dbmapping.Weapon - weaponsMutex sync.Mutex + weapons map[int]*datamapping.Weapon } // New is an initialization function for appcontext diff --git a/lib/datacache/leagues.go b/lib/datacache/leagues.go index ab07a42..d6860fd 100644 --- a/lib/datacache/leagues.go +++ b/lib/datacache/leagues.go @@ -5,44 +5,53 @@ package datacache import ( "errors" - "source.wtfteam.pro/i2_bot/i2_bot/lib/dbmapping" + "source.wtfteam.pro/i2_bot/i2_bot/lib/datamapping" "strconv" ) func (dc *DataCache) initLeagues() { c.Log.Info("Initializing Leagues storage...") - dc.leagues = make(map[int]*dbmapping.League) + dc.leagues = make(map[int]*datamapping.League) } func (dc *DataCache) loadLeagues() { - c.Log.Info("Load current Leagues data from database to DataCache...") - leagues := []dbmapping.League{} - err := c.Db.Select(&leagues, "SELECT * FROM leagues") - if err != nil { - // This is critical error and we need to stop immediately! - c.Log.Fatal(err.Error()) - } + c.Log.Info("Load current Leagues data to DataCache...") + leagues := dc.getLeagues() - dc.leaguesMutex.Lock() for i := range leagues { dc.leagues[leagues[i].ID] = &leagues[i] } c.Log.Info("Loaded leagues in DataCache: " + strconv.Itoa(len(dc.leagues))) - dc.leaguesMutex.Unlock() +} + +func (dc *DataCache) getLeagues() []datamapping.League { + leagues := []datamapping.League{} + + leagues = append(leagues, datamapping.League{1, "🈸", "ИНСТИНКТ"}) + leagues = append(leagues, datamapping.League{2, "🈳 ", "МИСТИКА"}) + leagues = append(leagues, datamapping.League{3, "🈵", "ОТВАГА"}) + + return leagues } // External functions +// GetLeagueByID returns league from datacache by ID +func (dc *DataCache) GetLeagueByID(leagueID int) (*datamapping.League, error) { + if dc.leagues[leagueID] != nil { + return dc.leagues[leagueID], nil + } + + return nil, errors.New("There is no league with ID = " + strconv.Itoa(leagueID)) +} + // GetLeagueBySymbol returns league from datacache by emoji -func (dc *DataCache) GetLeagueBySymbol(symbol string) (*dbmapping.League, error) { - dc.leaguesMutex.Lock() +func (dc *DataCache) GetLeagueBySymbol(symbol string) (*datamapping.League, error) { for i := range dc.leagues { if dc.leagues[i].Symbol == symbol { - dc.leaguesMutex.Unlock() return dc.leagues[i], nil } } - dc.leaguesMutex.Unlock() return nil, errors.New("There is no league with symbol = " + symbol) } diff --git a/lib/datacache/locations.go b/lib/datacache/locations.go index 83c759e..718a2ec 100644 --- a/lib/datacache/locations.go +++ b/lib/datacache/locations.go @@ -5,41 +5,44 @@ package datacache import ( "errors" - "source.wtfteam.pro/i2_bot/i2_bot/lib/dbmapping" + "source.wtfteam.pro/i2_bot/i2_bot/lib/datamapping" "strconv" ) func (dc *DataCache) initLocations() { c.Log.Info("Initializing Locations storage...") - dc.locations = make(map[int]*dbmapping.Location) + dc.locations = make(map[int]*datamapping.Location) } func (dc *DataCache) loadLocations() { - c.Log.Info("Load current Locations data from database to DataCache...") - locations := []dbmapping.Location{} - err := c.Db.Select(&locations, "SELECT * FROM locations") - if err != nil { - // This is critical error and we need to stop immediately! - c.Log.Fatal(err.Error()) - } + c.Log.Info("Load current Locations data to DataCache...") + locations := dc.getLocations() - dc.locationsMutex.Lock() for i := range locations { dc.locations[locations[i].ID] = &locations[i] } c.Log.Info("Loaded locations in DataCache: " + strconv.Itoa(len(dc.locations))) - dc.locationsMutex.Unlock() +} + +func (dc *DataCache) getLocations() []datamapping.Location { + locations := []datamapping.Location{} + + locations = append(locations, datamapping.Location{1, "🌲", "Лес"}) + locations = append(locations, datamapping.Location{2, "⛰", "Горы"}) + locations = append(locations, datamapping.Location{3, "🚣", "Озеро"}) + locations = append(locations, datamapping.Location{4, "🏙", "Город"}) + locations = append(locations, datamapping.Location{5, "🏛", "Катакомбы"}) + locations = append(locations, datamapping.Location{6, "⛪️", "Кладбище"}) + + return locations } func (dc *DataCache) findLocationIDByName(name string) (int, error) { - dc.locationsMutex.Lock() for i := range dc.locations { if dc.locations[i].Name == name { - dc.locationsMutex.Unlock() return i, nil } } - dc.locationsMutex.Unlock() return 0, errors.New("There is no location with name = " + name) } diff --git a/lib/datacache/pokememes.go b/lib/datacache/pokememes.go index 7534f7a..237242a 100644 --- a/lib/datacache/pokememes.go +++ b/lib/datacache/pokememes.go @@ -6,6 +6,7 @@ package datacache import ( "errors" "sort" + "source.wtfteam.pro/i2_bot/i2_bot/lib/datamapping" "source.wtfteam.pro/i2_bot/i2_bot/lib/dbmapping" "strconv" "strings" @@ -46,8 +47,8 @@ func (dc *DataCache) loadPokememes() { // Filling fullPokememes fullPokememe := dbmapping.PokememeFull{} - elementsListed := []dbmapping.Element{} - locationsListed := []dbmapping.Location{} + elementsListed := []datamapping.Element{} + locationsListed := []datamapping.Location{} for j := range pokememesLocations { if pokememesLocations[j].PokememeID == pokememes[i].ID { @@ -122,8 +123,8 @@ func (dc *DataCache) AddPokememe(pokememeData map[string]string, pokememeLocatio pokememe.PlayerID = creatorID pokememe.CreatedAt = time.Now().UTC() - locations := []dbmapping.Location{} - elements := []dbmapping.Element{} + locations := []datamapping.Location{} + elements := []datamapping.Element{} for i := range pokememeLocations { locationID, err := dc.findLocationIDByName(pokememeLocations[i]) @@ -343,8 +344,8 @@ func (dc *DataCache) UpdatePokememe(pokememeData map[string]string, pokememeLoca pokememe.PlayerID = creatorID pokememe.CreatedAt = time.Now().UTC() - locations := []dbmapping.Location{} - elements := []dbmapping.Element{} + locations := []datamapping.Location{} + elements := []datamapping.Element{} for i := range pokememeLocations { locationID, err := dc.findLocationIDByName(pokememeLocations[i]) diff --git a/lib/datacache/weapons.go b/lib/datacache/weapons.go index efdf82e..dd75c5a 100644 --- a/lib/datacache/weapons.go +++ b/lib/datacache/weapons.go @@ -5,57 +5,58 @@ package datacache import ( "errors" - "source.wtfteam.pro/i2_bot/i2_bot/lib/dbmapping" + "source.wtfteam.pro/i2_bot/i2_bot/lib/datamapping" "strconv" "strings" ) func (dc *DataCache) initWeapons() { c.Log.Info("Initializing Weapons storage...") - dc.weapons = make(map[int]*dbmapping.Weapon) + dc.weapons = make(map[int]*datamapping.Weapon) } func (dc *DataCache) loadWeapons() { - c.Log.Info("Load current Weapons data from database to DataCache...") - weapons := []dbmapping.Weapon{} - err := c.Db.Select(&weapons, "SELECT * FROM weapons") - if err != nil { - // This is critical error and we need to stop immediately! - c.Log.Fatal(err.Error()) - } + c.Log.Info("Load current Weapons data to DataCache...") + weapons := dc.getWeapons() - dc.weaponsMutex.Lock() for i := range weapons { dc.weapons[weapons[i].ID] = &weapons[i] } c.Log.Info("Loaded weapon types in DataCache: " + strconv.Itoa(len(dc.weapons))) - dc.weaponsMutex.Unlock() +} + +func (dc *DataCache) getWeapons() []datamapping.Weapon { + weapons := []datamapping.Weapon{} + + weapons = append(weapons, datamapping.Weapon{1, "Бита", 2, 5}) + weapons = append(weapons, datamapping.Weapon{2, "Стальная бита", 10, 40}) + weapons = append(weapons, datamapping.Weapon{3, "Чугунная бита", 200, 500}) + weapons = append(weapons, datamapping.Weapon{4, "Титановая бита", 2000, 10000}) + weapons = append(weapons, datamapping.Weapon{5, "Алмазная бита", 10000, 100000}) + weapons = append(weapons, datamapping.Weapon{6, "Криптонитовая бита", 100000, 500000}) + weapons = append(weapons, datamapping.Weapon{5, "Буханка из пятёры", 1000000, 5000000}) + + return weapons } // External functions // GetWeaponTypeByID returns weapon type from datacache by given ID -func (dc *DataCache) GetWeaponTypeByID(weaponID int) (*dbmapping.Weapon, error) { - dc.weaponsMutex.Lock() +func (dc *DataCache) GetWeaponTypeByID(weaponID int) (*datamapping.Weapon, error) { if dc.weapons[weaponID] != nil { c.Log.Debug("DataCache: found weapon type with ID = " + strconv.Itoa(weaponID)) - dc.weaponsMutex.Unlock() return dc.weapons[weaponID], nil } - dc.weaponsMutex.Unlock() return nil, errors.New("There is no weapon type with ID = " + strconv.Itoa(weaponID)) } // GetWeaponTypeByName returns weapon type from datacache by weapon name -func (dc *DataCache) GetWeaponTypeByName(name string) (*dbmapping.Weapon, error) { - dc.weaponsMutex.Lock() +func (dc *DataCache) GetWeaponTypeByName(name string) (*datamapping.Weapon, error) { for i := range dc.weapons { if strings.HasPrefix(dc.weapons[i].Name, name) { - dc.weaponsMutex.Unlock() return dc.weapons[i], nil } } - dc.weaponsMutex.Unlock() return nil, errors.New("There is no weapon type with name = " + name) } diff --git a/lib/datamapping/elements.go b/lib/datamapping/elements.go new file mode 100644 index 0000000..833df30 --- /dev/null +++ b/lib/datamapping/elements.go @@ -0,0 +1,12 @@ +// i2_bot – Instinct PokememBro Bot +// Copyright (c) 2017-2018 Vladimir "fat0troll" Hodakov + +package datamapping + +// Element is a struct, which represents element data +type Element struct { + ID int + Symbol string + Name string + LeagueID int +} diff --git a/lib/datamapping/leagues.go b/lib/datamapping/leagues.go new file mode 100644 index 0000000..5c9daa3 --- /dev/null +++ b/lib/datamapping/leagues.go @@ -0,0 +1,11 @@ +// i2_bot – Instinct PokememBro Bot +// Copyright (c) 2017-2018 Vladimir "fat0troll" Hodakov + +package datamapping + +// League is a struct, which represents league data +type League struct { + ID int + Symbol string + Name string +} diff --git a/lib/datamapping/locations.go b/lib/datamapping/locations.go new file mode 100644 index 0000000..6a32d27 --- /dev/null +++ b/lib/datamapping/locations.go @@ -0,0 +1,11 @@ +// i2_bot – Instinct PokememBro Bot +// Copyright (c) 2017-2018 Vladimir "fat0troll" Hodakov + +package datamapping + +// Location is a struct, which represents location data +type Location struct { + ID int + Symbol string + Name string +} diff --git a/lib/datamapping/weapons.go b/lib/datamapping/weapons.go new file mode 100644 index 0000000..3f2b530 --- /dev/null +++ b/lib/datamapping/weapons.go @@ -0,0 +1,12 @@ +// i2_bot – Instinct PokememBro Bot +// Copyright (c) 2017-2018 Vladimir "fat0troll" Hodakov + +package datamapping + +// Weapon is a struct, which represents weapon data +type Weapon struct { + ID int + Name string + Power int + Price int +} diff --git a/lib/dbmapping/elements.go b/lib/dbmapping/elements.go deleted file mode 100644 index e7f46a7..0000000 --- a/lib/dbmapping/elements.go +++ /dev/null @@ -1,17 +0,0 @@ -// i2_bot – Instinct PokememBro Bot -// Copyright (c) 2017 Vladimir "fat0troll" Hodakov - -package dbmapping - -import ( - "time" -) - -// Element is a struct, which represents `elements` table item in databse. -type Element struct { - ID int `db:"id"` - Symbol string `db:"symbol"` - Name string `db:"name"` - LeagueID int `db:"league_id"` - CreatedAt *time.Time `db:"created_at"` -} diff --git a/lib/dbmapping/leagues.go b/lib/dbmapping/leagues.go deleted file mode 100644 index 8d338f6..0000000 --- a/lib/dbmapping/leagues.go +++ /dev/null @@ -1,16 +0,0 @@ -// i2_bot – Instinct PokememBro Bot -// Copyright (c) 2017 Vladimir "fat0troll" Hodakov - -package dbmapping - -import ( - "time" -) - -// League is a struct, which represents `leagues` table item in databse. -type League struct { - ID int `db:"id"` - Symbol string `db:"symbol"` - Name string `db:"name"` - CreatedAt *time.Time `db:"created_at"` -} diff --git a/lib/dbmapping/locations.go b/lib/dbmapping/locations.go deleted file mode 100644 index f64a453..0000000 --- a/lib/dbmapping/locations.go +++ /dev/null @@ -1,16 +0,0 @@ -// i2_bot – Instinct PokememBro Bot -// Copyright (c) 2017 Vladimir "fat0troll" Hodakov - -package dbmapping - -import ( - "time" -) - -// Location is a struct, which represents `locations` table item in databse. -type Location struct { - ID int `db:"id"` - Symbol string `db:"symbol"` - Name string `db:"name"` - CreatedAt time.Time `db:"created_at"` -} diff --git a/lib/dbmapping/players.go b/lib/dbmapping/players.go index 8a9ba3f..039f88c 100644 --- a/lib/dbmapping/players.go +++ b/lib/dbmapping/players.go @@ -4,6 +4,7 @@ package dbmapping import ( + "source.wtfteam.pro/i2_bot/i2_bot/lib/datamapping" "time" ) @@ -21,6 +22,6 @@ type Player struct { type PlayerProfile struct { Player Player Profile Profile - League League + League datamapping.League HaveProfile bool } diff --git a/lib/dbmapping/pokememes.go b/lib/dbmapping/pokememes.go index b4019f7..d29fbc6 100644 --- a/lib/dbmapping/pokememes.go +++ b/lib/dbmapping/pokememes.go @@ -4,6 +4,7 @@ package dbmapping import ( + "source.wtfteam.pro/i2_bot/i2_bot/lib/datamapping" "time" ) @@ -28,6 +29,6 @@ type Pokememe struct { // PokememeFull is a struct for handling pokememe with all informations about locations and elements type PokememeFull struct { Pokememe Pokememe - Locations []Location - Elements []Element + Locations []datamapping.Location + Elements []datamapping.Element } diff --git a/lib/dbmapping/weapons.go b/lib/dbmapping/weapons.go deleted file mode 100644 index c40d8c5..0000000 --- a/lib/dbmapping/weapons.go +++ /dev/null @@ -1,17 +0,0 @@ -// i2_bot – Instinct PokememBro Bot -// Copyright (c) 2017 Vladimir "fat0troll" Hodakov - -package dbmapping - -import ( - "time" -) - -// Weapon is a struct, which represents `weapons` table item in databse. -type Weapon struct { - ID int `db:"id"` - Name string `db:"name"` - Power int `db:"power"` - Price int `db:"price"` - CreatedAt time.Time `db:"created_at"` -} diff --git a/lib/forwarder/forwarder.go b/lib/forwarder/forwarder.go index bbee2f7..3440ac4 100644 --- a/lib/forwarder/forwarder.go +++ b/lib/forwarder/forwarder.go @@ -4,9 +4,9 @@ package forwarder import ( - "source.wtfteam.pro/i2_bot/i2_bot/lib/dbmapping" "github.com/go-telegram-bot-api/telegram-bot-api" "regexp" + "source.wtfteam.pro/i2_bot/i2_bot/lib/dbmapping" ) // ProcessForward process forwards for single-user chats @@ -14,8 +14,8 @@ func (f *Forwarder) ProcessForward(update *tgbotapi.Update, playerRaw *dbmapping text := update.Message.Text // Forwards var pokememeMsg = regexp.MustCompile("(Уровень)(.+)(Опыт)(.+)\n(Элементы:)(.+)\n(.+)(💙MP)") - var profileMsg = regexp.MustCompile(`(Онлайн: )(\d+)\n(Турнир через)(.+)\n\n((.*)\n|(.*)\n(.*)\n)(Элементы)(.+)\n(.*)\n\n(.+)(Уровень)(.+)\n`) - var profileWithEffectsMsg = regexp.MustCompile(`(Онлайн: )(\d+)\n(Турнир через)(.+)\n\n((.*)\n|(.*)\n(.*)\n)(Элементы)(.+)\n(.*)\n(Эффекты)(.*)\n\n(.+)(Уровень)(.+)\n`) + var profileMsg = regexp.MustCompile(`(Онлайн: )(\d+)(| Турнир: )(.+)\n(.+)\n(.+)\n(👤Уровень)(.+)\n`) + var profileWithEffectsMsg = regexp.MustCompile(`(Онлайн: )(\d+)(| Турнир: )(.+)\n(.+)\n(.+)\n(.+)\n(👤Уровень)(.+)\n`) switch { case pokememeMsg.MatchString(text): diff --git a/lib/migrations/33_delete_datamapped_tables.go b/lib/migrations/33_delete_datamapped_tables.go new file mode 100644 index 0000000..80d8d16 --- /dev/null +++ b/lib/migrations/33_delete_datamapped_tables.go @@ -0,0 +1,220 @@ +// i2_bot – Instinct PokememBro Bot +// Copyright (c) 2017-2018 Vladimir "fat0troll" Hodakov + +package migrations + +import ( + "database/sql" +) + +// DeleteDataMappedTablesUp drops `locations`, `elements`, `weapons` and `leagues` tables +// These tables data is rarely changed, so I decided to hold such data in source code +func DeleteDataMappedTablesUp(tx *sql.Tx) error { + request := "DROP TABLE IF EXISTS `elements`" + _, err := tx.Exec(request) + if err != nil { + return err + } + + request = "DROP TABLE IF EXISTS `leagues`" + _, err = tx.Exec(request) + if err != nil { + return err + } + + request = "DROP TABLE IF EXISTS `locations`" + _, err = tx.Exec(request) + if err != nil { + return err + } + + request = "DROP TABLE IF EXISTS `weapons`" + _, err = tx.Exec(request) + if err != nil { + return err + } + + return nil +} + +// DeleteDataMappedTablesDown returns old tables with all data +func DeleteDataMappedTablesDown(tx *sql.Tx) error { + request := "CREATE TABLE `locations` (" + request += "`id` int(11) NOT NULL AUTO_INCREMENT COMMENT 'ID локации'," + request += "`symbol` varchar(191) COLLATE 'utf8mb4_unicode_520_ci' NOT NULL COMMENT 'Символ локации'," + request += "`name` varchar(191) NOT NULL COMMENT 'Имя локации'," + request += "`created_at` datetime NOT NULL COMMENT 'Добавлена в базу'," + request += "PRIMARY KEY (`id`)," + request += "UNIQUE KEY `id` (`id`)," + request += "KEY `locations_created_at` (`created_at`)" + request += ") ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8mb4 COMMENT='Локации';" + _, err := tx.Exec(request) + if err != nil { + return err + } + + // Insert locations + _, err = tx.Exec("INSERT INTO `locations` VALUES(NULL, '🌲', 'Лес', NOW());") + if err != nil { + return err + } + _, err = tx.Exec("INSERT INTO `locations` VALUES(NULL, '⛰', 'Горы', NOW());") + if err != nil { + return err + } + _, err = tx.Exec("INSERT INTO `locations` VALUES(NULL, '🚣', 'Озеро', NOW());") + if err != nil { + return err + } + _, err = tx.Exec("INSERT INTO `locations` VALUES(NULL, '🏙', 'Город', NOW());") + if err != nil { + return err + } + _, err = tx.Exec("INSERT INTO `locations` VALUES(NULL, '🏛', 'Катакомбы', NOW());") + if err != nil { + return err + } + _, err = tx.Exec("INSERT INTO `locations` VALUES(NULL, '⛪', 'Кладбище', NOW());") + if err != nil { + return err + } + + request = "CREATE TABLE `elements` (" + request += "`id` int(11) NOT NULL AUTO_INCREMENT COMMENT 'ID элемента'," + request += "`symbol` varchar(191) COLLATE 'utf8mb4_unicode_520_ci' NOT NULL COMMENT 'Символ элемента'," + request += "`name` varchar(191) NOT NULL COMMENT 'Имя элемента'," + request += "`league_id` int(11) NOT NULL COMMENT 'ID родной лиги'," + request += "`created_at` datetime NOT NULL COMMENT 'Добавлен в базу'," + request += "PRIMARY KEY (`id`)," + request += "UNIQUE KEY `id` (`id`)," + request += "KEY `elements_created_at` (`created_at`)" + request += ") ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8mb4 COMMENT='Элементы';" + _, err = tx.Exec(request) + if err != nil { + return err + } + + // Insert elements + _, err = tx.Exec("INSERT INTO `elements` VALUES(NULL, '👊', 'Боевой', 1, NOW());") + if err != nil { + return err + } + _, err = tx.Exec("INSERT INTO `elements` VALUES(NULL, '🌀', 'Летающий', 1, NOW());") + if err != nil { + return err + } + _, err = tx.Exec("INSERT INTO `elements` VALUES(NULL, '💀', 'Ядовитый', 1, NOW());") + if err != nil { + return err + } + _, err = tx.Exec("INSERT INTO `elements` VALUES(NULL, '🗿', 'Каменный', 1, NOW());") + if err != nil { + return err + } + _, err = tx.Exec("INSERT INTO `elements` VALUES(NULL, '🔥', 'Огненный', 2, NOW());") + if err != nil { + return err + } + _, err = tx.Exec("INSERT INTO `elements` VALUES(NULL, '⚡', 'Электрический', 2, NOW());") + if err != nil { + return err + } + _, err = tx.Exec("INSERT INTO `elements` VALUES(NULL, '💧', 'Водяной', 2, NOW());") + if err != nil { + return err + } + _, err = tx.Exec("INSERT INTO `elements` VALUES(NULL, '🍀', 'Травяной', 2, NOW());") + if err != nil { + return err + } + _, err = tx.Exec("INSERT INTO `elements` VALUES(NULL, '💩', 'Шоколадный', 3, NOW());") + if err != nil { + return err + } + _, err = tx.Exec("INSERT INTO `elements` VALUES(NULL, '👁', 'Психический', 3, NOW());") + if err != nil { + return err + } + _, err = tx.Exec("INSERT INTO `elements` VALUES(NULL, '👿', 'Темный', 3, NOW());") + if err != nil { + return err + } + _, err = tx.Exec("INSERT INTO `elements` VALUES(NULL, '⌛', 'Времени', 3, NOW());") + if err != nil { + return err + } + + request = "CREATE TABLE `leagues` (" + request += "`id` int(11) NOT NULL AUTO_INCREMENT COMMENT 'ID лиги'," + request += "`symbol` varchar(191) COLLATE 'utf8mb4_unicode_520_ci' NOT NULL COMMENT 'Символ лиги'," + request += "`name` varchar(191) NOT NULL COMMENT 'Имя лиги'," + request += "`created_at` datetime NOT NULL COMMENT 'Добавлена в базу'," + request += "PRIMARY KEY (`id`)," + request += "UNIQUE KEY `id` (`id`)," + request += "KEY `leagues_created_at` (`created_at`)" + request += ") ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8mb4 COMMENT='Лиги';" + _, err = tx.Exec(request) + if err != nil { + return err + } + + // Insert locations + _, err = tx.Exec("INSERT INTO `leagues` VALUES(NULL, '🈸', 'ИНСТИНКТ', NOW());") + if err != nil { + return err + } + _, err = tx.Exec("INSERT INTO `leagues` VALUES(NULL, '🈳', 'ОТВАГА', NOW());") + if err != nil { + return err + } + _, err = tx.Exec("INSERT INTO `leagues` VALUES(NULL, '🈵', 'МИСТИКА', NOW());") + if err != nil { + return err + } + + request = "CREATE TABLE `weapons` (" + request += "`id` int(11) NOT NULL AUTO_INCREMENT COMMENT 'ID оружия'," + request += "`name` varchar(191) NOT NULL COMMENT 'Название оружия'," + request += "`power` int(11) NOT NULL COMMENT 'Атака оружия'," + request += "`price` int(11) NOT NULL COMMENT 'Цена в магазине'," + request += "`created_at` datetime NOT NULL COMMENT 'Добавлено в базу'," + request += "PRIMARY KEY (`id`)," + request += "UNIQUE KEY `id` (`id`)," + request += "KEY `weapons_created_at` (`created_at`)" + request += ") ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8mb4 COMMENT='Оружие';" + _, err = tx.Exec(request) + if err != nil { + return err + } + + _, err = tx.Exec("INSERT INTO `weapons` VALUES(NULL, 'Бита', 2, 5, NOW());") + if err != nil { + return err + } + _, err = tx.Exec("INSERT INTO `weapons` VALUES(NULL, 'Стальная бита', 10, 40, NOW());") + if err != nil { + return err + } + _, err = tx.Exec("INSERT INTO `weapons` VALUES(NULL, 'Чугунная бита ', 200, 500, NOW());") + if err != nil { + return err + } + _, err = tx.Exec("INSERT INTO `weapons` VALUES(NULL, 'Титановая бита', 2000, 10000, NOW());") + if err != nil { + return err + } + _, err = tx.Exec("INSERT INTO `weapons` VALUES(NULL, 'Алмазная бита', 10000, 100000, NOW());") + if err != nil { + return err + } + _, err = tx.Exec("INSERT INTO `weapons` VALUES(NULL, 'Криптонитовая бита', 100000, 500000, NOW());") + if err != nil { + return err + } + _, err = tx.Exec("INSERT INTO `weapons` VALUES(NULL, 'Буханка из пятёры', 1000000, 5000000, NOW());") + if err != nil { + return err + } + + return nil +} diff --git a/lib/migrations/5_create_locations.go b/lib/migrations/5_create_locations.go index ab7b967..76df703 100644 --- a/lib/migrations/5_create_locations.go +++ b/lib/migrations/5_create_locations.go @@ -24,29 +24,29 @@ func CreateLocationsUp(tx *sql.Tx) error { } // Insert locations - _, err2 := tx.Exec("INSERT INTO `locations` VALUES(NULL, ':evergreen_tree:', 'Лес', NOW());") - if err2 != nil { - return err2 + _, err = tx.Exec("INSERT INTO `locations` VALUES(NULL, ':evergreen_tree:', 'Лес', NOW());") + if err != nil { + return err } - _, err3 := tx.Exec("INSERT INTO `locations` VALUES(NULL, '⛰', 'Горы', NOW());") - if err3 != nil { - return err2 + _, err = tx.Exec("INSERT INTO `locations` VALUES(NULL, '⛰', 'Горы', NOW());") + if err != nil { + return err } - _, err4 := tx.Exec("INSERT INTO `locations` VALUES(NULL, ':rowboat:', 'Озеро', NOW());") - if err4 != nil { - return err2 + _, err = tx.Exec("INSERT INTO `locations` VALUES(NULL, ':rowboat:', 'Озеро', NOW());") + if err != nil { + return err } - _, err5 := tx.Exec("INSERT INTO `locations` VALUES(NULL, '🏙', 'Город', NOW());") - if err5 != nil { - return err2 + _, err = tx.Exec("INSERT INTO `locations` VALUES(NULL, '🏙', 'Город', NOW());") + if err != nil { + return err } - _, err6 := tx.Exec("INSERT INTO `locations` VALUES(NULL, '🏛', 'Катакомбы', NOW());") - if err6 != nil { - return err2 + _, err = tx.Exec("INSERT INTO `locations` VALUES(NULL, '🏛', 'Катакомбы', NOW());") + if err != nil { + return err } - _, err7 := tx.Exec("INSERT INTO `locations` VALUES(NULL, ':church:', 'Кладбище', NOW());") - if err7 != nil { - return err2 + _, err = tx.Exec("INSERT INTO `locations` VALUES(NULL, ':church:', 'Кладбище', NOW());") + if err != nil { + return err } return nil diff --git a/lib/migrations/6_create_elements.go b/lib/migrations/6_create_elements.go index 4fa9323..57fe9c8 100644 --- a/lib/migrations/6_create_elements.go +++ b/lib/migrations/6_create_elements.go @@ -25,53 +25,53 @@ func CreateElementsUp(tx *sql.Tx) error { } // Insert elements - _, err2 := tx.Exec("INSERT INTO `elements` VALUES(NULL, '👊', 'Боевой', 1, NOW());") - if err2 != nil { - return err2 + _, err = tx.Exec("INSERT INTO `elements` VALUES(NULL, '👊', 'Боевой', 1, NOW());") + if err != nil { + return err } - _, err3 := tx.Exec("INSERT INTO `elements` VALUES(NULL, '🌀', 'Летающий', 1, NOW());") - if err3 != nil { - return err3 + _, err = tx.Exec("INSERT INTO `elements` VALUES(NULL, '🌀', 'Летающий', 1, NOW());") + if err != nil { + return err } - _, err4 := tx.Exec("INSERT INTO `elements` VALUES(NULL, '💀', 'Ядовитый', 1, NOW());") - if err4 != nil { - return err4 + _, err = tx.Exec("INSERT INTO `elements` VALUES(NULL, '💀', 'Ядовитый', 1, NOW());") + if err != nil { + return err } - _, err5 := tx.Exec("INSERT INTO `elements` VALUES(NULL, '🗿', 'Каменный', 1, NOW());") - if err5 != nil { - return err5 + _, err = tx.Exec("INSERT INTO `elements` VALUES(NULL, '🗿', 'Каменный', 1, NOW());") + if err != nil { + return err } - _, err6 := tx.Exec("INSERT INTO `elements` VALUES(NULL, '🔥', 'Огненный', 2, NOW());") - if err6 != nil { - return err6 + _, err = tx.Exec("INSERT INTO `elements` VALUES(NULL, '🔥', 'Огненный', 2, NOW());") + if err != nil { + return err } - _, err7 := tx.Exec("INSERT INTO `elements` VALUES(NULL, '⚡', 'Электрический', 2, NOW());") - if err7 != nil { - return err7 + _, err = tx.Exec("INSERT INTO `elements` VALUES(NULL, '⚡', 'Электрический', 2, NOW());") + if err != nil { + return err } - _, err8 := tx.Exec("INSERT INTO `elements` VALUES(NULL, '💧', 'Водяной', 2, NOW());") - if err8 != nil { - return err8 + _, err = tx.Exec("INSERT INTO `elements` VALUES(NULL, '💧', 'Водяной', 2, NOW());") + if err != nil { + return err } - _, err9 := tx.Exec("INSERT INTO `elements` VALUES(NULL, '🍀', 'Травяной', 2, NOW());") - if err9 != nil { - return err9 + _, err = tx.Exec("INSERT INTO `elements` VALUES(NULL, '🍀', 'Травяной', 2, NOW());") + if err != nil { + return err } - _, err10 := tx.Exec("INSERT INTO `elements` VALUES(NULL, '💩', 'Шоколадный', 3, NOW());") - if err10 != nil { - return err10 + _, err = tx.Exec("INSERT INTO `elements` VALUES(NULL, '💩', 'Шоколадный', 3, NOW());") + if err != nil { + return err } - _, err11 := tx.Exec("INSERT INTO `elements` VALUES(NULL, '👁', 'Психический', 3, NOW());") - if err11 != nil { - return err11 + _, err = tx.Exec("INSERT INTO `elements` VALUES(NULL, '👁', 'Психический', 3, NOW());") + if err != nil { + return err } - _, err12 := tx.Exec("INSERT INTO `elements` VALUES(NULL, '👿', 'Темный', 3, NOW());") - if err12 != nil { - return err12 + _, err = tx.Exec("INSERT INTO `elements` VALUES(NULL, '👿', 'Темный', 3, NOW());") + if err != nil { + return err } - _, err13 := tx.Exec("INSERT INTO `elements` VALUES(NULL, '⌛', 'Времени', 1, NOW());") - if err13 != nil { - return err13 + _, err = tx.Exec("INSERT INTO `elements` VALUES(NULL, '⌛', 'Времени', 1, NOW());") + if err != nil { + return err } return nil diff --git a/lib/migrations/7_create_leagues.go b/lib/migrations/7_create_leagues.go index cd6fff8..412a469 100644 --- a/lib/migrations/7_create_leagues.go +++ b/lib/migrations/7_create_leagues.go @@ -24,17 +24,17 @@ func CreateLeaguesUp(tx *sql.Tx) error { } // Insert locations - _, err2 := tx.Exec("INSERT INTO `leagues` VALUES(NULL, ':u7533:', 'ИНСТИНКТ', NOW());") - if err2 != nil { - return err2 + _, err = tx.Exec("INSERT INTO `leagues` VALUES(NULL, ':u7533:', 'ИНСТИНКТ', NOW());") + if err != nil { + return err } - _, err3 := tx.Exec("INSERT INTO `leagues` VALUES(NULL, ':u6e80', 'ОТВАГА', NOW());") - if err3 != nil { - return err2 + _, err = tx.Exec("INSERT INTO `leagues` VALUES(NULL, ':u6e80', 'ОТВАГА', NOW());") + if err != nil { + return err } - _, err4 := tx.Exec("INSERT INTO `leagues` VALUES(NULL, ':u7a7a:', 'МИСТИКА', NOW());") - if err4 != nil { - return err2 + _, err = tx.Exec("INSERT INTO `leagues` VALUES(NULL, ':u7a7a:', 'МИСТИКА', NOW());") + if err != nil { + return err } return nil diff --git a/lib/migrations/migrations.go b/lib/migrations/migrations.go index 4948bbb..d6e99f7 100644 --- a/lib/migrations/migrations.go +++ b/lib/migrations/migrations.go @@ -43,6 +43,7 @@ func (m *Migrations) Init() { goose.AddNamedMigration("30_create_alarms.go", CreateAlarmsUp, CreateAlarmsUp) goose.AddNamedMigration("31_change_squads_table.go", ChangeSquadsTableUp, ChangeSquadsTableDown) goose.AddNamedMigration("32_add_is_active_to_pokememes.go", AddIsActiveToPokememesUp, AddIsActiveToPokememesDown) + goose.AddNamedMigration("33_delete_datamapped_tables.go", DeleteDataMappedTablesUp, DeleteDataMappedTablesDown) } // Migrate migrates database to current version diff --git a/lib/users/parsers.go b/lib/users/parsers.go index c45ce82..0190916 100644 --- a/lib/users/parsers.go +++ b/lib/users/parsers.go @@ -6,6 +6,7 @@ package users import ( "github.com/go-telegram-bot-api/telegram-bot-api" "regexp" + "source.wtfteam.pro/i2_bot/i2_bot/lib/datamapping" "source.wtfteam.pro/i2_bot/i2_bot/lib/dbmapping" "strconv" "strings" @@ -46,7 +47,7 @@ func (u *Users) ParseProfile(update *tgbotapi.Update, playerRaw *dbmapping.Playe profileRunesArray = append(profileRunesArray, []rune(profileStringsArray[i])) } - league := dbmapping.League{} + league := datamapping.League{} telegramNickname := update.Message.From.UserName nickname := "" diff --git a/lib/users/responders.go b/lib/users/responders.go index 0fe72a2..f282376 100644 --- a/lib/users/responders.go +++ b/lib/users/responders.go @@ -117,10 +117,10 @@ func (u *Users) ProfileMessage(update *tgbotapi.Update, playerRaw *dbmapping.Pla c.Log.Error(err.Error()) return c.Talkers.AnyMessageUnauthorized(update) } - league := dbmapping.League{} - err = c.Db.Get(&league, c.Db.Rebind("SELECT * FROM leagues WHERE id=?"), playerRaw.LeagueID) + league, err := c.DataCache.GetLeagueByID(playerRaw.LeagueID) if err != nil { - c.Log.Error(err) + c.Log.Error(err.Error()) + return c.Talkers.BotError(update) } level := dbmapping.Level{} err = c.Db.Get(&level, c.Db.Rebind("SELECT * FROM levels WHERE id=?"), profileRaw.LevelID)