Skip to content

Commit

Permalink
internal/all: add more extendable tl parse info
Browse files Browse the repository at this point in the history
  • Loading branch information
scbizu committed Jul 27, 2019
1 parent ac43ccb commit 62d4041
Show file tree
Hide file tree
Showing 8 changed files with 180 additions and 41 deletions.
23 changes: 23 additions & 0 deletions internal/discord/discord.go
Original file line number Diff line number Diff line change
Expand Up @@ -85,3 +85,26 @@ func (b *Bot) SendToChannel(channelID string, msg string) error {

return nil
}

func (b *Bot) Edit(msgID string, content string) error {
return b.editByChannel(config.DiscordCNSC2ChannelID, msgID, content)
}

func (b *Bot) editByChannel(channelID string, msgID string, content string) error {
if err := b.session.Open(); err != nil {
return err
}
defer b.session.Close()
if _, err := b.session.ChannelMessageEditEmbed(channelID, msgID, &discordgo.MessageEmbed{
Fields: []*discordgo.MessageEmbedField{
&discordgo.MessageEmbedField{
Name: "Event Closed",
Value: content,
},
}},
); err != nil {
return err
}

return nil
}
26 changes: 26 additions & 0 deletions internal/telegram/editor.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
package telegram

import (
"strconv"

tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api"
)

func (ts *Telegram) Edit(msgID string, content string) error {
iMsgID, err := strconv.ParseInt(msgID, 10, 64)
if err != nil {
return err
}
msgConfig := tgbotapi.EditMessageTextConfig{
BaseEdit: tgbotapi.BaseEdit{
ChatID: iMsgID,
ChannelUsername: CNSC2EventChannelName,
},
Text: content,
ParseMode: tgbotapi.ModeMarkdown,
}
if _, err := ts.bot.Send(msgConfig); err != nil {
return err
}
return nil
}
12 changes: 6 additions & 6 deletions internal/telegram/sender.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,15 +12,15 @@ const (
CNSC2EventChannelName = "@CNSC2EventChannel"
)

func NewTGSender(bot *Bot) *TGSender {
return &TGSender{bot}
func NewTelegram(bot *Bot) *Telegram {
return &Telegram{bot}
}

type TGSender struct {
type Telegram struct {
*Bot
}

func (ts *TGSender) Send(msg string) error {
func (ts *Telegram) Send(msg string) error {
msgConfig := tgbotapi.MessageConfig{
BaseChat: tgbotapi.BaseChat{
ChannelUsername: CNSC2EventChannelName,
Expand All @@ -34,7 +34,7 @@ func (ts *TGSender) Send(msg string) error {
return nil
}

func (ts *TGSender) SendAndReturnID(msg string) (string, error) {
func (ts *Telegram) SendAndReturnID(msg string) (string, error) {
msgConfig := tgbotapi.MessageConfig{
BaseChat: tgbotapi.BaseChat{
ChannelUsername: CNSC2EventChannelName,
Expand All @@ -49,6 +49,6 @@ func (ts *TGSender) SendAndReturnID(msg string) (string, error) {
return strconv.Itoa(resp.MessageID), nil
}

func (ts *TGSender) ResolveMessage(msgs []string) string {
func (ts *Telegram) ResolveMessage(msgs []string) string {
return strings.Join(msgs, "\n\n")
}
15 changes: 8 additions & 7 deletions internal/tl/fetch.go
Original file line number Diff line number Diff line change
Expand Up @@ -39,18 +39,18 @@ func NewCron() *mCron {
type PMatch struct {
msgID string
matchIndex int
m Match
rawMatches []Match
}

type Fetcher struct {
c *mCron
cache *cache.Cache
dsts []Sender
dsts []IRC
pushedMatches map[string]PMatch
sync.Mutex
}

func NewFetcher(s ...Sender) *Fetcher {
func NewFetcher(s ...IRC) *Fetcher {
p := make(map[string]PMatch)
return &Fetcher{
c: new(mCron),
Expand All @@ -62,7 +62,8 @@ func NewFetcher(s ...Sender) *Fetcher {

func (f *Fetcher) Do() error {
// run match GC
go GetStashChan().Run()
go GetStashChan().Run(f.dsts...)

f.c = NewCron()
f.c.c.AddFunc("@every 5m", func() {
if err := f.refreshCache(); err != nil {
Expand Down Expand Up @@ -213,12 +214,12 @@ func (f *Fetcher) pushWithLimit(matches []Match, limit int) {
msgID, err := dst.SendAndReturnID(msg)
if err != nil {
logrus.Errorf("sender: %s", err.Error())
return
}
f.Lock()
for i, m := range splitMatches[idx] {
// TODO: msgid
msg := msgID
f.pushedMatches[m.GetMDMatchInfo()] = PMatch{msgID: msg, matchIndex: i, m: m}
mid := msgID
f.pushedMatches[m.GetMDMatchInfo()] = PMatch{rawMatches: splitMatches[idx], msgID: mid, matchIndex: i}
}
f.Unlock()
idx++
Expand Down
9 changes: 9 additions & 0 deletions internal/tl/sender.go → internal/tl/message_spec.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,3 +5,12 @@ type Sender interface {
ResolveMessage([]string) string
SendAndReturnID(string) (string, error)
}

type Editor interface {
Edit(msgID string, content string) error
}

type IRC interface {
Sender
Editor
}
99 changes: 74 additions & 25 deletions internal/tl/parse.go
Original file line number Diff line number Diff line change
Expand Up @@ -75,14 +75,15 @@ type MatchParser struct {

type Match struct {
isOnGoing bool
vs string
vs Versus
timeCountingDown string
series string
stream []string
detailURL *url.URL
}

func (m Match) GetVS() string {
return m.vs
return m.vs.f()
}

func (m Match) GetMDMatchInfo() string {
Expand Down Expand Up @@ -172,6 +173,19 @@ func (mp MatchParser) GetTimeMatches() (map[int64][]Match, error) {
lp := s.Find(`.team-left`).Text()
rp := s.Find(`.team-right`).Text()
versus := s.Find(`.versus`).Text()
vs := strings.Replace(versus, "\n", "", -1)
if strings.Contains(vs, "vs") {
vs = ""
}
score := strings.Split(versus, ":")
var s1, s2 string
if len(score) == 0 {
s1 = "0"
s2 = "0"
} else {
s1 = score[0]
s2 = score[1]
}
t, err := time.Parse(timeFmt, s.Find(`.timer-object-countdown-only`).Text())
if err != nil {
logrus.Errorf("parse failed: %s", err.Error())
Expand All @@ -185,6 +199,7 @@ func (mp MatchParser) GetTimeMatches() (map[int64][]Match, error) {
countDown := time.Until(t.In(cn))
if int64(countDown) <= 0 {
var streams []string
var u *url.URL
tournament := s.Find(`.match-filler > div`).Text()
if tournament == "" {
tournament = "未知"
Expand All @@ -197,20 +212,31 @@ func (mp MatchParser) GetTimeMatches() (map[int64][]Match, error) {
if !ok {
matches[t.In(cn).Unix()] = append(matches[t.In(cn).Unix()], Match{
isOnGoing: true,
vs: fmt.Sprintf("%s vs %s (%s)", trimText(lp), trimText(rp), versus),
series: strings.TrimSpace(tournament),
stream: []string{"直播源解析失败"},
vs: Versus{
P1: trimText(lp),
P2: trimText(rp),
P1Score: s1,
P2Score: s2,
},
series: strings.TrimSpace(tournament),
stream: []string{"直播源解析失败"},
})
return
}
u, err := url.Parse("https://liquipedia.net" + detailURL)
var err error
u, err = url.Parse("https://liquipedia.net" + detailURL)
if err != nil {
logrus.Warnf("match parser: %q", err)
matches[t.In(cn).Unix()] = append(matches[t.In(cn).Unix()], Match{
isOnGoing: true,
vs: fmt.Sprintf("%s vs %s (%s)", trimText(lp), trimText(rp), versus),
series: strings.TrimSpace(tournament),
stream: []string{"直播源解析失败"},
vs: Versus{
P1: trimText(lp),
P2: trimText(rp),
P1Score: s1,
P2Score: s2,
},
series: strings.TrimSpace(tournament),
stream: []string{"直播源解析失败"},
})
return
}
Expand All @@ -219,9 +245,14 @@ func (mp MatchParser) GetTimeMatches() (map[int64][]Match, error) {
logrus.Warnf("fetch match detail: %q", err)
matches[t.In(cn).Unix()] = append(matches[t.In(cn).Unix()], Match{
isOnGoing: true,
vs: fmt.Sprintf("%s vs %s (%s)", trimText(lp), trimText(rp), versus),
series: strings.TrimSpace(tournament),
stream: []string{"直播源解析失败"},
vs: Versus{
P1: trimText(lp),
P2: trimText(rp),
P1Score: s1,
P2Score: s2,
},
series: strings.TrimSpace(tournament),
stream: []string{"直播源解析失败"},
})
return
}
Expand All @@ -237,19 +268,17 @@ func (mp MatchParser) GetTimeMatches() (map[int64][]Match, error) {
if len(streams) == 0 {
streams = append(streams, "直播源解析失败")
}
vs := strings.Replace(versus, "\n", "", -1)
if strings.Contains(vs, "vs") {
vs = ""
}
matches[t.In(cn).Unix()] = append(matches[t.In(cn).Unix()], Match{
isOnGoing: true,
vs: fmt.Sprintf("%s vs %s (%s)",
trimText(lp),
trimText(rp),
vs,
),
series: strings.TrimSpace(tournament),
stream: streams,
vs: Versus{
P1: trimText(lp),
P2: trimText(rp),
P1Score: s1,
P2Score: s2,
},
series: strings.TrimSpace(tournament),
stream: streams,
detailURL: u,
})
}

Expand All @@ -259,8 +288,13 @@ func (mp MatchParser) GetTimeMatches() (map[int64][]Match, error) {
tournament = "未知"
}
matches[t.In(cn).Unix()] = append(matches[t.In(cn).Unix()], Match{
isOnGoing: false,
vs: fmt.Sprintf("%s vs %s", trimText(lp), trimText(rp)),
isOnGoing: false,
vs: Versus{
P1: trimText(lp),
P2: trimText(rp),
P1Score: s1,
P2Score: s2,
},
timeCountingDown: countDown.String(),
series: strings.TrimSpace(tournament),
})
Expand Down Expand Up @@ -372,3 +406,18 @@ type Stream struct {
func (s Stream) FmtToMarkdown() string {
return fmt.Sprintf("[%s](%s)", s.caster, s.streammingURL)
}

type Versus struct {
P1 string
P2 string
P1Score string
P2Score string
}

func (v Versus) f() string {
return fmt.Sprintf("%s vs %s (%s:%s)", v.P1, v.P2, v.P1Score, v.P2Score)
}

func GetFinalMatchRes(u *url.URL, p1, p2 string) (Versus, error) {
return Versus{}, nil
}
35 changes: 33 additions & 2 deletions internal/tl/terminated.go
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
package tl

import "github.com/sirupsen/logrus"

type Stash chan PMatch

var (
Expand All @@ -17,11 +19,40 @@ func (s Stash) Put(m PMatch) {
s <- m
}

func (s Stash) Run() {
func (s Stash) Run(ircs ...IRC) {
for {
select {
case <-s:
case msg := <-s:
// TODO: terminated the match
match := msg.rawMatches[msg.matchIndex]
vs, err := GetFinalMatchRes(match.detailURL, match.vs.P1, match.vs.P2)
if err != nil {
logrus.Warnf("update message: %q", err)
vs = Versus{
P1: match.vs.P1,
P2: match.vs.P2,
P1Score: match.vs.P1Score,
P2Score: match.vs.P2Score,
}
}
msg.rawMatches[msg.matchIndex] = Match{
isOnGoing: match.isOnGoing,
vs: vs,
timeCountingDown: match.timeCountingDown,
series: match.series,
stream: match.stream,
}
var strs []string
for _, m := range msg.rawMatches {
strs = append(strs, m.GetMDMatchInfo())
}
for _, irc := range ircs {
content := irc.ResolveMessage(strs)
if err := irc.Edit(msg.msgID, content); err != nil {
logrus.Errorf("update message: %q", err)
continue
}
}
}
}
}
2 changes: 1 addition & 1 deletion service/push/push.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ func (ps *PushService) ServePushSC2Event() error {
if err != nil {
return err
}
tgSender := telegram.NewTGSender(tgBot)
tgSender := telegram.NewTelegram(tgBot)
f := tl.NewFetcher(tgSender, discordSender)
if err := f.Do(); err != nil {
return fmt.Errorf("tl: %s", err.Error())
Expand Down

0 comments on commit 62d4041

Please sign in to comment.