Merge branch 'master' into account

This commit is contained in:
178inaba 2017-04-14 10:23:02 +09:00
commit 5952b20812
2 changed files with 192 additions and 84 deletions

View File

@ -3,23 +3,27 @@ package main
import ( import (
"bufio" "bufio"
"bytes" "bytes"
"context"
"encoding/json" "encoding/json"
"flag" "flag"
"fmt" "fmt"
"io/ioutil" "io/ioutil"
"log" "log"
"os" "os"
"os/signal"
"path/filepath" "path/filepath"
"runtime" "runtime"
"strings" "strings"
"github.com/fatih/color"
"github.com/mattn/go-mastodon" "github.com/mattn/go-mastodon"
"github.com/mattn/go-tty" "github.com/mattn/go-tty"
"golang.org/x/net/html" "golang.org/x/net/html"
) )
var ( var (
toot = flag.String("t", "", "toot text") toot = flag.String("t", "", "toot text")
stream = flag.Bool("S", false, "streaming public")
) )
func extractText(node *html.Node, w *bytes.Buffer) { func extractText(node *html.Node, w *bytes.Buffer) {
@ -38,6 +42,16 @@ func extractText(node *html.Node, w *bytes.Buffer) {
} }
} }
func textContent(s string) string {
doc, err := html.Parse(strings.NewReader(s))
if err != nil {
log.Fatal(err)
}
var buf bytes.Buffer
extractText(doc, &buf)
return buf.String()
}
func prompt() (string, string, error) { func prompt() (string, string, error) {
t, err := tty.Open() t, err := tty.Open()
if err != nil { if err != nil {
@ -132,19 +146,39 @@ func main() {
} }
return return
} }
if *stream {
ctx, cancel := context.WithCancel(context.Background())
sc := make(chan os.Signal, 1)
signal.Notify(sc, os.Interrupt)
q, err := client.StreamingPublic(ctx)
if err != nil {
log.Fatal(err)
}
go func() {
<-sc
cancel()
close(q)
}()
for e := range q {
switch t := e.(type) {
case *mastodon.UpdateEvent:
color.Set(color.FgHiRed)
fmt.Println(t.Status.Account.Username)
color.Set(color.Reset)
fmt.Println(textContent(t.Status.Content))
}
}
return
}
timeline, err := client.GetTimelineHome() timeline, err := client.GetTimelineHome()
if err != nil { if err != nil {
log.Fatal(err) log.Fatal(err)
} }
for _, t := range timeline { for _, t := range timeline {
doc, err := html.Parse(strings.NewReader(t.Content)) color.Set(color.FgHiRed)
if err != nil {
log.Fatal(err)
}
var buf bytes.Buffer
extractText(doc, &buf)
fmt.Println(t.Account.Username) fmt.Println(t.Account.Username)
fmt.Println(buf.String()) color.Set(color.Reset)
fmt.Println(textContent(t.Content))
} }
} }

View File

@ -1,6 +1,8 @@
package mastodon package mastodon
import ( import (
"bufio"
"context"
"encoding/json" "encoding/json"
"fmt" "fmt"
"net/http" "net/http"
@ -65,6 +67,63 @@ func (c *client) Authenticate(username, password string) error {
return nil return nil
} }
// AppConfig is a setting for registering applications.
type AppConfig struct {
http.Client
Server string
ClientName string
// Where the user should be redirected after authorization (for no redirect, use urn:ietf:wg:oauth:2.0:oob)
RedirectURIs string
// This can be a space-separated list of the following items: "read", "write" and "follow".
Scopes string
// Optional.
Website string
}
// Application is mastodon application.
type Application struct {
ID int64 `json:"id"`
RedirectURI string `json:"redirect_uri"`
ClientID string `json:"client_id"`
ClientSecret string `json:"client_secret"`
}
// RegisterApp returns the mastodon application.
func RegisterApp(appConfig *AppConfig) (*Application, error) {
params := url.Values{}
params.Set("client_name", appConfig.ClientName)
params.Set("redirect_uris", appConfig.RedirectURIs)
params.Set("scopes", appConfig.Scopes)
params.Set("website", appConfig.Website)
url, err := url.Parse(appConfig.Server)
if err != nil {
return nil, err
}
url.Path = path.Join(url.Path, "/api/v1/apps")
req, err := http.NewRequest("POST", url.String(), strings.NewReader(params.Encode()))
if err != nil {
return nil, err
}
resp, err := appConfig.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
app := &Application{}
err = json.NewDecoder(resp.Body).Decode(app)
if err != nil {
return nil, err
}
return app, nil
}
type Account struct { type Account struct {
ID int64 `json:"id"` ID int64 `json:"id"`
Username string `json:"username"` Username string `json:"username"`
@ -83,32 +142,6 @@ type Account struct {
HeaderStatic string `json:"header_static"` HeaderStatic string `json:"header_static"`
} }
func (c *client) GetAccount(id int) (*Account, error) {
url, err := url.Parse(c.config.Server)
if err != nil {
return nil, err
}
url.Path = path.Join(url.Path, fmt.Sprintf("/api/v1/accounts/%d", id))
req, err := http.NewRequest("GET", url.String(), nil)
if err != nil {
return nil, err
}
req.Header.Set("Authorization", "Bearer "+c.config.AccessToken)
resp, err := c.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
account := &Account{}
err = json.NewDecoder(resp.Body).Decode(account)
if err != nil {
return nil, err
}
return account, nil
}
type Visibility int64 type Visibility int64
type Toot struct { type Toot struct {
@ -143,6 +176,32 @@ type Status struct {
Reblogged interface{} `json:"reblogged"` Reblogged interface{} `json:"reblogged"`
} }
func (c *client) GetAccount(id int) (*Account, error) {
url, err := url.Parse(c.config.Server)
if err != nil {
return nil, err
}
url.Path = path.Join(url.Path, fmt.Sprintf("/api/v1/accounts/%d", id))
req, err := http.NewRequest("GET", url.String(), nil)
if err != nil {
return nil, err
}
req.Header.Set("Authorization", "Bearer "+c.config.AccessToken)
resp, err := c.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
account := &Account{}
err = json.NewDecoder(resp.Body).Decode(account)
if err != nil {
return nil, err
}
return account, nil
}
func (c *client) GetTimelineHome() ([]*Status, error) { func (c *client) GetTimelineHome() ([]*Status, error) {
url, err := url.Parse(c.config.Server) url, err := url.Parse(c.config.Server)
if err != nil { if err != nil {
@ -201,59 +260,74 @@ func (c *client) PostStatus(toot *Toot) (*Status, error) {
return &status, nil return &status, nil
} }
// AppConfig is a setting for registering applications. type UpdateEvent struct {
type AppConfig struct { Status *Status
http.Client
Server string
ClientName string
// Where the user should be redirected after authorization (for no redirect, use urn:ietf:wg:oauth:2.0:oob)
RedirectURIs string
// This can be a space-separated list of the following items: "read", "write" and "follow".
Scopes string
// Optional.
Website string
} }
// Application is mastodon application. func (e *UpdateEvent) event() {}
type Application struct {
ID int64 `json:"id"` type NotificationEvent struct {
RedirectURI string `json:"redirect_uri"`
ClientID string `json:"client_id"`
ClientSecret string `json:"client_secret"`
} }
// RegisterApp returns the mastodon application. func (e *NotificationEvent) event() {}
func RegisterApp(appConfig *AppConfig) (*Application, error) {
params := url.Values{}
params.Set("client_name", appConfig.ClientName)
params.Set("redirect_uris", appConfig.RedirectURIs)
params.Set("scopes", appConfig.Scopes)
params.Set("website", appConfig.Website)
url, err := url.Parse(appConfig.Server) type DeleteEvent struct {
if err != nil { ID int64
return nil, err }
}
url.Path = path.Join(url.Path, "/api/v1/apps") func (e *DeleteEvent) event() {}
req, err := http.NewRequest("POST", url.String(), strings.NewReader(params.Encode())) type Event interface {
if err != nil { event()
return nil, err }
}
resp, err := appConfig.Do(req) func (c *client) StreamingPublic(ctx context.Context) (chan Event, error) {
if err != nil { url, err := url.Parse(c.config.Server)
return nil, err if err != nil {
} return nil, err
defer resp.Body.Close() }
url.Path = path.Join(url.Path, "/api/v1/streaming/public")
app := &Application{}
err = json.NewDecoder(resp.Body).Decode(app) req, err := http.NewRequest("GET", url.String(), nil)
if err != nil { if err != nil {
return nil, err return nil, err
} }
req.Header.Set("Authorization", "Bearer "+c.config.AccessToken)
return app, nil resp, err := c.Do(req)
if err != nil {
return nil, err
}
q := make(chan Event)
go func() {
defer ctx.Done()
name := ""
s := bufio.NewScanner(resp.Body)
for s.Scan() {
line := s.Text()
token := strings.SplitN(line, ":", 2)
if len(token) != 2 {
continue
}
switch strings.TrimSpace(token[0]) {
case "event":
name = strings.TrimSpace(token[1])
case "data":
switch name {
case "update":
var status Status
json.Unmarshal([]byte(token[1]), &status)
q <- &UpdateEvent{&status}
case "notification":
case "delete":
}
}
}
fmt.Println(s.Err())
}()
go func() {
<-ctx.Done()
resp.Body.Close()
}()
return q, nil
} }