refactor: remove unused functions

This commit is contained in:
ayntgl 2022-01-09 16:32:21 +04:00
parent e6ec288975
commit 87a073d827
7 changed files with 177 additions and 239 deletions

109
discord/util.go Normal file
View file

@ -0,0 +1,109 @@
package discord
import (
"encoding/json"
"regexp"
"github.com/ayntgl/discordgo"
)
var (
boldRegex = regexp.MustCompile(`(?m)\*\*(.*?)\*\*`)
italicRegex = regexp.MustCompile(`(?m)\*(.*?)\*`)
underlineRegex = regexp.MustCompile(`(?m)__(.*?)__`)
strikeThroughRegex = regexp.MustCompile(`(?m)~~(.*?)~~`)
)
func ParseMarkdown(md string) string {
var res string
res = boldRegex.ReplaceAllString(md, "[::b]$1[::-]")
res = italicRegex.ReplaceAllString(res, "[::i]$1[::-]")
res = underlineRegex.ReplaceAllString(res, "[::u]$1[::-]")
res = strikeThroughRegex.ReplaceAllString(res, "[::s]$1[::-]")
return res
}
func FindMessageByID(ms []*discordgo.Message, mID string) (int, *discordgo.Message) {
for i, m := range ms {
if m.ID == mID {
return i, m
}
}
return -1, nil
}
func ChannelIsUnread(s *discordgo.State, c *discordgo.Channel) bool {
if c.LastMessageID == "" {
return false
}
for _, rs := range s.ReadState {
if c.ID == rs.ID {
return c.LastMessageID != rs.LastMessageID
}
}
return false
}
func HasPermission(s *discordgo.State, cID string, p int64) bool {
perm, err := s.UserChannelPermissions(s.User.ID, cID)
if err != nil {
return false
}
return perm&p == p
}
type loginResponse struct {
MFA bool `json:"mfa"`
SMS bool `json:"sms"`
Ticket string `json:"ticket"`
Token string `json:"token"`
}
func Login(s *discordgo.Session, email string, password string) (*loginResponse, error) {
data := struct {
Email string `json:"email"`
Password string `json:"password"`
}{email, password}
resp, err := s.RequestWithBucketID(
"POST",
discordgo.EndpointLogin,
data,
discordgo.EndpointLogin,
)
if err != nil {
return nil, err
}
var lr loginResponse
err = json.Unmarshal(resp, &lr)
if err != nil {
return nil, err
}
return &lr, nil
}
func TOTP(s *discordgo.Session, code string, ticket string) (*loginResponse, error) {
data := struct {
Code string `json:"code"`
Ticket string `json:"ticket"`
}{code, ticket}
e := discordgo.EndpointAuth + "mfa/totp"
resp, err := s.RequestWithBucketID("POST", e, data, e)
if err != nil {
return nil, err
}
var lr loginResponse
err = json.Unmarshal(resp, &lr)
if err != nil {
return nil, err
}
return &lr, nil
}

116
main.go
View file

@ -1,24 +1,19 @@
package main
import (
"encoding/json"
"os"
"github.com/ayntgl/discordgo"
"github.com/ayntgl/discordo/ui"
"github.com/rivo/tview"
"github.com/zalando/go-keyring"
)
const service = "discordo"
func main() {
app := ui.NewApp()
app.Config.Load()
token := os.Getenv("DISCORDO_TOKEN")
if token == "" {
token, _ = keyring.Get(service, "token")
token, _ = keyring.Get("discordo", "token")
}
if token != "" {
@ -31,9 +26,10 @@ func main() {
SetRoot(ui.NewMainFlex(app), true).
SetFocus(app.GuildsList)
} else {
app.LoginForm = ui.NewLoginForm(func() {
onLoginFormLoginButtonSelected(app)
ui.NewLoginForm(app, func() {
ui.OnLoginFormLoginButtonSelected(app)
}, false)
app.SetRoot(app.LoginForm, true)
}
@ -41,107 +37,3 @@ func main() {
panic(err)
}
}
func onLoginFormLoginButtonSelected(app *ui.App) {
email := app.LoginForm.GetFormItem(0).(*tview.InputField).GetText()
password := app.LoginForm.GetFormItem(1).(*tview.InputField).GetText()
if email == "" || password == "" {
return
}
// Login using the email and password
lr, err := login(app.Session, email, password)
if err != nil {
panic(err)
}
if lr.Token != "" && !lr.MFA {
app.
SetRoot(ui.NewMainFlex(app), true).
SetFocus(app.GuildsList)
err = app.Connect(lr.Token)
if err != nil {
panic(err)
}
go keyring.Set(service, "token", lr.Token)
} else if lr.MFA {
// The account has MFA enabled, reattempt login with code and ticket.
app.LoginForm = ui.NewLoginForm(func() {
code := app.LoginForm.GetFormItem(0).(*tview.InputField).GetText()
if code == "" {
return
}
lr, err = totp(app.Session, code, lr.Ticket)
if err != nil {
panic(err)
}
app.
SetRoot(ui.NewMainFlex(app), true).
SetFocus(app.GuildsList)
err = app.Connect(lr.Token)
if err != nil {
panic(err)
}
go keyring.Set(service, "token", lr.Token)
}, true)
app.SetRoot(app.LoginForm, true)
}
}
type loginResponse struct {
MFA bool `json:"mfa"`
SMS bool `json:"sms"`
Ticket string `json:"ticket"`
Token string `json:"token"`
}
func login(s *discordgo.Session, email string, password string) (*loginResponse, error) {
data := struct {
Email string `json:"email"`
Password string `json:"password"`
}{email, password}
resp, err := s.RequestWithBucketID(
"POST",
discordgo.EndpointLogin,
data,
discordgo.EndpointLogin,
)
if err != nil {
return nil, err
}
var lr loginResponse
err = json.Unmarshal(resp, &lr)
if err != nil {
return nil, err
}
return &lr, nil
}
func totp(s *discordgo.Session, code string, ticket string) (*loginResponse, error) {
data := struct {
Code string `json:"code"`
Ticket string `json:"ticket"`
}{code, ticket}
e := discordgo.EndpointAuth + "mfa/totp"
resp, err := s.RequestWithBucketID("POST", e, data, e)
if err != nil {
return nil, err
}
var lr loginResponse
err = json.Unmarshal(resp, &lr)
if err != nil {
return nil, err
}
return &lr, nil
}

View file

@ -6,9 +6,10 @@ import (
"github.com/atotto/clipboard"
"github.com/ayntgl/discordgo"
"github.com/ayntgl/discordo/util"
util "github.com/ayntgl/discordo/discord"
"github.com/gdamore/tcell/v2"
"github.com/rivo/tview"
"github.com/zalando/go-keyring"
)
func onAppInputCapture(app *App, e *tcell.EventKey) *tcell.EventKey {
@ -290,3 +291,56 @@ func onMessageInputFieldInputCapture(app *App, e *tcell.EventKey) *tcell.EventKe
return e
}
func OnLoginFormLoginButtonSelected(app *App) {
email := app.LoginForm.GetFormItem(0).(*tview.InputField).GetText()
password := app.LoginForm.GetFormItem(1).(*tview.InputField).GetText()
if email == "" || password == "" {
return
}
// Login using the email and password
lr, err := util.Login(app.Session, email, password)
if err != nil {
panic(err)
}
if lr.Token != "" && !lr.MFA {
app.
SetRoot(NewMainFlex(app), true).
SetFocus(app.GuildsList)
err = app.Connect(lr.Token)
if err != nil {
panic(err)
}
go keyring.Set("discordo", "token", lr.Token)
} else if lr.MFA {
// The account has MFA enabled, reattempt login with code and ticket.
NewLoginForm(app, func() {
code := app.LoginForm.GetFormItem(0).(*tview.InputField).GetText()
if code == "" {
return
}
lr, err = util.TOTP(app.Session, code, lr.Ticket)
if err != nil {
panic(err)
}
app.
SetRoot(NewMainFlex(app), true).
SetFocus(app.GuildsList)
err = app.Connect(lr.Token)
if err != nil {
panic(err)
}
go keyring.Set("discordo", "token", lr.Token)
}, true)
app.SetRoot(app.LoginForm, true)
}
}

View file

@ -2,17 +2,10 @@ package ui
import (
"fmt"
"regexp"
"strings"
"github.com/ayntgl/discordgo"
)
var (
boldRegex = regexp.MustCompile(`(?m)\*\*(.*?)\*\*`)
italicRegex = regexp.MustCompile(`(?m)\*(.*?)\*`)
underlineRegex = regexp.MustCompile(`(?m)__(.*?)__`)
strikeThroughRegex = regexp.MustCompile(`(?m)~~(.*?)~~`)
"github.com/ayntgl/discordo/discord"
)
func channelToString(c *discordgo.Channel) string {
@ -112,7 +105,7 @@ func buildReferencedMessage(b *strings.Builder, rm *discordgo.Message, clientID
if rm.Content != "" {
rm.Content = buildMentions(rm.Content, rm.Mentions, clientID)
b.WriteString(parseMarkdown(rm.Content))
b.WriteString(discord.ParseMarkdown(rm.Content))
}
b.WriteString("[::-]")
@ -123,7 +116,7 @@ func buildReferencedMessage(b *strings.Builder, rm *discordgo.Message, clientID
func buildContent(b *strings.Builder, m *discordgo.Message, clientID string) {
if m.Content != "" {
m.Content = buildMentions(m.Content, m.Mentions, clientID)
b.WriteString(parseMarkdown(m.Content))
b.WriteString(discord.ParseMarkdown(m.Content))
}
}
@ -159,7 +152,7 @@ func buildEmbeds(b *strings.Builder, es []*discordgo.MessageEmbed) {
embedBuilder.WriteString("\n\n")
}
embedBuilder.WriteString(parseMarkdown(e.Description))
embedBuilder.WriteString(discord.ParseMarkdown(e.Description))
}
if len(e.Fields) != 0 {
@ -172,7 +165,7 @@ func buildEmbeds(b *strings.Builder, es []*discordgo.MessageEmbed) {
embedBuilder.WriteString(ef.Name)
embedBuilder.WriteString("[::-]")
embedBuilder.WriteByte('\n')
embedBuilder.WriteString(parseMarkdown(ef.Value))
embedBuilder.WriteString(discord.ParseMarkdown(ef.Value))
if i != len(e.Fields)-1 {
embedBuilder.WriteString("\n\n")
@ -239,13 +232,3 @@ func buildAuthor(b *strings.Builder, u *discordgo.User, clientID string) {
b.WriteString("[#EB459E]BOT[-] ")
}
}
func parseMarkdown(md string) string {
var res string
res = boldRegex.ReplaceAllString(md, "[::b]$1[::-]")
res = italicRegex.ReplaceAllString(res, "[::i]$1[::-]")
res = underlineRegex.ReplaceAllString(res, "[::u]$1[::-]")
res = strikeThroughRegex.ReplaceAllString(res, "[::s]$1[::-]")
return res
}

View file

@ -68,21 +68,18 @@ func NewMainFlex(app *App) *tview.Flex {
AddItem(rightFlex, 0, 4, false)
}
func NewLoginForm(onLoginFormLoginButtonSelected func(), mfa bool) *tview.Form {
f := tview.NewForm()
f.
func NewLoginForm(app *App, onLoginFormLoginButtonSelected func(), mfa bool) {
app.LoginForm.
AddButton("Login", onLoginFormLoginButtonSelected).
SetButtonsAlign(tview.AlignCenter).
SetBorder(true).
SetBorderPadding(0, 0, 1, 0)
if mfa {
f.AddPasswordField("Code", "", 0, 0, nil)
app.LoginForm.AddPasswordField("Code", "", 0, 0, nil)
} else {
f.
app.LoginForm.
AddInputField("Email", "", 0, nil, nil).
AddPasswordField("Password", "", 0, 0, nil)
}
return f
}

View file

@ -1,38 +0,0 @@
package util
import (
"github.com/ayntgl/discordgo"
)
func FindMessageByID(ms []*discordgo.Message, mID string) (int, *discordgo.Message) {
for i, m := range ms {
if m.ID == mID {
return i, m
}
}
return -1, nil
}
func ChannelIsUnread(s *discordgo.State, c *discordgo.Channel) bool {
if c.LastMessageID == "" {
return false
}
for _, rs := range s.ReadState {
if c.ID == rs.ID {
return c.LastMessageID != rs.LastMessageID
}
}
return false
}
func HasPermission(s *discordgo.State, cID string, p int64) bool {
perm, err := s.UserChannelPermissions(s.User.ID, cID)
if err != nil {
return false
}
return perm&p == p
}

View file

@ -1,59 +0,0 @@
package util
import (
"strings"
"github.com/ayntgl/discordgo"
"github.com/rivo/tview"
)
func GetNodeByReference(treeView *tview.TreeView, r interface{}) (mn *tview.TreeNode) {
treeView.GetRoot().Walk(func(n, _ *tview.TreeNode) bool {
if n.GetReference() == r {
mn = n
return false
}
return true
})
return
}
func ChannelToString(c *discordgo.Channel) string {
var repr string
if c.Name != "" {
repr = "#" + c.Name
} else if len(c.Recipients) == 1 {
rp := c.Recipients[0]
repr = rp.Username + "#" + rp.Discriminator
} else {
rps := make([]string, len(c.Recipients))
for i, r := range c.Recipients {
rps[i] = r.Username + "#" + r.Discriminator
}
repr = strings.Join(rps, ", ")
}
return repr
}
func CreateChannelNode(s *discordgo.State, c *discordgo.Channel) *tview.TreeNode {
var cn *tview.TreeNode
switch c.Type {
case discordgo.ChannelTypeGuildText, discordgo.ChannelTypeGuildNews:
tag := "[::d]"
if ChannelIsUnread(s, c) {
tag = "[::b]"
}
cn = tview.NewTreeNode(tag + ChannelToString(c) + "[::-]").
SetReference(c.ID)
case discordgo.ChannelTypeGuildCategory:
cn = tview.NewTreeNode(c.Name).
SetReference(c.ID)
}
return cn
}