shithub: hell

ref: fe8e263ce4b63f537ede902c98f20557dd54e610
dir: /hellclient.go/

View raw version
package main

import (
	"context"
	"io"
	"strings"
	"sync"

	"github.com/ergochat/readline"
	"github.com/mattn/go-mastodon"
)

var (
	ErrInterrupt = readline.ErrInterrupt
	EOF          = io.EOF
)

type Hellclient struct {
	//if you're gonna touch or read anything here lock the mutex with hc.lock()
	isPaused    bool
	rl          *readline.Instance
	client      *mastodon.Client
	currentuser *mastodon.Account
	block       sync.Mutex

	homeMap      map[string]*mastodon.Status
	urlMap       map[string][]string
	debugMap     map[string]interface{}
	actionBuffer []func()
}

func NewHellclient() (*Hellclient, error) {
	rl, err := readline.New("Hell> ")
	rl.CaptureExitSignal()
	if err != nil {
		return nil, err
	}
	account, err := loadConfig()
	if err != nil {
		return nil, err
	}
	client := initClient(account)
	currentuser, err := client.GetAccountCurrentUser(context.Background())
	if err != nil {
		return nil, err
	}

	homeMap := make(map[string]*mastodon.Status)
	debugMap := make(map[string]interface{})
	urlMap := make(map[string][]string)
	return &Hellclient{rl: rl,
		homeMap:     homeMap,
		debugMap:    debugMap,
		isPaused:    false,
		urlMap:      urlMap,
		client:      client,
		currentuser: currentuser,
	}, nil
}

func (hc *Hellclient) updatePrompt() {
	var sb strings.Builder
	if hc.isPaused {
		sb.WriteString("STREAMING PAUSED ")
	}
	sb.WriteString("Hell> ")
	hc.rl.SetPrompt(sb.String())
}

func (hc *Hellclient) pause(on bool) {
	hc.isPaused = on
	hc.updatePrompt()
	hc.printPauseBuffer()
}

func (hc *Hellclient) togglepause() {
	hc.isPaused = !hc.isPaused
	hc.updatePrompt()
	hc.printPauseBuffer()
}

func (hc *Hellclient) printPauseBuffer() {
	if !hc.isPaused {
		for _, action := range hc.actionBuffer {
			action()
		}
		hc.actionBuffer = nil
	}
}

func (hc *Hellclient) lock() {
	hc.block.Lock()
}

func (hc *Hellclient) unlock() {
	hc.block.Unlock()
}