Skip to content

Commit

Permalink
feat: set buttom (indes#200)
Browse files Browse the repository at this point in the history
  • Loading branch information
indes committed Sep 14, 2022
1 parent 47e7195 commit 3a507c6
Show file tree
Hide file tree
Showing 13 changed files with 216 additions and 85 deletions.
6 changes: 3 additions & 3 deletions internal/bot/bot.go
Original file line number Diff line number Diff line change
Expand Up @@ -83,8 +83,8 @@ func setCommands() {
handler.NewRemoveAllSubscription(),
handler.NewOnDocument(B, Core),
handler.NewSet(B, Core),
handler.NewSetFeedTag(),
handler.NewSetUpdateInterval(),
handler.NewSetFeedTag(Core),
handler.NewSetUpdateInterval(Core),
handler.NewExport(Core),
handler.NewImport(),
handler.NewPauseAll(),
Expand All @@ -100,7 +100,7 @@ func setCommands() {
ButtonHandlers := []handler.ButtonHandler{
handler.NewRemoveAllSubscriptionButton(Core),
handler.NewCancelRemoveAllSubscriptionButton(),
handler.NewSetFeedItemButton(B),
handler.NewSetFeedItemButton(B, Core),
handler.NewRemoveSubscriptionItemButton(Core),
handler.NewNotificationSwitchButton(B),
handler.NewSetSubscriptionTagButton(B),
Expand Down
16 changes: 9 additions & 7 deletions internal/bot/handler/set.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import (
"strings"
"text/template"

"github.com/spf13/cast"
tb "gopkg.in/telebot.v3"

"github.com/indes/flowerss-bot/internal/bot/chat"
Expand Down Expand Up @@ -90,7 +91,7 @@ const (
SetFeedItemButtonUnique = "set_feed_item_btn"
feedSettingTmpl = `
订阅<b>设置</b>
[id] {{ .sub.ID }}
[id] {{ .source.ID }}
[标题] {{ .source.Title }}
[Link] {{.source.Link }}
[抓取更新] {{if ge .source.ErrorCount .Count }}暂停{{else if lt .source.ErrorCount .Count }}抓取中{{end}}
Expand All @@ -102,11 +103,12 @@ const (
)

type SetFeedItemButton struct {
bot *tb.Bot
bot *tb.Bot
core *core.Core
}

func NewSetFeedItemButton(bot *tb.Bot) *SetFeedItemButton {
return &SetFeedItemButton{bot: bot}
func NewSetFeedItemButton(bot *tb.Bot, core *core.Core) *SetFeedItemButton {
return &SetFeedItemButton{bot: bot, core: core}
}

func (r *SetFeedItemButton) CallbackUnique() string {
Expand Down Expand Up @@ -135,13 +137,13 @@ func (r *SetFeedItemButton) Handle(ctx tb.Context) error {
}
}

sourceID, _ := strconv.Atoi(data[1])
source, err := model.GetSourceById(uint(sourceID))
sourceID := cast.ToUint(data[1])
source, err := r.core.GetSource(context.Background(), sourceID)
if err != nil {
return ctx.Edit("找不到该订阅源")
}

sub, err := model.GetSubscribeByUserIDAndSourceID(subscriberID, source.ID)
sub, err := r.core.GetSubscription(context.Background(), subscriberID, source.ID)
if err != nil {
return ctx.Edit("用户未订阅该rss")
}
Expand Down
33 changes: 11 additions & 22 deletions internal/bot/handler/set_feed_tag.go
Original file line number Diff line number Diff line change
@@ -1,21 +1,23 @@
package handler

import (
"strconv"
"context"
"strings"

"github.com/spf13/cast"
tb "gopkg.in/telebot.v3"

"github.com/indes/flowerss-bot/internal/bot/message"
"github.com/indes/flowerss-bot/internal/bot/session"
"github.com/indes/flowerss-bot/internal/model"

tb "gopkg.in/telebot.v3"
"github.com/indes/flowerss-bot/internal/core"
)

type SetFeedTag struct {
core *core.Core
}

func NewSetFeedTag() *SetFeedTag {
return &SetFeedTag{}
func NewSetFeedTag(core *core.Core) *SetFeedTag {
return &SetFeedTag{core: core}
}

func (s *SetFeedTag) Command() string {
Expand All @@ -38,36 +40,23 @@ func (s *SetFeedTag) Handle(ctx tb.Context) error {
msg := s.getMessageWithoutMention(ctx)
args := strings.Split(strings.TrimSpace(msg), " ")
if len(args) < 1 {
return ctx.Reply("/setfeedtag [sub id] [tag1] [tag2] 设置订阅标签(最多设置三个Tag,以空格分割)")
return ctx.Reply("/setfeedtag [sourceID] [tag1] [tag2] 设置订阅标签(最多设置三个Tag,以空格分割)")
}

// 截短参数
if len(args) > 4 {
args = args[:4]
}
subID, err := strconv.Atoi(args[0])
if err != nil {
return ctx.Reply("请输入正确的订阅id!")
}

sub, err := model.GetSubscribeByID(subID)
if err != nil || sub == nil {
return ctx.Reply("请输入正确的订阅id!")
}

sourceID := cast.ToUint(args[0])
mentionChat, _ := session.GetMentionChatFromCtxStore(ctx)
subscribeUserID := ctx.Chat().ID
if mentionChat != nil {
subscribeUserID = mentionChat.ID
}

if subscribeUserID != sub.UserID {
return ctx.Reply("订阅记录与操作者id不一致")
}

if err := sub.SetTag(args[1:]); err != nil {
if err := s.core.SetSubscriptionTag(context.Background(), subscribeUserID, sourceID, args[1:]); err != nil {
return ctx.Reply("订阅标签设置失败!")

}
return ctx.Reply("订阅标签设置成功!")
}
Expand Down
12 changes: 3 additions & 9 deletions internal/bot/handler/set_subscription_tag_button.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,10 @@ import (
"strconv"
"strings"

"github.com/spf13/cast"
tb "gopkg.in/telebot.v3"

"github.com/indes/flowerss-bot/internal/bot/chat"
"github.com/indes/flowerss-bot/internal/model"
)

const (
Expand Down Expand Up @@ -55,17 +55,11 @@ func (b *SetSubscriptionTagButton) Handle(ctx tb.Context) error {
return ctx.Send("无权限")
}
data := strings.Split(c.Data, ":")
ownID, _ := strconv.Atoi(data[0])
sourceID, _ := strconv.Atoi(data[1])

sub, err := model.GetSubscribeByUserIDAndSourceID(int64(ownID), uint(sourceID))
if err != nil {
return ctx.Send("系统错误,代码04")
}
sourceID := cast.ToUint(data[1])
msg := fmt.Sprintf(
"请使用`/setfeedtag %d tags`命令为该订阅设置标签,tags为需要设置的标签,以空格分隔。(最多设置三个标签) \n"+
"例如:`/setfeedtag %d 科技 苹果`",
sub.ID, sub.ID,
sourceID, sourceID,
)
return ctx.Edit(msg, &tb.SendOptions{ParseMode: tb.ModeMarkdown})
}
Expand Down
33 changes: 15 additions & 18 deletions internal/bot/handler/set_update_interval.go
Original file line number Diff line number Diff line change
@@ -1,21 +1,25 @@
package handler

import (
"context"
"strconv"
"strings"

"github.com/spf13/cast"
tb "gopkg.in/telebot.v3"

"github.com/indes/flowerss-bot/internal/bot/message"
"github.com/indes/flowerss-bot/internal/bot/session"
"github.com/indes/flowerss-bot/internal/model"
"github.com/indes/flowerss-bot/internal/core"
"github.com/indes/flowerss-bot/internal/log"
)

type SetUpdateInterval struct {
core *core.Core
}

func NewSetUpdateInterval() *SetUpdateInterval {
return &SetUpdateInterval{}
func NewSetUpdateInterval(core *core.Core) *SetUpdateInterval {
return &SetUpdateInterval{core: core}
}

func (s *SetUpdateInterval) Command() string {
Expand All @@ -38,7 +42,7 @@ func (s *SetUpdateInterval) Handle(ctx tb.Context) error {
msg := s.getMessageWithoutMention(ctx)
args := strings.Split(strings.TrimSpace(msg), " ")
if len(args) < 2 {
return ctx.Reply("/setinterval [interval] [sub id] 设置订阅刷新频率(可设置多个sub id,以空格分割)")
return ctx.Reply("/setinterval [interval] [sourceID] 设置订阅刷新频率(可设置多个sub id,以空格分割)")
}

interval, err := strconv.Atoi(args[0])
Expand All @@ -51,22 +55,15 @@ func (s *SetUpdateInterval) Handle(ctx tb.Context) error {
if mentionChat != nil {
subscribeUserID = mentionChat.ID
}
for _, id := range args[1:] {
subID, err := strconv.Atoi(id)
if err != nil {
return ctx.Reply("请输入正确的订阅id!")
}

sub, err := model.GetSubscribeByID(subID)
if err != nil || sub == nil {
return ctx.Reply("请输入正确的订阅id!")
}

if sub.UserID != subscribeUserID {
return ctx.Reply("订阅id与订阅者id不匹配!")
for _, id := range args[1:] {
sourceID := cast.ToUint(id)
if err := s.core.SetSubscriptionInterval(
context.Background(), subscribeUserID, sourceID, interval,
); err != nil {
log.Errorf("SetSubscriptionInterval failed, %v", err)
return ctx.Reply("抓取频率设置失败!")
}

_ = sub.SetInterval(interval)
}
return ctx.Reply("抓取频率设置成功!")
}
Expand Down
35 changes: 35 additions & 0 deletions internal/core/core.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package core
import (
"context"
"errors"
"strings"
"sync"

"gorm.io/driver/mysql"
Expand Down Expand Up @@ -213,3 +214,37 @@ func (c *Core) UnsubscribeAllSource(ctx context.Context, userID int64) error {
wg.Wait()
return nil
}

// GetSubscription 获取订阅
func (c *Core) GetSubscription(ctx context.Context, userID int64, sourceID uint) (*model.Subscribe, error) {
subscription, err := c.subscriptionStorage.GetSubscription(ctx, userID, sourceID)
if err != nil {
if err == storage.ErrRecordNotFound {
return nil, ErrSubscriptionNotExist
}
return nil, err
}
return subscription, nil
}

// SetSubscriptionTag 设置订阅标签
func (c *Core) SetSubscriptionTag(ctx context.Context, userID int64, sourceID uint, tags []string) error {
subscription, err := c.GetSubscription(ctx, userID, sourceID)
if err != nil {
return err
}

subscription.Tag = "#" + strings.Join(tags, " #")
return c.subscriptionStorage.UpdateSubscription(ctx, userID, sourceID, subscription)
}

// SetSubscriptionInterval
func (c *Core) SetSubscriptionInterval(ctx context.Context, userID int64, sourceID uint, interval int) error {
subscription, err := c.GetSubscription(ctx, userID, sourceID)
if err != nil {
return err
}

subscription.Interval = interval
return c.subscriptionStorage.UpdateSubscription(ctx, userID, sourceID, subscription)
}
41 changes: 41 additions & 0 deletions internal/core/core_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -308,3 +308,44 @@ func TestCore_GetSource(t *testing.T) {
},
)
}

func TestCore_GetSubscription(t *testing.T) {
c, s := getTestCore(t)
defer s.Ctrl.Finish()
ctx := context.Background()
userID := int64(101)
sourceID := uint(1)

t.Run(
"subscription err", func(t *testing.T) {
s.Subscription.EXPECT().GetSubscription(ctx, userID, sourceID).Return(
nil, errors.New("err"),
).Times(1)
got, err := c.GetSubscription(ctx, userID, sourceID)
assert.Error(t, err)
assert.Nil(t, got)
},
)

t.Run(
"subscription not exist", func(t *testing.T) {
s.Subscription.EXPECT().GetSubscription(ctx, userID, sourceID).Return(
nil, storage.ErrRecordNotFound,
).Times(1)
got, err := c.GetSubscription(ctx, userID, sourceID)
assert.Equal(t, ErrSubscriptionNotExist, err)
assert.Nil(t, got)
},
)

t.Run(
"ok", func(t *testing.T) {
s.Subscription.EXPECT().GetSubscription(ctx, userID, sourceID).Return(
&model.Subscribe{}, nil,
).Times(1)
got, err := c.GetSubscription(ctx, userID, sourceID)
assert.Nil(t, err)
assert.NotNil(t, got)
},
)
}
4 changes: 4 additions & 0 deletions internal/log/log.go
Original file line number Diff line number Diff line change
Expand Up @@ -71,3 +71,7 @@ func Fatal(args ...interface{}) {
func Fatalf(template string, args ...interface{}) {
globalLogger.Sugar().Fatalf(template, args...)
}

func Debugf(template string, args ...interface{}) {
globalLogger.Sugar().Debugf(template, args...)
}
25 changes: 0 additions & 25 deletions internal/model/subscribe.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ package model

import (
"errors"
"strings"

"github.com/indes/flowerss-bot/internal/config"
)
Expand All @@ -23,15 +22,6 @@ type Subscribe struct {
EditTime
}

func GetSubscribeByUserIDAndSourceID(userID int64, sourceID uint) (*Subscribe, error) {
var sub Subscribe
db.Where("user_id=? and source_id=?", userID, sourceID).First(&sub)
if sub.UserID != int64(userID) {
return nil, errors.New("未订阅该RSS源")
}
return &sub, nil
}

func GetSubscriberBySource(s *Source) []*Subscribe {
if s == nil {
return []*Subscribe{}
Expand Down Expand Up @@ -86,21 +76,6 @@ func (s *Source) ToggleEnabled() error {
return nil
}

func (s *Subscribe) SetTag(tags []string) error {
defer s.Save()

tagStr := strings.Join(tags, " #")

s.Tag = "#" + tagStr
return nil
}

func (s *Subscribe) SetInterval(interval int) error {
defer s.Save()
s.Interval = interval
return nil
}

func (s *Subscribe) Unsub() error {
if s.ID == 0 {
return errors.New("can't delete 0 subscribe")
Expand Down
Loading

0 comments on commit 3a507c6

Please sign in to comment.