shithub: hell

ref: 64e034333bc1a4e35c778bb4508d1f4be913722c
dir: /dispatch.go/

View raw version
package main

import (
	"fmt"
	"time"

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

func (hc *Hellclient) queueManager() {

}

func (hc *Hellclient) clientDispatch() {
	var tootQueue []*mastodon.Toot
	//Last time we sent an API call
	var lastfire time.Time
	//Last time the user sent us a line
	var lastreceive time.Time
	var comingfast bool

	receiveStatus := func(statustoot *mastodon.Toot) {
		//Got multiple lines within a second
		if time.Since(lastreceive) < time.Second {
			comingfast = true
		}
		lastreceive = time.Now()
		tootQueue = append(tootQueue, statustoot)
	}

	for {
		select {
		case statustoot := <-hc.dispatch:
			receiveStatus(statustoot)
		//API delay needs to be tracked without being reset by new inputs
		case <-time.After(hc.preferences.apidelay - time.Since(lastfire)):
			if 1 > len(tootQueue) {
				//Queue is empty, block the loop until we get a new input
				statustoot := <-hc.dispatch
				receiveStatus(statustoot)
				break
			}
			//User is sending lines faster than one a second, flood control
			if comingfast {
				//Take over the loop until we stop getting messages fast
				for comingfast {
					select {
					case statustoot := <-hc.dispatch:
						receiveStatus(statustoot)
					//We already know we're flooding so we can probably be a little less sensitive
					case <-time.After(time.Second / 5):
						fmt.Printf("Got %v lines fast!\n", len(tootQueue))
						tootQueue = nil
						comingfast = false
					}
				}
				//Nothing to send
				break
			}

			toot := tootQueue[0]
			lastfire = time.Now()
			var err error
			status, err := postStatusDetailed(*hc.client, *toot)
			if err != nil {
				fmt.Println(err)
			}
			hc.lock()
			hc.recentpost = status
			hc.unlock()
			tootQueue = tootQueue[1:]
		}
	}
}

func (hc *Hellclient) dispatchStatus(status string, visibility string) {
	hc.dispatch <- postStatus(status, visibility)
}

func (hc *Hellclient) dispatchReply(posttext string, replyto mastodon.ID, postItem *mastodon.Status) {
	hc.dispatch <- postReply(posttext, replyto, hc.currentuser.ID, postItem)
}