Compare commits

..

No commits in common. "108ba6a5df821fa2375f1a23496884c4da320605" and "2c5123253a180493c4c59c13edbbb464fa63b7ac" have entirely different histories.

7 changed files with 130 additions and 323 deletions

View file

@ -4,37 +4,69 @@ import (
"errors"
"flag"
"fmt"
"strings"
"unicode"
"codeflow.dananglin.me.uk/apollo/enbas/internal/client"
"codeflow.dananglin.me.uk/apollo/enbas/internal/config"
"codeflow.dananglin.me.uk/apollo/enbas/internal/model"
"golang.org/x/net/html"
)
var instanceDetailsFormat = `INSTANCE:
%s - %s
DOMAIN:
%s
VERSION:
Running GoToSocial %s
CONTACT:
name: %s
username: %s
email: %s
`
var accountDetailsFormat = `
%s (@%s)
ACCOUNT ID:
%s
JOINED ON:
%s
STATS:
Followers: %d
Following: %d
Statuses: %d
BIOGRAPHY:
%s
METADATA: %s
ACCOUNT URL:
%s
`
type showCommand struct {
*flag.FlagSet
myAccount bool
targetType string
account string
statusID string
timelineType string
timelineListID string
timelineTagName string
timelineLimit int
myAccount bool
}
func newShowCommand(name, summary string) *showCommand {
command := showCommand{
FlagSet: flag.NewFlagSet(name, flag.ExitOnError),
targetType: "",
myAccount: false,
}
command.BoolVar(&command.myAccount, "my-account", false, "set to true to lookup your account")
command.StringVar(&command.targetType, "type", "", "specify the type of resource to display")
command.StringVar(&command.account, "account", "", "specify the account URI to lookup")
command.StringVar(&command.statusID, "status-id", "", "specify the ID of the status to display")
command.StringVar(&command.timelineType, "timeline-type", "home", "specify the type of timeline to display (valid values are home, public, list and tag)")
command.StringVar(&command.timelineListID, "timeline-list-id", "", "specify the ID of the list timeline to display")
command.StringVar(&command.timelineTagName, "timeline-tag-name", "", "specify the name of the tag timeline to display")
command.IntVar(&command.timelineLimit, "timeline-limit", 5, "specify the number of statuses to display")
command.BoolVar(&command.myAccount, "my-account", false, "set to true to lookup your account")
command.Usage = commandUsageFunc(name, summary, command.FlagSet)
return &command
@ -49,8 +81,6 @@ func (c *showCommand) Execute() error {
funcMap := map[string]func(*client.Client) error{
"instance": c.showInstance,
"account": c.showAccount,
"status": c.showStatus,
"timeline": c.showTimeline,
}
doFunc, ok := funcMap[c.targetType]
@ -67,7 +97,16 @@ func (c *showCommand) showInstance(gts *client.Client) error {
return fmt.Errorf("unable to retrieve the instance details; %w", err)
}
fmt.Println(instance)
fmt.Printf(
instanceDetailsFormat,
instance.Title,
instance.Description,
instance.Domain,
instance.Version,
instance.Contact.Account.DisplayName,
instance.Contact.Account.Username,
instance.Contact.Email,
)
return nil
}
@ -95,72 +134,64 @@ func (c *showCommand) showAccount(gts *client.Client) error {
return fmt.Errorf("unable to retrieve the account details; %w", err)
}
fmt.Println(account)
metadata := ""
return nil
for _, field := range account.Fields {
metadata += fmt.Sprintf("\n %s: %s", field.Name, stripHTMLTags(field.Value))
}
func (c *showCommand) showStatus(gts *client.Client) error {
if c.statusID == "" {
return errors.New("the status-id flag is not set")
}
status, err := gts.GetStatus(c.statusID)
if err != nil {
return fmt.Errorf("unable to retrieve the status; %w", err)
}
fmt.Println(status)
return nil
}
func (c *showCommand) showTimeline(gts *client.Client) error {
var (
statuses []model.Status
err error
fmt.Printf(
accountDetailsFormat,
account.DisplayName,
account.Username,
account.ID,
account.CreatedAt.Format("02 Jan 2006"),
account.FollowersCount,
account.FollowingCount,
account.StatusCount,
wrapLine(stripHTMLTags(account.Note), "\n ", 80),
metadata,
account.URL,
)
switch c.timelineType {
case "home":
statuses, err = gts.GetHomeTimeline(c.timelineLimit)
case "public":
statuses, err = gts.GetPublicTimeline(c.timelineLimit)
case "list":
if c.timelineListID == "" {
return errors.New("the timeline-list-id flag is not set")
}
statuses, err = gts.GetListTimeline(c.timelineListID, c.timelineLimit)
case "tag":
if c.timelineTagName == "" {
return errors.New("the timeline-tag-name flag is not set")
}
statuses, err = gts.GetTagTimeline(c.timelineTagName, c.timelineLimit)
default:
return fmt.Errorf("%q is not a valid type of timeline", c.timelineType)
}
if err != nil {
return fmt.Errorf("unable to retrieve the %s timeline; %w", c.timelineType, err)
}
if len(statuses) == 0 {
fmt.Println("There are no statuses in this timeline.")
return nil
}
func stripHTMLTags(text string) string {
token := html.NewTokenizer(strings.NewReader(text))
separator := "────────────────────────────────────────────────────────────────────────"
var builder strings.Builder
fmt.Println(separator)
for _, status := range statuses {
fmt.Println(status)
fmt.Println(separator)
for {
tt := token.Next()
switch tt {
case html.ErrorToken:
return builder.String()
case html.TextToken:
builder.WriteString(token.Token().Data + " ")
}
}
}
return nil
func wrapLine(line, separator string, charLimit int) string {
if len(line) <= charLimit {
return line
}
leftcursor, rightcursor := 0, 0
var builder strings.Builder
for rightcursor < (len(line) - charLimit) {
rightcursor += charLimit
for !unicode.IsSpace(rune(line[rightcursor-1])) {
rightcursor--
}
builder.WriteString(line[leftcursor:rightcursor] + separator)
leftcursor = rightcursor
}
builder.WriteString(line[rightcursor:])
return builder.String()
}

View file

@ -22,7 +22,8 @@ func commandUsageFunc(name, summary string, flagset *flag.FlagSet) func() {
flagset.VisitAll(func(f *flag.Flag) {
fmt.Fprintf(
&builder,
"\n --%s\n %s",
"\n -%s, --%s\n %s",
f.Name,
f.Name,
f.Usage,
)
@ -62,9 +63,9 @@ func enbasUsageFunc(summaries map[string]string) func() {
fmt.Fprintf(&builder, "\n %s\t%s", cmd, summaries[cmd])
}
builder.WriteString("\n\nFLAGS:\n --help\n print the help message\n")
builder.WriteString("\n\nFLAGS:\n -help, --help\n print the help message\n")
flag.VisitAll(func(f *flag.Flag) {
fmt.Fprintf(&builder, "\n --%s\n %s\n", f.Name, f.Usage)
fmt.Fprintf(&builder, "\n -%s, --%s\n %s\n", f.Name, f.Name, f.Usage)
})
builder.WriteString("\nUse \"enbas [command] --help\" for more information about a command.\n")

View file

@ -71,8 +71,8 @@ func (g *Client) GetInstance() (model.InstanceV2, error) {
}
func (g *Client) GetAccount(accountURI string) (model.Account, error) {
path := "/api/v1/accounts/lookup?acct=" + accountURI
url := g.Authentication.Instance + path
path := "/api/v1/accounts/lookup"
url := g.Authentication.Instance + path + "?acct=" + accountURI
var account model.Account
@ -83,55 +83,6 @@ func (g *Client) GetAccount(accountURI string) (model.Account, error) {
return account, nil
}
func (g *Client) GetStatus(statusID string) (model.Status, error) {
path := "/api/v1/statuses/" + statusID
url := g.Authentication.Instance + path
var status model.Status
if err := g.sendRequest(http.MethodGet, url, nil, &status); err != nil {
return model.Status{}, fmt.Errorf("received an error after sending the request to get the status information; %w", err)
}
return status, nil
}
func (g *Client) GetHomeTimeline(limit int) ([]model.Status, error) {
path := fmt.Sprintf("/api/v1/timelines/home?limit=%d", limit)
return g.getTimeline(path)
}
func (g *Client) GetPublicTimeline(limit int) ([]model.Status, error) {
path := fmt.Sprintf("/api/v1/timelines/public?limit=%d", limit)
return g.getTimeline(path)
}
func (g *Client) GetListTimeline(listID string, limit int) ([]model.Status, error) {
path := fmt.Sprintf("/api/v1/timelines/list/%s?limit=%d", listID, limit)
return g.getTimeline(path)
}
func (g *Client) GetTagTimeline(tag string, limit int) ([]model.Status, error) {
path := fmt.Sprintf("/api/v1/timelines/tag/%s?limit=%d", tag, limit)
return g.getTimeline(path)
}
func (g *Client) getTimeline(path string) ([]model.Status, error) {
url := g.Authentication.Instance + path
var statuses []model.Status
if err := g.sendRequest(http.MethodGet, url, nil, &statuses); err != nil {
return nil, fmt.Errorf("received an error after sending the request to get the timeline; %w", err)
}
return statuses, nil
}
func (g *Client) sendRequest(method string, url string, requestBody io.Reader, object any) error {
ctx, cancel := context.WithTimeout(context.Background(), g.Timeout)
defer cancel()

View file

@ -1,37 +1,32 @@
package model
import (
"fmt"
"time"
"codeflow.dananglin.me.uk/apollo/enbas/internal/utilities"
)
import "time"
type Account struct {
Acct string `json:"acct"`
Avatar string `json:"avatar"`
AvatarStatic string `json:"avatar_static"`
Bot bool `json:"bot"`
CreatedAt time.Time `json:"created_at"`
CustomCSS string `json:"custom_css"`
Discoverable bool `json:"discoverable"`
DisplayName string `json:"display_name"`
Emojis []Emoji `json:"emojis"`
EnableRSS bool `json:"enable_rss"`
Fields []Field `json:"fields"`
FollowersCount int `json:"followers_count"`
FollowingCount int `json:"following_count"`
Header string `json:"header"`
HeaderStatic string `json:"header_static"`
ID string `json:"id"`
LastStatusAt string `json:"last_status_at"`
DisplayName string `json:"display_name"`
Emojis []Emoji `json:"emojis"`
EnableRSS bool `json:"enable_rss"`
Bot bool `json:"bot"`
Locked bool `json:"locked"`
Suspended bool `json:"suspended"`
Discoverable bool `json:"discoverable"`
Fields []Field `json:"fields"`
FollowersCount int `json:"followers_count"`
FollowingCount int `json:"following_count"`
CreatedAt time.Time `json:"created_at"`
MuteExpiresAt time.Time `json:"mute_expires_at"`
Note string `json:"note"`
Role AccountRole `json:"role"`
Source Source `json:"source"`
StatusCount int `json:"statuses_count"`
Suspended bool `json:"suspended"`
URL string `json:"url"`
Username string `json:"username"`
}
@ -55,51 +50,3 @@ type Field struct {
Value string `json:"value"`
VerifiedAt string `json:"verified_at"`
}
func (a Account) String() string {
format := `
%s (@%s)
ACCOUNT ID:
%s
JOINED ON:
%s
STATS:
Followers: %d
Following: %d
Statuses: %d
BIOGRAPHY:
%s
METADATA: %s
ACCOUNT URL:
%s
`
metadata := ""
for _, field := range a.Fields {
metadata += fmt.Sprintf(
"\n %s: %s",
field.Name,
utilities.StripHTMLTags(field.Value),
)
}
return fmt.Sprintf(
format,
a.DisplayName,
a.Username,
a.ID,
a.CreatedAt.Format("02 Jan 2006"),
a.FollowersCount,
a.FollowingCount,
a.StatusCount,
utilities.WrapLine(utilities.StripHTMLTags(a.Note), "\n ", 80),
metadata,
a.URL,
)
}

View file

@ -1,7 +1,5 @@
package model
import "fmt"
type InstanceV2 struct {
AccountDomain string `json:"account_domain"`
Configuration InstanceConfiguration `json:"configuration"`
@ -106,32 +104,3 @@ type InstanceV2Usage struct {
type InstanceV2Users struct {
ActiveMonth int `json:"active_month"`
}
func (i InstanceV2) String() string {
format := `
INSTANCE:
%s - %s
DOMAIN:
%s
VERSION:
Running GoToSocial %s
CONTACT:
name: %s
username: %s
email: %s
`
return fmt.Sprintf(
format,
i.Title,
i.Description,
i.Domain,
i.Version,
i.Contact.Account.DisplayName,
i.Contact.Account.Username,
i.Contact.Email,
)
}

View file

@ -1,11 +1,6 @@
package model
import (
"fmt"
"time"
"codeflow.dananglin.me.uk/apollo/enbas/internal/utilities"
)
import "time"
type Status struct {
Account Account `json:"account"`
@ -151,43 +146,3 @@ type MediaDimensions struct {
Height int `json:"height"`
Width int `json:"width"`
}
func (s Status) String() string {
format := `
%s (@%s)
CONTENT:
%s
STATUS ID:
%s
CREATED AT:
%s
STATS:
Boosts: %d
Likes: %d
Replies: %d
VISIBILITY:
%s
URL:
%s
`
return fmt.Sprintf(
format,
s.Account.DisplayName,
s.Account.Username,
utilities.StripHTMLTags(s.Content),
s.ID,
s.CreatedAt.Format("02 Jan 2006, 03:04"),
s.RebloggsCount,
s.FavouritesCount,
s.RepliesCount,
s.Visibility,
s.URL,
)
}

View file

@ -1,47 +0,0 @@
package utilities
import (
"strings"
"unicode"
"golang.org/x/net/html"
)
func StripHTMLTags(text string) string {
token := html.NewTokenizer(strings.NewReader(text))
var builder strings.Builder
for {
tt := token.Next()
switch tt {
case html.ErrorToken:
return builder.String()
case html.TextToken:
builder.WriteString(token.Token().Data + " ")
}
}
}
func WrapLine(line, separator string, charLimit int) string {
if len(line) <= charLimit {
return line
}
leftcursor, rightcursor := 0, 0
var builder strings.Builder
for rightcursor < (len(line) - charLimit) {
rightcursor += charLimit
for !unicode.IsSpace(rune(line[rightcursor-1])) {
rightcursor--
}
builder.WriteString(line[leftcursor:rightcursor] + separator)
leftcursor = rightcursor
}
builder.WriteString(line[rightcursor:])
return builder.String()
}