shithub: hell

ref: 416169ab2ea220f6396a557bc3dad0f1566552cf
dir: /mastodon.go/

View raw version
package main

import (
	"bytes"
	"context"
	"fmt"
	"log"
	"net/url"
	"strings"
	"time"

	mastodon "codeberg.org/penny64/hellclient-go-mastodon"
	"github.com/k3a/html2text"
	"golang.org/x/net/html"
)

func ConfigureClient() *mastodon.Client {
	appConfig := &mastodon.AppConfig{
		Server:       "",
		ClientName:   "hellclient",
		Scopes:       "read write follow",
		Website:      "https://codeberg.org/penny64/hellclient",
		RedirectURIs: "urn:ietf:wg:oauth:2.0:oob",
	}
	fmt.Print("Enter server URL:")
	fmt.Scanln(&appConfig.Server)
	app, err := mastodon.RegisterApp(context.Background(), appConfig)
	if err != nil {
		log.Fatal(err)
	}

	// Have the user manually get the token and send it back to us
	u, err := url.Parse(app.AuthURI)
	if err != nil {
		log.Fatal(err)
	}

	fmt.Printf("Open your browser to \n%s\n and copy/paste the given authroization code\n", u)
	var userAuthorizationCode string
	fmt.Print("Paste the code here:")
	fmt.Scanln(&userAuthorizationCode)

	config := &mastodon.Config{
		Server:       "https://eldritch.cafe",
		ClientID:     app.ClientID,
		ClientSecret: app.ClientSecret,
	}

	// Create the client
	c := mastodon.NewClient(config)

	// Exchange the User authentication code with an access token, that can be used to interact with the api on behalf of the user
	err = c.GetUserAccessToken(context.Background(), userAuthorizationCode, app.RedirectURI)
	if err != nil {
		log.Fatal(err)
	}

	return c
}

func initClient(account *mastodon_account) *mastodon.Client {

	clientID := account.MASTODON_CLIENT_ID
	clientSecret := account.MASTODON_CLIENT_ID
	accessToken := account.MASTODON_ACCESS_TOKEN
	url := account.URL

	config := &mastodon.Config{
		Server:       url,
		ClientID:     clientID,
		ClientSecret: clientSecret,
		AccessToken:  accessToken,
	}

	c := mastodon.NewClient(config)
	return c
}

func (hc *Hellclient) renderStatus(content string, index string) (string, map[string]string) {
	doc, err := html.Parse(strings.NewReader(content))
	if err != nil {
		fmt.Printf("Failed to parse status\n")
		return "", nil
	}

	//clear out the url map
	hc.urlMap[index] = []string{}
	preformats := make(map[string]string)

	for node := range doc.Descendants() {
		if (node.Data == "pre" || node.Data == "") && node.FirstChild != nil {
			preformats[fmt.Sprintf("%p%p", hc, node.FirstChild)] = node.FirstChild.Data
			node.FirstChild.Data = fmt.Sprintf("%p%p", hc, node.FirstChild)
		}
		if node.Data == "a" && node.Type == html.ElementNode {
			ismention := false
			href := ""

			for attr := range node.Attr {
				if node.Attr[attr].Key == "class" && strings.Contains(node.Attr[attr].Val, "mention") {
					node.Data = "div"
					ismention = true
					continue
				}
				if node.Attr[attr].Key == "href" {
					href = node.Attr[attr].Val
					//Replace the href with the description if the URL has one
					if node.FirstChild != nil && node.FirstChild.Type == html.TextNode && !ismention {
						node.Attr[attr].Val = fmt.Sprintf("(%s)", node.FirstChild.Data)
					} else {
						href = href + " "
					}
				}
			}
			if !ismention {
				hc.urlMap[index] = append(hc.urlMap[index], href)
				refnode := &html.Node{
					Type: html.TextNode,
					Data: fmt.Sprintf(" [%v]", len(hc.urlMap[index]))}
				if node.Parent != nil {
					node.Parent.InsertBefore(refnode, node.NextSibling)
				}
			}
		}
	}

	//Rip off the HTML body the parser made for us
	for node := range doc.Descendants() {
		if node.Data == "body" {
			node.Type = html.DocumentNode
			doc = node
		}
	}

	var rendered bytes.Buffer
	err = html.Render(&rendered, doc)

	if err != nil {
		return "", nil
	}

	renderedPlainText := rendered.String()

	return renderedPlainText, preformats
}

func processStatusHints(toot *mastodon.Toot, postpointer *string) {
	posttext := *postpointer
	posttext, hints := extractInputParameters(posttext)
	toot.Status = posttext

	for _, arg := range hints {
		key := arg[0]
		val := arg[1]
		switch key {
		case "unlisted":
			toot.Visibility = "unlisted"
		case "public":
			toot.Visibility = "public"
		case "followers":
			toot.Visibility = "private"
		case "direct":
			toot.Visibility = "direct"
		case "subject":
			if len(val) > 0 {
				toot.SpoilerText = val
			}
		case "sensitive":
			toot.Sensitive = true
		}
	}
	*postpointer = posttext
}

func postReply(posttext string, replyto mastodon.ID, currentuser mastodon.ID, postItem *mastodon.Status) (status *mastodon.Toot) {
	toot := mastodon.Toot{
		Status:      posttext,
		InReplyToID: replyto,
	}

	toot.Visibility = postItem.Visibility

	processStatusHints(&toot, &posttext)

	if currentuser == postItem.Account.ID {
		return &toot
	}
	var sb strings.Builder
	sb.WriteString("@")
	sb.WriteString(getUserString(postItem))
	sb.WriteString(" ")
	sb.WriteString(posttext)

	toot.Status = sb.String()
	return &toot
}

func postStatus(posttext string, visibility string) (status *mastodon.Toot) {
	// Post a toot
	toot := mastodon.Toot{
		Status:     posttext,
		Visibility: visibility,
	}

	processStatusHints(&toot, &posttext)

	return &toot
}

func postStatusDetailed(client mastodon.Client, toot mastodon.Toot) (status *mastodon.Status, err error) {
	status, err = client.PostStatus(context.Background(), &toot)
	return
}

func getUserString(post *mastodon.Status) string {
	return post.Account.Acct
}

func (hc *Hellclient) formatAccount(account *mastodon.Account) string {
	var sb strings.Builder

	sb.WriteString(fmt.Sprintf("%s\n", account.DisplayName))
	sb.WriteString(fmt.Sprintf("%s <%s>\n", account.Username, account.Acct))
	sb.WriteString(fmt.Sprintf("Posts: %v Followers: %v Following: %v\n", account.StatusesCount, account.FollowersCount, account.FollowingCount))
	sb.WriteString(fmt.Sprintf("Created %v\n", account.CreatedAt))
	sb.WriteString(fmt.Sprintf("Locked: %v\n", account.Locked))
	sb.WriteString(fmt.Sprintf("%s\n\n", html2text.HTML2Text(account.Note)))

	relationships, err := hc.client.GetAccountRelationships(context.Background(), []string{string(account.ID)})
	relationship := relationships[0]
	if err == nil {
		if relationship.Following {
			sb.WriteString("You follow them\n")
		}
		if relationship.FollowedBy {
			sb.WriteString("They follow you\n")
		}
		if relationship.Blocking {
			sb.WriteString("Account is blocked\n")
		}
		if relationship.Muting {
			sb.WriteString("Account is muted\n")
		}
		if relationship.Requested {
			sb.WriteString("Follow request pending\n")
		}
	}

	return hyphenate(sb.String())
}

// Spaces before prefixes (no space if you're not passing a prefix)
func (hc *Hellclient) formatReblog(post *mastodon.Status, index string) string {
	reblogString := fmt.Sprintf(" <%s> Reblogged", post.Account.Username)
	return hyphenate(hc.formatStatusDetailed(post.Reblog, index, reblogString))
}

func (hc *Hellclient) formatWithPrefix(post *mastodon.Status, index string, prefix string) string {
	postString := fmt.Sprintf("%s %s>", prefix, index)
	return hyphenate(hc.formatStatusDetailed(post, "", postString))
}
func (hc *Hellclient) formatFavorite(post *mastodon.Status, index string) string {
	favString := fmt.Sprintf("Favorited: %s", index)
	return hyphenate(hc.formatStatusDetailed(post, "", favString))
}

func (hc *Hellclient) formatBookmark(post *mastodon.Status, index string) string {
	favString := fmt.Sprintf("Bookmarked: %s", index)
	return hyphenate(hc.formatStatusDetailed(post, "", favString))
}

func (hc *Hellclient) formatUnbookmark(post *mastodon.Status, index string) string {
	favString := fmt.Sprintf("Unbookmarked: %s", index)
	return hyphenate(hc.formatStatusDetailed(post, "", favString))
}

func (hc *Hellclient) formatStatus(post *mastodon.Status, index string) string {
	return hc.formatStatusDetailed(post, index, " ")
}

func (hc *Hellclient) formatStatusDetailed(post *mastodon.Status, index string, prefix string) string {
	renderedPost, plaintexts := hc.renderStatus(post.Content, index)

	rendered := fmt.Sprintf("%s>%s <%s> %s", index, prefix, post.Account.Username, html2text.HTML2Text(renderedPost))
	for key, plaintext := range plaintexts {
		rendered = strings.Replace(rendered, key, plaintext, 1)
	}
	return rendered
}

func (hc *Hellclient) formatEdit(post *mastodon.Status, index string) string {
	editString := fmt.Sprintf(" <%s> EDITED:", post.Account.Username)
	return hyphenate(hc.formatStatusDetailed(post, index, editString))
}

func printMastodonErr(err error) {
	fmt.Printf("\r%v\n", err)
}

func (hc *Hellclient) printPostS(ref postref, post *mastodon.Status) *mastodon.Status {
	return hc.printPostDetailed(ref.prefix+ref.ref, post, "")
}

func (hc *Hellclient) printPost(postref string, post *mastodon.Status) *mastodon.Status {
	return hc.printPostDetailed(postref, post, "")
}

func (hc *Hellclient) printPostDetailed(postref string, post *mastodon.Status, prefix string) *mastodon.Status {
	post, plaintext := hc.RenderPostPlaintext(post, postref, prefix)
	fmt.Println(hyphenate(plaintext))
	return post
}

func (hc *Hellclient) renderPostS(ref postref, post *mastodon.Status) string {
	_, plaintext := hc.RenderPostPlaintext(post, ref.prefix+ref.ref, "")
	return hyphenate(plaintext)
}

func (hc *Hellclient) RenderPostPlaintext(post *mastodon.Status, postref string, prefix string) (selectedPost *mastodon.Status, plaintext string) {
	poststring := ""
	postfix := ""
	var media []mastodon.Attachment
	if post.Reblog != nil {
		poststring = hc.formatReblog(post, postref)
		selectedPost = post.Reblog
		media = post.Reblog.MediaAttachments
	} else {
		poststring = hc.formatStatusDetailed(post, postref, prefix)
		selectedPost = post
		media = post.MediaAttachments
	}

	for _, item := range media {
		if item.Description != "" {
			postfix += fmt.Sprintf("\n🖼️[%s]", item.Description)
			continue
		}
		postfix += "🖼️"
	}

	plaintext = fmt.Sprintf("%s %s", poststring, postfix)
	return
}

func StreamHomeTimeline(client *mastodon.Client, postMap map[string]*mastodon.Status, hc *Hellclient) {

	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()

	eventCh, err := client.StreamingUser(ctx)
	if err != nil {
		log.Fatalf("Error starting user stream: %v\n", err)
	}

	initReferenceSystem()

	idmap := make(map[mastodon.ID]*mastodon.Status)
	readchan := hc.readMarkerUpdater()

	// Enter a loop to continuously listen for events from the event channel.
	for event := range eventCh {
		func() {
			hc.lock()
			defer hc.unlock()
			switch post := event.(type) {
			case *mastodon.UpdateEvent:
				//Count the statuses
				hc.stats.slock.Lock()
				hc.stats.IncomingStatuses++
				hc.stats.slock.Unlock()
				//Tell the timeline marker updater the most recent post
				readchan <- &post.Status.ID
				if hc.isPaused {
					currentPostRef := hc.homeref.ref
					capturedPost := post
					hc.actionBuffer = append(hc.actionBuffer, func() {
						capturedPost.Status = hc.printPost(currentPostRef, capturedPost.Status)
					})
					justIncrementPostref(hc.homeref, post.Status)
					idmap[post.Status.ID] = post.Status
					return
				}
				hc.printAndIncrement(hc.homeref, post.Status)
				idmap[post.Status.ID] = post.Status
				return

			case *mastodon.UpdateEditEvent:
				//Count the statuses
				hc.stats.slock.Lock()
				hc.stats.IncomingStatuses++
				hc.stats.slock.Unlock()
				if hc.isPaused {
					currentPostRef := hc.homeref.ref
					capturedPost := post
					hc.actionBuffer = append(hc.actionBuffer, func() {
						fmt.Println(hc.formatEdit(capturedPost.Status, currentPostRef))
					})
					justIncrementPostref(hc.homeref, post.Status)
					idmap[post.Status.ID] = post.Status
					return
				}
				printAndIncrementDetailed(hc.homeref, post.Status, hc.formatEdit)
				idmap[post.Status.ID] = post.Status
				return

			case *mastodon.DeleteEvent:
				deleted, ok := idmap[post.ID]
				//didn't have this in the cache
				if !ok {
					capturedID := post.ID
					if hc.isPaused {
						hc.actionBuffer = append(hc.actionBuffer, func() {
							fmt.Printf("Deleted: ID %v\n", capturedID)
						})
					} else {
						fmt.Printf("Deleted: ID %v\n", capturedID)
					}
					return
				}
				if hc.isPaused {
					hc.actionBuffer = append(hc.actionBuffer, func() {
						hc.printPostDetailed("", deleted, "Deleted:")
					})
				} else {
					hc.printPostDetailed("", deleted, "Deleted:")
				}
				return

			case *mastodon.NotificationEvent:
				hc.prompt.UpdatePrompt()
				if post.Notification.Status == nil {
					if hc.isPaused {
						hc.actionBuffer = append(hc.actionBuffer, func() {
							hc.PrintReceivedNotification(post.Notification)
						})
					} else {
						hc.PrintReceivedNotification(post.Notification)
					}
					return
				}
				if hc.isPaused {
					hc.actionBuffer = append(hc.actionBuffer, func() {
						hc.PrintReceivedNotification(post.Notification)
					})
				} else {
					hc.PrintReceivedNotification(post.Notification)
				}
				justIncrementPostref(hc.homeref, post.Notification.Status)
			default:
				// Catch any other unexpected event types.
				unhandledEvent := event
				if hc.isPaused {
					hc.actionBuffer = append(hc.actionBuffer, func() {
						fmt.Printf("Unhandled event: %T\n", unhandledEvent)
					})
				} else {
					fmt.Printf("Unhandled event: %T\n", unhandledEvent)
				}
			}
		}()
	}
}

// Options are home and notifications
func (hc *Hellclient) updateReadMarker(ID *mastodon.ID, timeline string) {
	marker := &mastodon.Marker{
		Timeline: timeline,
		ID:       *ID,
	}
	var err error
	setmarker := func(job *GenericJob) {
		err = hc.client.SetTimelineMarkers(context.Background(), &[]mastodon.Marker{*marker})
	}
	job := hc.dispatchFunc(setmarker)
	job.Wait()
	if err != nil {
		fmt.Printf("Error: %s", err)
	}

}

// Periodically set the timeline read marker to the most recent status
// Currently this will leak if a client is destroyed
func (hc *Hellclient) readMarkerUpdater() (statuschan chan *mastodon.ID) {
	statuschan = make(chan *mastodon.ID)
	var ID *mastodon.ID
	var lastfire time.Time
	go func() {
		for {
			select {
			case ID = <-statuschan:
				continue
			case <-time.After((time.Minute * 4) - time.Since(lastfire)):
				lastfire = time.Now()
				if ID != nil {
					hc.updateReadMarker(ID, "home")
				}
			}
		}
	}()
	return
}

func (hc *Hellclient) resolveAccount(lookup string) *mastodon.Account {
	var accounts []*mastodon.Account
	var err error
	searchfunc := func(job *GenericJob) {
		accounts, err = hc.client.AccountsSearchResolve(context.Background(), lookup, 1, true)
	}
	searchjob := hc.dispatchFunc(searchfunc)
	searchjob.Wait()
	if err != nil {
		fmt.Printf("Error resolving account %s: %v\n", lookup, err)
		return nil
	}
	if len(accounts) < 1 {
		fmt.Printf("No account matched %s\n", lookup)
		return nil
	}
	return accounts[0]
}