go-mastodon/cmd/mstdn/cmd_stream.go

84 lines
1.9 KiB
Go
Raw Normal View History

2017-04-15 14:52:11 +02:00
package main
import (
"context"
2017-04-17 16:29:44 +02:00
"encoding/json"
2017-04-19 09:13:07 +02:00
"errors"
2017-04-15 14:52:11 +02:00
"fmt"
"os"
"os/signal"
2017-04-19 09:13:07 +02:00
"strings"
2017-04-15 14:52:11 +02:00
"github.com/fatih/color"
"github.com/mattn/go-mastodon"
"github.com/urfave/cli"
)
2017-04-17 16:43:11 +02:00
type SimpleJSON struct {
2017-04-19 08:17:26 +02:00
ID int64 `json:"id"`
2017-04-17 16:43:11 +02:00
Username string `json:"username"`
Avatar string `json:"avatar"`
Content string `json:"content"`
}
2017-04-15 14:52:11 +02:00
func cmdStream(c *cli.Context) error {
2017-04-17 16:29:44 +02:00
asJSON := c.Bool("json")
2017-04-17 16:43:11 +02:00
asSimpleJSON := c.Bool("simplejson")
2017-04-15 14:52:11 +02:00
client := c.App.Metadata["client"].(*mastodon.Client)
ctx, cancel := context.WithCancel(context.Background())
2017-04-16 16:38:53 +02:00
defer cancel()
2017-04-15 14:52:11 +02:00
sc := make(chan os.Signal, 1)
signal.Notify(sc, os.Interrupt)
2017-04-19 09:13:07 +02:00
var q chan mastodon.Event
var err error
t := c.String("type")
if t == "public" {
q, err = client.StreamingPublic(ctx)
} else if t == "" || t == "public/local" {
q, err = client.StreamingPublicLocal(ctx)
} else if strings.HasPrefix(t, "user:") {
q, err = client.StreamingUser(ctx, t[5:])
} else if strings.HasPrefix(t, "hashtag:") {
q, err = client.StreamingHashtag(ctx, t[8:])
} else {
return errors.New("invalid type")
}
2017-04-15 14:52:11 +02:00
if err != nil {
return err
}
go func() {
<-sc
cancel()
close(q)
}()
for e := range q {
2017-04-17 16:29:44 +02:00
if asJSON {
json.NewEncoder(c.App.Writer).Encode(e)
2017-04-17 16:43:11 +02:00
} else if asSimpleJSON {
if t, ok := e.(*mastodon.UpdateEvent); ok {
json.NewEncoder(c.App.Writer).Encode(&SimpleJSON{
2017-04-19 08:17:26 +02:00
ID: t.Status.ID,
2017-04-17 16:43:11 +02:00
Username: t.Status.Account.Username,
Avatar: t.Status.Account.AvatarStatic,
Content: textContent(t.Status.Content),
})
}
2017-04-17 16:29:44 +02:00
} else {
switch t := e.(type) {
case *mastodon.UpdateEvent:
color.Set(color.FgHiRed)
fmt.Fprintln(c.App.Writer, t.Status.Account.Username)
color.Set(color.Reset)
fmt.Fprintln(c.App.Writer, textContent(t.Status.Content))
case *mastodon.ErrorEvent:
color.Set(color.FgYellow)
fmt.Fprintln(c.App.Writer, t.Error())
color.Set(color.Reset)
}
2017-04-15 14:52:11 +02:00
}
}
return nil
}