Skip to content Search Apps Documentation Source Content Run Reset Eval Playground File Folder Download Copy Actions State String Boolean Number Struct Map Slice Pointer Function Closure Reference Nil Package Type Interface Unknown

Community realm. Read the code first. Community realm, deployed by its author. Read the code before you interact or send coins.

Playground

activity.gno

package radio

import (
	"strings"

	"gno.land/p/nym-alexiscolin000/gnoradio/store/v0"
	"gno.land/p/nym-alexiscolin000/gnoradio/text/v0"
)

const activitySize = 64

// Activity is one programming action on a station.
type Activity struct {
	Kind    string // queue | curator | sponsored
	By      address
	Track   int
	Station int
	Start   int64
	At      int64
}

// recordActivity writes the next slot of the fixed-size ring (storage
// never grows): Rec(kind, by, numbers), the numbers the track (4 digits),
// the station (1), the start (6) and the time (6). The head is in the flow
// record.
func recordActivity(t *tx, kind string, by address, track, station int, start int64) {
	h := t.flowAt(fHead, 1)
	n := store.AppendFixed(store.AppendFixed(store.AppendFixed(store.AppendFixed(make([]byte, 0, 17), int64(track), 4), int64(station), 1), start, 6), now(), 6)
	t.put(cActivity, store.Pad(h), store.Rec(kind, by.String(), string(n)))
	t.setFlowAt(fHead, 1, (h+1)%activitySize)
}

func activityOf(rec string) Activity {
	f := store.Fields(rec)
	n := f[2]
	return Activity{Kind: f[0], By: address(f[1]), Track: int(store.Num(n, 0, 4)), Station: int(store.Num(n, 4, 1)), Start: store.Num(n, 5, 6), At: store.Num(n, 11, 6)}
}

// activities returns up to limit records, newest first: the ring's slots
// before its head, read one by one (the ring fills from slot 0 and no slot
// is ever deleted, so the first empty one ends it).
func activities(limit int) []string {
	limit = store.Limit(limit, activitySize)
	t := rd()
	head := t.flowAt(fHead, 1)
	out := make([]string, 0, limit)
	for i := 1; i <= limit; i++ {
		rec := t.val(cActivity, store.Pad((head-i+activitySize)%activitySize))
		if rec == "" {
			break // the ring is not full yet
		}
		out = append(out, rec)
	}
	return out
}

// Activities returns up to limit entries, newest first.
func Activities(limit int) []Activity {
	var out []Activity
	for _, rec := range activities(limit) {
		out = append(out, activityOf(rec))
	}
	return out
}

// ActivityJSON returns the programming feed, newest first (limit <= 64).
func ActivityJSON(limit int) string {
	var b strings.Builder
	b.WriteString("[")
	for i, rec := range activities(limit) {
		a := activityOf(rec)
		if i > 0 {
			b.WriteString(",")
		}
		b.WriteString(`{"kind":` + text.Str(a.Kind) + `,"by":` + text.Str(a.By.String()) + `,"track":` + text.Itoa(a.Track) +
			`,"station":` + text.Itoa(a.Station) + `,"start":` + text.Itoa64(a.Start) + `,"at":` + text.Itoa64(a.At) + `}`)
	}
	b.WriteString("]")
	return b.String()
}

admin.gno

package radio

import (
	"chain"
	"strings"

	"gno.land/p/nym-alexiscolin000/gnoradio/role/v0"
	"gno.land/p/nym-alexiscolin000/gnoradio/text/v0"
	"gno.land/r/nym-alexiscolin000/gnoradio/data"
)

// The radio admin (curator and moderator) is a p/role held by this realm,
// passed in two steps. Each change is mirrored to radio/config "admin", so
// the next release keeps it, and the mirror is the authority: a change the
// previous release made after this one's init counts.

// adminAddr is the admin ("" once renounced).
func adminAddr() address {
	h, ok := data.Get(cConfig, "admin")
	return role.Mirror(admin, h, ok)
}

// syncAdmin adopts the mirror when the previous release changed it after
// this one's init (during the release's delay).
func syncAdmin() {
	h, ok := data.Get(cConfig, "admin")
	admin = role.Adopt(admin, "admin", h, ok)
}

func onlyAdmin(cur realm) {
	syncAdmin()
	if admin == nil || !admin.Is(0, cur) {
		panic("radio: admin only")
	}
	noPayment()
}

// Admin is the radio admin ("" once renounced).
func Admin() address { return adminAddr() }

// PendingAdmin is the address the admin role is offered to ("" if none).
func PendingAdmin() address { return admin.Pending() }

// Ready tells the data realm that this release is on chain (see
// data.Propose). Anyone may call it.
func Ready(cur realm) {
	noPayment()
	data.Ready(cross(cur))
}

// OfferAdmin offers the admin role to an address (offering it to the admin
// cancels the offer); AcceptAdmin takes it. Each change is mirrored to the
// data realm, so the next release keeps the admin.
func OfferAdmin(cur realm, to address) {
	onlyAdmin(cur)
	admin.Offer(0, cur, to)
}

func AcceptAdmin(cur realm) {
	noPayment()
	syncAdmin()
	if admin == nil {
		panic("radio: nothing offered to you")
	}
	admin.Accept(0, cur)
	data.Set(cross(cur), cConfig, "admin", admin.Holder().String())
}

// RenounceAdmin gives the admin role up for good, for this release and the
// next ones.
func RenounceAdmin(cur realm) {
	onlyAdmin(cur)
	admin.Renounce(0, cur)
	data.Set(cross(cur), cConfig, "admin", "")
}

// DropSlot silences a track in one station's rotation (moderation of last
// resort). It stays silent through Refresh until RestoreSlot. Radio admin only.
func DropSlot(cur realm, stationID, trackID int) {
	onlyAdmin(cur)
	t := rd()
	st := t.station(stationID)
	i, ok := st.slot(trackID)
	if st.id == MainStation {
		ok = trackID >= 1 && trackID <= t.synced() // Main simulcasts: the drop flag alone silences it there
	}
	if !ok {
		panic("radio: track not in this station's rotation")
	}
	ts := now()
	if !t.has(cDropped, dropKey(st.id, trackID)) {
		t.set(cDropped, dropKey(st.id, trackID), "1")
		t.setFlowAt(fDrops, 4, t.flowAt(fDrops, 4)+1)
	}
	if st.id != MainStation {
		st.setDuration(i, 0, ts)
	}
	release(cur, st.dropSlots(trackID, ts))
	save(cur, t)
	chain.Emit("SlotDropped", "station", text.Itoa(st.id), "track", text.Itoa(trackID))
}

// RestoreSlot undoes DropSlot: the track plays again on that station if the
// catalog still allows it. Radio admin only.
func RestoreSlot(cur realm, stationID, trackID int) {
	onlyAdmin(cur)
	mustStation(stationID)
	t := rd()
	if !t.del(cDropped, dropKey(stationID, trackID)) {
		panic("radio: this slot was not dropped")
	}
	t.setFlowAt(fDrops, 4, t.flowAt(fDrops, 4)-1)
	refresh(cur, t, trackID)
	save(cur, t)
	chain.Emit("SlotRestored", "station", text.Itoa(stationID), "track", text.Itoa(trackID))
}

// Unqueue removes a track's programmed slots from a station; one on air ends
// now. Radio admin (curator) only.
func Unqueue(cur realm, stationID, trackID int) {
	onlyAdmin(cur)
	t := rd()
	st := t.station(stationID)
	release(cur, st.dropSlots(trackID, now()))
	save(cur, t)
	chain.Emit("Unqueued", "station", text.Itoa(st.id), "track", text.Itoa(trackID))
}

// Render points gnoweb visitors to the GnoRadio site; a retired release says
// which realm took over.
func Render(_ string) string {
	home := strings.TrimPrefix(strings.TrimSuffix(self, "radio/v1"), "gno.land") + "home/v1"
	d := strings.TrimPrefix(dataPath, "gno.land")
	out := "# GnoRadio · radio\n\nThis contract holds GnoRadio's radio rules; its data lives in [" + d + "](" + d +
		"). The site lives at [" + home + "](" + home + ").\n"
	if w := data.Writer("radio"); w != self {
		out += "\nThis release is retired: the radio is now `" + w + "`.\n"
	}
	return out
}

curators.gno

package radio

import (
	"chain"
	"chain/banker"
	"chain/runtime/unsafe"
	"strings"

	"gno.land/p/nym-alexiscolin000/gnoradio/role/v0"
	"gno.land/p/nym-alexiscolin000/gnoradio/store/v0"
	"gno.land/p/nym-alexiscolin000/gnoradio/text/v0"
	"gno.land/r/nym-alexiscolin000/gnoradio/catalog/v1"
	"gno.land/r/nym-alexiscolin000/gnoradio/data"
)

// Curators are the listeners who pick tracks. While a pick is on air, a tip to
// its artist made with TipOnAir sends the artist's promo share to the picker
// (catalog/promo.gno). Every pick and every shared tip updates the picker's
// counters and the weekly top of the station and of all stations: one record
// and a 10-entry list, whatever the number of curators.

const (
	allStations = -1
	topCurators = 10
	topMax      = 5 + topCurators*46 // the longest station top: week, count, then score and key per curator
	week        = 7 * 24 * 3600
	tipGrace    = 120 // seconds after a pick ends during which a tip still credits its picker
)

// Curator is a picker's record, all time or for one week.
type Curator struct {
	Address address
	Picks   int
	Tips    int   // tips received while their picks were on air
	Earned  int64 // ugnot from those tips
	Promo   int64 // ugnot refunded by artists for sponsored picks (sponsor.gno)
}

// A curator is one record: all time, picks, tips, earned, promo, first
// pick, period, picks this period, picks the period before (sponsor.gno);
// this week across stations, week, picks, tips, earned; each a fixed-width
// number (cWidths). Then one entry per station picked on lately: the
// station (1 digit), week, picks, tips, earned and the last pick time
// (sWidths).
const (
	cWeek   = 8
	cFields = 12
	cLen    = 62 // the numbers
	sLen    = 27 // one station entry
)

var (
	cWidths = [cFields]int{4, 4, 8, 8, 6, 4, 4, 4, 4, 4, 4, 8}
	sWidths = [5]int{4, 4, 4, 8, 6}
)

// TipOnAir tips the artist of trackID: the attached ugnot go through the
// catalog, which pays the artist and collaborators exactly as
// catalog.TipWithSupport does. When trackID is a listener's pick on air on
// stationID (or ended less than two minutes ago), the artist's promo share
// goes to that listener; the radio reads the picker from its own schedule.
// ref is who shared the link the tipper came from ("" for none): picker and
// ref split the promo share, never more.
func TipOnAir(cur realm, stationID, trackID, supportPct int, ref address) {
	tipper := userCaller(cur)
	if ref != "" && !role.Canonical(ref) {
		panic("radio: ref is not an address (lower-case g1...)")
	}
	sent := unsafe.OriginSend()
	if len(sent) != 1 || sent[0].Denom != "ugnot" || sent[0].Amount <= 0 {
		panic("radio: attach an amount in ugnot")
	}
	t := rd()
	st := t.station(stationID)
	picker, home := st.picker(trackID, now(), adminAddr())
	bk := banker.NewBanker(banker.BankerTypeRealmSend, cur)
	bk.SendCoins(cur.Address(), chain.PackageAddress(data.Writer("catalog")), sent)
	toPicker, _ := catalog.RadioTip(cross(cur), trackID, supportPct, tipper, picker, ref, sent[0].Amount)
	if toPicker > 0 {
		credit(t, picker, home, 0, 1, toPicker) // ranked where the pick lives
		save(cur, t)
		chain.Emit("CuratorTipped", "station", text.Itoa(st.id), "track", text.Itoa(trackID), "picker", picker.String(), "amount", text.Itoa64(toPicker))
	}
}

// credit adds picks or a shared tip to a curator, all time and this week.
// The station's entry also keeps the time of the last pick there, which the
// queue cooldown reads (lastPickAt): no extra write per pick.
func credit(t *tx, by address, stationID, picks, tips int, earned int64) {
	k := by.String()
	ts := now()
	c, sts := curRec(t, k)
	c[0], c[1], c[2] = c[0]+int64(picks), c[1]+int64(tips), c[2]+earned
	if picks > 0 {
		// The reputation sponsored picks need (sponsor.gno): the first pick,
		// and picks counted per period, this one and the one before.
		if c[4] == 0 {
			c[4] = ts
		}
		switch p := ts / repPeriod; c[5] {
		case p:
			c[6]++
		case p - 1:
			c[5], c[6], c[7] = p, 1, c[6]
		default:
			c[5], c[6], c[7] = p, 1, 0
		}
	}
	wk := weekOf(ts)
	if c[cWeek] != wk {
		c[cWeek], c[cWeek+1], c[cWeek+2], c[cWeek+3] = wk, 0, 0, 0
	}
	c[cWeek+1], c[cWeek+2], c[cWeek+3] = c[cWeek+1]+int64(picks), c[cWeek+2]+int64(tips), c[cWeek+3]+earned
	w := stationOf(sts, stationID)
	if w[0] != wk {
		w = []int64{wk, 0, 0, 0, w[4]}
	}
	w[1], w[2], w[3] = w[1]+int64(picks), w[2]+int64(tips), w[3]+earned
	if picks > 0 {
		w[4] = ts
	}
	putCur(t, k, c, withStation(sts, stationID, w, ts))
	setTop(t, 0, wk, k, c[cWeek+1]+c[cWeek+2])
	setTop(t, stationID+1, wk, k, w[1]+w[2])
}

// curRec reads a curator record (zeros when absent) and its station entries.
func curRec(t *tx, k string) ([]int64, string) {
	c := make([]int64, cFields)
	rec := t.val(cCurators, k)
	if rec == "" {
		return c, ""
	}
	at := 0
	for i, w := range cWidths {
		c[i] = store.Num(rec, at, w)
		at += w
	}
	return c, rec[at:]
}

func putCur(t *tx, k string, c []int64, sts string) {
	b := make([]byte, 0, cLen+len(sts))
	for i, w := range cWidths {
		b = store.AppendFixed(b, c[i], w)
	}
	t.set(cCurators, k, string(append(b, sts...)))
}

// stationOf returns a curator's entry for a station: week, picks, tips,
// earned, last pick time (zeros when none).
func stationOf(sts string, stationID int) []int64 {
	w := make([]int64, 5)
	for i := 0; i+sLen <= len(sts); i += sLen {
		if int(dec[sts[i]]) == stationID {
			at := i + 1
			for j, n := range sWidths {
				w[j] = store.Num(sts, at, n)
				at += n
			}
			break
		}
	}
	return w
}

// withStation sets a station's entry and drops the entries that no longer
// count: an older week whose last pick is past the cooldown.
func withStation(sts string, stationID int, w []int64, ts int64) string {
	b := store.AppendFixed(make([]byte, 0, sLen+len(sts)), int64(stationID), 1)
	for j, n := range sWidths {
		b = store.AppendFixed(b, w[j], n)
	}
	wk := weekOf(ts)
	for i := 0; i+sLen <= len(sts); i += sLen {
		e := sts[i : i+sLen]
		if int(dec[e[0]]) == stationID {
			continue
		}
		if store.Num(e, 1, 4) == wk || ts-store.Num(e, sLen-6, 6) < queueCooldown {
			b = append(b, e...)
		}
	}
	return string(b)
}

// markPick keeps the time of a pick that earns no point (a sponsored one) for
// the queue cooldown.
func markPick(t *tx, by address, stationID int) {
	k := by.String()
	ts := now()
	c, sts := curRec(t, k)
	w := stationOf(sts, stationID)
	if wk := weekOf(ts); w[0] != wk {
		w = []int64{wk, 0, 0, 0, 0}
	}
	w[4] = ts
	putCur(t, k, c, withStation(sts, stationID, w, ts))
}

// lastPickAt is when addr last picked on a station (0: never).
func lastPickAt(t *tx, addr address, stationID int) int64 {
	rec := t.val(cCurators, addr.String())
	if rec == "" {
		return 0
	}
	return stationOf(rec[cLen:], stationID)[4]
}

// weekOf numbers weeks from Monday 00:00 UTC.
func weekOf(ts int64) int64 { return (ts + 3*24*3600) / week }

// ---- weekly tops: radio/tops P(station+1), 0 all stations ----

// A top is the week (4 digits), the number of entries n (1) and their
// scores, best first (4 each), then their addresses, each after its length
// (1).

type rank struct {
	key   string // address
	score int64  // picks + tips this week
}

// topRec is ranking i: 0 across stations, else station i-1's (in its
// record, which a pick there writes anyway).
func topRec(t *tx, i int) string {
	if i == 0 {
		return t.val(cTops, "all")
	}
	return t.station(i - 1).top
}

// top reads ranking i of week wk (nil when another week's).
func top(t *tx, i int, wk int64) []rank {
	rec := topRec(t, i)
	if rec == "" || store.Num(rec, 0, 4) != wk {
		return nil
	}
	n := int(dec[rec[4]])
	out := make([]rank, 0, n)
	for j, at := 0, 5+4*n; j < n; j++ {
		l := int(dec[rec[at]])
		out = append(out, rank{rec[at+1 : at+1+l], store.Num(rec, 5+4*j, 4)})
		at += 1 + l
	}
	return out
}

// setTop raises k's score in a ranking, emptied when a new week starts.
// Scores only grow, so a score below the last of a full top leaves it
// untouched (and unsaved): k cannot be in it. That is read without
// decoding the list.
func setTop(t *tx, i int, wk int64, k string, v int64) {
	if i == 0 {
		if int64(t.flowAt(fTopWeek, 4)) == wk && int64(t.flowAt(fTopLast, 4)) > v {
			return
		}
	} else if rec := topRec(t, i); rec != "" && store.Num(rec, 0, 4) == wk && int(dec[rec[4]]) == topCurators && v < store.Num(rec, 1+4*topCurators, 4) {
		return
	}
	list := top(t, i, wk)
	out := make([]rank, 0, topCurators+1)
	for _, r := range list {
		if r.key != k {
			out = append(out, r)
		}
	}
	j := len(out)
	for j > 0 && out[j-1].score < v {
		j--
	}
	if j >= topCurators {
		return
	}
	out = append(out, rank{})
	copy(out[j+1:], out[j:])
	out[j] = rank{k, v}
	if len(out) > topCurators {
		out = out[:topCurators]
	}
	b := store.AppendFixed(store.AppendFixed(make([]byte, 0, topMax), wk, 4), int64(len(out)), 1)
	for _, r := range out {
		b = store.AppendFixed(b, r.score, 4)
	}
	for _, r := range out {
		b = append(store.AppendFixed(b, int64(len(r.key)), 1), r.key...)
	}
	if i == 0 {
		t.set(cTops, "all", string(b))
		last := int64(0)
		if len(out) == topCurators {
			last = out[topCurators-1].score
		}
		t.setFlowAt(fTopWeek, 4, int(wk))
		t.setFlowAt(fTopLast, 4, int(last))
		return
	}
	st := t.station(i - 1)
	st.top, st.dirty = string(b), true
}

// CuratorOf returns a listener's curator record, all time.
func CuratorOf(addr address) Curator {
	c, _ := curRec(rd(), addr.String())
	return Curator{Address: addr, Picks: int(c[0]), Tips: int(c[1]), Earned: c[2], Promo: c[3]}
}

// TopCurators returns this week's top curators of a station (allStations:
// every station), best first, with their counts for the week. Picks and tips
// received on air score one point each.
func TopCurators(stationID int) []Curator {
	return weekTop(rd(), stationID)
}

func weekTop(t *tx, stationID int) []Curator {
	if stationID != allStations {
		mustStation(stationID)
	}
	list := top(t, stationID+1, weekOf(now()))
	out := make([]Curator, 0, len(list))
	for _, r := range list {
		c, sts := curRec(t, r.key)
		n := c[cWeek:]
		if stationID != allStations {
			n = stationOf(sts, stationID)
		}
		out = append(out, Curator{Address: address(r.key), Picks: int(n[1]), Tips: int(n[2]), Earned: n[3]})
	}
	return out
}

// CuratorJSON returns a listener's curator record: all time, this week, and
// their place in this week's top across stations (0 when outside the top 10).
func CuratorJSON(addr address) string {
	t := rd()
	r, _ := curRec(t, addr.String())
	w := r[cWeek:]
	if w[0] != weekOf(now()) {
		w = []int64{0, 0, 0, 0}
	}
	place := 0
	for i, c := range weekTop(t, allStations) {
		if c.Address == addr {
			place = i + 1
		}
	}
	return `{"address":` + text.Str(addr.String()) + `,"picks":` + text.Itoa64(r[0]) + `,"tips":` + text.Itoa64(r[1]) + `,"earned":` + text.Itoa64(r[2]) + `,"promo":` + text.Itoa64(r[3]) +
		`,"week":{"picks":` + text.Itoa64(w[1]) + `,"tips":` + text.Itoa64(w[2]) + `,"earned":` + text.Itoa64(w[3]) + `,"rank":` + text.Itoa(place) + `}}`
}

// TopCuratorsJSON returns TopCurators as JSON with the week's start (unix).
func TopCuratorsJSON(stationID int) string {
	var b strings.Builder
	b.WriteString(`{"station":` + text.Itoa(stationID) + `,"since":` + text.Itoa64(weekOf(now())*week-3*24*3600) + `,"top":[`)
	for i, c := range TopCurators(stationID) {
		if i > 0 {
			b.WriteString(",")
		}
		b.WriteString(`{"address":` + text.Str(c.Address.String()) + `,"picks":` + text.Itoa(c.Picks) + `,"tips":` + text.Itoa(c.Tips) + `,"earned":` + text.Itoa64(c.Earned) + `}`)
	}
	b.WriteString(`]}`)
	return b.String()
}

db.gno

package radio

import (
	"strings"

	"gno.land/p/nym-alexiscolin000/gnoradio/blocks/v0"
	"gno.land/p/nym-alexiscolin000/gnoradio/store/v0"
	"gno.land/r/nym-alexiscolin000/gnoradio/data"
)

// The radio's collections in the data realm (docs/ARCHITECTURE-v1.md,
// section 3). P(n) is store.Pad, T(t) a 12-digit unix time. Numbers inside
// the hot records are fixed-width base-64 digits (store.Num, store.Fixed): a decimal
// conversion costs the VM several times more.
const (
	cStations = "radio/stations" // P(station) -> Rec(epoch, ring, live, rotation header, schedule, recent picks, weekly top[, ring rotation, ring index])
	cRot      = "radio/rot"      // P(station)/b/P(block) -> block; P(station)/g/P(group) -> block sums (p/blocks)
	cHomes    = "radio/homes"    // P((id-1)/homesChunk) -> Rec of homes entries (the genre stations of a track), one per synced track
	cMeta     = "radio/meta"     // "flow" -> flow record
	cCurators = "radio/curators" // address -> curator record (curators.gno)
	cTops     = "radio/tops"     // "all" -> this week's top curators across stations (a station's is in its record)
	cDropped  = "radio/dropped"  // P(station)/P(track) -> "1"
	cNotes    = "radio/notes"    // P(station)/T(start) -> reporters, or the strike a hide gave (notes.gno)
	cMuted    = "radio/muted"    // address -> unix time its dedications are refused until
	cStrikes  = "radio/strikes"  // address -> unix time one of its dedications was last hidden
	cSponsor  = "radio/sponsor"  // address/P(station) -> open sponsored pick (sponsor.gno)
	cActivity = "radio/activity" // P(0..63) -> activity record (a ring, its head in the flow record)
	cConfig   = "radio/config"   // "admin" (mirror of the admin role), "modbot" (hex key)
)

var collections = []string{cStations, cRot, cHomes, cMeta, cCurators, cTops, cDropped, cNotes,
	cMuted, cStrikes, cSponsor, cActivity, cConfig}

const (
	homesChunk = 16       // homes entries per key
	maxRecord  = 16 << 10 // the data realm's longest value
)

// setup makes the radio's collections and its first records, once: a later
// release finds them made (it is not the writer in its init).
func setup(cur realm, holder address) {
	for _, c := range collections {
		data.Make(cross(cur), c)
	}
	if data.Has(cMeta, "flow") {
		return
	}
	ops := store.Ops{}.Set(cMeta, "flow", strings.Repeat("0", flowLen)).Set(cConfig, "admin", holder.String())
	data.Batch(cross(cur), ops)
}

// Fixed-width base-64 numbers are store.Num, store.Fixed and
// store.AppendFixed. dec is store.Digits' decoding table, for the digits
// the hot loops read in place: a call per digit costs about 1% of a pick.
var dec = decTable()

func decTable() (d [128]int64) {
	for i := 0; i < len(store.Digits); i++ {
		d[store.Digits[i]] = int64(i)
	}
	return d
}

// ---- tx: every key read once and written once ----

// tx reads each key from the data realm once and writes every key it
// changed once, in one call (data.Set or data.Batch); the stations it
// loaded are decoded once and encoded back when changed. Every entrypoint
// loads what it needs, changes it in its tx, then saves; readers use one
// too. A tx is never stored.
type tx struct {
	es  []entry
	idx map[string]int // entry key -> position in es
	sts [numStations]*station
	flw string // the flow record, once read (flowRec)
}

type entry struct {
	c, k  string // collection and key
	val   string
	ok    bool // the key exists
	dirty bool
}

func rd() *tx { return &tx{idx: map[string]int{}} }

// at finds a key's entry, reading it from data the first time unless blind
// (a key about to be overwritten).
func (t *tx) at(c, k string, blind bool) *entry {
	key := c + " " + k
	if i, ok := t.idx[key]; ok {
		return &t.es[i]
	}
	e := entry{c: c, k: k}
	if !blind {
		e.val, e.ok = data.Get(c, k)
	}
	t.idx[key] = len(t.es)
	t.es = append(t.es, e)
	return &t.es[len(t.es)-1]
}

func (t *tx) get(c, k string) (string, bool) {
	e := t.at(c, k, false)
	return e.val, e.ok
}

func (t *tx) val(c, k string) string { return t.at(c, k, false).val }

func (t *tx) has(c, k string) bool { return t.at(c, k, false).ok }

func (t *tx) set(c, k, v string) {
	e := t.at(c, k, false)
	e.val, e.ok, e.dirty = v, true, true
}

// put writes a key without reading it first.
func (t *tx) put(c, k, v string) {
	e := t.at(c, k, true)
	e.val, e.ok, e.dirty = v, true, true
}

func (t *tx) del(c, k string) bool {
	e := t.at(c, k, false)
	if !e.ok {
		return false
	}
	e.val, e.ok, e.dirty = "", false, true
	return true
}

// save writes what t changed: one data.Set or data.Remove, or Batches of
// 64 ops (a Sync or a RefreshArtist may change more keys than one Batch
// takes; the transaction keeps them atomic).
func save(cur realm, t *tx) {
	for _, st := range t.sts {
		if st != nil && st.dirty {
			sched := st.raw
			if st.decoded {
				sched = encodeSchedule(st.sched)
			}
			f := []string{store.Fixed(st.epoch, 6), store.Fixed(int64(st.ring), 6), store.Fixed(int64(st.live), 4), st.h, sched, st.picks, st.top}
			if st.ringed() {
				f = append(f, st.rot, st.idx)
			}
			// A pick is refused once its station's record would leave less
			// than recordHeadroom, and the writes a pick or a Sync makes on
			// other stations wait while theirs does (full): this is a last
			// resort.
			rec := store.Rec(f...)
			if len(rec) > maxRecord {
				panic("radio: this station is full for now, try again later")
			}
			t.set(cStations, store.Pad(st.id), rec)
			st.dirty = false
		}
	}
	var ops store.Ops
	for _, e := range t.es {
		if !e.dirty {
			continue
		}
		if e.ok {
			ops = ops.Set(e.c, e.k, e.val)
		} else {
			ops = ops.Del(e.c, e.k)
		}
	}
	for len(ops) > 4*64 {
		data.Batch(cross(cur), ops[:4*64])
		ops = ops[4*64:]
	}
	switch {
	case len(ops) == 0:
	case len(ops) > 4:
		data.Batch(cross(cur), ops)
	case ops[0] == store.OpSet:
		data.Set(cross(cur), ops[1], ops[2], ops[3])
	default:
		data.Remove(cross(cur), ops[1], ops[2])
	}
}

// ---- the flow record: radio/meta "flow" ----

// The flow record is fixed-width: synced (4 digits), the number of dropped
// slots (4), the activity ring's next slot (1), the week of the top across
// stations and its last score when it holds topCurators (0 else) (4 and
// 4: a pick that scores less leaves it as it is, unread), then "1" for each
// genre station with a live track ("0" else, index = genre): Main relays
// one of those (hourGenre). Every call reads it.
const (
	fSynced  = 0
	fDrops   = 4
	fHead    = 8
	fTopWeek = 9
	fTopLast = 13
	fLive    = 17
	flowLen  = fLive + NumGenres + 1
)

// flowRec is the flow record, read once per tx: every call reads it. The data
// realm is permanent: a record an earlier release wrote shorter is padded
// with "0" (a later one's extra fields are kept as they are).
func (t *tx) flowRec() string {
	if t.flw == "" {
		t.flw = t.val(cMeta, "flow")
		if len(t.flw) < flowLen {
			t.flw += strings.Repeat("0", flowLen-len(t.flw))
		}
	}
	return t.flw
}

func (t *tx) flowAt(at, w int) int { return int(store.Num(t.flowRec(), at, w)) }

func (t *tx) setFlowAt(at, w, v int) {
	f := t.flowRec()
	if n := store.Fixed(int64(v), w); n != f[at:at+w] {
		t.flw = f[:at] + n + f[at+w:]
		t.set(cMeta, "flow", t.flw)
	}
}

func (t *tx) synced() int { return t.flowAt(fSynced, 4) }

// hasLive reports whether a genre station has a live track.
func (t *tx) hasLive(genre int) bool {
	return genre >= 1 && genre <= NumGenres && t.flowRec()[fLive+genre] == '1'
}

// dropped reports whether the admin dropped a track from a station.
func (t *tx) dropped(stationID, trackID int) bool {
	return t.flowAt(fDrops, 4) > 0 && t.has(cDropped, dropKey(stationID, trackID))
}

func dropKey(stationID, trackID int) string { return store.Pad(stationID) + "/" + store.Pad(trackID) }

// ---- stations ----

// station is a station loaded in a tx: its header and schedule are one
// record (cStations); its rotation is read and written a block at a time
// (cRot), but for New and Choice: their rings (at most 500 slots) and the
// index of the tracks in them are part of their record, which a pick
// changes anyway.
// The schedule is decoded on first use (slots): a call that only needs the
// time paused under it (paused) or a picker (picker) reads it as it is.
type station struct {
	t       *tx
	id      int
	genre   int // 0 = every genre
	epoch   int64
	ring    int    // New and Choice: joins so far; the slot reused next is ring % keep
	live    int    // rotation slots with a duration > 0
	h       string // the rotation's header (p/blocks)
	raw     string // the encoded schedule
	picks   string // the picks of the last replayGap (lastPicked)
	top     string // this week's top curators here (curators.gno)
	rot     string // New and Choice: the group then the blocks of their ring
	idx     string // and the ring's tracks: sorted entries, the track (4 digits) and its slot (2)
	sched   []Slot // sorted by Start, short (folded as it ages), once decoded
	decoded bool
	dirty   bool
	pz      int64 // paused(pzAt), while pzOK: the schedule did not move since
	pzAt    int64
	pzOK    bool
}

// station loads a station once per tx.
func (t *tx) station(id int) *station {
	if id < 0 || id >= numStations {
		panic("radio: unknown station")
	}
	if st := t.sts[id]; st != nil {
		return st
	}
	st := &station{t: t, id: id, genre: id}
	if id > NumGenres {
		st.genre = 0
	}
	if rec := t.val(cStations, store.Pad(id)); rec != "" {
		f := store.Fields(rec)
		st.epoch, st.ring, st.live, st.h, st.raw, st.picks, st.top = store.Num(f[0], 0, 6), int(store.Num(f[1], 0, 6)), int(store.Num(f[2], 0, 4)), f[3], f[4], f[5], f[6]
		if len(f) > 7 {
			st.rot, st.idx = f[7], f[8]
		}
	}
	t.sts[id] = st
	return st
}

// size is the length of the record save writes for the station, its
// schedule measured as encodeSchedule writes it, without writing it.
func (st *station) size() int {
	n := 1 + 3*7 + 6 + 6 + 4 + len(st.h) + len(st.picks) + len(st.top)
	if st.ringed() {
		n += 3*2 + len(st.rot) + len(st.idx)
	}
	if !st.decoded {
		return n + len(st.raw)
	}
	var prevEnd int64
	for i := range st.sched {
		s := &st.sched[i]
		switch gap := s.Start - prevEnd; {
		case gap == 0:
			n++
		case gap < 0:
			n += 7
		default:
			n += 2
			for gap>>6 != 0 {
				gap >>= 6
				n++
			}
		}
		n += 25 + len(s.By) + len(s.Note)
		prevEnd = s.Start + s.Dur
	}
	return n
}

// full reports whether the record keeps less than recordHeadroom: a new pick
// is refused, and a write a pick makes on the side (a Choice or New join)
// waits. A side write adds far less than recordHeadroom, so
// the record never reaches the data realm's limit (maxRecord).
func (st *station) full() bool { return st.size() > maxRecord-recordHeadroom }

// slots is the decoded schedule.
func (st *station) slots() []Slot {
	if !st.decoded {
		st.sched, st.decoded = decodeSchedule(st.raw), true
	}
	return st.sched
}

// setSlots replaces the schedule.
func (st *station) setSlots(s []Slot) {
	st.sched, st.decoded, st.dirty, st.pzOK = s, true, true, false
}

// addLive counts a slot going live (d = 1) or silent (-1); the flow record
// keeps which genre stations have one.
func (st *station) addLive(d int) {
	st.live += d
	st.dirty = true
	if st.id >= 1 && st.id <= NumGenres && (st.live > 0) != st.t.hasLive(st.id) {
		on := 0
		if st.live > 0 {
			on = 1
		}
		st.t.setFlowAt(fLive+st.id, 1, on)
	}
}

// ---- a station's rotation: p/blocks over its keys ----

func (st *station) ringed() bool { return st.id == NewStation || st.id == ChoiceStation }

// A ring's rotation (one group) is its group's sums, 4 digits per block,
// then its blocks, blocks.Size slots each but the last.
const blockLen = blocks.Size * 6

// ringBlocks is where a ring's blocks start.
func (st *station) ringBlocks() int { return 4 * ((st.count() + blocks.Size - 1) / blocks.Size) }

// group and block read group g and block b of the rotation.
func (st *station) group(g int) string {
	if st.ringed() {
		return st.rot[:st.ringBlocks()]
	}
	return st.t.val(cRot, store.Pad(st.id)+"/g/"+store.Pad(g))
}

func (st *station) block(b int) string {
	if !st.ringed() {
		return st.t.val(cRot, store.Pad(st.id)+"/b/"+store.Pad(b))
	}
	at := st.ringBlocks() + b*blockLen
	if at >= len(st.rot) {
		return ""
	}
	if at+blockLen < len(st.rot) {
		return st.rot[at : at+blockLen]
	}
	return st.rot[at:]
}

// setRotVal writes group g and block b; st.h is still the rotation's
// header before the change.
func (st *station) setRotVal(g int, grp string, b int, blk string) {
	if !st.ringed() {
		st.t.set(cRot, store.Pad(st.id)+"/g/"+store.Pad(g), grp)
		st.t.set(cRot, store.Pad(st.id)+"/b/"+store.Pad(b), blk)
		return
	}
	bs := st.rot[st.ringBlocks():]
	at, end := b*blockLen, b*blockLen+blockLen
	if at > len(bs) {
		at = len(bs)
	}
	if end > len(bs) {
		end = len(bs)
	}
	st.rot, st.dirty = grp+bs[:at]+blk+bs[end:], true
}

func (st *station) total() int64 { return blocks.Total(st.h) }
func (st *station) count() int   { return blocks.Len(st.h) }

func (st *station) rotSlot(i int) (int, int64) {
	if i < 0 || i >= st.count() {
		panic("radio: rotation index out of range")
	}
	_, b := blocks.Where(i)
	return blocks.Slot(st.block(b), i)
}

// find returns the rotation slot playing at position pos of the loop.
func (st *station) find(pos int64) (slot, id int, offset int64, ok bool) {
	g, rest, ok := blocks.FindGroup(st.h, pos)
	if !ok {
		return 0, 0, 0, false
	}
	b, rest := blocks.FindBlock(st.group(g), g, rest)
	slot, id, offset = blocks.FindSlot(st.block(b), b, rest)
	return slot, id, offset, true
}

func (st *station) prefixBefore(i int) int64 {
	g, b := blocks.Where(i)
	return blocks.PrefixBefore(st.h, st.group(g), st.block(b), i)
}

// appendRot adds a slot at the end of the rotation and returns its index.
func (st *station) appendRot(id int, dur int64) int {
	g, b := blocks.Where(st.count())
	h, grp, blk, i := blocks.Append(st.h, st.group(g), st.block(b), id, dur)
	st.setRotVal(g, grp, b, blk)
	st.h, st.dirty = h, true
	return i
}

// setRot replaces slot i's id and duration.
func (st *station) setRot(i, id int, dur int64) {
	g, b := blocks.Where(i)
	h, grp, blk := blocks.Set(st.h, st.group(g), st.block(b), i, id, dur)
	st.setRotVal(g, grp, b, blk)
	st.h, st.dirty = h, true
}

// ---- schedules ----

// A schedule is its slots in order, each a record that starts with the gap
// since the previous slot's end (one digit "0" when it follows it, else the
// number of digits and the gap, "z" and the start if it overlaps), then its
// body: "L" (listener), the duration (2 digits), the track (4), the artist
// (4), the time booked (6), the refund (4), "1" when its note is hidden, and
// its address and note, each after its length (1 and 2 digits). A body is reused as long as its slot keeps
// its duration and note, so moving slots together costs no encoding.

func decodeSchedule(s string) []Slot {
	out := make([]Slot, 0, len(s)/8+1)
	for c := (cursor{s: s}); c.next(); {
		b := s[c.b:c.i]
		x := Slot{Track: int(dec[b[3]]<<18 | dec[b[4]]<<12 | dec[b[5]]<<6 | dec[b[6]]), Start: c.start, Dur: c.end - c.start, body: b, bdur: c.end - c.start}
		bl := int(dec[b[22]])
		x.artist, x.At, x.Pay, x.NoteHidden = int(store.Num(b, 7, 4)), store.Num(b, 11, 6), store.Num(b, 17, 4), b[21] == '1'
		x.By, x.Note = address(b[23:23+bl]), b[25+bl:]
		out = append(out, x)
	}
	return out
}

func encodeSchedule(ss []Slot) string {
	b := make([]byte, 0, 8*len(ss)+64)
	var prevEnd int64
	for i := range ss {
		s := &ss[i]
		switch {
		case s.body == "":
			s.body = s.encodeBody()
		case s.bdur != s.Dur:
			s.body = s.body[:1] + string(store.AppendFixed(make([]byte, 0, 2), s.Dur, 2)) + s.body[3:]
		}
		s.bdur = s.Dur
		switch gap := s.Start - prevEnd; {
		case gap == 0:
			b = append(b, '0')
		case gap < 0:
			b = store.AppendFixed(append(b, 'z'), s.Start, 6)
		default:
			n := 1
			for gap>>(6*n) != 0 {
				n++
			}
			b = store.AppendFixed(append(b, store.Digits[n]), gap, n)
		}
		b = append(b, s.body...)
		prevEnd = s.Start + s.Dur
	}
	return string(b)
}

func (s *Slot) encodeBody() string {
	b := make([]byte, 0, 32+len(s.By)+len(s.Note))
	b = store.AppendFixed(store.AppendFixed(store.AppendFixed(append(b, 'L'), s.Dur, 2), int64(s.Track), 4), int64(s.artist), 4)
	b = store.AppendFixed(store.AppendFixed(b, s.At, 6), s.Pay, 4)
	if s.NoteHidden {
		b = append(b, '1')
	} else {
		b = append(b, '0')
	}
	b = append(store.AppendFixed(b, int64(len(s.By)), 1), s.By...)
	return string(append(store.AppendFixed(b, int64(len(s.Note)), 2), s.Note...))
}

// cursor walks an encoded schedule a slot at a time without decoding it:
// after next, the slot's body is s[b:i] and it plays from start to end.
type cursor struct {
	s          string
	i, b       int
	start, end int64
}

func (c *cursor) next() bool {
	s, i := c.s, c.i
	if i >= len(s) {
		return false
	}
	start := c.end
	switch ch := s[i]; ch {
	case '0':
		i++
	case 'z':
		start, i = store.Num(s, i+1, 6), i+7
	default:
		n := int(dec[s[i]])
		start, i = c.end+store.Num(s, i+1, n), i+1+n
	}
	c.b, c.start, c.end = i, start, start+(dec[s[i+1]]<<6|dec[s[i+2]])
	k := i + 23 + int(dec[s[i+22]])
	c.i = k + 2 + int(dec[s[k]]<<6|dec[s[k+1]])
	return true
}

// ---- where a track rotates: Main at id-1, New and Choice in their ring
// index, genre stations in homes ----

const idxW = 6 // a ring index entry

// ringFind returns the position of a track in the ring index, or where it goes.
func (st *station) ringFind(trackID int) (int, bool) {
	lo, hi := 0, len(st.idx)/idxW
	for lo < hi {
		mid := (lo + hi) / 2
		if int(store.Num(st.idx, idxW*mid, 4)) < trackID {
			lo = mid + 1
		} else {
			hi = mid
		}
	}
	return lo, lo < len(st.idx)/idxW && int(store.Num(st.idx, idxW*lo, 4)) == trackID
}

// ringSlot is a track's slot in the ring.
func (st *station) ringSlot(trackID int) (int, bool) {
	p, ok := st.ringFind(trackID)
	if !ok {
		return 0, false
	}
	return int(store.Num(st.idx, idxW*p+4, 2)), true
}

// ringIndex files a track at a slot of the ring, at position p of the
// index (ringFind), replacing the entry there when found.
func (st *station) ringIndex(p int, found bool, trackID, slot int) {
	end := idxW * p
	if found {
		end += idxW
	}
	st.idx, st.dirty = st.idx[:idxW*p]+store.Fixed(int64(trackID), 4)+store.Fixed(int64(slot), 2)+st.idx[end:], true
}

// ringUnindex forgets a track that left the ring's slot and returns where
// it was in the index (-1: it was not there).
func (st *station) ringUnindex(trackID, slot int) int {
	if p, ok := st.ringFind(trackID); ok && int(store.Num(st.idx, idxW*p+4, 2)) == slot {
		st.idx, st.dirty = st.idx[:idxW*p]+st.idx[idxW*p+idxW:], true
		return p
	}
	return -1
}

// A homes entry is 5 digits per genre station: the station (1) and the slot (4).

func homesKey(trackID int) (string, int) {
	return store.Pad((trackID - 1) / homesChunk), (trackID - 1) % homesChunk
}

// homes returns a synced track's entry.
func (t *tx) homes(trackID int) string {
	k, i := homesKey(trackID)
	if ch := t.val(cHomes, k); ch != "" {
		return store.Field(ch, i)
	}
	return ""
}

func (t *tx) setHomes(trackID int, e string) {
	k, i := homesKey(trackID)
	t.set(cHomes, k, store.With(t.val(cHomes, k), i, e))
}

// appendHomes files the entry of the next synced track.
func (t *tx) appendHomes(trackID int, e string) {
	k, i := homesKey(trackID)
	if i == 0 {
		t.put(cHomes, k, store.Rec(e))
		return
	}
	t.set(cHomes, k, store.Append(t.val(cHomes, k), e))
}

func homeEntry(stationID, slot int) string {
	return store.Fixed(int64(stationID), 1) + store.Fixed(int64(slot), 4)
}

// homeSlot finds a station's slot in an entry.
func homeSlot(e string, stationID int) (int, bool) {
	for i := 0; i+5 <= len(e); i += 5 {
		if int(dec[e[i]]) == stationID {
			return int(store.Num(e, i+1, 4)), true
		}
	}
	return 0, false
}

flow.gno

package radio

// Main's flow is a pure function of the clock and the stations: between
// listeners' picks, each UTC hour Main simulcasts one genre station, playing
// what it plays (its own picks included) until the next hour. The hour's genre follows an energy line around the
// target of the time of day (UTC dayparts: calm at night, peak in the
// evening): one step below the target in a 3-hour block's first hour, the
// target in its second, one step above in its third, or the nearest genre
// with a live track. Reads compute it and nothing is written, so it never
// runs dry and costs GnoRadio nothing: no Sync, robot or keeper.

// energy orders the genres from calm to intense; neighbours blend well.
var energy = [NumGenres]int{
	3,  // Ambient
	16, // Cinematic & Classical
	15, // Folk & Acoustic
	14, // Jazz & Blues
	8,  // Lo-fi Beats
	10, // R&B & Soul
	19, // Reggae & Dub
	17, // World
	18, // Latin
	20, // Funk & Disco
	13, // Pop
	9,  // Hip-hop & Rap
	11, // Rock & Indie
	2,  // Synthwave
	1,  // Electronica
	5,  // House
	4,  // Techno
	7,  // Dubstep & Trap
	6,  // Drum & Bass
	12, // Metal & Punk
}

// dayparts is the target index in energy for each 3-hour block of the UTC day:
// Jazz, Ambient, Lo-fi, World, Pop, Rock, House, then Drum & Bass at the peak.
var dayparts = [8]int{3, 0, 4, 7, 10, 12, 15, 18}

// hourGenre is the genre Main relays at ts: the daypart's target, one step
// below it in the block's first hour, above it in the last, or the nearest
// genre with a live track (0: none).
func hourGenre(t *tx, ts int64) int {
	h := ts / 3600
	i := dayparts[h%24/3] + int(h%3) - 1
	if i < 0 {
		i = 0
	} else if i >= len(energy) {
		i = len(energy) - 1
	}
	for k := 0; k < 2*len(energy); k++ {
		if j := i + (k+1)/2*(1-2*(k%2)); j >= 0 && j < len(energy) && t.hasLive(energy[j]) {
			return energy[j]
		}
	}
	return 0
}

// HourGenre is the genre Main relays at unix time at (0: none), for pages
// that explain it.
func HourGenre(at int64) int { return hourGenre(rd(), at) }

gnomod.toml

module = "gno.land/r/nym-alexiscolin000/gnoradio/radio/v1"
gno = "0.9"

[addpkg]
  creator = "g1mpkp5lm8lwpm0pym4388836d009zfe4maxlqsq"
  height = 253163
  max_deposit = "100000000ugnot"

json.gno

package radio

import (
	"strconv"
	"strings"

	"gno.land/p/nym-alexiscolin000/gnoradio/text/v0"
	"gno.land/r/nym-alexiscolin000/gnoradio/catalog/v1"
)

// Read API for the GnoRadio app (vm/qeval).

// ScheduleJSON returns what a station plays from now until now+horizon seconds
// (60..7200, at most 60 entries): programmed slots and the rotation between
// them (on Main, the hour's genre station, simulcast and cut at each hour). A client plays entry i from offset+max(0, clock-start) and resyncs on
// "now". "relay" marks, on Main, an entry that is not Main's own slot but
// the hour's genre station simulcast (its picks included). "sponsored" is the refund its artist pays the picker (0: a normal
// pick), "at" the time a booked pick asked for (0: none). "booked" lists every
// booked pick still to air, whatever the horizon, and those that aired in the
// last hour (they count toward their clock hour's cap until they fold):
// {"track","start","end","at","by","note"}. Fetch it again every few minutes, not
// every second.
func ScheduleJSON(stationID, horizon int) string {
	st := rd().station(stationID)
	if horizon < 60 || horizon > 7200 {
		horizon = 3600
	}
	ts := now()
	end := ts + int64(horizon)
	var b strings.Builder
	b.WriteString(`{"station":` + text.Itoa(st.id) + `,"now":` + text.Itoa64(ts) + `,"entries":[`)
	n := 0
	emit := func(track int, title string, start, stop, offset int64, queued bool, by, note string, pay, at int64, relay bool) {
		if n > 0 {
			b.WriteString(",")
		}
		b.WriteString(`{"track":` + text.Itoa(track) + `,"title":` + text.Str(title) +
			`,"start":` + text.Itoa64(start) + `,"end":` + text.Itoa64(stop) + `,"offset":` + text.Itoa64(offset) +
			`,"queued":` + strconv.FormatBool(queued) + `,"by":` + text.Str(by) + `,"note":` + text.Str(note) + `,"sponsored":` + text.Itoa64(pay) + `,"at":` + text.Itoa64(at) + `,"relay":` + strconv.FormatBool(relay) + `}`)
		n++
	}
	cur := ts
	for cur < end && n < 60 {
		var slot *Slot
		next := int64(-1)
		sl := st.slots()
		for i := range sl {
			s := &sl[i]
			if cur >= s.Start && cur < s.Start+s.Dur {
				slot = s
				break
			}
			if s.Start > cur && (next < 0 || s.Start < next) {
				next = s.Start
			}
		}
		if slot != nil {
			stop := slot.Start + slot.Dur
			if title := catalog.PlayableTitle(slot.Track); title != "" {
				emit(slot.Track, title, slot.Start, stop, 0, true, slot.By.String(), slot.shownNote(), slot.Pay, slot.At, false)
			}
			cur = stop
			continue
		}
		track, off, dur, ok := st.between(cur)
		relay := st.id == MainStation // not Main's own slot: the hour's genre station, simulcast
		if !ok {
			if next < 0 {
				break
			}
			cur = next
			continue
		}
		stop := cur + dur - off
		if next >= 0 && next < stop {
			stop = next // the rotation (or Main's relay) pauses for the programmed slot
		}
		if title := catalog.PlayableTitle(track); title != "" {
			if s, ok := st.pickAt(cur); ok && s.Track == track { // Main simulcasting a genre station's pick
				emit(track, title, cur-off, stop, off, true, s.By.String(), s.shownNote(), s.Pay, s.At, relay)
			} else {
				emit(track, title, cur-off, stop, off, false, "", "", 0, 0, relay)
			}
		}
		cur = stop
	}
	b.WriteString(`],"booked":[`)
	n = 0
	for _, s := range st.slots() {
		if s.At > 0 && s.Start+s.Dur > ts-foldAfter {
			if n > 0 {
				b.WriteString(",")
			}
			b.WriteString(`{"track":` + text.Itoa(s.Track) + `,"start":` + text.Itoa64(s.Start) + `,"end":` + text.Itoa64(s.Start+s.Dur) + `,"at":` + text.Itoa64(s.At) + `,"by":` + text.Str(s.By.String()) + `,"note":` + text.Str(s.shownNote()) + `}`)
			n++
		}
	}
	b.WriteString(`]}`)
	return b.String()
}

// StationsJSON lists every station with what it plays now.
func StationsJSON() string {
	t := rd()
	var b strings.Builder
	// newFloor: only tracks above this id may be picked on New this week.
	synced := t.synced()
	floor := synced - newCap
	if floor < 0 {
		floor = 0
	}
	ts := now()
	b.WriteString(`{"pending":` + text.Itoa(catalog.TrackCount()-synced) + `,"newFloor":` + text.Itoa(floor) + `,"stations":[`)
	for id := 0; id < numStations; id++ {
		st := t.station(id)
		if id > 0 {
			b.WriteString(",")
		}
		track, offset, isQueued := st.onAir(ts)
		live, loop := st.rotating()
		b.WriteString(`{"id":` + text.Itoa(id) + `,"name":` + text.Str(StationName(id)) + `,"genre":` + text.Itoa(st.genre) +
			`,"tracks":` + text.Itoa(live) + `,"loop":` + text.Itoa64(loop) + `,"queued":` + text.Itoa(st.queued(ts)) +
			`,"now":{"track":` + text.Itoa(track) + `,"offset":` + text.Itoa64(offset) + `,"queued":` + strconv.FormatBool(isQueued) + `}}`)
	}
	b.WriteString(`]}`)
	return b.String()
}

notes.gno

package radio

import (
	"chain"
	"encoding/hex"
	"strconv"
	"strings"

	"gno.land/p/nym-alexiscolin000/gnoradio/role/v0"
	"gno.land/p/nym-alexiscolin000/gnoradio/store/v0"
	"gno.land/p/nym-alexiscolin000/gnoradio/text/v0"
)

// Dedications: reports, strikes and mutes. A dedication's reports are
// radio/notes P(station)/T(start) -> the reporters' addresses, each followed
// by ","; once hidden, struckMark, the strike time it gave its author and
// the one before ("" none), so that RestoreNote takes back this strike only.

const struckMark = "struck:"

func noteKey(stationID int, start int64) string {
	return store.Pad(stationID) + "/" + store.TimeKey(start)
}

// ReportNote flags the dedication of the slot starting at start. Only a
// listener with the reputation sponsored picks need (a first pick a week
// old, 3 normal picks this 15-day period and the one before: sponsorBlock) may report, so
// throwaway wallets cannot; the third such listener hides it at once, with
// no moderator involved. A first hidden dedication is a strike; a second
// within muteFor pauses its author's dedications for muteFor (the admin can
// lift it: Unmute).
func ReportNote(cur realm, stationID int, start int64) {
	caller := userCaller(cur)
	noPayment()
	t := rd()
	st, s := noteSlot(t, stationID, start)
	if s.NoteHidden {
		panic("radio: no dedication at this time on this station")
	}
	if s.By == caller {
		panic("radio: you cannot report your own dedication")
	}
	if sponsorBlock(t, caller) != "" {
		panic("radio: reporting needs a first pick 7 days old and 3 normal picks in the last two 15-day periods")
	}
	key := noteKey(st.id, start)
	by := t.val(cNotes, key)
	if strings.Contains(by, caller.String()) {
		panic("radio: you already reported this dedication")
	}
	by += caller.String() + ","
	if strings.Count(by, ",") < hideAfter {
		t.set(cNotes, key, by)
		save(cur, t)
		chain.Emit("NoteReported", "station", text.Itoa(st.id), "start", text.Itoa64(start), "by", caller.String())
		return
	}
	s.NoteHidden, s.body, st.dirty = true, "", true
	ts, author := now(), s.By.String()
	last, struck := t.get(cStrikes, author)
	mute := struck && ts-text.MustAtoi64(last) < muteFor
	if mute {
		t.set(cMuted, author, text.Itoa64(ts+muteFor))
	}
	t.set(cStrikes, author, text.Itoa64(ts))
	t.set(cNotes, key, struckMark+text.Itoa64(ts)+":"+last)
	save(cur, t)
	chain.Emit("NoteHidden", "station", text.Itoa(st.id), "start", text.Itoa64(start), "author", author, "muted", strconv.FormatBool(mute))
}

// RestoreNote shows again a dedication hidden by reports by mistake and
// clears its author's strike (Unmute lifts a pause). Radio admin only.
func RestoreNote(cur realm, stationID int, start int64) {
	onlyAdmin(cur)
	t := rd()
	st, s := noteSlot(t, stationID, start)
	if !s.NoteHidden {
		panic("radio: this dedication is not hidden") // its pending reports stay
	}
	s.NoteHidden, s.body, st.dirty = false, "", true
	key := noteKey(st.id, start)
	// A wrong hide is no strike: take back the one it gave, if it is still
	// the author's last, and keep any earlier one.
	if rec := t.val(cNotes, key); strings.HasPrefix(rec, struckMark) {
		gave, before, _ := strings.Cut(rec[len(struckMark):], ":")
		author := s.By.String()
		if t.val(cStrikes, author) == gave {
			if before == "" {
				t.del(cStrikes, author)
			} else {
				t.set(cStrikes, author, before)
			}
		}
	}
	t.del(cNotes, key)
	save(cur, t)
	chain.Emit("NoteRestored", "station", text.Itoa(st.id), "start", text.Itoa64(start))
}

// SetModBot names the moderation robot by its Ed25519 public key in hex
// ("" turns dedications off). Radio admin only.
func SetModBot(cur realm, pubKeyHex string) {
	onlyAdmin(cur)
	key, err := hex.DecodeString(pubKeyHex)
	if err != nil || (len(key) != 0 && len(key) != 32) {
		panic("radio: the robot key is a 32-byte Ed25519 public key in hex")
	}
	t := rd()
	t.set(cConfig, "modbot", hex.EncodeToString(key))
	save(cur, t)
	chain.Emit("ModBotSet", "key", pubKeyHex)
}

// MutedUntil returns the unix time until which who's dedications are paused
// after reports, 0 when they are not: the moderation robot refuses to sign
// for a muted author.
func MutedUntil(who address) int64 {
	if v := rd().val(cMuted, who.String()); v != "" {
		if until := text.MustAtoi64(v); now() < until {
			return until
		}
	}
	return 0
}

// Unmute lets a muted listener dedicate again before the week ends, e.g.
// after reports by throwaway wallets. Radio admin only.
func Unmute(cur realm, who address) {
	onlyAdmin(cur)
	if !role.Canonical(who) {
		panic("radio: not an address (lower-case g1...)")
	}
	t := rd()
	if !t.del(cMuted, who.String()) {
		panic("radio: this address is not muted")
	}
	save(cur, t)
	chain.Emit("Unmuted", "address", who.String())
}

// noteSlot finds the dedicated slot starting at start. On Main between its
// own picks it is the genre station's slot Main simulcast: the genre of the
// hour the slot began in, or of now when the hour changed under it.
func noteSlot(t *tx, stationID int, start int64) (*station, *Slot) {
	st := t.station(stationID)
	cands := []*station{st}
	if _, own := st.playing(start); !own {
		cands = []*station{st.relay(start), st.relay(now())}
	}
	for _, c := range cands {
		sl := c.slots()
		for i := range sl {
			if s := &sl[i]; s.Start == start && s.Note != "" {
				return c, s
			}
		}
	}
	panic("radio: no dedication at this time on this station")
}

publish.gno

package radio

import (
	"strings"

	"gno.land/p/nym-alexiscolin000/gnoradio/text/v0"
	"gno.land/r/nym-alexiscolin000/gnoradio/catalog/v1"
)

// Tracks enter and change through this realm: the catalog accepts
// PublishFor, ImportFor and EditFor from the radio writer only, so a track
// is in the station rotations from the transaction that publishes it, paid
// by its publisher. Nothing waits for Sync, and no robot pays for it.

// PublishTrack publishes a track by the caller's own artist profile (the
// arguments are catalog.PublishFor's) and puts it on the air in the same
// transaction: the main station, its genre station and New this week.
func PublishTrack(cur realm, title string, genre int, duration, license, cmo, credits, audio, audioSHA, cover, coverSHA, splits, rights string) int {
	caller := userCaller(cur)
	noPayment()
	id := catalog.PublishFor(cross(cur), caller, title, genre, duration, license, cmo, credits, audio, audioSHA, cover, coverSHA, splits, rights)
	onAir(cur, id, true)
	return id
}

// ImportTrack adds a curated or Audius track to an unclaimed artist (the
// arguments are catalog.ImportFor's) and puts it on the air, New this week
// left out: an import is not a new release. The catalog admin only, from its
// wallet or a realm that holds the role (a launch import).
func ImportTrack(cur realm, artistID int, title string, genre int, duration, license, credits, audio, audioSHA, cover, coverSHA, sourceURL, attribution string) int {
	noPayment()
	id := catalog.ImportFor(cross(cur), cur.Previous().Address(), artistID, title, genre, duration, license, credits, audio, audioSHA, cover, coverSHA, sourceURL, attribution)
	onAir(cur, id, false)
	return id
}

// maxImportBatch bounds ImportTracks: each track costs a few M gas once the
// realms are loaded, so a full batch stays far under the block's gas.
const maxImportBatch = 25

// ImportTracks imports up to maxImportBatch tracks in one transaction, so the
// realms load once for the batch instead of once per track. batch holds one
// track per line ("\n"), ImportTrack's 12 arguments separated by tabs ("\t";
// neither can appear in a valid field). All or nothing: a bad track panics the
// whole transaction (a malformed line is named before anything is written). It returns the id of the last track. Admin only, as
// ImportTrack.
func ImportTracks(cur realm, batch string) int {
	noPayment()
	lines := strings.Split(batch, "\n")
	if batch == "" || len(lines) > maxImportBatch {
		panic("radio: a batch holds 1 to " + text.Itoa(maxImportBatch) + " tracks")
	}
	rows := make([][]string, len(lines))
	for i, line := range lines { // the whole batch is read before anything is written
		f := strings.Split(line, "\t")
		if len(f) != 12 || !text.Digits(f[0]) || !text.Digits(f[2]) {
			panic("radio: batch line " + text.Itoa(i+1) + ": 12 tab-separated fields expected, artist and genre in digits")
		}
		rows[i] = f
	}
	by, id, t := cur.Previous().Address(), 0, rd()
	for _, f := range rows {
		id = catalog.ImportFor(cross(cur), by, text.MustAtoi(f[0]), f[1], text.MustAtoi(f[2]), f[3], f[4], f[5], f[6], f[7], f[8], f[9], f[10], f[11])
		airNext(t, id, false)
	}
	save(cur, t)
	return id
}

// EditTrack fixes a track's details (the arguments are catalog.EditFor's).
// A new genre or duration is applied to the stations in the same
// transaction, as Refresh does; other details need nothing on air.
func EditTrack(cur realm, trackID int, title string, genre int, duration, credits, audio, audioSHA, cover, coverSHA string) {
	caller := userCaller(cur)
	noPayment()
	_, oldGenre, oldDur, _ := catalog.TrackBrief(trackID)
	catalog.EditFor(cross(cur), caller, trackID, title, genre, duration, credits, audio, audioSHA, cover, coverSHA)
	if _, g, d, _ := catalog.TrackBrief(trackID); g != oldGenre || d != oldDur {
		t := rd()
		refresh(cur, t, trackID)
		save(cur, t)
	}
}

// onAir ingests the track the catalog just added, with Sync's own code: it
// is the next one (Sync and every add keep the stations level with the
// catalog), so this is one track's work whatever the catalog size.
func onAir(cur realm, id int, isNew bool) {
	t := rd()
	airNext(t, id, isNew)
	save(cur, t)
}

func airNext(t *tx, id int, isNew bool) {
	if n := id - t.synced(); n != 1 {
		panic("radio: the stations are behind the catalog, call Sync first")
	}
	ingest(t, now(), 1, isNew)
}

queue.gno

package radio

import (
	"chain"
	"chain/runtime"
	"crypto/ed25519"
	"encoding/hex"
	"strconv"

	"gno.land/p/nym-alexiscolin000/gnoradio/safe/v0"
	"gno.land/p/nym-alexiscolin000/gnoradio/store/v0"
	"gno.land/p/nym-alexiscolin000/gnoradio/text/v0"
	"gno.land/r/nym-alexiscolin000/gnoradio/catalog/v1"
	"gno.land/r/nym-alexiscolin000/gnoradio/data"
)

// ---- Programming ----

// Queue programs a track on a station and adds it to Listeners' choice. It
// starts after the last track a listener programmed, or when the song on air
// ends: nothing is cut. On Main it starts at once over the hour's relay (the
// app crossfades), which resumes after it.
// Limits per station: one waiting slot per listener, two per artist, a track
// at most once, 30 upcoming.
func Queue(cur realm, stationID, trackID int) {
	queue(cur, userCaller(cur), stationID, trackID, false, false, "", 0)
}

// QueueAt is Queue for a chosen time: at (unix, UTC) between 15 minutes and
// 24 hours from now; 0 is Queue. The pick starts at the first track boundary
// at or after at (on Main, at at: the relay's track fades out as for any
// pick), unless listener picks fill that moment, then right after them. It
// keeps its time: later picks go before it only if they end by then, else
// after it. Every Queue rule applies, the 3-hour replay gap around at; the
// 2-hour airtime cap does not, but at most 4 picks are booked per station and
// clock hour and at most 15 booked picks wait per station.
func QueueAt(cur realm, stationID, trackID int, at int64) {
	queue(cur, userCaller(cur), stationID, trackID, false, false, "", at)
}

// QueueWithNote is Queue with a dedication shown on air ("for Marie!"). The
// moderation robot judges it before the transaction (word filter and a
// moderation model, app/netlify/functions/dedication.mts) and signs
// NoteMessage(note, expires): the listener sends that certificate and pays
// their own gas, so a dedication shows at once and costs GnoRadio nothing. It
// must also pass p/gnoradio/safe (plain text, no link, no blocked word).
// Listeners can report it: three reports hide it and give its author a strike;
// a second hidden dedication within a week pauses their dedications for a
// week (ReportNote). The pause is per wallet: an author can dedicate again
// from a fresh one, which reports hide and pause the same way (accepted
// residual; the robot and the word filter still judge every note).
func QueueWithNote(cur realm, stationID, trackID int, note string, expires int64, sigHex string) {
	queueWithNote(cur, stationID, trackID, 0, note, expires, sigHex)
}

// QueueWithNoteAt is QueueWithNote for a chosen time (see QueueAt; 0: now).
func QueueWithNoteAt(cur realm, stationID, trackID int, at int64, note string, expires int64, sigHex string) {
	queueWithNote(cur, stationID, trackID, at, note, expires, sigHex)
}

func queueWithNote(cur realm, stationID, trackID int, at int64, note string, expires int64, sigHex string) {
	caller := userCaller(cur)
	if until, ok := data.Get(cMuted, caller.String()); ok && now() < text.MustAtoi64(until) {
		panic("radio: your dedications are paused after reports, pick without one")
	}
	if why := safe.Note(note, maxNote); why != "" {
		panic("radio: dedication: " + why)
	}
	checkNote(caller, stationID, note, expires, sigHex)
	queue(cur, caller, stationID, trackID, false, false, note, at)
}

// NoteMessage is what the moderation robot signs to approve a dedication by
// author on stationID until expires (unix seconds), on this chain and this
// GnoRadio deployment (its data realm) only:
// "gnoradio-note|<chain id>|<data realm>|<author>|<station>|<note>|<expires>".
// A certificate seen in a public transaction serves no other wallet,
// station or deployment.
func NoteMessage(author address, stationID int, note string, expires int64) string {
	return "gnoradio-note|" + runtime.ChainID() + "|" + dataPath + "|" + author.String() + "|" + text.Itoa(stationID) + "|" + note + "|" + text.Itoa64(expires)
}

func checkNote(author address, stationID int, note string, expires int64, sigHex string) {
	v, _ := data.Get(cConfig, "modbot")
	key, _ := hex.DecodeString(v)
	if len(key) == 0 {
		panic("radio: dedications are paused, pick without one")
	}
	if ts := now(); expires <= ts || expires > ts+noteCertLife {
		panic("radio: the dedication check expired, send it again")
	}
	sig, err := hex.DecodeString(sigHex)
	if err != nil || len(sig) != 64 || !ed25519.Verify(key, []byte(NoteMessage(author, stationID, note, expires)), sig) {
		panic("radio: this dedication was not approved, send it again")
	}
}

// CuratorQueue programs a track like Queue but without the per-listener and
// per-artist quotas (the duplicate, genre and queue-size rules still apply).
// Radio admin only.
func CuratorQueue(cur realm, stationID, trackID int) {
	onlyAdmin(cur)
	queue(cur, cur.Previous().Address(), stationID, trackID, true, false, "", 0)
}

func queue(cur realm, caller address, stationID, trackID int, curator, sponsored bool, note string, at int64) {
	noPayment()
	t := rd()
	st := t.station(stationID)
	who := caller // own picks earn nothing: only a listener's needs the check
	if curator || sponsored {
		who = ""
	}
	artistID, genre, dur, playable, own := catalog.TrackBriefFor(trackID, who)
	if !playable {
		panic("radio: unknown track")
	}
	if st.genre != 0 && genre != st.genre {
		panic("radio: this track does not belong to this station")
	}
	if t.dropped(st.id, trackID) { // a pick must not undo the admin's DropSlot
		panic("radio: this track was removed from this station")
	}
	if st.id == NewStation && trackID <= t.synced()-newCap {
		panic("radio: only new tracks can be picked on New this week")
	}
	ts := now()
	airs := ts // when the pick is meant to air
	if at != 0 {
		if at < ts+bookMin || at > ts+bookMax {
			panic("radio: book a time between 15 minutes and 24 hours from now")
		}
		airs = at
	}
	st.fold(ts)
	start := st.place(ts, dur, at)
	// Main's simulcast is not a slot: picking the track it plays would
	// restart it over itself.
	if st.id == MainStation && at == 0 {
		if _, prog := st.playing(ts); !prog {
			if tr, _, _, _ := st.between(ts); tr == trackID {
				panic("radio: this track is already programmed")
			}
		}
	}
	// The replay gap counts from when the pick really airs: a pick for now
	// may wait up to 2 hours behind others, a booked one keeps its time.
	gapAt := airs
	if at == 0 {
		gapAt = start
	}
	// realign may still move a booked pick by up to a track: around one,
	// the replay gap takes that much more.
	gap := int64(replayGap)
	if at != 0 {
		gap += maxTrack
	}
	upcoming, kept, perArtist, booked, bookedUp := 0, 0, 0, 0, 0
	var ahead int64 // listener airtime for now still to play
	for _, s := range st.slots() {
		// A slot of the track blocks it within the replay gap.
		if s.Track == trackID && s.Start+s.Dur > ts {
			g := gap
			if s.At > 0 {
				g = replayGap + maxTrack
			}
			if abs64(s.Start-gapAt) < g {
				panic("radio: this track is already programmed")
			}
		}
		// A booked pick enters lastpick when folded, an hour after it ends:
		// until then its slot keeps the replay gap.
		if s.Track == trackID && s.At > 0 && s.Start+s.Dur <= ts && !curator && gapAt-s.Start < replayGap {
			panic("radio: this track was picked here less than 3 hours ago, pick another one")
		}
		kept++ // aired or not: a listener slot stays in the record until it folds
		if at != 0 && s.At/3600 == at/3600 {
			booked++ // aired ones too: at most maxBookedHour per clock hour
		}
		if s.Start+s.Dur <= ts {
			continue
		}
		upcoming++
		if s.At > 0 {
			bookedUp++
		}
		if !curator && s.Start > ts && s.By == caller {
			panic("radio: you already have a track waiting on this station")
		}
		if s.artist == artistID {
			perArtist++
		}
		if s.At == 0 {
			ahead += s.Start + s.Dur - max64(s.Start, ts)
		}
	}
	if upcoming >= maxQueue || kept >= maxKept {
		panic("radio: the queue is full, try again later")
	}
	// Bookings may cover the next 24 hours: they take at most half the
	// queue, so they never leave picks for now without room.
	if at != 0 && bookedUp >= maxBooked {
		panic("radio: booked picks are full on this station, pick for now or later")
	}
	if booked >= maxBookedHour {
		panic("radio: 4 picks are already booked for that hour here, choose another time")
	}
	// No track on a loop: many wallets cannot replay one song for hours.
	if last, ok := st.lastPicked(trackID); ok && !curator && gapAt-last < gap {
		panic("radio: this track was picked here less than 3 hours ago, pick another one")
	}
	if !curator {
		if last := lastPickAt(t, caller, st.id); last > 0 && ts-last < queueCooldown {
			panic("radio: you can queue one track per station per hour")
		}
		if at == 0 && ahead+dur > maxAheadAir {
			panic("radio: this station is programmed two hours ahead, try again later")
		}
	}
	if !curator && perArtist >= maxPerArtistQ {
		panic("radio: this artist already has 2 tracks in the queue")
	}
	if sponsored {
		sponsorQuota(st, artistID, dur, airs, gapAt)
	}
	if at == 0 {
		st.setPicked(trackID, start) // a booked pick is in the schedule; fold records it once aired
	}
	var pay int64
	if sponsored {
		pay = reserve(cur, t, caller, st.id, trackID, start, dur, Slot{Start: start, Dur: dur, At: at}.held())
	}
	st.put(Slot{Track: trackID, Start: start, Dur: dur, By: caller, Note: note, Pay: pay, At: at, artist: artistID})
	if st.full() {
		panic("radio: this station is full for now, try again later")
	}
	// Dedications use only the room the station's other listener slots, their
	// replay entries and a full curator top cannot need: plain picks always
	// fit (TestChoiceRecordWorstCase).
	if note != "" && st.size()+noteReserve(st, kept) > maxRecord-recordHeadroom {
		panic("radio: dedications are full on this station for now, pick without one")
	}
	kind := "queue"
	if curator {
		kind = "curator"
	} else if sponsored {
		kind = "sponsored"
	}
	recordActivity(t, kind, caller, trackID, st.id, start)
	// A sponsored pick is paid for by its artist: it feeds neither Listeners'
	// choice nor the curator ranking, and only keeps the cooldown. Nor does
	// an artist's (or a collaborator's) pick of their own track (an alt
	// wallet remains a residual, as for any sybil pick).
	switch {
	case sponsored || own:
		markPick(t, caller, st.id)
	case !curator:
		choose(t, trackID, dur, ts)
		credit(t, caller, st.id, 1, 0, 0)
	}
	save(cur, t)
	chain.Emit("Queued", "curator", strconv.FormatBool(curator), "station", text.Itoa(st.id), "track", text.Itoa(trackID), "by", caller.String(), "start", text.Itoa64(start), "sponsored", text.Itoa64(pay), "at", text.Itoa64(at))
}

// place says when a new pick of d seconds starts. A pick for now starts when
// the song on air ends (at once on Main, over the relay), after the picks
// for now already waiting; one booked for at starts at the first track
// boundary at or after at. Both go around booked picks: before one only if
// they end by its time, else after it.
func (st *station) place(ts, d, at int64) int64 {
	t := at
	if at == 0 {
		t = ts
		if st.id != MainStation {
			if _, _, off, slotDur, ok := st.rotationAt(ts); ok {
				t = ts + slotDur - off
			}
		}
		for _, s := range st.slots() {
			// after the picks for now, and after a booked pick on air (the
			// rotation is paused under it: its track would only play a
			// fragment before the pick)
			if end := s.Start + s.Dur; end > ts && (s.At == 0 || s.Start <= ts) {
				t = end
			}
		}
	} else {
		t = st.boundary(at)
	}
	for _, s := range st.slots() {
		if s.Start+s.Dur <= t {
			continue
		}
		if s.Start <= t {
			t = s.Start + s.Dur // playing then: wait for its end
			continue
		}
		limit := s.Start
		if s.At > 0 {
			limit = s.At // a booked pick may come back to its own time
		}
		if t+d <= limit {
			break
		}
		t = s.Start + s.Dur
	}
	return t
}

// boundary is the first track boundary at or after t outside listener
// picks: t itself on Main (the relay fades out) or inside a programmed
// slot (place waits for its end), else the end of the rotation track on air.
func (st *station) boundary(t int64) int64 {
	if st.id == MainStation {
		return t
	}
	for _, s := range st.slots() {
		if s.Start <= t && t < s.Start+s.Dur {
			return t
		}
	}
	if _, _, off, d, ok := st.rotationAt(t); ok && off > 0 {
		return t + d - off
	}
	return t
}

// put puts a new listener slot in the schedule. Elsewhere than on Main the
// slots after it are realigned: they moved with the rotation.
func (st *station) put(n Slot) {
	sl, i := insert(st.slots(), n)
	st.setSlots(sl)
	if st.id != MainStation {
		st.realign(i)
	}
}

// insert puts s in a schedule, sorted by start, and returns its index.
func insert(sl []Slot, s Slot) ([]Slot, int) {
	i := len(sl)
	for i > 0 && sl[i-1].Start > s.Start {
		i--
	}
	sl = append(sl, Slot{})
	copy(sl[i+1:], sl[i:])
	sl[i] = s
	return sl, i
}

// realign re-times the listener slots after index i once the rotation moved
// under them: a booked one to the first boundary at or after its time (or
// right after the slot before it), a pick that followed the slot before it
// still follows it, a pick for now that waited for a rotation track after a
// gap waits for the new end of that track. Sponsored records, note reports and
// the replay record move along.
// ponytail: only queue realigns; Unqueue, DropSlot and rotation edits leave
// booked slots in place (the rotation track then pauses around them, as
// around any pick after a removed one); realign there too if it matters.
func (st *station) realign(i int) {
	sl := st.slots()
	var paused int64 // airtime of the slots before k: they all ended by its time (paused, inline)
	for _, s := range sl[:i+1] {
		paused += s.Dur
	}
	total := st.total()
	oldEnd := sl[i].Start + sl[i].Dur
	var notes []int64 // the dedicated slots moved: old start, new start
	for k := i + 1; k < len(sl); k++ {
		prev, s := sl[k-1], sl[k]
		end := prev.Start + prev.Dur
		start := max64(s.Start, end)
		t := s.At
		if t == 0 && s.Start != oldEnd {
			t = s.Start // a pick for now that started on a rotation boundary after a gap
		}
		if t > end && total > 0 { // the rotation plays until then: wait for the end of that track
			start = t
			p := (t - st.epoch - paused) % total
			if p < 0 {
				p += total
			}
			if slot, _, off, ok := st.find(p); ok && off > 0 {
				_, d := st.rotSlot(slot)
				start += d - off
			}
		} else if s.At > 0 || s.Start == oldEnd {
			start = max64(s.At, end)
		}
		oldEnd = s.Start + s.Dur
		paused += s.Dur
		if start != s.Start {
			if s.Note != "" {
				notes = append(notes, s.Start, start)
			}
			st.move(k, start)
		}
	}
	st.moveNotes(notes)
}

// moveNotes re-keys the reports of moved dedications: all read, then all
// removed, then all written, so that a slot moved to where another one
// started never takes or loses its reports.
func (st *station) moveNotes(moves []int64) {
	t := st.t
	recs := make([]string, len(moves)/2)
	for j := 0; j < len(moves); j += 2 {
		recs[j/2] = t.val(cNotes, noteKey(st.id, moves[j]))
	}
	for j := 0; j < len(moves); j += 2 {
		t.del(cNotes, noteKey(st.id, moves[j]))
	}
	for j := 0; j < len(moves); j += 2 {
		if recs[j/2] != "" {
			t.set(cNotes, noteKey(st.id, moves[j+1]), recs[j/2])
		}
	}
}

// move re-times slot k, with its sponsored record and its replay record
// (its dedication's reports move with moveNotes).
func (st *station) move(k int, start int64) {
	t := st.t
	s := &st.sched[k]
	if s.Pay > 0 {
		k := sponsorKey(st.id, s.By)
		if rec, ok := t.get(cSponsor, k); ok && text.Atoi64(store.Field(rec, 0)) == s.Start {
			f := store.Fields(rec)
			t.set(cSponsor, k, store.Rec(text.Itoa64(start), f[1], text.Itoa64(start+s.Dur), f[3], f[4], f[5], f[6]))
		}
	}
	if s.At == 0 {
		st.setPicked(s.Track, start) // a pick for now: the replay gap counts from its airing
	}
	s.Start = start
	st.dirty, st.pzOK = true, false
}

// noteReserve is the record room the other plain picks a station may still
// take need: a slot and a replay entry each, plus its curator top at full.
func noteReserve(st *station, kept int) int {
	return (maxKept-kept-1)*(plainSlot+pickW) + topMax - len(st.top)
}

radio.gno

// Package radio is GnoRadio's radio rules, release 1: a main station that
// plays the whole catalog through the genre stations, one station per genre,
// "New this week" (the newest tracks) and "Listeners' choice" (the tracks
// listeners picked).
// Everyone tuned to a station hears the same track at the same second,
// computed from block time; no streaming server is involved. Between picks
// the main station simulcasts one genre station an hour, by the time of day
// (flow.gno); it has no rotation of its own.
//
// Each station has a rotation (every playable track of its genre, looping)
// stored in fixed-size blocks so that every operation costs the same
// whatever the catalog size, and a short schedule of tracks programmed by
// listeners. While a programmed track plays the rotation pauses, then
// resumes where it was. Adding, removing or editing a track never makes
// listeners jump.
//
// It keeps no state but its admin role. Every record lives in the data realm
// (gno.land/r/nym-alexiscolin000/gnoradio/data), in the "radio/…" collections only the current
// radio writer may change (db.gno). It reads the catalog through its value
// getters; sponsored picks are paid from data's vault through the catalog.
package radio

import (
	"chain"
	"chain/runtime"
	"chain/runtime/unsafe"
	"strconv"
	"time"

	"gno.land/p/nym-alexiscolin000/gnoradio/role/v0"
	"gno.land/p/nym-alexiscolin000/gnoradio/store/v0"
	"gno.land/p/nym-alexiscolin000/gnoradio/text/v0"
	"gno.land/r/nym-alexiscolin000/gnoradio/catalog/v1"
	"gno.land/r/nym-alexiscolin000/gnoradio/data"
)

// NumGenres is the catalog's: genre stations are 1..NumGenres.
const NumGenres = catalog.NumGenres

// Station ids are stored keys in the permanent data realm (schedules, drops,
// notes, curator ranks): Main 0, genres 1..NumGenres, New, Choice. A later
// release must keep them, and add any new station after Choice.
const (
	MainStation     = 0
	NewStation      = NumGenres + 1 // the newest newCap ingested tracks
	ChoiceStation   = NumGenres + 2 // the last choiceCap distinct listener picks
	numStations     = ChoiceStation + 1
	newCap          = 300
	choiceCap       = 500
	maxQueue        = 30 // upcoming slots per station
	maxPerArtistQ   = 2  // upcoming slots per artist and station
	maxSyncBatch    = 200
	maxRefreshBatch = 50
	foldAfter       = 3600          // programmed slots ended this long ago fold into the epoch
	queueCooldown   = 3600          // a listener may queue once per station per hour
	replayGap       = 3 * 3600      // a track picked on a station cannot be picked there again for 3 hours, by anyone
	maxAheadAir     = 7200          // listener-programmed airtime ahead on a station, seconds
	maxNote         = 40            // characters of a dedication
	noteCertLife    = 900           // seconds a moderation certificate may still have to live
	hideAfter       = 3             // distinct reputable listeners (sponsorBlock) reporting a dedication hide it
	muteFor         = 7 * 24 * 3600 // a second hidden dedication within this time mutes its author this long
	bookMin         = 15 * 60       // a pick booked for a time: at least this far ahead
	bookMax         = 24 * 3600     // and at most this far
	maxBookedHour   = 4             // booked picks per station and clock hour (UTC)
	maxKept         = 3 * maxQueue  // listener slots a station keeps, aired ones included until they fold
	maxBooked       = maxQueue / 2  // booked picks waiting per station
	maxTrack        = 1200          // the catalog's longest track, seconds
	recordHeadroom  = 1024          // bytes a station record keeps free for the writes that follow a pick
	plainSlot       = 72            // record bytes of a listener slot without a dedication: 25, an address, at most 7 of gap
)

// dataPath is the data realm: certificates are bound to it.
const dataPath = "gno.land/r/nym-alexiscolin000/gnoradio/data"

// Slot is a track a listener (or a curator) programmed on a station. Dur is
// captured when queued so later catalog edits cannot move the timeline.
type Slot struct {
	Track      int
	Start      int64
	Dur        int64
	By         address
	Note       string // the picker's dedication, checked by p/gnoradio/safe and the moderation robot
	NoteHidden bool   // hidden by reports or the admin
	Pay        int64  // a sponsored pick: the ugnot its artist reserved to refund the picker (sponsor.gno)
	At         int64  // a booked pick: the time asked (unix); it starts at the first track boundary at or after it
	artist     int    // a listener slot's artist (a track never changes artist): the per-artist rules read it
	body       string // the encoded slot without its start, reused while it does not change (db.gno)
	bdur       int64  // the duration body holds
}

var (
	self  string     // this realm's path
	admin *role.Role // the radio admin; nil when a release before renounced it
)

// init takes the admin over from the previous release (radio/config
// "admin"), or names the deployer. While this realm is the radio writer
// (release 1 at deploy) it also makes the radio's collections.
func init(cur realm) {
	self = cur.PkgPath()
	holder, mirrored := data.Get(cConfig, "admin")
	if !mirrored {
		deployer := unsafe.OriginCaller()
		if deployer == "" && runtime.ChainID() == "dev" {
			deployer = chain.PackageAddress(self + "/dev") // gno test: a key nobody holds
		}
		holder = deployer.String()
	}
	if holder != "" {
		admin = role.New("admin", address(holder))
	}
	if data.Writer("radio") == self {
		setup(cur, address(holder))
	}
}

// ---- Catalog ingestion (permissionless) ----

// Sync ingests up to max catalog tracks not yet on the stations into the
// main station, the station of their genre and New; the catalog's most
// liked tracks join Listeners' choice. Main's flow needs no Sync (flow.gno).
// Anyone may call it. PublishTrack and ImportTrack put each new track on the
// air themselves (publish.gno), so this is a safety net: a track is never
// ingested twice (the flow record counts the synced ones). A track that is
// not playable yet is added silent (duration 0) and Refresh turns it on.
func Sync(cur realm, max int) int {
	noPayment()
	max = store.Limit(max, maxSyncBatch)
	t := rd()
	ts := now()
	n := ingest(t, ts, max, true)
	synced, choice := t.synced(), t.station(ChoiceStation)
	for _, r := range catalog.TopLiked() {
		if id := text.Atoi(r.Key); id <= synced {
			if _, in := choice.ringFind(id); in {
				continue // there already: no need to read the catalog
			}
			if _, _, dur, ok := catalog.TrackBrief(id); ok {
				choose(t, id, dur, ts)
			}
		}
	}
	save(cur, t)
	return n
}

// ingest adds up to max newly published tracks to the stations, and to New
// when joinNew (a launch-catalog import is not a new release).
func ingest(t *tx, ts int64, max int, joinNew bool) int {
	synced := t.synced()
	from := synced + 1
	last := catalog.TrackCount()
	if last > synced+max {
		last = synced + max
	}
	for id := from; id <= last; id++ {
		_, genre, dur, playable := catalog.TrackBrief(id)
		if !playable {
			dur = 0
		}
		home := ""
		if genre >= 1 && genre <= NumGenres {
			home = homeEntry(genre, t.station(genre).add(id, dur, ts))
		}
		if joinNew {
			t.station(NewStation).join(id, dur, ts, newCap)
		}
		t.appendHomes(id, home)
	}
	n := last - synced
	if n > 0 {
		t.setFlowAt(fSynced, 4, last)
		chain.Emit("Synced", "from", text.Itoa(from), "to", text.Itoa(last))
	}
	return n
}

// Refresh re-reads a track from the catalog and updates its rotation slots:
// a hidden track goes silent, a restored one comes back, an edited duration is
// applied. Programmed slots of a track that is no longer playable are dropped.
// Anyone may call it. A slot the admin dropped stays silent.
func Refresh(cur realm, trackID int) {
	noPayment()
	t := rd()
	refresh(cur, t, trackID)
	save(cur, t)
}

// RefreshArtist refreshes up to maxRefreshBatch synced tracks of an artist,
// from offset in the artist's track list, so hiding (or restoring) a whole
// artist takes a few calls instead of one per track. It returns the offset to
// pass next, or 0 when the list is done. Anyone may call it.
func RefreshArtist(cur realm, artistID, offset int) int {
	noPayment()
	n := catalog.ArtistTrackCount(artistID)
	if n == 0 && catalog.ArtistName(artistID) == "" {
		panic("radio: unknown artist")
	}
	if offset < 0 || offset > n {
		offset = 0
	}
	t := rd()
	synced := t.synced()
	for _, id := range catalog.ArtistTrackPage(artistID, offset, maxRefreshBatch) {
		if id >= 1 && id <= synced {
			refresh(cur, t, id)
		}
	}
	save(cur, t)
	if end := offset + maxRefreshBatch; end < n {
		return end
	}
	return 0
}

func refresh(cur realm, t *tx, trackID int) {
	if trackID < 1 || trackID > t.synced() {
		panic("radio: track not synced yet")
	}
	_, genre, dur, playable := catalog.TrackBrief(trackID)
	if !playable {
		dur = 0
	}
	ts := now()
	// Only the stations that hold the track in their rotation need a slot
	// lookup (Main, New and Choice as they say, the genre stations listed in
	// homes). Programmed slots are checked on every station: a genre edit
	// must not leave a slot nobody can silence.
	inGenre := false
	for id := 0; id < numStations; id++ {
		st := t.station(id)
		belongs := st.genre == 0 || st.id == genre
		if i, ok := st.slot(trackID); ok {
			d := dur
			if !belongs || t.dropped(st.id, trackID) {
				d = 0
			}
			st.setDuration(i, d, ts)
			if st.id == genre {
				inGenre = true
			}
		}
		if !playable || !belongs {
			release(cur, st.dropSlots(trackID, ts))
		}
	}
	if !inGenre && genre >= 1 && genre <= NumGenres && dur > 0 {
		t.setHomes(trackID, t.homes(trackID)+homeEntry(genre, t.station(genre).add(trackID, dur, ts)))
	}
	chain.Emit("Refreshed", "track", text.Itoa(trackID), "playable", strconv.FormatBool(playable))
}

// ---- Reads ----

// NowPlaying returns what a station plays at the last block: the track, the
// offset into it in seconds, and whether a listener programmed it. trackID is
// 0 when nothing plays. Clients should prefer ScheduleJSON and their clock.
func NowPlaying(stationID int) (trackID int, offset int64, queued bool) {
	return rd().station(stationID).onAir(now())
}

// OnAirNote returns the dedication of the programmed slot on air ("" when
// none, or once reports hid it).
func OnAirNote(stationID int) string {
	if s, ok := rd().station(stationID).pickAt(now()); ok {
		return s.shownNote()
	}
	return ""
}

// OnAirPay is the refund of the sponsored pick on air (0: none), for labels.
func OnAirPay(stationID int) int64 {
	if s, ok := rd().station(stationID).pickAt(now()); ok {
		return s.Pay
	}
	return 0
}

// UpNext returns the slots listeners programmed on a station that have not
// started yet.
func UpNext(stationID int) []Slot {
	st := rd().station(stationID)
	ts := now()
	var out []Slot
	for _, s := range st.slots() {
		if s.Start > ts {
			if _, _, _, ok := catalog.TrackBrief(s.Track); ok {
				s.Note = s.shownNote()
				out = append(out, s)
			}
		}
	}
	return out
}

// StationCount returns the number of stations (ids 0..StationCount()-1).
func StationCount() int { return numStations }

// StationName is "Main", the genre name, "New this week" or "Listeners' choice".
func StationName(stationID int) string {
	switch mustStation(stationID) {
	case MainStation:
		return "Main"
	case NewStation:
		return "New this week"
	case ChoiceStation:
		return "Listeners' choice"
	default:
		return catalog.GenreName(stationID)
	}
}

// StationInfo returns how many tracks rotate on a station and the loop length.
func StationInfo(stationID int) (tracks int, loop int64, queued int) {
	st := rd().station(stationID)
	tracks, loop = st.rotating()
	return tracks, loop, st.queued(now())
}

// Pending returns how many catalog tracks are not on the stations yet: 0, since
// publishing puts a track on the air (Sync is the safety net).
func Pending() int { return catalog.TrackCount() - rd().synced() }

// PickRules returns the limits on listeners' picks, for pages that explain
// them: one pick per cooldown per station, a track not again within replay,
// at most ahead seconds and queue slots waiting, perArtist waiting per artist,
// booked picks bookFrom to bookTo ahead, bookedPerHour per clock hour and
// booked of the queue slots at most.
func PickRules() (cooldown, replay, ahead int64, queue, perArtist int, bookFrom, bookTo int64, bookedPerHour, booked int) {
	return queueCooldown, replayGap, maxAheadAir, maxQueue, maxPerArtistQ, bookMin, bookMax, maxBookedHour, maxBooked
}

// ---- helpers ----

func now() int64 { return time.Now().Unix() }

func mustStation(id int) int {
	if id < 0 || id >= numStations {
		panic("radio: unknown station")
	}
	return id
}

func userCaller(cur realm) address {
	if !cur.Previous().IsUserCall() {
		panic("radio: call this directly from your wallet")
	}
	return cur.Previous().Address()
}

func noPayment() {
	if len(unsafe.OriginSend()) != 0 {
		panic("radio: this action does not take coins")
	}
}

func abs64(n int64) int64 {
	if n < 0 {
		return -n
	}
	return n
}

func max64(a, b int64) int64 {
	if a > b {
		return a
	}
	return b
}

sponsor.gno

package radio

import (
	"chain"

	"gno.land/p/nym-alexiscolin000/gnoradio/store/v0"
	"gno.land/p/nym-alexiscolin000/gnoradio/text/v0"
	"gno.land/r/nym-alexiscolin000/gnoradio/catalog/v1"
	"gno.land/r/nym-alexiscolin000/gnoradio/data"
)

// Sponsored picks: an artist's promo budget (catalog/sponsor.gno) refunds a
// listener's pick of their track: by default what the pick and collecting
// its refund cost (0.2 GNOT, catalog/sponsor.gno). The listener
// chooses it (QueueSponsored) instead of a normal pick; the artist's refund is
// reserved at once in the data realm's vault, and the listener collects it
// (ClaimPickPayout, one signature, their gas) once the slot has aired in
// full. A slot dropped or cut before its end gives the reservation back; one
// not collected within 7 days lapses back to the budget by itself.
//
// Farming with throwaway wallets earns at most the pick cost back, and these
// rules keep it rare: a wallet needs a first pick 7 days old and 3 normal
// picks in the last two 15-day periods (two counters in the curator record: the
// current period and the one before, so the window is 15 to 30 days, never
// more);
// one sponsored pick per artist per station and hour; sponsored airtime at
// most a quarter of the 2 hours listeners may program; and per wallet one per
// artist and three a day (the catalog). They earn no curator point, do not
// join Listeners' choice and carry no dedication.

const (
	repPeriod     = 15 * 24 * 3600 // reputation counters roll over every 15 days
	repAge        = 7 * 24 * 3600  // a wallet's first pick must be this old
	repPicks      = 3              // normal picks this period and the one before
	sponsorShare  = maxAheadAir / 4
	sponsorWindow = 3600
)

// A sponsored pick not collected yet is radio/sponsor address/P(station) ->
// Rec(start, track, end, ugnot, held, reserved, gen): one open per
// wallet and station; held is the end the catalog reserved for, reserved
// when (unix), gen the budget's funding generation then.
//
// The vault pools an artist's holds per day, and a new owner's funding
// refunds the previous funder everything, holds included, and starts a new
// funding generation (catalog/sponsor.gno): a reservation made before is
// cancelled, never paid from (nor released into) a later listener's hold,
// even when the budget went back to the same funder.

func sponsorKey(stationID int, addr address) string {
	return addr.String() + "/" + store.Pad(stationID)
}

// QueueSponsored is Queue paid by the artist: once the pick has aired in
// full, ClaimPickPayout sends the picker the artist's refund (catalog
// PromoOffer). No dedication. A wallet has one sponsored pick open per
// station: it must be collected (or have lapsed) before the next.
func QueueSponsored(cur realm, stationID, trackID int) {
	queueSponsored(cur, stationID, trackID, 0)
}

// QueueSponsoredAt is QueueSponsored for a chosen time (see QueueAt; 0: now).
// The refund lapses 7 days after the booked time plus the track's length.
func QueueSponsoredAt(cur realm, stationID, trackID int, at int64) {
	queueSponsored(cur, stationID, trackID, at)
}

func queueSponsored(cur realm, stationID, trackID int, at int64) {
	caller := userCaller(cur)
	t := rd()
	if why := sponsorBlock(t, caller); why != "" {
		panic("radio: " + why)
	}
	mustStation(stationID)
	// One open per station until it lapses: collected, or nothing left to
	// pay (the catalog lapses it at the end of a UTC day, so a record past
	// end+7d may still pay).
	if rec, ok := data.Get(cSponsor, sponsorKey(stationID, caller)); ok {
		if payoutStatus(store.Fields(rec)) != "lapsed" {
			panic("radio: collect your last sponsored pick on this station first")
		}
	}
	queue(cur, caller, stationID, trackID, false, true, "", at)
}

// ClaimPickPayout sends the caller the refund of their sponsored pick that
// started at start on stationID, once it has aired in full.
func ClaimPickPayout(cur realm, stationID int, start int64) {
	caller := userCaller(cur)
	noPayment()
	mustStation(stationID)
	t := rd()
	k := sponsorKey(stationID, caller)
	rec, ok := t.get(cSponsor, k)
	if !ok || text.MustAtoi64(store.Field(rec, 0)) != start {
		panic("radio: no sponsored pick of yours to collect at this time")
	}
	f := store.Fields(rec)
	track, amt, held := text.MustAtoi(f[1]), text.MustAtoi64(f[3]), text.MustAtoi64(f[4])
	status := payoutStatus(f)
	if status == "airing" {
		panic("radio: your pick has not finished airing yet")
	}
	t.del(cSponsor, k)
	// A removed track, a cancelled sponsorship or a lapsed refund leaves
	// nothing to pay: the record goes, so the next sponsored pick is open.
	if status == "lapsed" {
		save(cur, t)
		chain.Emit("PickPayoutVoid", "station", text.Itoa(stationID), "start", text.Itoa64(start), "track", text.Itoa(track), "to", caller.String())
		return
	}
	catalog.PromoClaim(cross(cur), track, caller, held, amt, text.MustAtoi(f[6]))
	c, sts := curRec(t, caller.String())
	c[3] += amt
	putCur(t, caller.String(), c, sts)
	save(cur, t)
	chain.Emit("PickPaid", "station", text.Itoa(stationID), "start", text.Itoa64(start), "track", text.Itoa(track), "to", caller.String(), "amount", text.Itoa64(amt))
}

// sponsorBlock says why a wallet may not take sponsored picks yet ("" when it may).
func sponsorBlock(t *tx, addr address) string {
	c, _ := curRec(t, addr.String())
	ts := now()
	if c[4] == 0 || ts-c[4] < repAge {
		return "sponsored picks open 7 days after your first pick"
	}
	recent := int64(0)
	switch ts / repPeriod {
	case c[5]:
		recent = c[6] + c[7]
	case c[5] + 1:
		recent = c[6]
	}
	if recent < repPicks {
		return "sponsored picks need 3 normal picks in the last two 15-day periods"
	}
	return ""
}

// sponsorQuota: one sponsored pick per artist per station and hour, and
// sponsored airtime at most a quarter of the listener window, both around
// airs (now, or the time booked).
// The share counts the listener window from airs; the per-artist hour is
// checked around plays, when the pick really airs (review R31).
func sponsorQuota(st *station, artistID int, dur, airs, plays int64) {
	air := dur
	for _, s := range st.slots() {
		if s.Pay == 0 {
			continue
		}
		if end := s.Start + s.Dur; end > airs && s.Start < airs+maxAheadAir {
			air += end - max64(s.Start, airs)
		}
		if s.Start+s.Dur > plays-sponsorWindow && s.Start < plays+sponsorWindow && s.artist == artistID {
			panic("radio: this artist already has a sponsored pick this hour here, pick it normally")
		}
	}
	if air > sponsorShare {
		panic("radio: sponsored picks are full on this station for now, pick normally")
	}
}

// reserve books the artist's refund for a sponsored slot, lapsing after held.
func reserve(cur realm, t *tx, picker address, stationID, trackID int, start, dur, held int64) int64 {
	amt, gen := catalog.PromoReserve(cross(cur), trackID, picker, held)
	t.set(cSponsor, sponsorKey(stationID, picker), store.Rec(text.Itoa64(start), text.Itoa(trackID), text.Itoa64(start+dur), text.Itoa64(amt), text.Itoa64(held), text.Itoa64(now()), text.Itoa(gen)))
	return amt
}

// held is the end the catalog reserves a sponsored slot's refund for: a
// booked slot keeps the one of its time even if it moves to a boundary.
func (s Slot) held() int64 {
	if s.At > 0 {
		return s.At + s.Dur
	}
	return s.Start + s.Dur
}

// hold is a sponsored slot's reservation in the catalog: filed under the end
// it was reserved for (the slot may have moved since). reserved is when it
// was taken, 0 once the slot started airing: only a pick that never aired
// gives its daily counts back.
type hold struct {
	track                int
	picker               address
	held, paid, reserved int64
	gen                  int
}

// unsponsor forgets the open record of a sponsored slot cut at ts before it
// started, and returns its reservation; ok is false when there was none. A
// slot already on air keeps its record: whoever cut it (a hide, a genre edit,
// a drop), the picker earned the refund and collects it once its end passes.
func unsponsor(t *tx, stationID int, s Slot, ts int64) (hold, bool) {
	k := sponsorKey(stationID, s.By)
	rec, ok := t.get(cSponsor, k)
	if !ok || s.Start < ts || text.MustAtoi64(store.Field(rec, 0)) != s.Start {
		return hold{}, false
	}
	t.del(cSponsor, k)
	f := store.Fields(rec)
	return hold{s.Track, s.By, text.MustAtoi64(f[4]), s.Pay, text.MustAtoi64(f[5]), text.MustAtoi(f[6])}, true
}

// release gives the reservations of cut sponsored slots back to their
// artists. While the catalog is paused it gives nothing back, so the radio
// can still drop slots: each hold lapses back to its budget by itself.
func release(cur realm, cut []hold) {
	if data.Paused("catalog") {
		return
	}
	for _, h := range cut {
		catalog.PromoRelease(cross(cur), h.track, h.picker, h.held, h.paid, h.reserved, h.gen)
	}
}

// PickPayoutStatus says what ClaimPickPayout would do for addr's sponsored
// pick that started at start on stationID: "ok" (it pays), "airing" (not
// finished yet), "lapsed" (nothing to pay: lapsed or cancelled; collecting only clears it) or
// "none" (no such open pick).
func PickPayoutStatus(addr address, stationID int, start int64) string {
	rec, ok := data.Get(cSponsor, sponsorKey(stationID, addr))
	if !ok || text.Atoi64(store.Field(rec, 0)) != start {
		return "none"
	}
	return payoutStatus(store.Fields(rec))
}

func payoutStatus(f []string) string {
	track, end, amt, held := text.MustAtoi(f[1]), text.MustAtoi64(f[2]), text.MustAtoi64(f[3]), text.MustAtoi64(f[4])
	if now() < end {
		return "airing"
	}
	// An aired pick pays whatever happened to its track since: hiding it
	// must not let its artist take back a refund the picker earned.
	if !catalog.PromoClaimable(track, held, amt, text.MustAtoi(f[6])) {
		return "lapsed"
	}
	return "ok"
}

// SponsoredJSON lists a wallet's sponsored picks not collected yet, with
// whether it may take new ones and each one's PickPayoutStatus:
// {"block":"why not, or empty","open":[{"station","start","track","end","amount","status"}]}.
func SponsoredJSON(addr address) string {
	out := `{"block":` + text.Str(sponsorBlock(rd(), addr)) + `,"open":[`
	p := addr.String() + "/"
	keys, recs := store.Rows(data.Page(cSponsor, p, addr.String()+"0", numStations, false))
	for i, rec := range recs {
		f := store.Fields(rec)
		if i > 0 {
			out += ","
		}
		out += `{"station":` + text.Itoa(text.Atoi(keys[i][len(p):])) + `,"start":` + f[0] + `,"track":` + f[1] + `,"end":` + f[2] + `,"amount":` + f[3] + `,"status":"` + payoutStatus(f) + `"}`
	}
	return out + `]}`
}

station.gno

package radio

import (
	"gno.land/p/nym-alexiscolin000/gnoradio/store/v0"
	"gno.land/r/nym-alexiscolin000/gnoradio/catalog/v1"
)

// ---- Station internals: the rotation loop and the schedule over it ----

// paused is the airtime taken by programmed slots before ts. It reads an
// undecoded schedule as it is, and keeps its result until the schedule
// moves (setSlots, move).
func (st *station) paused(ts int64) int64 {
	if st.pzOK && st.pzAt == ts {
		return st.pz
	}
	var p int64
	if st.decoded {
		for _, s := range st.sched {
			if ts <= s.Start {
				break
			}
			if ts >= s.Start+s.Dur {
				p += s.Dur
			} else {
				p += ts - s.Start
			}
		}
	} else {
		for c := (cursor{s: st.raw}); c.next() && ts > c.start; {
			if ts >= c.end {
				p += c.end - c.start
			} else {
				p += ts - c.start
			}
		}
	}
	st.pz, st.pzAt, st.pzOK = p, ts, true
	return p
}

// pos is the position in the rotation loop at ts.
func (st *station) pos(ts int64) int64 {
	total := st.total()
	if total == 0 {
		return 0
	}
	p := (ts - st.epoch - st.paused(ts)) % total
	if p < 0 {
		p += total
	}
	return p
}

// anchor sets the epoch so that the rotation is at position p at ts.
func (st *station) anchor(ts, p int64) {
	st.epoch, st.dirty = ts-st.paused(ts)-p, true
}

func (st *station) rotationAt(ts int64) (slot, track int, offset, dur int64, ok bool) {
	if st.total() == 0 {
		return 0, 0, 0, 0, false
	}
	slot, track, offset, ok = st.find(st.pos(ts))
	if !ok {
		return 0, 0, 0, 0, false
	}
	_, dur = st.rotSlot(slot)
	return slot, track, offset, dur, true
}

// rotating is how many tracks play on the station and its loop length: on
// Main, which simulcasts the genre stations, theirs added up.
func (st *station) rotating() (live int, loop int64) {
	if st.id != MainStation {
		return st.live, st.total()
	}
	for g := 1; g <= NumGenres; g++ {
		gs := st.t.station(g)
		live, loop = live+gs.live, loop+gs.total()
	}
	return
}

// playing is the programmed slot on air at ts.
func (st *station) playing(ts int64) (Slot, bool) {
	for _, s := range st.slots() {
		if ts >= s.Start && ts < s.Start+s.Dur {
			return s, true
		}
	}
	return Slot{}, false
}

// between is what a station plays at ts outside programmed slots: its
// rotation, or on Main a simulcast of the hour's genre station (flow.gno):
// what that station plays at ts, its own picks included, cut where it pauses
// for a pick and at the hour (the app's top-of-hour jingle covers the cut).
// The genre station never jumps (its edits re-anchor it), so neither does Main.
func (st *station) between(ts int64) (track int, off, dur int64, ok bool) {
	if st.id != MainStation {
		_, track, off, dur, ok = st.rotationAt(ts)
		return
	}
	g := hourGenre(st.t, ts)
	if g == 0 {
		return
	}
	gs := st.t.station(g)
	if s, prog := gs.playing(ts); prog {
		track, off, dur, ok = s.Track, ts-s.Start, s.Dur, true
	} else if _, track, off, dur, ok = gs.rotationAt(ts); !ok {
		return
	} else {
		for _, s := range gs.slots() { // the genre rotation pauses for its next pick
			if s.Start > ts && s.Start < ts-off+dur {
				dur = s.Start - (ts - off)
			}
		}
	}
	if end := ts - ts%3600 + 3600; ts-off+dur > end {
		dur = end - (ts - off)
	}
	if st.t.dropped(MainStation, track) {
		track = 0 // dropped from Main: silence (onAir and ScheduleJSON skip it)
	}
	return
}

// relay is the station Main simulcasts at ts (the hour's genre station), or st.
func (st *station) relay(ts int64) *station {
	if st.id == MainStation {
		if g := hourGenre(st.t, ts); g != 0 {
			return st.t.station(g)
		}
	}
	return st
}

// pickAt is the listener pick on air at ts: the station's own or, on Main
// between its own picks, the genre station's pick it simulcasts, so Main
// shows, tips and reports it as that pick.
func (st *station) pickAt(ts int64) (Slot, bool) {
	if s, ok := st.playing(ts); ok || st.id != MainStation {
		return s, ok
	}
	if r := st.relay(ts); r != st {
		if s, ok := r.playing(ts); ok && !st.t.dropped(MainStation, s.Track) {
			return s, true
		}
	}
	return Slot{}, false
}

func (st *station) onAir(ts int64) (int, int64, bool) {
	if s, ok := st.pickAt(ts); ok {
		if _, _, _, ok := catalog.TrackBrief(s.Track); ok {
			return s.Track, ts - s.Start, true
		}
		return 0, 0, false // a removed programmed slot plays silence until its end
	}
	track, off, _, ok := st.between(ts)
	if !ok {
		return 0, 0, false
	}
	if _, _, _, playable := catalog.TrackBrief(track); !playable {
		return 0, 0, false // hidden but not refreshed yet: silence, never its title
	}
	return track, off, false
}

// queued counts the listener slots not ended yet.
func (st *station) queued(ts int64) int {
	n := 0
	for _, s := range st.slots() {
		if s.Start+s.Dur > ts {
			n++
		}
	}
	return n
}

// add appends a track at the end of the loop and returns its slot; listeners do not move.
func (st *station) add(trackID int, dur int64, ts int64) int {
	p := st.pos(ts)
	i := st.appendRot(trackID, dur)
	if dur > 0 {
		st.addLive(1)
	}
	st.anchor(ts, p)
	return i
}

// join puts a synced track in New or Choice, a ring of keep slots: once
// full, the oldest slot is reused in place, so the rotation never outgrows
// keep whatever the catalog size or the number of picks. The track it held
// leaves the ring's index, so Refresh leaves it out. Listeners do not jump:
// replace re-anchors around the change.
func (st *station) join(trackID int, dur int64, ts int64, keep int) {
	p, found := st.ringFind(trackID)
	st.joinAt(p, found, trackID, dur, ts, keep)
}

// joinAt is join for a track at position p of the ring's index (ringFind).
func (st *station) joinAt(p int, found bool, trackID int, dur int64, ts int64, keep int) {
	if st.full() {
		return // no room in the record now: the track misses this ring (Choice takes it again with a later pick or Sync)
	}
	i := st.ring % keep
	st.ring++
	st.dirty = true
	if st.count() < keep {
		st.ringIndex(p, found, trackID, st.add(trackID, dur, ts))
		return
	}
	old, _ := st.rotSlot(i)
	st.replace(i, trackID, dur, ts)
	if q := st.ringUnindex(old, i); q >= 0 && q < p {
		p--
	} else if q == p && old == trackID {
		found = false
	}
	st.ringIndex(p, found, trackID, i)
}

// choose adds a synced track to Listeners' choice unless it is already there.
func choose(t *tx, trackID int, dur int64, ts int64) {
	if trackID < 1 || trackID > t.synced() {
		return // not ingested yet
	}
	cs := t.station(ChoiceStation)
	p, in := cs.ringFind(trackID)
	if in {
		return
	}
	if t.dropped(ChoiceStation, trackID) {
		dur = 0
	}
	cs.joinAt(p, false, trackID, dur, ts, choiceCap)
}

// slot returns a track's index in this station's rotation. Main has no
// rotation (it simulcasts the genre stations); New and Choice keep an index;
// genre stations look the slot up in homes.
func (st *station) slot(trackID int) (int, bool) {
	switch {
	case st.id == MainStation:
		return 0, false
	case st.ringed():
		return st.ringSlot(trackID)
	}
	return homeSlot(st.t.homes(trackID), st.id)
}

// setDuration changes slot i and re-anchors so the song on air keeps playing
// (or, if it is the one removed, the next one starts now). O(n/Size + Size).
func (st *station) setDuration(i int, d int64, ts int64) {
	id, old := st.rotSlot(i)
	if old == d {
		return
	}
	p := st.pos(ts)
	prefix := st.prefixBefore(i)
	np := p
	switch {
	case st.total() == 0 || p < prefix:
		// the change is ahead of the listeners
	case p >= prefix+old:
		np = p - old + d // the change is behind them
	default:
		// the slot on air changes
		if p-prefix >= d {
			np = prefix + d // cut short: the next track starts now
		}
	}
	st.setRot(i, id, d)
	if old == 0 && d > 0 {
		st.addLive(1)
	} else if old > 0 && d == 0 {
		st.addLive(-1)
	}
	if total := st.total(); total > 0 {
		st.anchor(ts, np%total)
	}
}

// replace puts another track in slot i, as setDuration(i, 0), a new id,
// then setDuration(i, d) would, in one rotation write: the old track stops
// if on air (the next starts now), listeners do not jump.
func (st *station) replace(i, id int, d int64, ts int64) {
	_, old := st.rotSlot(i)
	if old == 0 && d == 0 {
		st.setRot(i, id, 0) // the old sequence left the epoch alone
		return
	}
	p, prefix := st.pos(ts), st.prefixBefore(i)
	np := p
	switch {
	case st.total() == 0 || p < prefix:
	case p >= prefix+old:
		np = p - old + d
	default:
		np = prefix + d // the slot on air ends now
	}
	st.setRot(i, id, d)
	if old == 0 && d > 0 {
		st.addLive(1)
	} else if old > 0 && d == 0 {
		st.addLive(-1)
	}
	if total := st.total(); total > 0 {
		st.anchor(ts, np%total)
	}
}

// fold moves programmed slots that ended long ago into the epoch.
func (st *station) fold(ts int64) {
	sl := st.slots()
	i := 0
	for i < len(sl) && sl[i].Start+sl[i].Dur <= ts-foldAfter {
		s := sl[i]
		st.epoch += s.Dur
		if s.Note != "" { // only a dedication has reports
			st.t.del(cNotes, noteKey(st.id, s.Start))
		}
		if s.At > 0 { // the replay gap counts from when a booked pick aired
			st.setPicked(s.Track, s.Start)
		}
		i++
	}
	if i > 0 {
		st.setSlots(sl[i:])
	}
}

// dropSlots removes a track's programmed slots; one on air ends now. It
// returns the sponsored ones, which no longer air in full: their payout goes
// back to the artist (release).
func (st *station) dropSlots(trackID int, ts int64) (cut []hold) {
	var out []Slot
	changed := false
	for _, s := range st.slots() {
		if s.Track == trackID && s.Pay > 0 && s.Start+s.Dur > ts {
			if h, ok := unsponsor(st.t, st.id, s, ts); ok {
				cut = append(cut, h)
			}
		}
		if s.Track == trackID {
			if s.Start >= ts {
				// a later pick may reuse this start: its reports go too
				if s.Note != "" {
					st.t.del(cNotes, noteKey(st.id, s.Start))
				}
				changed = true
				continue
			}
			if s.Start+s.Dur > ts {
				s.Dur = ts - s.Start
				changed = true
			}
		}
		out = append(out, s)
	}
	if changed {
		st.setSlots(out)
	}
	return cut
}

// The replay record of a station (in its record: a pick changes both) is
// fixed-width entries, the track (4 digits) then the pick time (6), read by
// slicing.
const pickW = 10

// lastPicked is when a track was last picked on the station, within replayGap.
func (st *station) lastPicked(trackID int) (int64, bool) {
	rec := st.picks
	key := store.Fixed(int64(trackID), 4)
	for i := 0; i+pickW <= len(rec); i += pickW {
		if rec[i:i+4] == key {
			return store.Num(rec, i+4, 6), true
		}
	}
	return 0, false
}

// setPicked records a pick time (the later one wins) and drops the picks
// older than replayGap, which no check reads: the record stays as short as
// the picks of the last three hours.
func (st *station) setPicked(trackID int, at int64) {
	rec := st.picks
	key := store.Fixed(int64(trackID), 4)
	cut := now() - replayGap
	out := ""
	for i := 0; i+pickW <= len(rec); i += pickW {
		when := store.Num(rec, i+4, 6)
		if rec[i:i+4] == key {
			if when > at {
				at = when
			}
		} else if when > cut {
			out += rec[i : i+pickW]
		}
	}
	if at > cut {
		out += key + store.Fixed(at, 6)
	}
	if out != rec {
		st.picks, st.dirty = out, true
	}
}

// shownNote is the dedication listeners see ("" once hidden).
func (s Slot) shownNote() string {
	if s.NoteHidden {
		return ""
	}
	return s.Note
}

// picker is the listener whose pick of trackID plays at ts on the station,
// or ended less than tipGrace ago, read from the stored schedule: "" when
// none, a sponsored pick (its artist already refunds it) or the admin's (a
// curator pick: GnoRadio takes no share), and the station the pick lives on
// (on Main, the genre station whose pick it simulcast).
func (st *station) picker(trackID int, ts int64, adm address) (address, int) {
	var by address
	for c := (cursor{s: st.raw}); c.next(); {
		b := st.raw[c.b:c.i]
		if c.start > ts || ts >= c.end+tipGrace || int(dec[b[3]]<<18|dec[b[4]]<<12|dec[b[5]]<<6|dec[b[6]]) != trackID || store.Num(b, 17, 4) != 0 {
			continue
		}
		if p := address(b[23 : 23+int(dec[b[22]])]); p != adm {
			by = p
		}
	}
	if by == "" && st.id == MainStation && !st.t.dropped(MainStation, trackID) {
		for _, at := range []int64{ts, ts - tipGrace} { // the pick may have ended in the hour before
			if r := st.relay(at); r != st {
				if by, _ = r.picker(trackID, ts, adm); by != "" {
					return by, r.id
				}
			}
		}
	}
	return by, st.id
}