some optimizations

This commit is contained in:
Dot-Rar 2020-04-14 17:01:50 +01:00
parent ce3e50725b
commit 66add26714
71 changed files with 464 additions and 1182 deletions

View File

@ -3,8 +3,8 @@ package manage
import ( import (
"github.com/TicketsBot/GoPanel/config" "github.com/TicketsBot/GoPanel/config"
"github.com/TicketsBot/GoPanel/database/table" "github.com/TicketsBot/GoPanel/database/table"
"github.com/TicketsBot/GoPanel/rpc/cache"
"github.com/TicketsBot/GoPanel/utils" "github.com/TicketsBot/GoPanel/utils"
"github.com/TicketsBot/GoPanel/utils/discord/objects"
"github.com/gin-gonic/contrib/sessions" "github.com/gin-gonic/contrib/sessions"
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"
"strconv" "strconv"
@ -18,7 +18,6 @@ func BlacklistHandler(ctx *gin.Context) {
defer store.Save() defer store.Save()
if utils.IsLoggedIn(store) { if utils.IsLoggedIn(store) {
userIdStr := store.Get("userid").(string)
userId, err := utils.GetUserId(store) userId, err := utils.GetUserId(store)
if err != nil { if err != nil {
ctx.String(500, err.Error()) ctx.String(500, err.Error())
@ -34,13 +33,7 @@ func BlacklistHandler(ctx *gin.Context) {
} }
// Get object for selected guild // Get object for selected guild
var guild objects.Guild guild, _ := cache.Instance.GetGuild(guildId, false)
for _, g := range table.GetGuilds(userIdStr) {
if g.Id == guildIdStr {
guild = g
break
}
}
// Verify the user has permissions to be here // Verify the user has permissions to be here
isAdmin := make(chan bool) isAdmin := make(chan bool)
@ -79,7 +72,7 @@ func BlacklistHandler(ctx *gin.Context) {
exists := targetId != 0 exists := targetId != 0
if exists { if exists {
if guild.OwnerId == strconv.Itoa(int(targetId)) || table.IsStaff(guildId, targetId) { // Prevent users from blacklisting staff if guild.OwnerId == targetId || table.IsStaff(guildId, targetId) { // Prevent users from blacklisting staff
isStaff = true isStaff = true
} else { } else {
if !utils.Contains(blacklistedIds, targetId) { // Prevent duplicates if !utils.Contains(blacklistedIds, targetId) { // Prevent duplicates

View File

@ -4,8 +4,8 @@ import (
"fmt" "fmt"
"github.com/TicketsBot/GoPanel/config" "github.com/TicketsBot/GoPanel/config"
"github.com/TicketsBot/GoPanel/database/table" "github.com/TicketsBot/GoPanel/database/table"
"github.com/TicketsBot/GoPanel/rpc/cache"
"github.com/TicketsBot/GoPanel/utils" "github.com/TicketsBot/GoPanel/utils"
"github.com/TicketsBot/GoPanel/utils/discord/objects"
"github.com/gin-gonic/contrib/sessions" "github.com/gin-gonic/contrib/sessions"
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"
"strconv" "strconv"
@ -19,7 +19,6 @@ func BlacklistRemoveHandler(ctx *gin.Context) {
defer store.Save() defer store.Save()
if utils.IsLoggedIn(store) { if utils.IsLoggedIn(store) {
userIdStr := store.Get("userid").(string)
userId, err := utils.GetUserId(store) userId, err := utils.GetUserId(store)
if err != nil { if err != nil {
ctx.String(500, err.Error()) ctx.String(500, err.Error())
@ -35,13 +34,7 @@ func BlacklistRemoveHandler(ctx *gin.Context) {
} }
// Get object for selected guild // Get object for selected guild
var guild objects.Guild guild, _ := cache.Instance.GetGuild(guildId, false)
for _, g := range table.GetGuilds(userIdStr) {
if g.Id == guildIdStr {
guild = g
break
}
}
// Verify the user has permissions to be here // Verify the user has permissions to be here
isAdmin := make(chan bool) isAdmin := make(chan bool)

View File

@ -3,8 +3,8 @@ package manage
import ( import (
"github.com/TicketsBot/GoPanel/config" "github.com/TicketsBot/GoPanel/config"
"github.com/TicketsBot/GoPanel/database/table" "github.com/TicketsBot/GoPanel/database/table"
"github.com/TicketsBot/GoPanel/rpc/cache"
"github.com/TicketsBot/GoPanel/utils" "github.com/TicketsBot/GoPanel/utils"
"github.com/TicketsBot/GoPanel/utils/discord/objects"
"github.com/gin-gonic/contrib/sessions" "github.com/gin-gonic/contrib/sessions"
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"
"strconv" "strconv"
@ -18,7 +18,6 @@ func LogsHandler(ctx *gin.Context) {
defer store.Save() defer store.Save()
if utils.IsLoggedIn(store) { if utils.IsLoggedIn(store) {
userIdStr := store.Get("userid").(string)
userId, err := utils.GetUserId(store) userId, err := utils.GetUserId(store)
if err != nil { if err != nil {
ctx.String(500, err.Error()) ctx.String(500, err.Error())
@ -43,13 +42,7 @@ func LogsHandler(ctx *gin.Context) {
} }
// Get object for selected guild // Get object for selected guild
var guild objects.Guild guild, _ := cache.Instance.GetGuild(guildId, false)
for _, g := range table.GetGuilds(userIdStr) {
if g.Id == guildIdStr {
guild = g
break
}
}
// Verify the user has permissions to be here // Verify the user has permissions to be here
isAdmin := make(chan bool) isAdmin := make(chan bool)

View File

@ -2,13 +2,14 @@ package manage
import ( import (
"fmt" "fmt"
"github.com/TicketsBot/GoPanel/cache"
"github.com/TicketsBot/GoPanel/config" "github.com/TicketsBot/GoPanel/config"
"github.com/TicketsBot/GoPanel/database/table" "github.com/TicketsBot/GoPanel/database/table"
"github.com/TicketsBot/GoPanel/messagequeue"
"github.com/TicketsBot/GoPanel/rpc/cache"
"github.com/TicketsBot/GoPanel/utils" "github.com/TicketsBot/GoPanel/utils"
"github.com/TicketsBot/GoPanel/utils/discord/objects"
"github.com/gin-gonic/contrib/sessions" "github.com/gin-gonic/contrib/sessions"
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"
"github.com/rxdn/gdl/objects/channel"
"strconv" "strconv"
"strings" "strings"
) )
@ -21,7 +22,6 @@ func PanelCreateHandler(ctx *gin.Context) {
defer store.Save() defer store.Save()
if utils.IsLoggedIn(store) { if utils.IsLoggedIn(store) {
userIdStr := store.Get("userid").(string)
userId, err := utils.GetUserId(store) userId, err := utils.GetUserId(store)
if err != nil { if err != nil {
ctx.String(500, err.Error()) ctx.String(500, err.Error())
@ -37,13 +37,7 @@ func PanelCreateHandler(ctx *gin.Context) {
} }
// Get object for selected guild // Get object for selected guild
var guild objects.Guild guild, _ := cache.Instance.GetGuild(guildId, false)
for _, g := range table.GetGuilds(userIdStr) {
if g.Id == guildIdStr {
guild = g
break
}
}
// Verify the user has permissions to be here // Verify the user has permissions to be here
isAdmin := make(chan bool) isAdmin := make(chan bool)
@ -150,7 +144,7 @@ func PanelCreateHandler(ctx *gin.Context) {
ReactionEmote: emoji, ReactionEmote: emoji,
} }
go cache.Client.PublishPanelCreate(settings) go messagequeue.Client.PublishPanelCreate(settings)
ctx.Redirect(302, fmt.Sprintf("/manage/%d/panels?created=true&validColour=%t", guildId, validColour)) ctx.Redirect(302, fmt.Sprintf("/manage/%d/panels?created=true&validColour=%t", guildId, validColour))
} else { } else {
@ -159,15 +153,10 @@ func PanelCreateHandler(ctx *gin.Context) {
} }
func validateChannel(guildId, channelId uint64, res chan bool) { func validateChannel(guildId, channelId uint64, res chan bool) {
// Get channels from DB
channelsChan := make(chan []table.Channel)
go table.GetCachedChannelsByGuild(guildId, channelsChan)
channels := <-channelsChan
// Compare channel IDs // Compare channel IDs
validChannel := false validChannel := false
for _, guildChannel := range channels { for _, guildChannel := range cache.Instance.GetGuildChannels(guildId) {
if guildChannel.ChannelId == channelId { if guildChannel.Id == channelId {
validChannel = true validChannel = true
break break
} }
@ -177,15 +166,10 @@ func validateChannel(guildId, channelId uint64, res chan bool) {
} }
func validateCategory(guildId, categoryId uint64, res chan bool) { func validateCategory(guildId, categoryId uint64, res chan bool) {
// Get channels from DB // Compare ch IDs
categoriesChan := make(chan []table.Channel)
go table.GetCategories(guildId, categoriesChan)
categories := <-categoriesChan
// Compare channel IDs
validCategory := false validCategory := false
for _, category := range categories { for _, ch := range cache.Instance.GetGuildChannels(guildId) {
if category.ChannelId == categoryId { if ch.Type == channel.ChannelTypeGuildCategory && ch.Id == categoryId {
validCategory = true validCategory = true
break break
} }

View File

@ -4,8 +4,8 @@ import (
"fmt" "fmt"
"github.com/TicketsBot/GoPanel/config" "github.com/TicketsBot/GoPanel/config"
"github.com/TicketsBot/GoPanel/database/table" "github.com/TicketsBot/GoPanel/database/table"
"github.com/TicketsBot/GoPanel/rpc/cache"
"github.com/TicketsBot/GoPanel/utils" "github.com/TicketsBot/GoPanel/utils"
"github.com/TicketsBot/GoPanel/utils/discord/objects"
"github.com/gin-gonic/contrib/sessions" "github.com/gin-gonic/contrib/sessions"
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"
"strconv" "strconv"
@ -19,7 +19,6 @@ func PanelDeleteHandler(ctx *gin.Context) {
defer store.Save() defer store.Save()
if utils.IsLoggedIn(store) { if utils.IsLoggedIn(store) {
userIdStr := store.Get("userid").(string)
userId, err := utils.GetUserId(store) userId, err := utils.GetUserId(store)
if err != nil { if err != nil {
ctx.String(500, err.Error()) ctx.String(500, err.Error())
@ -41,13 +40,7 @@ func PanelDeleteHandler(ctx *gin.Context) {
} }
// Get object for selected guild // Get object for selected guild
var guild objects.Guild guild, _ := cache.Instance.GetGuild(guildId, false)
for _, g := range table.GetGuilds(userIdStr) {
if g.Id == guildIdStr {
guild = g
break
}
}
// Verify the user has permissions to be here // Verify the user has permissions to be here
isAdmin := make(chan bool) isAdmin := make(chan bool)

View File

@ -3,8 +3,8 @@ package manage
import ( import (
"github.com/TicketsBot/GoPanel/config" "github.com/TicketsBot/GoPanel/config"
"github.com/TicketsBot/GoPanel/database/table" "github.com/TicketsBot/GoPanel/database/table"
"github.com/TicketsBot/GoPanel/rpc/cache"
"github.com/TicketsBot/GoPanel/utils" "github.com/TicketsBot/GoPanel/utils"
"github.com/TicketsBot/GoPanel/utils/discord/objects"
"github.com/gin-gonic/contrib/sessions" "github.com/gin-gonic/contrib/sessions"
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"
"strconv" "strconv"
@ -26,7 +26,6 @@ func PanelHandler(ctx *gin.Context) {
defer store.Save() defer store.Save()
if utils.IsLoggedIn(store) { if utils.IsLoggedIn(store) {
userIdStr := store.Get("userid").(string)
userId, err := utils.GetUserId(store) userId, err := utils.GetUserId(store)
if err != nil { if err != nil {
ctx.String(500, err.Error()) ctx.String(500, err.Error())
@ -42,13 +41,7 @@ func PanelHandler(ctx *gin.Context) {
} }
// Get object for selected guild // Get object for selected guild
var guild objects.Guild guild, _ := cache.Instance.GetGuild(guildId, false)
for _, g := range table.GetGuilds(userIdStr) {
if g.Id == guildIdStr {
guild = g
break
}
}
// Verify the user has permissions to be here // Verify the user has permissions to be here
isAdmin := make(chan bool) isAdmin := make(chan bool)
@ -64,12 +57,7 @@ func PanelHandler(ctx *gin.Context) {
panels := <-panelChan panels := <-panelChan
// Get channels // Get channels
channelsChan := make(chan []table.Channel) channels := cache.Instance.GetGuildChannels(guildId)
go table.GetCachedChannelsByGuild(guildId, channelsChan)
channels := <-channelsChan
// Get default panel settings
settings := table.GetPanelSettings(guildId)
// Convert to wrapped panels // Convert to wrapped panels
wrappedPanels := make([]wrappedPanel, 0) wrappedPanels := make([]wrappedPanel, 0)
@ -81,18 +69,11 @@ func PanelHandler(ctx *gin.Context) {
CategoryName: "", CategoryName: "",
} }
if panel.Title == "" {
wrapper.Title = settings.Title
}
if panel.Content == "" {
wrapper.Content = settings.Content
}
// Get channel name & category name // Get channel name & category name
for _, guildChannel := range channels { for _, guildChannel := range channels {
if guildChannel.ChannelId == panel.ChannelId { if guildChannel.Id == panel.ChannelId {
wrapper.ChannelName = guildChannel.Name wrapper.ChannelName = guildChannel.Name
} else if guildChannel.ChannelId == panel.TargetCategory { } else if guildChannel.Id == panel.TargetCategory {
wrapper.CategoryName = guildChannel.Name wrapper.CategoryName = guildChannel.Name
} }
} }
@ -100,22 +81,6 @@ func PanelHandler(ctx *gin.Context) {
wrappedPanels = append(wrappedPanels, wrapper) wrappedPanels = append(wrappedPanels, wrapper)
} }
// Format channels to be text channels only
channelMap := make(map[uint64]string)
for _, channel := range channels {
if channel.Type == 0 {
channelMap[channel.ChannelId] = channel.Name
}
}
// Get categories & format
categories := make(map[uint64]string)
for _, channel := range channels {
if channel.Type == 4 {
categories[channel.ChannelId] = channel.Name
}
}
// Get is premium // Get is premium
isPremiumChan := make(chan bool) isPremiumChan := make(chan bool)
go utils.IsPremiumGuild(store, guildId, isPremiumChan) go utils.IsPremiumGuild(store, guildId, isPremiumChan)
@ -130,8 +95,7 @@ func PanelHandler(ctx *gin.Context) {
"panelcount": len(panels), "panelcount": len(panels),
"premium": isPremium, "premium": isPremium,
"panels": wrappedPanels, "panels": wrappedPanels,
"channels": channelMap, "channels": channels,
"categories": categories,
"validTitle": ctx.Query("validTitle") != "true", "validTitle": ctx.Query("validTitle") != "true",
"validContent": ctx.Query("validContent") != "false", "validContent": ctx.Query("validContent") != "false",

View File

@ -4,12 +4,12 @@ import (
"fmt" "fmt"
"github.com/TicketsBot/GoPanel/config" "github.com/TicketsBot/GoPanel/config"
"github.com/TicketsBot/GoPanel/database/table" "github.com/TicketsBot/GoPanel/database/table"
"github.com/TicketsBot/GoPanel/rpc/cache"
"github.com/TicketsBot/GoPanel/rpc/ratelimit"
"github.com/TicketsBot/GoPanel/utils" "github.com/TicketsBot/GoPanel/utils"
"github.com/TicketsBot/GoPanel/utils/discord"
"github.com/TicketsBot/GoPanel/utils/discord/endpoints/channel"
"github.com/TicketsBot/GoPanel/utils/discord/objects"
"github.com/gin-gonic/contrib/sessions" "github.com/gin-gonic/contrib/sessions"
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"
"github.com/rxdn/gdl/rest"
"strconv" "strconv"
) )
@ -21,7 +21,6 @@ func SendMessage(ctx *gin.Context) {
defer store.Save() defer store.Save()
if utils.IsLoggedIn(store) { if utils.IsLoggedIn(store) {
userIdStr := store.Get("userid").(string)
userId, err := utils.GetUserId(store) userId, err := utils.GetUserId(store)
if err != nil { if err != nil {
ctx.String(500, err.Error()) ctx.String(500, err.Error())
@ -37,13 +36,7 @@ func SendMessage(ctx *gin.Context) {
} }
// Get object for selected guild // Get object for selected guild
var guild objects.Guild guild, _ := cache.Instance.GetGuild(guildId, false)
for _, g := range table.GetGuilds(userIdStr) {
if g.Id == guildIdStr {
guild = g
break
}
}
// Verify the user has permissions to be here // Verify the user has permissions to be here
isAdmin := make(chan bool) isAdmin := make(chan bool)
@ -65,18 +58,13 @@ func SendMessage(ctx *gin.Context) {
return return
} }
contentType := discord.ApplicationJson
if exists { if exists {
content := fmt.Sprintf("**%s**: %s", store.Get("name").(string), ctx.PostForm("message")) content := fmt.Sprintf("**%s**: %s", store.Get("name").(string), ctx.PostForm("message"))
if len(content) > 2000 { if len(content) > 2000 {
content = content[0:1999] content = content[0:1999]
} }
endpoint := channel.CreateMessage(int(ticket.Channel)) _, _ = rest.CreateMessage(config.Conf.Bot.Token, ratelimit.Ratelimiter, ticket.Channel, rest.CreateMessageData{Content: content})
err, _ = endpoint.Request(store, &contentType, channel.CreateMessageBody{
Content: content,
}, nil)
} }
} else { } else {
ctx.Redirect(302, "/login") ctx.Redirect(302, "/login")

View File

@ -2,13 +2,13 @@ package manage
import ( import (
"fmt" "fmt"
"github.com/TicketsBot/GoPanel/cache"
"github.com/TicketsBot/GoPanel/config" "github.com/TicketsBot/GoPanel/config"
"github.com/TicketsBot/GoPanel/database/table" "github.com/TicketsBot/GoPanel/database/table"
"github.com/TicketsBot/GoPanel/rpc/cache"
"github.com/TicketsBot/GoPanel/utils" "github.com/TicketsBot/GoPanel/utils"
"github.com/TicketsBot/GoPanel/utils/discord/objects"
"github.com/gin-gonic/contrib/sessions" "github.com/gin-gonic/contrib/sessions"
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"
"github.com/rxdn/gdl/objects/channel"
"strconv" "strconv"
) )
@ -20,7 +20,6 @@ func SettingsHandler(ctx *gin.Context) {
defer store.Save() defer store.Save()
if utils.IsLoggedIn(store) { if utils.IsLoggedIn(store) {
userIdStr := store.Get("userid").(string)
userId, err := utils.GetUserId(store) userId, err := utils.GetUserId(store)
if err != nil { if err != nil {
ctx.String(500, err.Error()) ctx.String(500, err.Error())
@ -36,21 +35,14 @@ func SettingsHandler(ctx *gin.Context) {
} }
// Check the bot is in the guild // Check the bot is in the guild
isInGuild := make(chan bool) _, isInGuild := cache.Instance.GetGuild(guildId, false)
go cache.Client.GuildExists(guildIdStr, isInGuild) if !isInGuild {
if !<-isInGuild {
ctx.Redirect(302, fmt.Sprintf("https://invite.ticketsbot.net/?guild_id=%s&disable_guild_select=true&response_type=code&scope=bot%%20identify&redirect_uri=%s", guildIdStr, config.Conf.Server.BaseUrl)) ctx.Redirect(302, fmt.Sprintf("https://invite.ticketsbot.net/?guild_id=%s&disable_guild_select=true&response_type=code&scope=bot%%20identify&redirect_uri=%s", guildIdStr, config.Conf.Server.BaseUrl))
return return
} }
// Get object for selected guild // Get object for selected guild
var guild objects.Guild guild, _ := cache.Instance.GetGuild(guildId, false)
for _, g := range table.GetGuilds(userIdStr) {
if g.Id == guildIdStr {
guild = g
break
}
}
// Verify the user has permissions to be here // Verify the user has permissions to be here
isAdmin := make(chan bool) isAdmin := make(chan bool)
@ -72,21 +64,15 @@ func SettingsHandler(ctx *gin.Context) {
go table.GetTicketNamingScheme(guildId, namingSchemeChan) go table.GetTicketNamingScheme(guildId, namingSchemeChan)
namingScheme := <-namingSchemeChan namingScheme := <-namingSchemeChan
// /users/@me/guilds doesn't return channels, so we have to get them for the specific guild // get guild channels from cache
channelsChan := make(chan []table.Channel) channels := cache.Instance.GetGuildChannels(guildId)
go table.GetCachedChannelsByGuild(guildId, channelsChan)
channels := <-channelsChan
// Get a list of actual category IDs // separate out categories
categoriesChan := make(chan []table.Channel) categories := make([]channel.Channel, 0)
go table.GetCategories(guildId, categoriesChan) for _, ch := range channels {
categories := <-categoriesChan if ch.Type == channel.ChannelTypeGuildCategory {
categories = append(categories, ch)
// Archive channel }
// Create a list of IDs
var channelIds []string
for _, c := range channels {
channelIds = append(channelIds, strconv.Itoa(int(c.ChannelId)))
} }
panelSettings := table.GetPanelSettings(guildId) panelSettings := table.GetPanelSettings(guildId)
@ -101,26 +87,26 @@ func SettingsHandler(ctx *gin.Context) {
invalidTicketLimit := ctx.Query("validTicketLimit") == "false" invalidTicketLimit := ctx.Query("validTicketLimit") == "false"
ctx.HTML(200, "manage/settings", gin.H{ ctx.HTML(200, "manage/settings", gin.H{
"name": store.Get("name").(string), "name": store.Get("name").(string),
"guildId": guildIdStr, "guildId": guildIdStr,
"avatar": store.Get("avatar").(string), "avatar": store.Get("avatar").(string),
"prefix": prefix, "prefix": prefix,
"welcomeMessage": welcomeMessage, "welcomeMessage": welcomeMessage,
"ticketLimit": limit, "ticketLimit": limit,
"categories": categories, "categories": categories,
"activecategory": categoryId, "activecategory": categoryId,
"channels": channels, "channels": channels,
"archivechannel": archiveChannel, "archivechannel": archiveChannel,
"invalidPrefix": invalidPrefix, "invalidPrefix": invalidPrefix,
"invalidWelcomeMessage": invalidWelcomeMessage, "invalidWelcomeMessage": invalidWelcomeMessage,
"invalidTicketLimit": invalidTicketLimit, "invalidTicketLimit": invalidTicketLimit,
"csrf": store.Get("csrf").(string), "csrf": store.Get("csrf").(string),
"pingEveryone": pingEveryone, "pingEveryone": pingEveryone,
"paneltitle": panelSettings.Title, "paneltitle": panelSettings.Title,
"panelcontent": panelSettings.Content, "panelcontent": panelSettings.Content,
"panelcolour": strconv.FormatInt(int64(panelSettings.Colour), 16), "panelcolour": strconv.FormatInt(int64(panelSettings.Colour), 16),
"usersCanClose": usersCanClose, "usersCanClose": usersCanClose,
"namingScheme": string(namingScheme), "namingScheme": string(namingScheme),
}) })
} else { } else {
ctx.Redirect(302, "/login") ctx.Redirect(302, "/login")

View File

@ -2,11 +2,11 @@ package manage
import ( import (
"fmt" "fmt"
"github.com/TicketsBot/GoPanel/cache"
"github.com/TicketsBot/GoPanel/config" "github.com/TicketsBot/GoPanel/config"
"github.com/TicketsBot/GoPanel/database/table" "github.com/TicketsBot/GoPanel/database/table"
"github.com/TicketsBot/GoPanel/messagequeue"
"github.com/TicketsBot/GoPanel/rpc/cache"
"github.com/TicketsBot/GoPanel/utils" "github.com/TicketsBot/GoPanel/utils"
"github.com/TicketsBot/GoPanel/utils/discord/objects"
"github.com/gin-gonic/contrib/sessions" "github.com/gin-gonic/contrib/sessions"
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"
"strconv" "strconv"
@ -20,7 +20,6 @@ func TicketCloseHandler(ctx *gin.Context) {
defer store.Save() defer store.Save()
if utils.IsLoggedIn(store) { if utils.IsLoggedIn(store) {
userIdStr := store.Get("userid").(string)
userId, err := utils.GetUserId(store) userId, err := utils.GetUserId(store)
if err != nil { if err != nil {
ctx.String(500, err.Error()) ctx.String(500, err.Error())
@ -36,13 +35,7 @@ func TicketCloseHandler(ctx *gin.Context) {
} }
// Get object for selected guild // Get object for selected guild
var guild objects.Guild guild, _ := cache.Instance.GetGuild(guildId, false)
for _, g := range table.GetGuilds(userIdStr) {
if g.Id == guildIdStr {
guild = g
break
}
}
// Verify the user has permissions to be here // Verify the user has permissions to be here
isAdmin := make(chan bool) isAdmin := make(chan bool)
@ -78,7 +71,7 @@ func TicketCloseHandler(ctx *gin.Context) {
reason = reason[:255] reason = reason[:255]
} }
go cache.Client.PublishTicketClose(ticket.Uuid, userId, reason) go messagequeue.Client.PublishTicketClose(ticket.Uuid, userId, reason)
ctx.Redirect(302, fmt.Sprintf("/manage/%d/tickets", guildId)) ctx.Redirect(302, fmt.Sprintf("/manage/%d/tickets", guildId))
} else { } else {

View File

@ -3,8 +3,8 @@ package manage
import ( import (
"github.com/TicketsBot/GoPanel/config" "github.com/TicketsBot/GoPanel/config"
"github.com/TicketsBot/GoPanel/database/table" "github.com/TicketsBot/GoPanel/database/table"
"github.com/TicketsBot/GoPanel/rpc/cache"
"github.com/TicketsBot/GoPanel/utils" "github.com/TicketsBot/GoPanel/utils"
"github.com/TicketsBot/GoPanel/utils/discord/objects"
"github.com/gin-gonic/contrib/sessions" "github.com/gin-gonic/contrib/sessions"
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"
"strconv" "strconv"
@ -19,7 +19,6 @@ func TicketListHandler(ctx *gin.Context) {
defer store.Save() defer store.Save()
if utils.IsLoggedIn(store) { if utils.IsLoggedIn(store) {
userIdStr := store.Get("userid").(string)
userId, err := utils.GetUserId(store) userId, err := utils.GetUserId(store)
if err != nil { if err != nil {
ctx.String(500, err.Error()) ctx.String(500, err.Error())
@ -35,13 +34,7 @@ func TicketListHandler(ctx *gin.Context) {
} }
// Get object for selected guild // Get object for selected guild
var guild objects.Guild guild, _ := cache.Instance.GetGuild(guildId, false)
for _, g := range table.GetGuilds(userIdStr) {
if g.Id == guildIdStr {
guild = g
break
}
}
// Verify the user has permissions to be here // Verify the user has permissions to be here
isAdmin := make(chan bool) isAdmin := make(chan bool)

View File

@ -4,11 +4,12 @@ import (
"fmt" "fmt"
"github.com/TicketsBot/GoPanel/config" "github.com/TicketsBot/GoPanel/config"
"github.com/TicketsBot/GoPanel/database/table" "github.com/TicketsBot/GoPanel/database/table"
"github.com/TicketsBot/GoPanel/rpc/cache"
"github.com/TicketsBot/GoPanel/rpc/ratelimit"
"github.com/TicketsBot/GoPanel/utils" "github.com/TicketsBot/GoPanel/utils"
"github.com/TicketsBot/GoPanel/utils/discord/endpoints/channel"
"github.com/TicketsBot/GoPanel/utils/discord/objects"
"github.com/gin-gonic/contrib/sessions" "github.com/gin-gonic/contrib/sessions"
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"
"github.com/rxdn/gdl/rest"
"regexp" "regexp"
"strconv" "strconv"
"strings" "strings"
@ -24,7 +25,6 @@ func TicketViewHandler(ctx *gin.Context) {
defer store.Save() defer store.Save()
if utils.IsLoggedIn(store) { if utils.IsLoggedIn(store) {
userIdStr := store.Get("userid").(string)
userId, err := utils.GetUserId(store) userId, err := utils.GetUserId(store)
if err != nil { if err != nil {
ctx.String(500, err.Error()) ctx.String(500, err.Error())
@ -40,13 +40,7 @@ func TicketViewHandler(ctx *gin.Context) {
} }
// Get object for selected guild // Get object for selected guild
var guild objects.Guild guild, _ := cache.Instance.GetGuild(guildId, false)
for _, g := range table.GetGuilds(userIdStr) {
if g.Id == guildIdStr {
guild = g
break
}
}
// Verify the user has permissions to be here // Verify the user has permissions to be here
isAdmin := make(chan bool) isAdmin := make(chan bool)
@ -76,16 +70,7 @@ func TicketViewHandler(ctx *gin.Context) {
} }
// Get messages // Get messages
var messages []objects.Message messages, err := rest.GetChannelMessages(config.Conf.Bot.Token, ratelimit.Ratelimiter, ticket.Channel, rest.GetChannelMessagesData{Limit: 100})
// We want to show users error messages so they can report them
isError := false
var errorMessage string
endpoint := channel.GetChannelMessages(int(ticket.Channel))
if err, _ = endpoint.Request(store, nil, nil, &messages); err != nil {
isError = true
errorMessage = err.Error()
}
// Format messages, exclude unneeded data // Format messages, exclude unneeded data
var messagesFormatted []map[string]interface{} var messagesFormatted []map[string]interface{}
@ -96,7 +81,8 @@ func TicketViewHandler(ctx *gin.Context) {
match := MentionRegex.FindAllStringSubmatch(content, -1) match := MentionRegex.FindAllStringSubmatch(content, -1)
for _, mention := range match { for _, mention := range match {
if len(mention) >= 2 { if len(mention) >= 2 {
mentionedId, err := strconv.ParseUint(mention[1], 10, 64); if err != nil { mentionedId, err := strconv.ParseUint(mention[1], 10, 64)
if err != nil {
continue continue
} }
@ -108,7 +94,7 @@ func TicketViewHandler(ctx *gin.Context) {
messagesFormatted = append(messagesFormatted, map[string]interface{}{ messagesFormatted = append(messagesFormatted, map[string]interface{}{
"username": message.Author.Username, "username": message.Author.Username,
"content": content, "content": content,
}) })
} }
@ -116,18 +102,18 @@ func TicketViewHandler(ctx *gin.Context) {
go utils.IsPremiumGuild(store, guildId, premium) go utils.IsPremiumGuild(store, guildId, premium)
ctx.HTML(200, "manage/ticketview", gin.H{ ctx.HTML(200, "manage/ticketview", gin.H{
"name": store.Get("name").(string), "name": store.Get("name").(string),
"guildId": guildIdStr, "guildId": guildIdStr,
"csrf": store.Get("csrf").(string), "csrf": store.Get("csrf").(string),
"avatar": store.Get("avatar").(string), "avatar": store.Get("avatar").(string),
"baseUrl": config.Conf.Server.BaseUrl, "baseUrl": config.Conf.Server.BaseUrl,
"isError": isError, "isError": err != nil,
"error": errorMessage, "error": err.Error(),
"messages": messagesFormatted, "messages": messagesFormatted,
"ticketId": ticket.TicketId, "ticketId": ticket.TicketId,
"uuid": ticket.Uuid, "uuid": ticket.Uuid,
"include_mock": true, "include_mock": true,
"premium": <-premium, "premium": <-premium,
}) })
} else { } else {
ctx.Redirect(302, "/login") ctx.Redirect(302, "/login")

View File

@ -4,10 +4,11 @@ import (
"fmt" "fmt"
"github.com/TicketsBot/GoPanel/config" "github.com/TicketsBot/GoPanel/config"
"github.com/TicketsBot/GoPanel/database/table" "github.com/TicketsBot/GoPanel/database/table"
"github.com/TicketsBot/GoPanel/rpc/cache"
"github.com/TicketsBot/GoPanel/utils" "github.com/TicketsBot/GoPanel/utils"
"github.com/TicketsBot/GoPanel/utils/discord/objects"
"github.com/gin-gonic/contrib/sessions" "github.com/gin-gonic/contrib/sessions"
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"
"github.com/rxdn/gdl/objects/channel"
"strconv" "strconv"
) )
@ -19,7 +20,6 @@ func UpdateSettingsHandler(ctx *gin.Context) {
defer store.Save() defer store.Save()
if utils.IsLoggedIn(store) { if utils.IsLoggedIn(store) {
userIdStr := store.Get("userid").(string)
userId, err := utils.GetUserId(store) userId, err := utils.GetUserId(store)
if err != nil { if err != nil {
ctx.String(500, err.Error()) ctx.String(500, err.Error())
@ -35,13 +35,7 @@ func UpdateSettingsHandler(ctx *gin.Context) {
} }
// Get object for selected guild // Get object for selected guild
var guild objects.Guild guild, _ := cache.Instance.GetGuild(guildId, false)
for _, g := range table.GetGuilds(userIdStr) {
if g.Id == guildIdStr {
guild = g
break
}
}
// Verify the user has permissions to be here // Verify the user has permissions to be here
isAdmin := make(chan bool) isAdmin := make(chan bool)
@ -95,39 +89,30 @@ func UpdateSettingsHandler(ctx *gin.Context) {
table.UpdatePingEveryone(guildId, pingEveryone) table.UpdatePingEveryone(guildId, pingEveryone)
// Get a list of actual category IDs // Get a list of actual category IDs
categories := make(chan []table.Channel) channels := cache.Instance.GetGuildChannels(guildId)
go table.GetCategories(guildId, categories)
// Convert to category IDs
var categoryIds []string
for _, category := range <-categories {
categoryIds = append(categoryIds, strconv.Itoa(int(category.ChannelId)))
}
// Update category // Update category
categoryStr := ctx.PostForm("category") if categoryId, err := strconv.ParseUint(ctx.PostForm("category"), 10, 64); err == nil {
if utils.Contains(categoryIds, categoryStr) { for _, ch := range channels {
// Error is impossible, as we check it's a valid channel already if ch.Id == categoryId { // compare ID
category, _ := strconv.ParseUint(categoryStr, 10, 64) if ch.Type == channel.ChannelTypeGuildCategory { // verify we're dealing with a category
table.UpdateChannelCategory(guildId, category) table.UpdateChannelCategory(guildId, categoryId)
}
break
}
}
} }
// Archive channel // Archive channel
// Create a list of IDs if archiveChannelId, err := strconv.ParseUint(ctx.PostForm("archivechannel"), 10, 64); err == nil {
channelsChan := make(chan []table.Channel) for _, ch := range channels {
go table.GetCachedChannelsByGuild(guildId, channelsChan) if ch.Id == archiveChannelId { // compare ID
channels := <-channelsChan if ch.Type == channel.ChannelTypeGuildText { // verify channel type
table.UpdateArchiveChannel(guildId, archiveChannelId)
var channelIds []uint64 }
for _, channel := range channels { break
channelIds = append(channelIds, channel.ChannelId) }
} }
// Update or archive channel
archiveChannelStr := ctx.PostForm("archivechannel")
archiveChannelId, err := strconv.ParseUint(archiveChannelStr, 10, 64)
if err == nil && utils.Contains(channelIds, archiveChannelId) {
table.UpdateArchiveChannel(guildId, archiveChannelId)
} }
// Users can close // Users can close

View File

@ -4,8 +4,8 @@ import (
"fmt" "fmt"
"github.com/TicketsBot/GoPanel/config" "github.com/TicketsBot/GoPanel/config"
"github.com/TicketsBot/GoPanel/database/table" "github.com/TicketsBot/GoPanel/database/table"
"github.com/TicketsBot/GoPanel/rpc/cache"
"github.com/TicketsBot/GoPanel/utils" "github.com/TicketsBot/GoPanel/utils"
"github.com/TicketsBot/GoPanel/utils/discord/objects"
"github.com/gin-gonic/contrib/sessions" "github.com/gin-gonic/contrib/sessions"
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"
"io/ioutil" "io/ioutil"
@ -22,7 +22,6 @@ func LogViewHandler(ctx *gin.Context) {
defer store.Save() defer store.Save()
if utils.IsLoggedIn(store) { if utils.IsLoggedIn(store) {
userIdStr := store.Get("userid").(string)
userId, err := utils.GetUserId(store) userId, err := utils.GetUserId(store)
if err != nil { if err != nil {
ctx.String(500, err.Error()) ctx.String(500, err.Error())
@ -38,13 +37,7 @@ func LogViewHandler(ctx *gin.Context) {
} }
// Get object for selected guild // Get object for selected guild
var guild objects.Guild guild, _ := cache.Instance.GetGuild(guildId, false)
for _, g := range table.GetGuilds(userIdStr) {
if g.Id == guildIdStr {
guild = g
break
}
}
// Verify the user has permissions to be here // Verify the user has permissions to be here
isAdmin := make(chan bool) isAdmin := make(chan bool)

View File

@ -4,14 +4,15 @@ import (
"bytes" "bytes"
"encoding/json" "encoding/json"
"fmt" "fmt"
"github.com/TicketsBot/GoPanel/config"
"github.com/TicketsBot/GoPanel/database/table" "github.com/TicketsBot/GoPanel/database/table"
"github.com/TicketsBot/GoPanel/rpc/cache"
"github.com/TicketsBot/GoPanel/rpc/ratelimit"
"github.com/TicketsBot/GoPanel/utils" "github.com/TicketsBot/GoPanel/utils"
"github.com/TicketsBot/GoPanel/utils/discord"
"github.com/TicketsBot/GoPanel/utils/discord/endpoints/channel"
"github.com/TicketsBot/GoPanel/utils/discord/objects"
"github.com/gin-gonic/contrib/sessions" "github.com/gin-gonic/contrib/sessions"
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"
"github.com/gorilla/websocket" "github.com/gorilla/websocket"
"github.com/rxdn/gdl/rest"
"net/http" "net/http"
"strconv" "strconv"
"sync" "sync"
@ -84,8 +85,6 @@ func WebChatWs(ctx *gin.Context) {
SocketsLock.Lock() SocketsLock.Lock()
Sockets = append(Sockets, socket) Sockets = append(Sockets, socket)
SocketsLock.Unlock() SocketsLock.Unlock()
userIdStr := store.Get("userid").(string)
userId, err := utils.GetUserId(store) userId, err := utils.GetUserId(store)
if err != nil { if err != nil {
conn.Close() conn.Close()
@ -127,13 +126,7 @@ func WebChatWs(ctx *gin.Context) {
} }
// Get object for selected guild // Get object for selected guild
var guild objects.Guild guild, _ := cache.Instance.GetGuild(guildIdParsed, false)
for _, g := range table.GetGuilds(userIdStr) {
if g.Id == guildId {
guild = g
break
}
}
// Verify the user has permissions to be here // Verify the user has permissions to be here
isAdmin := make(chan bool) isAdmin := make(chan bool)
@ -164,8 +157,6 @@ func WebChatWs(ctx *gin.Context) {
ticket := <-ticketChan ticket := <-ticketChan
exists := ticket != table.Ticket{} exists := ticket != table.Ticket{}
contentType := discord.ApplicationJson
if exists { if exists {
content := data content := data
if len(content) > 2000 { if len(content) > 2000 {
@ -188,10 +179,7 @@ func WebChatWs(ctx *gin.Context) {
content = content[0:1999] content = content[0:1999]
} }
endpoint := channel.CreateMessage(int(ticket.Channel)) _, _ = rest.CreateMessage(config.Conf.Bot.Token, ratelimit.Ratelimiter, ticket.Channel, rest.CreateMessageData{Content: content})
err, _ = endpoint.Request(store, &contentType, channel.CreateMessageBody{
Content: content,
}, nil)
} }
} }
} }

View File

@ -4,17 +4,16 @@ import (
"encoding/base64" "encoding/base64"
"encoding/json" "encoding/json"
"fmt" "fmt"
"github.com/TicketsBot/GoPanel/cache"
"github.com/TicketsBot/GoPanel/config" "github.com/TicketsBot/GoPanel/config"
"github.com/TicketsBot/GoPanel/database/table" "github.com/TicketsBot/GoPanel/database/table"
"github.com/TicketsBot/GoPanel/utils" "github.com/TicketsBot/GoPanel/utils"
"github.com/TicketsBot/GoPanel/utils/discord" "github.com/TicketsBot/GoPanel/utils/discord"
"github.com/TicketsBot/GoPanel/utils/discord/endpoints/user" userEndpoint "github.com/TicketsBot/GoPanel/utils/discord/endpoints/user"
"github.com/TicketsBot/GoPanel/utils/discord/objects" "github.com/TicketsBot/GoPanel/utils/discord/objects"
"github.com/apex/log" "github.com/apex/log"
"github.com/gin-gonic/contrib/sessions" "github.com/gin-gonic/contrib/sessions"
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"
"strconv" "github.com/rxdn/gdl/objects/user"
"time" "time"
) )
@ -65,8 +64,8 @@ func CallbackHandler(ctx *gin.Context) {
store.Set("expiry", (time.Now().UnixNano()/int64(time.Second))+int64(res.ExpiresIn)) store.Set("expiry", (time.Now().UnixNano()/int64(time.Second))+int64(res.ExpiresIn))
// Get ID + name // Get ID + name
var currentUser objects.User var currentUser user.User
err, _ = user.CurrentUser.Request(store, nil, nil, &currentUser) err, _ = userEndpoint.CurrentUser.Request(store, nil, nil, &currentUser)
if err != nil { if err != nil {
ctx.String(500, err.Error()) ctx.String(500, err.Error())
return return
@ -83,50 +82,22 @@ func CallbackHandler(ctx *gin.Context) {
ctx.Redirect(302, config.Conf.Server.BaseUrl) ctx.Redirect(302, config.Conf.Server.BaseUrl)
userId, err := strconv.ParseUint(currentUser.Id, 10, 64); if err != nil { // ???
return
}
// Cache guilds because Discord takes like 2 whole seconds to return then // Cache guilds because Discord takes like 2 whole seconds to return then
go func() { go func() {
var guilds []objects.Guild var guilds []objects.Guild
err, _ = user.CurrentUserGuilds.Request(store, nil, nil, &guilds) err, _ = userEndpoint.CurrentUserGuilds.Request(store, nil, nil, &guilds)
if err != nil { if err != nil {
log.Error(err.Error()) log.Error(err.Error())
return return
} }
for _, guild := range guilds {
go cache.Client.StoreGuild(guild)
// cache roles
guildId, err := strconv.ParseUint(guild.Id, 10, 64); if err != nil {
continue
}
go cacheRoles(store, guildId, userId)
}
marshalled, err := json.Marshal(guilds) marshalled, err := json.Marshal(guilds)
if err != nil { if err != nil {
log.Error(err.Error()) log.Error(err.Error())
return return
} }
// TODO: unfuck this
table.UpdateGuilds(currentUser.Id, base64.StdEncoding.EncodeToString(marshalled)) table.UpdateGuilds(currentUser.Id, base64.StdEncoding.EncodeToString(marshalled))
}() }()
} }
func cacheRoles(store sessions.Session, guildId, userId uint64) {
roles := utils.GetRolesRest(store, guildId, userId)
if roles == nil {
return
}
// Delete old roles
table.DeleteRoles(guildId, userId)
for _, role := range *roles {
table.CacheRole(guildId, userId, role)
}
}

View File

@ -7,6 +7,7 @@ import (
"github.com/TicketsBot/GoPanel/utils/discord/objects" "github.com/TicketsBot/GoPanel/utils/discord/objects"
"github.com/gin-gonic/contrib/sessions" "github.com/gin-gonic/contrib/sessions"
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"
"github.com/rxdn/gdl/objects/guild"
"strconv" "strconv"
) )
@ -18,25 +19,29 @@ func IndexHandler(ctx *gin.Context) {
defer store.Save() defer store.Save()
if utils.IsLoggedIn(store) { if utils.IsLoggedIn(store) {
userIdStr := store.Get("userid").(string)
userId, err := utils.GetUserId(store) userId, err := utils.GetUserId(store)
if err != nil { if err != nil {
ctx.String(500, err.Error()) ctx.String(500, err.Error())
return return
} }
userGuilds := table.GetGuilds(userIdStr) userGuilds := table.GetGuilds(userId)
adminGuilds := make([]objects.Guild, 0) adminGuilds := make([]objects.Guild, 0)
for _, guild := range userGuilds { for _, g := range userGuilds {
guildId, err := strconv.ParseUint(guild.Id, 10, 64) guildId, err := strconv.ParseUint(g.Id, 10, 64)
if err != nil { // I think this happens when a server was deleted? We should just skip though. if err != nil { // I think this happens when a server was deleted? We should just skip though.
continue continue
} }
fakeGuild := guild.Guild{
Owner: g.Owner,
Permissions: g.Permissions,
}
isAdmin := make(chan bool) isAdmin := make(chan bool)
go utils.IsAdmin(guild, guildId, userId, isAdmin) go utils.IsAdmin(fakeGuild, guildId, userId, isAdmin)
if <-isAdmin { if <-isAdmin {
adminGuilds = append(adminGuilds, guild) adminGuilds = append(adminGuilds, g)
} }
} }
@ -46,7 +51,7 @@ func IndexHandler(ctx *gin.Context) {
"servers": adminGuilds, "servers": adminGuilds,
"empty": len(adminGuilds) == 0, "empty": len(adminGuilds) == 0,
"isIndex": true, "isIndex": true,
"avatar": store.Get("avatar").(string), "avatar": store.Get("avatar").(string),
}) })
} else { } else {
ctx.Redirect(302, "/login") ctx.Redirect(302, "/login")

View File

@ -1,49 +0,0 @@
package cache
import (
"fmt"
"github.com/TicketsBot/GoPanel/utils/discord/objects"
"github.com/apex/log"
"github.com/vmihailenco/msgpack"
"time"
)
func (c *RedisClient) StoreGuild(guild objects.Guild) {
packed, err := msgpack.Marshal(guild)
if err != nil {
log.Error(err.Error())
return
}
key := fmt.Sprintf("ticketspanel:guilds:%s", string(packed))
c.Set(key, string(packed), time.Hour*48)
}
func (c *RedisClient) GetGuildByID(guildId string, res chan *objects.Guild) {
key := fmt.Sprintf("ticketspanel:guilds:%s", guildId)
packed, err := c.Get(key).Result()
if err != nil {
res <- nil
} else {
var unpacked objects.Guild
if err = msgpack.Unmarshal([]byte(packed), &unpacked); err != nil {
log.Error(err.Error())
res <- nil
} else {
res <- &unpacked
}
}
}
func (c *RedisClient) GuildExists(guildId string, res chan bool) {
key := fmt.Sprintf("tickets:guilds:%s", guildId)
intResult, err := c.Exists(key).Result()
if err != nil {
res <- false
return
}
res <- intResult == 1
}

21
cache/uriparser.go vendored
View File

@ -1,21 +0,0 @@
package cache
import "net/url"
type RedisURI struct {
Addr string
Password string
}
func ParseURI(raw string) RedisURI {
parsed, err := url.Parse(raw); if err != nil {
panic(err)
}
passwd, _ := parsed.User.Password()
return RedisURI{
Addr: parsed.Host,
Password: passwd,
}
}

View File

@ -6,9 +6,10 @@ import (
"fmt" "fmt"
"github.com/TicketsBot/GoPanel/app/http" "github.com/TicketsBot/GoPanel/app/http"
"github.com/TicketsBot/GoPanel/app/http/endpoints/manage" "github.com/TicketsBot/GoPanel/app/http/endpoints/manage"
"github.com/TicketsBot/GoPanel/cache"
"github.com/TicketsBot/GoPanel/config" "github.com/TicketsBot/GoPanel/config"
"github.com/TicketsBot/GoPanel/database" "github.com/TicketsBot/GoPanel/database"
"github.com/TicketsBot/GoPanel/messagequeue"
"github.com/TicketsBot/GoPanel/rpc/cache"
"github.com/TicketsBot/GoPanel/utils" "github.com/TicketsBot/GoPanel/utils"
"github.com/apex/log" "github.com/apex/log"
"math/rand" "math/rand"
@ -27,17 +28,18 @@ func main() {
config.LoadConfig() config.LoadConfig()
database.ConnectToDatabase() database.ConnectToDatabase()
cache.Instance = cache.NewCache()
utils.LoadEmoji() utils.LoadEmoji()
cache.Client = cache.NewRedisClient() messagequeue.Client = messagequeue.NewRedisClient()
go Listen(cache.Client) go Listen(messagequeue.Client)
http.StartServer() http.StartServer()
} }
func Listen(client cache.RedisClient) { func Listen(client messagequeue.RedisClient) {
ch := make(chan cache.TicketMessage) ch := make(chan messagequeue.TicketMessage)
go client.ListenForMessages(ch) go client.ListenForMessages(ch)
for decoded := range ch { for decoded := range ch {

View File

@ -33,3 +33,6 @@ host="127.0.0.1"
port=6379 port=6379
password="" password=""
threads=5 threads=5
[cache]
uri="postgres://pwd:user@localhost:5432/db"

View File

@ -7,12 +7,13 @@ import (
type ( type (
Config struct { Config struct {
Admins []string Admins []string
Server Server Server Server
Oauth Oauth Oauth Oauth
MariaDB MariaDB MariaDB MariaDB
Bot Bot Bot Bot
Redis Redis Redis Redis
Cache Cache
} }
Server struct { Server struct {
@ -48,7 +49,7 @@ type (
} }
Bot struct { Bot struct {
Token string Token string
PremiumLookupProxyUrl string `toml:"premium-lookup-proxy-url"` PremiumLookupProxyUrl string `toml:"premium-lookup-proxy-url"`
PremiumLookupProxyKey string `toml:"premium-lookup-proxy-key"` PremiumLookupProxyKey string `toml:"premium-lookup-proxy-key"`
} }
@ -59,6 +60,10 @@ type (
Password string Password string
Threads int Threads int
} }
Cache struct {
Uri string
}
) )
var ( var (

View File

@ -1,56 +0,0 @@
package table
import (
"github.com/TicketsBot/GoPanel/database"
)
type Channel struct {
ChannelId uint64 `gorm:"column:CHANNELID"`
GuildId uint64 `gorm:"column:GUILDID"`
Name string `gorm:"column:NAME;type:VARCHAR(32)"`
Type int `gorm:"column:CHANNELTYPE;type:TINYINT(1)"`
}
func (Channel) TableName() string {
return "Channel"
}
func StoreChannel(channelId, guildId uint64, name string, channelType int) {
channel := Channel{
ChannelId: channelId,
GuildId: guildId,
Name: name,
Type: channelType,
}
database.Database.Where(&Channel{ChannelId: channelId}).Assign(&channel).FirstOrCreate(&Channel{})
}
func DeleteChannel(channelId uint64) {
var node Channel
database.Database.Where(Channel{ChannelId: channelId}).Take(&node)
database.Database.Delete(&node)
}
func GetCachedChannelsByGuild(guildId uint64, res chan []Channel) {
var nodes []Channel
database.Database.Where(Channel{GuildId: guildId}).Find(&nodes)
res <- nodes
}
// Util function ig
func GetCategories(guildId uint64, res chan []Channel) {
channelsChan := make(chan []Channel)
go GetCachedChannelsByGuild(guildId, channelsChan)
channels := <-channelsChan
var categories []Channel
for _, channel := range channels {
if channel.Type == 4 {
categories = append(categories, channel)
}
}
res <- categories
}

View File

@ -8,7 +8,7 @@ import (
) )
type GuildCache struct { type GuildCache struct {
UserId string `gorm:"column:USERID;type:varchar(20)"` // Apparently I made this a VARCHAR in the JS version UserId uint64 `gorm:"column:USERID"`
Guilds string `gorm:"column:guilds;type:mediumtext"` Guilds string `gorm:"column:guilds;type:mediumtext"`
} }
@ -16,12 +16,13 @@ func (GuildCache) TableName() string {
return "guildscache" return "guildscache"
} }
func UpdateGuilds(userId string, guilds string) { // this is horrible
func UpdateGuilds(userId uint64, guilds string) {
var cache GuildCache var cache GuildCache
database.Database.Where(&GuildCache{UserId: userId}).Assign(&GuildCache{Guilds: guilds}).FirstOrCreate(&cache) database.Database.Where(&GuildCache{UserId: userId}).Assign(&GuildCache{Guilds: guilds}).FirstOrCreate(&cache)
} }
func GetGuilds(userId string) []objects.Guild { func GetGuilds(userId uint64) []objects.Guild {
var cache GuildCache var cache GuildCache
database.Database.Where(&GuildCache{UserId: userId}).First(&cache) database.Database.Where(&GuildCache{UserId: userId}).First(&cache)
decoded, err := base64.StdEncoding.DecodeString(cache.Guilds) decoded, err := base64.StdEncoding.DecodeString(cache.Guilds)

View File

@ -1,47 +0,0 @@
package table
import (
"github.com/TicketsBot/GoPanel/database"
)
type CachedRole struct {
AssociationId int `gorm:"column:ASSOCIATIONID;primary_key;auto_increment"`
GuildId uint64 `gorm:"column:GUILDID"`
UserId uint64 `gorm:"column:USERID"`
RoleId uint64 `gorm:"column:ROLEID"`
}
func (CachedRole) TableName() string {
return "cache_roles"
}
func DeleteRoles(guildId, userId uint64) {
database.Database.Where(CachedRole{
GuildId: guildId,
UserId: userId,
}).Delete(CachedRole{})
}
// TODO: Cache invalidation
func CacheRole(guildId, userId, roleId uint64) {
database.Database.Create(&CachedRole{
GuildId: guildId,
UserId: userId,
RoleId: roleId,
})
}
func GetCachedRoles(guildId, userId uint64, res chan []uint64) {
var rows []CachedRole
database.Database.Where(&CachedRole{
GuildId: guildId,
UserId: userId,
}).Find(&rows)
roles := make([]uint64, 0)
for _, row := range rows {
roles = append(roles, row.RoleId)
}
res <- roles
}

24
go.mod Normal file
View File

@ -0,0 +1,24 @@
module github.com/TicketsBot/GoPanel
go 1.14
require (
github.com/BurntSushi/toml v0.3.1
github.com/apex/log v1.1.2
github.com/boj/redistore v0.0.0-20180917114910-cd5dcc76aeff // indirect
github.com/gin-contrib/multitemplate v0.0.0-20200226145339-3e397ee01bc6
github.com/gin-contrib/static v0.0.0-20191128031702-f81c604d8ac2
github.com/gin-gonic/contrib v0.0.0-20191209060500-d6e26eeaa607
github.com/gin-gonic/gin v1.6.2
github.com/go-redis/redis v6.15.7+incompatible
github.com/go-sql-driver/mysql v1.5.0
github.com/gorilla/sessions v1.2.0 // indirect
github.com/gorilla/websocket v1.4.2
github.com/jackc/pgx/v4 v4.6.0
github.com/jinzhu/gorm v1.9.12
github.com/pasztorpisti/qs v0.0.0-20171216220353-8d6c33ee906c
github.com/pkg/errors v0.9.1
github.com/robfig/go-cache v0.0.0-20130306151617-9fc39e0dbf62
github.com/rxdn/gdl v0.0.0-20200410134146-c1b0871088c5
github.com/vmihailenco/msgpack v4.0.4+incompatible
)

View File

@ -1,4 +1,4 @@
package cache package messagequeue
import ( import (
"encoding/json" "encoding/json"

View File

@ -1,4 +1,4 @@
package cache package messagequeue
import ( import (
"fmt" "fmt"

View File

@ -1,4 +1,4 @@
package cache package messagequeue
import ( import (
"encoding/json" "encoding/json"

View File

@ -1,4 +1,4 @@
package cache package messagequeue
import ( import (
"encoding/json" "encoding/json"

View File

@ -74,8 +74,10 @@
<div class="input-group-text">#</div> <div class="input-group-text">#</div>
</div> </div>
<select class="form-control" name="channel"> <select class="form-control" name="channel">
{{range $id, $name := .channels}} {{range .channels}}
<option value="{{$id}}">{{$name}}</option> {{if eq .Type 0}} <!-- Check the channel is a text channel -->
<option value="{{.Id}}">{{.Name}}</option>
{{end}}
{{end}} {{end}}
</select> </select>
</div> </div>
@ -88,8 +90,10 @@
<div class="input-group-text">#</div> <div class="input-group-text">#</div>
</div> </div>
<select class="form-control" name="categories"> <select class="form-control" name="categories">
{{range $id, $name := .categories}} {{range .channels}}
<option value="{{$id}}">{{$name}}</option> {{if eq .Type 4}} <!-- Check the channel is a category -->
<option value="{{.Id}}">{{.Name}}</option>
{{end}}
{{end}} {{end}}
</select> </select>
</div> </div>
@ -155,8 +159,9 @@
</button> </button>
</div> </div>
<div class="toast-body"> <div class="toast-body">
Invalid panel colour. You must use the hex value of the colour, which you can find <a href="https://www.google.co.uk/search?client=opera&q=html+colour+picker">here</a>. Invalid panel colour. You must use the hex value of the colour, which you can find <a
<br />Colour has defaulted to green. href="https://www.google.co.uk/search?client=opera&q=html+colour+picker">here</a>.
<br/>Colour has defaulted to green.
</div> </div>
</div> </div>
{{end}} {{end}}
@ -221,7 +226,8 @@
</button> </button>
</div> </div>
<div class="toast-body"> <div class="toast-body">
You've hit your panel quota. Premium users can create <b>unlimited panels</b>. Click <a href="https://ticketsbot.net/premium">here</a> to learn more about premium. You've hit your panel quota. Premium users can create <b>unlimited panels</b>. Click <a
href="https://ticketsbot.net/premium">here</a> to learn more about premium.
</div> </div>
</div> </div>
{{end}} {{end}}

View File

@ -51,7 +51,7 @@
</div> </div>
<select class="form-control" name="archivechannel"> <select class="form-control" name="archivechannel">
{{range .channels}} {{range .channels}}
<option {{if eq .ChannelId $.archivechannel }}selected{{end}} value="{{.ChannelId}}">{{.Name}}</option> <option {{if eq .Id $.archivechannel }}selected{{end}} value="{{.Id}}">{{.Name}}</option>
{{end}} {{end}}
</select> </select>
</div> </div>
@ -62,7 +62,7 @@
<label>Channel Category</label> <label>Channel Category</label>
<select class="form-control" name="category"> <select class="form-control" name="category">
{{range .categories}} {{range .categories}}
<option {{if eq $.activecategory .ChannelId}}selected{{end}} value="{{.ChannelId}}">{{.Name}}</option> <option {{if eq $.activecategory .Id}}selected{{end}} value="{{.Id}}">{{.Name}}</option>
{{end}} {{end}}
</select> </select>
</div> </div>

33
rpc/cache/cache.go vendored Normal file
View File

@ -0,0 +1,33 @@
package cache
import (
"context"
"github.com/TicketsBot/GoPanel/config"
"github.com/jackc/pgx/v4/pgxpool"
gdlcache "github.com/rxdn/gdl/cache"
)
type Cache struct {
*gdlcache.PgCache
}
var Instance *Cache
func NewCache() *Cache {
pool, err := pgxpool.Connect(context.Background(), config.Conf.Cache.Uri)
if err != nil {
panic(err)
}
cache := gdlcache.NewPgCache(pool, gdlcache.CacheOptions{
Guilds: true,
Users: true,
Members: true,
Channels: true,
Roles: true,
})
return &Cache{
PgCache: &cache,
}
}

View File

@ -0,0 +1,8 @@
package ratelimit
import (
"github.com/TicketsBot/GoPanel/messagequeue"
"github.com/rxdn/gdl/rest/ratelimit"
)
var Ratelimiter = ratelimit.NewRateLimiter(ratelimit.NewRedisStore(messagequeue.Client.Client, "ratelimit")) // TODO: Use values from config

View File

@ -1,18 +0,0 @@
package channel
import (
"fmt"
"github.com/TicketsBot/GoPanel/utils/discord"
)
type CreateMessageBody struct {
Content string `json:"content"`
}
func CreateMessage(id int) discord.Endpoint {
return discord.Endpoint{
RequestType: discord.POST,
AuthorizationType: discord.BOT,
Endpoint: fmt.Sprintf("/channels/%d/messages", id),
}
}

View File

@ -1,14 +0,0 @@
package channel
import (
"fmt"
"github.com/TicketsBot/GoPanel/utils/discord"
)
func GetChannelMessages(id int) discord.Endpoint {
return discord.Endpoint{
RequestType: discord.GET,
AuthorizationType: discord.BOT,
Endpoint: fmt.Sprintf("/channels/%d/messages", id),
}
}

View File

@ -1,15 +0,0 @@
package guild
import (
"fmt"
"github.com/TicketsBot/GoPanel/utils/discord"
"strconv"
)
func GetGuild(id int) discord.Endpoint {
return discord.Endpoint{
RequestType: discord.GET,
AuthorizationType: discord.BOT,
Endpoint: fmt.Sprintf("/guilds/%s", strconv.Itoa(id)),
}
}

View File

@ -1,14 +0,0 @@
package guild
import (
"fmt"
"github.com/TicketsBot/GoPanel/utils/discord"
)
func GetGuildChannels(id int) discord.Endpoint {
return discord.Endpoint{
RequestType: discord.GET,
AuthorizationType: discord.BOT,
Endpoint: fmt.Sprintf("/guilds/%d/channels", id),
}
}

View File

@ -1,14 +0,0 @@
package guild
import (
"fmt"
"github.com/TicketsBot/GoPanel/utils/discord"
)
func GetGuildMember(guildId, userId uint64) discord.Endpoint {
return discord.Endpoint{
RequestType: discord.GET,
AuthorizationType: discord.BOT,
Endpoint: fmt.Sprintf("/guilds/%d/members/%d", guildId, userId),
}
}

View File

@ -1,22 +0,0 @@
package webhooks
import (
"fmt"
"github.com/TicketsBot/GoPanel/utils/discord"
"github.com/TicketsBot/GoPanel/utils/discord/objects"
)
type ExecuteWebhookBody struct {
Content string `json:"content"`
Username string `json:"username"`
AvatarUrl string `json:"avatar_url"`
AllowedMentions objects.AllowedMention `json:"allowed_mentions"`
}
func ExecuteWebhook(webhook string) discord.Endpoint {
return discord.Endpoint{
RequestType: discord.POST,
AuthorizationType: discord.NONE,
Endpoint: fmt.Sprintf("/webhooks/%s?wait=true", webhook),
}
}

View File

@ -1,16 +0,0 @@
package objects
type Activity struct {
Name string
Type int
Url string
Timestamps Timestamp
ApplicationId string
Details string
State string
Party Party
Assets Asset
Secrets Secret
Instance bool
Flags int
}

View File

@ -1,7 +0,0 @@
package objects
type AllowedMention struct {
Parse []AllowedMentionType
Roles []string
Users []string
}

View File

@ -1,9 +0,0 @@
package objects
type AllowedMentionType string
const(
EVERYONE AllowedMentionType = "everyone"
USERS AllowedMentionType = "users"
ROLES AllowedMentionType = "roles"
)

View File

@ -1,8 +0,0 @@
package objects
type Asset struct {
LargeImage string
LargeText string
SmallImage string
SmallText string
}

View File

@ -1,11 +0,0 @@
package objects
type Attachment struct {
Id string
Filename string
Size int
url string
ProxyUrl string
height int
Width int
}

View File

@ -1,22 +0,0 @@
package objects
type Channel struct {
Id string
Type int
GuildId string
Position int
PermissionsOverwrites []Overwrite
Name string
Topic string
Nsfw bool
LastMessageId string
Bitrate int
userLimit int
RateLimitPerUser int
Recipients []User
Icon string
Ownerid string
ApplicationId string
ParentId string
LastPinTimestamp string
}

View File

@ -1,7 +0,0 @@
package objects
type ClientStatus struct {
Desktop string
Mobile string
Web string
}

View File

@ -1,17 +0,0 @@
package objects
type Embed struct {
Title string
Type string
Description string
Url string
Timestamp string
Color int
Footer EmbedField
Image EmbedImage
Thumbnail EmbedThumbnail
Video EmbedVideo
Provider EmbedProvider
Author EmbedAuthor
Fields []EmbedField
}

View File

@ -1,8 +0,0 @@
package objects
type EmbedAuthor struct {
Name string
Url string
IconUrl string
ProxyIconUrl string
}

View File

@ -1,7 +0,0 @@
package objects
type EmbedField struct {
Name string
Value string
Inline bool
}

View File

@ -1,7 +0,0 @@
package objects
type EmbedFooter struct {
Text string
IconUrl string
ProxyIconUrl string
}

View File

@ -1,8 +0,0 @@
package objects
type EmbedImage struct {
Url string
ProxyUrl string
Height int
Width int
}

View File

@ -1,6 +0,0 @@
package objects
type EmbedProvider struct {
Name string
Url string
}

View File

@ -1,8 +0,0 @@
package objects
type EmbedThumbnail struct {
Url string
ProxyUrl string
Height int
Width int
}

View File

@ -1,7 +0,0 @@
package objects
type EmbedVideo struct {
Url string
Height int
Width int
}

View File

@ -1,11 +0,0 @@
package objects
type Emoji struct {
Id string
Name string
Roles []string
User User
RequireColons bool
Managed bool
Animated bool
}

View File

@ -1,43 +1,9 @@
package objects package objects
type Guild struct { type Guild struct {
Id string Id string
Name string Name string
Icon string Icon string
Splash string Owner bool
Owner bool Permissions int
OwnerId string `json:"owner_id"`
Permissions int
Region string
AfkChannelid string `json:"afk_channel_id"`
AfkTimeout int
EmbedEnabled bool `json:"embed_enabled"`
EmbedChannelId string `json:"embed_channel_id"`
VerificationLevel int `json:"verification_level"`
DefaultMessageNotifications int `json:"default_message_notifications"`
ExplicitContentFilter int `json:"explicit_content_filter"`
Roles []Role
Emojis []Emoji
Features []string
MfaLevel int `json:"mfa_level"`
ApplicationId string `json:"application_id"`
WidgetEnabled bool `json:"widget_enabled"`
WidgetChannelId string `json:"widget_channel_id"`
SystemChannelId string `json:"system_channel_id"`
JoinedAt string `json:"joined_at"`
Large bool
Unavailable bool
MemberCount int `json:"member_count"`
VoiceStates []VoiceState
Members []Member
Channels []Channel
Presences []Presence
MaxPresences int `json:"max_presences"`
MaxMembers int `json:"max_members"`
VanityUrlCode string `json:"vanity_url_code"`
Description string
Banner string
PremiumTier int `json:"premium_tier"`
PremiumSubscriptionCount int `json:"premium_subscription_count"`
PreferredLocale string `json:"preferred_locale"`
} }

View File

@ -1,12 +0,0 @@
package objects
import "github.com/TicketsBot/GoPanel/utils/types"
type Member struct {
User User
Nick string
Roles types.UInt64StringSlice `json:"roles,string"`
JoinedAt string
Deaf bool
Mute bool
}

View File

@ -1,25 +0,0 @@
package objects
type Message struct {
Id string
ChannelId string
GuildId string
Author User
Member Member
Content string
Timestamp string
EditedTimestamp string
Tts bool
MentionEveryone bool
Mentions []interface{}
MentionsRoles []int64
Attachments []Attachment
Embeds []Embed
Reactions []Reaction
Nonce string
Pinned bool
WebhookId string
Type int
Activity MessageActivity
Application MessageApplication
}

View File

@ -1,6 +0,0 @@
package objects
type MessageActivity struct {
Type int
PartyId string
}

View File

@ -1,9 +0,0 @@
package objects
type MessageApplication struct {
Id string
CoverImage string
Description string
Icon string
Name string
}

View File

@ -1,8 +0,0 @@
package objects
type Overwrite struct {
Id string
Type string
Allow int
Deny int
}

View File

@ -1,6 +0,0 @@
package objects
type Party struct {
Id string
Size []int
}

View File

@ -1,11 +0,0 @@
package objects
type Presence struct {
User User
Roles []string
Game Activity
GuildId string
Status string
Activities []Activity
ClientStatus ClientStatus
}

View File

@ -1,7 +0,0 @@
package objects
type Reaction struct {
Count int
Me bool
Emoji Emoji
}

View File

@ -1,12 +0,0 @@
package objects
type Role struct {
Id string
Name string
Color int
Hoist bool
Position int
Permissions int
Managed bool
Mentionable bool
}

View File

@ -1,7 +0,0 @@
package objects
type Secret struct {
Join string
Spectate string
Match string
}

View File

@ -1,6 +0,0 @@
package objects
type Timestamp struct {
Start int
End int
}

View File

@ -1,14 +0,0 @@
package objects
type VoiceState struct {
GuildId string
ChannelId string
UserId string
Member Member
SessionId string
Deaf bool
Mute bool
SelfDeaf bool
SelfMute bool
Suppress bool
}

View File

@ -3,23 +3,19 @@ package utils
import ( import (
"github.com/TicketsBot/GoPanel/config" "github.com/TicketsBot/GoPanel/config"
"github.com/TicketsBot/GoPanel/database/table" "github.com/TicketsBot/GoPanel/database/table"
"github.com/TicketsBot/GoPanel/utils/discord/endpoints/guild" "github.com/TicketsBot/GoPanel/rpc/cache"
"github.com/TicketsBot/GoPanel/utils/discord/objects" "github.com/TicketsBot/GoPanel/rpc/ratelimit"
"github.com/apex/log" "github.com/rxdn/gdl/objects/guild"
"github.com/gin-gonic/contrib/sessions" "github.com/rxdn/gdl/rest"
"github.com/robfig/go-cache"
"strconv" "strconv"
"time"
) )
var roleCache = cache.New(time.Minute, time.Minute) func IsAdmin(g guild.Guild, guildId, userId uint64, res chan bool) {
func IsAdmin(guild objects.Guild, guildId, userId uint64, res chan bool) {
if Contains(config.Conf.Admins, strconv.Itoa(int(userId))) { if Contains(config.Conf.Admins, strconv.Itoa(int(userId))) {
res <- true res <- true
} }
if guild.Owner { if g.Owner {
res <- true res <- true
} }
@ -27,24 +23,24 @@ func IsAdmin(guild objects.Guild, guildId, userId uint64, res chan bool) {
res <- true res <- true
} }
if guild.Permissions & 0x8 != 0 { if g.Permissions & 0x8 != 0 {
res <- true res <- true
} }
userRolesChan := make(chan []uint64)
go table.GetCachedRoles(guildId, userId, userRolesChan)
userRoles := <-userRolesChan
adminRolesChan := make(chan []uint64) adminRolesChan := make(chan []uint64)
go table.GetAdminRoles(guildId, adminRolesChan) go table.GetAdminRoles(guildId, adminRolesChan)
adminRoles := <- adminRolesChan adminRoles := <- adminRolesChan
userRoles, found := getRoles(guildId, userId)
hasAdminRole := false hasAdminRole := false
for _, userRole := range userRoles { if found {
for _, adminRole := range adminRoles { for _, userRole := range userRoles {
if userRole == adminRole { for _, adminRole := range adminRoles {
hasAdminRole = true if userRole == adminRole {
break hasAdminRole = true
break
}
} }
} }
} }
@ -56,15 +52,18 @@ func IsAdmin(guild objects.Guild, guildId, userId uint64, res chan bool) {
res <- false res <- false
} }
func GetRolesRest(store sessions.Session, guildId, userId uint64) *[]uint64 { func getRoles(guildId, userId uint64) ([]uint64, bool) {
var member objects.Member member, found := cache.Instance.GetMember(guildId, userId)
endpoint := guild.GetGuildMember(guildId, userId) if !found { // get from rest
var err error
member, err = rest.GetGuildMember(config.Conf.Bot.Token, ratelimit.Ratelimiter, guildId, userId)
if err != nil {
return nil, false
}
if err, _ := endpoint.Request(store, nil, nil, &member); err != nil { // cache
log.Error(err.Error()) cache.Instance.StoreMember(member, guildId)
return nil
} }
roles := []uint64(member.Roles) return member.Roles, true
return &roles
} }

View File

@ -3,13 +3,13 @@ package utils
import ( import (
"encoding/json" "encoding/json"
"fmt" "fmt"
redis "github.com/TicketsBot/GoPanel/cache"
"github.com/TicketsBot/GoPanel/config" "github.com/TicketsBot/GoPanel/config"
"github.com/TicketsBot/GoPanel/database/table" "github.com/TicketsBot/GoPanel/database/table"
"github.com/TicketsBot/GoPanel/utils/discord/endpoints/guild" "github.com/TicketsBot/GoPanel/rpc/cache"
"github.com/TicketsBot/GoPanel/utils/discord/objects" "github.com/TicketsBot/GoPanel/rpc/ratelimit"
"github.com/gin-gonic/contrib/sessions" "github.com/gin-gonic/contrib/sessions"
"github.com/robfig/go-cache" gocache "github.com/robfig/go-cache"
"github.com/rxdn/gdl/rest"
"io/ioutil" "io/ioutil"
"net/http" "net/http"
"strconv" "strconv"
@ -21,7 +21,7 @@ type ProxyResponse struct {
Tier int Tier int
} }
var premiumCache = cache.New(10 * time.Minute, 10 * time.Minute) var premiumCache = gocache.New(10 * time.Minute, 10 * time.Minute)
func IsPremiumGuild(store sessions.Session, guildId uint64, ch chan bool) { func IsPremiumGuild(store sessions.Session, guildId uint64, ch chan bool) {
guildIdRaw := strconv.FormatUint(guildId, 10) guildIdRaw := strconv.FormatUint(guildId, 10)
@ -43,47 +43,25 @@ func IsPremiumGuild(store sessions.Session, guildId uint64, ch chan bool) {
ch<-true ch<-true
} else { } else {
// Get guild object // Get guild object
guildChan := make(chan *objects.Guild) guild, found := cache.Instance.GetGuild(guildId, false)
go redis.Client.GetGuildByID(guildIdRaw, guildChan)
g := <-guildChan
ownerIdRaw := "" if !found {
if g == nil { var err error
var g objects.Guild guild, err = rest.GetGuild(config.Conf.Bot.Token, ratelimit.Ratelimiter, guildId)
endpoint := guild.GetGuild(int(guildId))
endpoint.Request(store, nil, nil, &g) if err == nil { // cache
go cache.Instance.StoreGuild(guild)
ownerIdRaw = g.OwnerId }
go redis.Client.StoreGuild(g)
} }
// TODO: Find a way to stop people using votes to exploit panels // TODO: Find a way to stop people using votes to exploit panels
// Lookup votes
/*ownerId, err := strconv.ParseInt(ownerIdRaw, 10, 64); if err != nil {
fmt.Println(err.Error())
ch <- false
return
}
hasVoted := make(chan bool)
go table.HasVoted(ownerId, hasVoted)
if <-hasVoted {
ch <- true
if err := premiumCache.Add(guildIdRaw, true, 10 * time.Minute); err != nil {
fmt.Println(err.Error())
}
return
}*/
// Lookup Patreon // Lookup Patreon
client := &http.Client{ client := &http.Client{
Timeout: time.Second * 3, Timeout: time.Second * 3,
} }
url := fmt.Sprintf("%s/ispremium?key=%s&id=%s", config.Conf.Bot.PremiumLookupProxyUrl, config.Conf.Bot.PremiumLookupProxyKey, ownerIdRaw) url := fmt.Sprintf("%s/ispremium?key=%s&id=%d", config.Conf.Bot.PremiumLookupProxyUrl, config.Conf.Bot.PremiumLookupProxyKey, guild.OwnerId)
req, err := http.NewRequest("GET", url, nil) req, err := http.NewRequest("GET", url, nil)
res, err := client.Do(req); if err != nil { res, err := client.Do(req); if err != nil {

View File

@ -2,6 +2,7 @@ package utils
import ( import (
"github.com/TicketsBot/GoPanel/utils/discord/objects" "github.com/TicketsBot/GoPanel/utils/discord/objects"
"github.com/rxdn/gdl/objects/channel/message"
"reflect" "reflect"
) )
@ -33,7 +34,7 @@ func Insert(slice []objects.Guild, index int, value objects.Guild) []objects.Gui
return slice return slice
} }
func Reverse(slice []objects.Message) []objects.Message { func Reverse(slice []message.Message) []message.Message {
for i := len(slice)/2-1; i >= 0; i-- { for i := len(slice)/2-1; i >= 0; i-- {
opp := len(slice)-1-i opp := len(slice)-1-i
slice[i], slice[opp] = slice[opp], slice[i] slice[i], slice[opp] = slice[opp], slice[i]