cchat-discord/internal/discord/channel/message/action/actioner.go

104 lines
2.1 KiB
Go
Raw Normal View History

2020-10-07 01:53:15 +00:00
package action
2020-09-08 04:44:09 +00:00
import (
"github.com/diamondburned/arikawa/discord"
"github.com/diamondburned/cchat"
2020-10-07 01:53:15 +00:00
"github.com/diamondburned/cchat-discord/internal/discord/channel/shared"
2020-09-08 04:44:09 +00:00
"github.com/pkg/errors"
)
2020-10-07 01:53:15 +00:00
type Actioner struct {
*shared.Channel
}
var _ cchat.Actioner = (*Actioner)(nil)
2020-09-08 04:44:09 +00:00
2020-10-07 01:53:15 +00:00
func New(ch *shared.Channel) Actioner {
return Actioner{ch}
}
2020-09-08 04:44:09 +00:00
const (
ActionDelete = "Delete"
)
var ErrUnknownAction = errors.New("unknown message action")
2020-10-07 01:53:15 +00:00
func (ac Actioner) DoAction(action, id string) error {
2020-09-08 04:44:09 +00:00
s, err := discord.ParseSnowflake(id)
if err != nil {
return errors.Wrap(err, "Failed to parse ID")
}
switch action {
case ActionDelete:
2020-10-07 01:53:15 +00:00
return ac.State.DeleteMessage(ac.ID, discord.MessageID(s))
2020-09-08 04:44:09 +00:00
default:
return ErrUnknownAction
}
}
2020-10-07 01:53:15 +00:00
func (ac Actioner) Actions(id string) []string {
2020-09-08 04:44:09 +00:00
s, err := discord.ParseSnowflake(id)
if err != nil {
return nil
}
2020-10-07 01:53:15 +00:00
m, err := ac.State.Store.Message(ac.ID, discord.MessageID(s))
2020-09-08 04:44:09 +00:00
if err != nil {
return nil
}
// Get the current user.
2020-10-07 01:53:15 +00:00
u, err := ac.State.Store.Me()
2020-09-08 04:44:09 +00:00
if err != nil {
return nil
}
// Can we have delete? We can if this is our own message.
var canDelete = m.Author.ID == u.ID
// We also can if we have the Manage Messages permission, which would allow
// us to delete others' messages.
if !canDelete {
2020-10-07 01:53:15 +00:00
canDelete = ac.canManageMessages(u.ID)
2020-09-08 04:44:09 +00:00
}
if canDelete {
return []string{ActionDelete}
}
return []string{}
}
// canManageMessages returns whether or not the user is allowed to manage
// messages.
2020-10-07 01:53:15 +00:00
func (ac Actioner) canManageMessages(userID discord.UserID) bool {
2020-09-08 04:44:09 +00:00
// If we're not in a guild, then clearly we cannot.
2020-10-07 01:53:15 +00:00
if !ac.GuildID.IsValid() {
2020-09-08 04:44:09 +00:00
return false
}
// We need the guild, member and channel to calculate the permission
// overrides.
2020-10-07 01:53:15 +00:00
g, err := ac.Guild()
2020-09-08 04:44:09 +00:00
if err != nil {
return false
}
2020-10-07 01:53:15 +00:00
c, err := ac.Self()
2020-09-08 04:44:09 +00:00
if err != nil {
return false
}
2020-10-07 01:53:15 +00:00
m, err := ac.State.Store.Member(ac.GuildID, userID)
2020-09-08 04:44:09 +00:00
if err != nil {
return false
}
p := discord.CalcOverwrites(*g, *c, *m)
// The Manage Messages permission allows the user to delete others'
// messages, so we'll return true if that is the case.
return p.Has(discord.PermissionManageMessages)
}