Playground
artists.gno
package catalog
import (
"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/data"
)
// RegisterArtist creates or updates the caller's artist profile. Names use
// Latin letters so look-alike names in other scripts cannot impersonate.
func RegisterArtist(cur realm, name, bio string) int {
caller := userCaller(cur)
noPayment()
name, bio = strings.TrimSpace(name), strings.TrimSpace(bio)
mustText("bio", bio, 0, maxBio)
t := rd()
id := artistOf(t, caller)
if id != 0 {
a := getArtist(t, id)
if name != a.Name { // a kept name stays valid when the reserved list grows
mustName(name)
}
rename(t, a, name)
a.Bio = bio
t.setRec(cArtists, id, fits(artistRecord(a)))
save(cur, t)
emitEvent("ArtistUpdated", "id", text.Itoa(id), "name", name)
return id
}
mustName(name)
a := newArtist(t, OriginArtist, name, bio, "", caller)
t.set(cOwners, caller.String(), text.Itoa(a.ID))
save(cur, t)
emitEvent("ArtistRegistered", "id", text.Itoa(a.ID), "owner", caller.String(), "name", name)
return a.ID
}
// CreateArtist adds an unclaimed artist. Admin only. A curated artist has a
// name and its page at the source (https), shown for attribution. An Audius
// or Jamendo artist is a pointer: no name or bio, and source is its platform
// id ("audius-user:<id>", "jamendo-artist:<id>"), which also keeps it unique;
// the app reads its name live from the platform.
func CreateArtist(cur realm, kind, name, bio, source string) int {
onlyAdmin(cur)
name, bio, source = strings.TrimSpace(name), strings.TrimSpace(bio), strings.TrimSpace(source)
switch {
case kind == OriginCurated:
mustName(name)
mustText("bio", bio, 0, maxBio)
if source != "" && !text.HTTPS(source, 300) {
panic("catalog: source must be an https link")
}
case isRef(kind):
if name != "" || bio != "" || !validRef(kind, source) {
panic("catalog: an Audius or Jamendo artist has no name or bio, and source " + refUser(kind) + "<id>")
}
default:
panic("catalog: kind must be curated, audius or jamendo")
}
t := rd()
a := newArtist(t, kind, name, bio, source, "")
save(cur, t)
emitEvent("ArtistCreated", "id", text.Itoa(a.ID), "kind", kind, "name", name)
return a.ID
}
// AssignArtist hands an unclaimed artist to the wallet that proved it owns
// the profile (claim checked off-chain). Their tracks then receive tips.
func AssignArtist(cur realm, artistID int, owner address) {
onlyAdmin(cur)
t := rd()
a := mustArtist(t, artistID)
if a.Owner != "" {
panic("catalog: artist already claimed")
}
if !role.Canonical(owner) || data.IsGnoRadio(owner) || artistOf(t, owner) != 0 {
panic("catalog: this wallet is invalid or already has an artist profile")
}
a.Owner, a.Verified = owner, true
putArtist(t, a)
t.del(cClaims, store.Pad(a.ID))
t.set(cOwners, owner.String(), text.Itoa(a.ID))
t.activity("claim", owner, "0", text.Itoa(a.ID), "0")
save(cur, t)
emitEvent("ArtistClaimed", "id", text.Itoa(a.ID), "owner", owner.String())
}
// Follow and Unfollow an artist.
func Follow(cur realm, artistID int) {
caller := userCaller(cur)
noPayment()
t := rd()
a := mustArtist(t, artistID)
if a.Owner == caller {
panic("catalog: you cannot follow yourself")
}
u := user(t, caller)
follows, ok := store.Add(u.Follows, artistID)
if !ok {
panic("catalog: already following")
}
if store.Count(u.Follows) >= maxFollows {
panic("catalog: follows limit reached")
}
u.Follows = follows
putUser(t, caller, u)
a.Followers++
putArtist(t, a)
t.activityOnce("follow", caller, "0", text.Itoa(artistID))
save(cur, t)
emitEvent("Followed", "artist", text.Itoa(artistID), "by", caller.String())
}
func Unfollow(cur realm, artistID int) {
caller := userCaller(cur)
noPayment()
t := rd()
u := user(t, caller)
follows, ok := store.Remove(u.Follows, artistID)
if !ok {
panic("catalog: not following")
}
u.Follows = follows
putUser(t, caller, u)
if a := getArtist(t, artistID); a != nil && a.Followers > 0 {
a.Followers--
putArtist(t, a)
}
save(cur, t)
emitEvent("Unfollowed", "artist", text.Itoa(artistID), "by", caller.String())
}
func newArtist(t *tx, kind, name, bio, source string, owner address) *Artist {
k := skeleton(name)
if isRef(kind) {
k = source // a pointer is reserved under its platform id ("audius-user:12")
}
if _, taken := t.get(cNames, k); taken {
panic("catalog: this artist name is already taken")
}
a := &Artist{ID: int(t.bump(mArtists, 1)), Owner: owner, Kind: kind, Name: name, Bio: bio, Source: source, Joined: now()}
t.addRec(cArtists, a.ID, fits(artistRecord(a)))
t.set(cNames, k, text.Itoa(a.ID))
return a
}
// rename moves the artist to a new name and frees the old one (the caller
// saves a). A hidden artist keeps its name so it cannot dodge moderation.
func rename(t *tx, a *Artist, name string) {
k, old := skeleton(name), skeleton(a.Name)
if k == old {
a.Name = name
return
}
if a.Hidden {
panic("catalog: a hidden artist cannot change its name")
}
if id, ok := t.get(cNames, k); ok && text.Atoi(id) != a.ID {
panic("catalog: this artist name is already taken")
}
t.set(cNames, k, text.Itoa(a.ID))
if id, ok := t.get(cNames, old); old != "" && ok && text.Atoi(id) == a.ID { // a pointer had no name
t.del(cNames, old)
}
a.Name = name
if a.Verified {
emitEvent("Verified", "artist", text.Itoa(a.ID), "verified", "false")
}
a.Verified = false
// A pending claim was checked for the old name: a rename must not inherit
// it, nor the old proof (a later Verify by the admin shows no host).
t.del(cClaims, store.Pad(a.ID))
t.del(cProofs, store.Pad(a.ID))
}
// ReleaseName frees a reserved name no visible artist is using. Admin only.
func ReleaseName(cur realm, name string) {
onlyAdmin(cur)
t := rd()
k := strings.TrimSpace(name)
if strings.HasPrefix(k, refKey) { // a pointer track's key: free once the track is hidden
v, ok := t.get(cNames, k)
if !ok {
panic("catalog: this name is not reserved")
}
if tr := getTrack(t, text.Atoi(v)); tr != nil && !tr.Hidden {
panic("catalog: this pointer track is visible")
}
t.del(cNames, k)
save(cur, t)
emitEvent("NameReleased", "name", k)
return
}
ref := strings.HasPrefix(k, refUser(OriginAudius)) || strings.HasPrefix(k, refUser(OriginJamendo)) // a pointer's raw platform key
if !ref {
k = skeleton(k)
}
v, ok := t.get(cNames, k)
if !ok {
panic("catalog: this name is not reserved")
}
if a := getArtist(t, text.Atoi(v)); a != nil && !a.Hidden && (ref && a.Source == k || !ref && skeleton(a.Name) == k) {
panic("catalog: this name belongs to a visible artist")
}
t.del(cNames, k)
save(cur, t)
emitEvent("NameReleased", "name", k)
}
// refUser is the source prefix of a pointer artist's platform id.
func refUser(kind string) string {
if kind == OriginJamendo {
return "jamendo-artist:"
}
return "audius-user:"
}
func validRef(kind, source string) bool {
return strings.HasPrefix(source, refUser(kind)) && alnum(strings.TrimPrefix(source, refUser(kind)), 1, 32)
}
catalog.gno
// Package catalog is GnoRadio's catalog rules, release 1: artists, tracks,
// albums, playlists, likes, follows, tips, support, moderation and
// verification. Other GnoRadio realms (radio, tickets, home) read it through
// the value getters in read.gno; it imports none of them.
//
// It keeps no state but its admin role. Every record lives in the data realm
// (gno.land/r/nym-alexiscolin000/gnoradio/data), in the "catalog/…" collections only the current
// catalog writer may change (db.gno). Promo budgets sit in data's vault, so a
// later release takes over the data and the coins without copying anything.
//
// Four track origins share one catalog:
// - "artist": published by the artist's own wallet, tips enabled;
// - "curated": imported by the admin from CC0 / CC BY / CC BY-SA / CC BY-NC / CC BY-NC-SA sources;
// - "audius", "jamendo": pointers the admin imports. The record keeps only
// what the radio needs (platform id, genre, duration, licence); the app
// reads title, artist and cover live, since both platforms' API terms
// allow session caching only (attribution required).
//
// Imported artists start unclaimed; once the admin assigns them to
// a wallet (AssignArtist) or the robot verifies a claim, their tracks receive
// tips.
//
// Tips and support are forwarded in the same transaction: this realm ends
// every transaction holding no coins.
package catalog
import (
"chain"
"chain/runtime"
"chain/runtime/unsafe"
"strings"
"time"
"gno.land/p/nym-alexiscolin000/gnoradio/role/v0"
"gno.land/p/nym-alexiscolin000/gnoradio/text/v0"
"gno.land/r/nym-alexiscolin000/gnoradio/data"
)
const (
version = "1.0.0"
denom = "ugnot"
ugnot = 1_000_000
OriginArtist = "artist"
OriginCurated = "curated"
OriginAudius = "audius"
OriginJamendo = "jamendo"
minTip = 100_000 // 0.1 GNOT
maxTip = 1_000_000 * ugnot // keeps share math far from overflow
maxSplits = 4
maxSplitPct = 90 // the artist always keeps at least 10%
earlyBadges = 10
minDuration = 10
maxDuration = 1200
maxPerArtist = 500 // tracks per artist
maxAlbumTracks = 40
maxListTracks = 200
maxUserLists = 50
maxFollows = 1000
maxUserReports = 5 // open reports per reporter
maxTitle = 64 // track, album and playlist titles, in characters
maxBio = 280 // artist bio
maxCredits = 160 // a track's credits and a curated import's attribution
maxReason = 200 // report and moderation reasons
topSize = 10
maxSupportPct = 50
)
// NumGenres is the size of the fixed genre list; genre ids are 1..NumGenres.
const NumGenres = 20
var genres = [NumGenres + 1]string{"",
"Electronica", "Synthwave", "Ambient", "Techno", "House", "Drum & Bass", "Dubstep & Trap",
"Lo-fi Beats", "Hip-hop & Rap", "R&B & Soul", "Rock & Indie", "Metal & Punk", "Pop",
"Jazz & Blues", "Folk & Acoustic", "Cinematic & Classical", "World", "Latin", "Reggae & Dub", "Funk & Disco"}
// licenses an artist may pick; curated imports are limited to CC0, BY, BY-SA, BY-NC and BY-NC-SA
// (no ND, no reserved rights).
var licenses = []string{
"CC0-1.0", "CC-BY-4.0", "CC-BY-SA-4.0", "CC-BY-ND-4.0",
"CC-BY-NC-4.0", "CC-BY-NC-SA-4.0", "CC-BY-NC-ND-4.0", "ALL-RIGHTS-RESERVED",
}
// AudiusLicense is the license id of tracks streamed from Audius.
const AudiusLicense = "Audius-OML"
const rightsTerms = "I own or control the rights to this recording and its composition, or hold a licence that allows this, and I grant the operator of GnoRadio and its users a worldwide, non-exclusive, royalty-free licence to store, stream, broadcast and display it through GnoRadio and gno.land for as long as it is published."
var (
self string // this realm's path
admin *role.Role // the moderator; nil when a release before renounced it
)
// init takes the admin over from the previous release (catalog/config
// "admin"), or names the deployer. While this realm is the catalog writer
// (release 1 at deploy) it also makes the catalog'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("catalog") == self {
setup(cur, address(holder))
}
}
// ---- helpers shared by every file ----
func now() int64 { return time.Now().Unix() }
func userCaller(cur realm) address {
if !cur.Previous().IsUserCall() {
panic("catalog: call this directly from your wallet")
}
return cur.Previous().Address()
}
// adminAddr is the admin: the data realm's mirror is the authority, so a
// change the previous release made after this one was deployed counts.
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("catalog: admin only")
}
noPayment()
}
func noPayment() {
if len(unsafe.OriginSend()) != 0 {
panic("catalog: this action does not take coins")
}
}
// paid returns the ugnot attached to the call; anything else is refused.
func paid() int64 {
sent := unsafe.OriginSend()
if len(sent) != 1 || sent[0].Denom != denom || sent[0].Amount <= 0 {
panic("catalog: attach an amount in ugnot")
}
return sent[0].Amount
}
func emitEvent(name string, kv ...string) { chain.Emit(name, kv...) }
// ---- release and admin ----
// 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("catalog: 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", "")
}
// 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, "catalog/v1"), "gno.land") + "home/v1"
d := strings.TrimPrefix(dataPath, "gno.land")
out := "# GnoRadio · catalog\n\nThis contract holds GnoRadio's catalog rules; its data lives in [" + d + "](" + d +
"). The site lives at [" + home + "](" + home + ").\n"
if w := data.Writer("catalog"); w != self {
out += "\nThis release is retired: the catalog is now `" + w + "`.\n"
}
return out
}
// Info is the catalog's summary for the app: counts, the admin and the
// realm that writes the catalog now ("current", this one unless retired).
func Info() string {
t := rd()
return `{"version":` + text.Str(version) + `,"artists":` + text.Itoa64(t.count(mArtists)) + `,"tracks":` + text.Itoa64(t.count(mTracks)) +
`,"albums":` + text.Itoa64(t.count(mAlbums)) + `,"playlists":` + text.Itoa64(t.count(mPlaylists)) + `,"listeners":` + text.Itoa(data.Size(cUsers)) +
`,"genres":` + text.Itoa(NumGenres) + `,"now":` + text.Itoa64(now()) + `,"current":` + text.Str(data.Writer("catalog")) +
`,"admin":` + text.Str(adminAddr().String()) + `}`
}
db.gno
package catalog
import (
"strings"
"gno.land/p/nym-alexiscolin000/gnoradio/store/v0"
"gno.land/p/nym-alexiscolin000/gnoradio/text/v0"
"gno.land/r/nym-alexiscolin000/gnoradio/data"
)
// The catalog's collections in the data realm (docs/ARCHITECTURE-v1.md,
// section 3). P(n) is store.Pad. Records are store.Rec values; id lists are
// store's packed lists.
const (
cArtists = "catalog/artists" // P((id-1)/chunkSize) -> artist heads (chunk)
cAlists = "catalog/alists" // P(artist) -> Rec(track ids, album ids)
cOwners = "catalog/owners" // owner address -> artist id
cNames = "catalog/names" // name skeleton -> artist id
cTracks = "catalog/tracks" // P((id-1)/chunkSize) -> track records (chunk)
cGenres = "catalog/genres" // P(genre)/P(id>>9) -> packed track ids
cAlbums = "catalog/albums" // P((id-1)/chunkSize) -> album records (chunk)
cPlaylists = "catalog/playlists" // P(id) -> playlist record
cUsers = "catalog/users" // address -> Rec(follows, tipped, playlists, reports)
cLikes = "catalog/likes" // address/P(id>>9) -> packed liked track ids
cTipped = "catalog/tipped" // address/P(id>>9) -> packed tipped track ids
cReports = "catalog/reports" // P(id) -> report record (open reports only)
cRemoved = "catalog/removed" // kind:id -> moderator's reason, "" when its artist hid it
cHosts = "catalog/hosts" // allowed https host -> "1"
cMeta = "catalog/meta" // "n" -> counts
cTops = "catalog/tops" // liked|artists|fans|support -> ranks
cActivity = "catalog/activity" // P(0..63) -> activity record (ring, head in meta)
cConfig = "catalog/config" // admin, treasury, goal, bot, gen
cSupporters = "catalog/supporters" // address -> lifetime support
cMonthly = "catalog/monthly" // YYYY-MM -> support that month
cPromo = "catalog/promo" // P(artist) -> promo percent
cBudgets = "catalog/budgets" // P(artist) -> sponsored-pick settings and stats
cWalletDay = "catalog/walletday" // address -> day|artist ids sponsored that day
cClaims = "catalog/claims" // P(artist) -> pending claim
cProofs = "catalog/proofs" // P(artist) -> proof URL of the last finalized claim
)
var collections = []string{cArtists, cAlists, cOwners, cNames, cTracks, cGenres, cAlbums, cPlaylists, cUsers,
cLikes, cTipped, cReports, cRemoved, cHosts, cMeta, cTops, cActivity, cConfig, cSupporters, cMonthly,
cPromo, cBudgets, cWalletDay, cClaims, cProofs}
const (
chunkSize = 8 // records per key of the chunked collections; tickets/nft reads artists with it: frozen
maxRec = 1500 // longest artist, track or album record when written by its author
idRange = 9 // likes, tips and genres are kept per range of 1<<idRange track ids
activitySize = 64
)
// setup makes the catalog's collections and its first settings, 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, "n") {
return
}
ops := store.Ops{}.Set(cMeta, "n", newCounts()).Set(cConfig, "admin", holder.String()).
Set(cHosts, "archive.org", "1").Set(cHosts, "upload.wikimedia.org", "1")
data.Batch(cross(cur), ops)
}
// tx reads each key from the data realm once and writes every key it
// changed once, in one call (data.Set or data.Batch). Every entrypoint loads
// what it needs, changes it in its tx, then saves; readers use one too, so a
// chunk is decoded once per call. A tx is never stored.
type tx struct {
es []entry
idx map[string]int // entry key -> position in es
}
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) 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) {
if e := t.at(c, k, false); e.ok {
e.val, e.ok, e.dirty = "", false, true
}
}
// save writes what t changed: one data.Set or data.Remove, or Batches of
// 64 ops (a bulk ResolveReports may change more keys than one Batch takes;
// the transaction keeps them atomic, as in radio).
func save(cur realm, t *tx) {
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])
}
}
// ---- chunked records: artists, tracks and albums, chunkSize per key ----
// rec returns record id of a chunked collection ("" when absent).
func (t *tx) rec(c string, id int) string {
if id < 1 {
return ""
}
k, i := store.Slot(id, chunkSize)
ch := t.val(c, k)
if ch == "" {
return ""
}
return store.Field(ch, i)
}
// point is tx.rec without a tx, for the getters that read one or two
// records: no tx to build for a call the radio makes in loops.
func point(c string, id int) string {
if id < 1 {
return ""
}
k, i := store.Slot(id, chunkSize)
if ch, _ := data.Get(c, k); ch != "" {
return store.Field(ch, i)
}
return ""
}
// artistAt is field f of an artist's record, "" when unknown (point).
func artistAt(id, f int) string {
if rec := point(cArtists, id); rec != "" {
return store.Field(rec, f)
}
return ""
}
// setRec replaces record id.
func (t *tx) setRec(c string, id int, rec string) {
k, i := store.Slot(id, chunkSize)
t.set(c, k, store.With(t.val(c, k), i, rec))
}
// addRec appends record id, the collection's next one.
func (t *tx) addRec(c string, id int, rec string) {
k, i := store.Slot(id, chunkSize)
if i == 0 {
t.put(c, k, store.Rec(rec))
return
}
t.set(c, k, store.Append(t.val(c, k), rec))
}
// fits refuses a record too long for its chunk: chunkSize records, each
// with room left for its counters and early badges, stay under data's
// 16 KiB value limit, so one author can never fill a chunk others share.
func fits(rec string) string {
if len(rec) > maxRec {
panic("catalog: these details are too long, shorten the links or texts")
}
return rec
}
// ---- counts: catalog/meta "n", one field each ----
// Count fields. A count is read and changed in place (store.Field and
// store.With): converting numbers costs gas, so nothing decodes the record.
// Reaching field i walks the i before it: what a publish changes comes first.
const (
mTracks = 0
mGenre = 0 // + genre id (1..NumGenres): tracks filed under it
)
const (
mArtists = NumGenres + 1 + iota
mAlbums
mPlaylists
mReports // filed
mOpen // reports not yet resolved
mSupporters
mSupport // ugnot
mFields
)
func newCounts() string {
fs := make([]string, mFields)
for i := range fs {
fs[i] = "0"
}
return store.Rec(fs...)
}
func (t *tx) count(i int) int64 {
if m := t.val(cMeta, "n"); m != "" {
return text.Atoi64(store.Field(m, i))
}
return 0
}
// bump adds d to count i and returns the new value; save writes it.
func (t *tx) bump(i int, d int64) int64 {
n := t.count(i) + d
t.set(cMeta, "n", store.With(t.val(cMeta, "n"), i, text.Itoa64(n)))
return n
}
// ---- id ranges: a sorted packed list per 512 ids ----
func rangeKey(prefix string, id int) string { return prefix + "/" + store.Pad(id>>idRange) }
// addID and removeID change a ranged id set; false when nothing changed.
func (t *tx) addID(c, prefix string, id int) bool {
k := rangeKey(prefix, id)
list := t.val(c, k)
if n := store.Count(list); n == 0 || store.At(list, n-1) < id {
t.set(c, k, list+store.Enc(id)) // a new highest id, as every new track's
return true
}
list, ok := store.Add(list, id)
if ok {
t.set(c, k, list)
}
return ok
}
func (t *tx) removeID(c, prefix string, id int) bool {
k := rangeKey(prefix, id)
list, ok := store.Remove(t.val(c, k), id)
switch {
case !ok:
case list == "":
t.del(c, k)
default:
t.set(c, k, list)
}
return ok
}
// rangePage reads up to limit ids of a ranged set from offset, highest
// first, and the set's size, one data.Page per 100 ranges.
func rangePage(c, prefix string, offset, limit int) (ids []int, total int) {
end := prefix + "0"
// ponytail: at most 10 pages of 100 ranges (512,000 track ids); keep a
// counter per set if the catalog ever gets near that.
for p := 0; p < 10; p++ {
keys, lists := store.Rows(data.Page(c, prefix+"/", end, 100, true))
for _, l := range lists {
n := store.Count(l)
total += n
if offset >= n {
offset -= n
continue
}
if len(ids) < limit {
ids = append(ids, store.Page(l, offset, limit-len(ids), true)...)
}
offset = 0
}
if len(keys) < 100 {
break
}
end = keys[len(keys)-1]
}
return ids, total
}
// ---- activity ring and leaderboards ----
// Activity is one entry of the public activity feed.
type Activity struct {
Kind string // publish | like | follow | tip | support | playlist | album | claim
By address
Track int // track, playlist or album id depending on Kind
Artist int
Amount int64
At int64
}
// activity writes the next slot of the fixed-size ring (storage never
// grows), numbers given as decimal strings. The ring's head is a key of its
// own in catalog/meta: rewriting the counts would cost a like more.
func (t *tx) activity(kind string, by address, track, artist, amount string) {
h := text.Atoi(t.val(cMeta, "head"))
t.put(cActivity, store.Pad(h), store.Rec(kind, by.String(), track, artist, amount, text.Itoa64(now())))
t.set(cMeta, "head", text.Itoa((h+1)%activitySize))
}
// activityOnce is activity for likes and follows, skipped when the newest
// entry is already this wallet's of the same kind: like and unlike cycles,
// or a run of likes, take one slot of the feed, not the whole ring.
func (t *tx) activityOnce(kind string, by address, track, artist string) {
h := text.Atoi(t.val(cMeta, "head"))
last := t.val(cActivity, store.Pad((h+activitySize-1)%activitySize))
if store.Field(last, 0) == kind && store.Field(last, 1) == by.String() {
return
}
t.activity(kind, by, track, artist, "0")
}
type Rank struct {
Key string
Value int64
}
// Leaderboard names in cTops.
const (
topLiked = "liked" // track ids by likes
topArtists = "artists" // artist ids by tips
topFans = "fans" // addresses by tipped
topSupport = "support" // addresses by support
)
func ranks(rec string) []Rank {
if rec == "" {
return nil
}
f := store.Fields(rec)
out := make([]Rank, 0, len(f)/2)
for i := 0; i+1 < len(f); i += 2 {
out = append(out, Rank{f[i], text.Atoi64(f[i+1])})
}
return out
}
func (t *tx) top(name string) []Rank { return ranks(t.val(cTops, name)) }
// rank moves k to v in a leaderboard, written only when the ranking
// changed. Most changes leave it alone: when v grew (up) and is no higher
// than the tenth value, k was not ranked either, so nothing is decoded. A
// value that went down is looked for in the list (a substring match only
// means "maybe ranked").
func (t *tx) rank(name, k string, v int64, up bool) {
old := t.val(cTops, name)
if old != "" {
if last := store.Field(old, 2*topSize-1); last != "" && v <= text.Atoi64(last) && (up || !strings.Contains(old, k)) {
return
}
}
list := updateTop(ranks(old), k, v)
fs := make([]string, 0, 2*len(list))
for _, r := range list {
fs = append(fs, r.Key, text.Itoa64(r.Value))
}
if rec := store.Rec(fs...); rec != old {
t.set(cTops, name, rec)
}
}
// updateTop keeps a short leaderboard sorted by value, highest first.
func updateTop(list []Rank, k string, v int64) []Rank {
if len(list) == topSize && v <= list[topSize-1].Value {
ranked := false
for _, r := range list {
ranked = ranked || r.Key == k
}
if !ranked {
return list
}
}
out := make([]Rank, 0, topSize+1)
for _, r := range list {
if r.Key != k {
out = append(out, r)
}
}
i := len(out)
for i > 0 && out[i-1].Value < v {
i--
}
if i >= topSize {
return out
}
out = append(out, Rank{})
copy(out[i+1:], out[i:])
out[i] = Rank{k, v}
if len(out) > topSize {
out = out[:topSize]
}
return out
}
gnomod.toml
module = "gno.land/r/nym-alexiscolin000/gnoradio/catalog/v1" gno = "0.9" [addpkg] creator = "g1mpkp5lm8lwpm0pym4388836d009zfe4maxlqsq" height = 253141 max_deposit = "100000000ugnot"
json.gno
package catalog
import (
"strconv"
"strings"
"gno.land/p/nym-alexiscolin000/gnoradio/store/v0"
"gno.land/p/nym-alexiscolin000/gnoradio/text/v0"
)
// JSON exports for the GnoRadio app and indexers (vm/qeval). Their shapes
// are the app's contract (app/src/lib): change them together.
func ints(xs []int) string {
var b strings.Builder
b.WriteString("[")
for i, x := range xs {
if i > 0 {
b.WriteString(",")
}
b.WriteString(text.Itoa(x))
}
b.WriteString("]")
return b.String()
}
// The JSON is written from the records' fields as stored: numbers are
// already decimal strings, and converting them costs gas.
// trackJSON writes track id from its record and its artist's head.
func trackJSON(id int, rec, arec string) string {
f := store.Fields(rec)
out := `{"id":` + text.Itoa(id) + `,"artist":` + f[fArtist] + `,"artistName":"` + store.Field(arec, aName) +
`","claimed":` + strconv.FormatBool(store.Field(arec, aOwner) != "") + `,"origin":"` + f[fOrigin] + `","title":"` + f[fTitle] +
`","genre":` + f[fGenre] + `,"duration":` + f[fDuration] + `,"license":"` + f[fLicense] +
`","cmo":"` + f[fCMO] + `","credits":"` + f[fCredits] + `","audio":"` + f[fAudio] + `","audioSha256":"` + f[fAudioSHA] +
`","cover":"` + f[fCover] + `","coverSha256":"` + f[fCoverSHA] + `","source":"` + f[fSource] +
`","attribution":"` + f[fAttribution] + `","album":` + f[fAlbum] + `,"created":` + f[fCreated] +
`,"likes":` + f[fLikes] + `,"tips":` + f[fTips] + `,"supporters":` + f[fSupporters] + `,"splits":[`
if f[fSplits] != "" {
for i, p := range strings.Split(f[fSplits], ",") {
to, pct, _ := strings.Cut(p, ":")
if i > 0 {
out += ","
}
out += `{"to":"` + to + `","pct":` + pct + `}`
}
}
return out + `]}`
}
// playableRec returns a track's record and its artist's head when both are
// visible ("" otherwise).
func playableRec(t *tx, id int) (rec, arec string) {
rec = t.rec(cTracks, id)
if rec == "" || store.Field(rec, fHidden) != "" {
return "", ""
}
arec = t.rec(cArtists, text.Atoi(store.Field(rec, fArtist)))
if arec == "" || store.Field(arec, aHidden) != "" {
return "", ""
}
return rec, arec
}
// TrackJSON returns one playable track.
func TrackJSON(id int) string {
rec, arec := playableRec(rd(), id)
if rec == "" {
panic("catalog: unknown track")
}
return trackJSON(id, rec, arec)
}
// TracksJSON pages through playable tracks (newest first), at most 100.
// Chunks and artist heads are read once per page.
func TracksJSON(offset, limit int) string {
limit = store.Limit(limit, maxBatch)
t := rd()
total := int(t.count(mTracks))
var b strings.Builder
b.WriteString(`{"total":` + text.Itoa(total) + `,"tracks":[`)
n := 0
for _, id := range seqPage(total, offset, limit, true) {
if rec, arec := playableRec(t, id); rec != "" {
if n > 0 {
b.WriteString(",")
}
b.WriteString(trackJSON(id, rec, arec))
n++
}
}
b.WriteString(`]}`)
return b.String()
}
func ArtistJSON(id int) string {
t := rd()
arec := t.rec(cArtists, id)
if arec == "" || store.Field(arec, aHidden) != "" {
panic("catalog: unknown artist")
}
return artistJSON(t, id, arec)
}
func artistJSON(t *tx, id int, arec string) string {
f := store.Fields(arec)
trackIDs, albumIDs := lists(t, id)
promo, ok := t.get(cPromo, store.Pad(id))
if !ok {
promo = text.Itoa(defaultPromoPct)
}
a := &Artist{ID: id, Hidden: f[aHidden] != "", Owner: address(f[aOwner]), Verified: f[aVerified] != ""}
return `{"id":` + text.Itoa(id) + `,"name":` + text.Str(f[aName]) + `,"kind":` + text.Str(f[aKind]) + `,"owner":` + text.Str(f[aOwner]) +
`,"bio":` + text.Str(f[aBio]) + `,"source":` + text.Str(f[aSource]) + `,"joined":` + f[aJoined] + `,"tips":` + f[aTips] +
`,"followers":` + f[aFollowers] + `,"verified":` + strconv.FormatBool(a.Verified) +
`,"proofHost":` + text.Str(proofHost(t, id, f[aVerified])) + `,"promo":` + promo +
`,"sponsor":` + text.Itoa64(offer(t, a)) + `,"tracks":` + store.JSON(trackIDs) + `,"albums":` + store.JSON(albumIDs) + `}`
}
// albumJSON writes a visible album ("" when it or its artist is hidden).
func albumJSON(t *tx, id int) string {
rec := t.rec(cAlbums, id)
if rec == "" {
return ""
}
f := store.Fields(rec)
if f[6] != "" || !artistVisible(t, text.Atoi(f[0])) {
return ""
}
return `{"id":` + text.Itoa(id) + `,"artist":` + f[0] + `,"title":` + text.Str(f[1]) + `,"cover":` + text.Str(f[2]) +
`,"coverSha256":` + text.Str(f[3]) + `,"year":` + f[4] + `,"tracks":` + store.JSON(f[7]) + `}`
}
func AlbumJSON(id int) string {
s := albumJSON(rd(), id)
if s == "" {
panic("catalog: unknown album")
}
return s
}
// playlistJSON writes a visible playlist ("" when hidden or unknown).
func playlistJSON(t *tx, id int) string {
rec := ""
if id > 0 {
rec = t.val(cPlaylists, store.Pad(id))
}
if rec == "" || store.Field(rec, 3) != "" {
return ""
}
f := store.Fields(rec)
return `{"id":` + text.Itoa(id) + `,"owner":` + text.Str(f[0]) + `,"title":` + text.Str(f[1]) +
`,"updated":` + f[2] + `,"tracks":` + store.JSON(f[4]) + `}`
}
func PlaylistJSON(id int) string {
s := playlistJSON(rd(), id)
if s == "" {
panic("catalog: unknown playlist")
}
return s
}
// UserJSON returns a listener's public counters (likes are paged with LikesJSON).
func UserJSON(addr address) string {
likes, follows, tipped, lists := UserStats(addr)
return `{"address":` + text.Str(addr.String()) + `,"likes":` + text.Itoa(likes) + `,"follows":` + text.Itoa(follows) +
`,"tipped":` + text.Itoa64(tipped) + `,"playlists":` + ints(lists) + `,"artist":` + text.Itoa(ArtistOf(addr)) + `}`
}
func LikesJSON(addr address, offset, limit int) string { return ints(LikedPage(addr, offset, limit)) }
func GenresJSON() string {
var b strings.Builder
b.WriteString("[")
for g := 1; g <= NumGenres; g++ {
if g > 1 {
b.WriteString(",")
}
b.WriteString(`{"id":` + text.Itoa(g) + `,"name":` + text.Str(genres[g]) + `}`)
}
b.WriteString("]")
return b.String()
}
// maxBatch caps the batched readers, so one query stays far below the qeval budget.
const maxBatch = 100
// batch writes {"total":n,"<key>":[...]} for ids offset+1..offset+limit, skipping
// hidden items; one query replaces up to 100 single reads.
func batch(key string, total, offset, limit int, one func(id int) string) string {
limit = store.Limit(limit, maxBatch)
offset = max0(offset)
var b strings.Builder
b.WriteString(`{"total":` + text.Itoa(total) + `,"` + key + `":[`)
n := 0
for id := offset + 1; id <= total && id <= offset+limit; id++ {
if s := one(id); s != "" {
if n > 0 {
b.WriteString(",")
}
b.WriteString(s)
n++
}
}
b.WriteString(`]}`)
return b.String()
}
// ArtistsJSON returns visible artists with ids offset+1..offset+limit (at most 100).
func ArtistsJSON(offset, limit int) string {
t := rd()
return batch("artists", int(t.count(mArtists)), offset, limit, func(id int) string {
if arec := t.rec(cArtists, id); arec != "" && store.Field(arec, aHidden) == "" {
return artistJSON(t, id, arec)
}
return ""
})
}
// AlbumsJSON returns visible albums with ids offset+1..offset+limit (at most 100).
func AlbumsJSON(offset, limit int) string {
t := rd()
return batch("albums", int(t.count(mAlbums)), offset, limit, func(id int) string { return albumJSON(t, id) })
}
// PlaylistsJSON returns visible playlists with ids offset+1..offset+limit (at most 100).
func PlaylistsJSON(offset, limit int) string {
t := rd()
return batch("playlists", int(t.count(mPlaylists)), offset, limit, func(id int) string { return playlistJSON(t, id) })
}
moderation.gno
package catalog
import (
"strconv"
"strings"
"gno.land/p/nym-alexiscolin000/gnoradio/store/v0"
"gno.land/p/nym-alexiscolin000/gnoradio/text/v0"
)
// Report flags a track, album, artist or playlist for the moderators
// (e.g. "broken link", "not the real artist", "copyright").
func Report(cur realm, kind string, target int, reason string) {
caller := userCaller(cur)
noPayment()
reason = strings.TrimSpace(reason)
mustText("reason", reason, 4, maxReason)
t := rd()
switch kind {
case "track":
mustTrack(t, target)
case "album":
if al := getAlbum(t, target); al == nil || al.Hidden {
panic("catalog: unknown album")
}
case "artist":
mustArtist(t, target)
case "playlist":
if p := getPlaylist(t, target); p == nil || p.Hidden {
panic("catalog: unknown playlist")
}
default:
panic("catalog: kind must be track, album, artist or playlist")
}
u := user(t, caller)
if u.Reports >= maxUserReports {
panic("catalog: you have " + text.Itoa(maxUserReports) + " open reports, wait for the moderators")
}
u.Reports++
putUser(t, caller, u)
t.bump(mOpen, 1)
t.put(cReports, store.Pad(int(t.bump(mReports, 1))), store.Rec(kind, text.Itoa(target), reason, caller.String(), text.Itoa64(now())))
save(cur, t)
emitEvent("Reported", "kind", kind, "target", text.Itoa(target), "by", caller.String())
}
func getReport(t *tx, id int) (ReportInfo, bool) {
rec, ok := t.get(cReports, store.Pad(id))
if !ok || id < 1 {
return ReportInfo{}, false
}
f := store.Fields(rec)
return ReportInfo{ID: id, Kind: f[0], Target: f[1], Reason: f[2], By: address(f[3]), At: text.Atoi64(f[4])}, true
}
// ResolveReport closes a report once handled. Admin only.
func ResolveReport(cur realm, id int) {
onlyAdmin(cur)
t := rd()
if !resolve(t, id) {
panic("catalog: unknown report")
}
save(cur, t)
}
// ResolveReports closes the open reports with ids from..from+count-1 (count
// 1-50) in one transaction, e.g. a run of spam reports; ids already closed
// are skipped. There is no global cap on open reports, so spam never blocks
// an honest reporter: each wallet keeps at most 5 open. Admin only.
func ResolveReports(cur realm, from, count int) {
onlyAdmin(cur)
if count < 1 || count > 50 {
panic("catalog: resolve 1 to 50 reports at a time")
}
t := rd()
for id := from; id < from+count; id++ {
resolve(t, id)
}
save(cur, t)
}
// resolve closes one report, false when there is no such open report.
func resolve(t *tx, id int) bool {
r, ok := getReport(t, id)
if !ok {
return false
}
t.del(cReports, store.Pad(id))
if t.count(mOpen) > 0 {
t.bump(mOpen, -1)
}
if u := user(t, r.By); u.Reports > 0 {
u.Reports--
putUser(t, r.By, u)
}
emitEvent("ReportResolved", "id", text.Itoa(id))
return true
}
// Hide or restore content. Admin only; hiding takes a public reason (4-200
// characters) and restoring works on anything, whoever hid it. Hidden content
// stays on-chain (and on IPFS); it is no longer listed, played or tippable.
// Radio stations drop a hidden track on their next Refresh
// (radio.RefreshArtist for a whole artist).
func HideTrack(cur realm, trackID int, hidden bool, reason string) {
onlyAdmin(cur)
t := rd()
tr := getTrack(t, trackID)
if tr == nil {
panic("catalog: unknown track")
}
tr.Hidden = hidden
putTrack(t, tr)
moderate(cur, t, "track", trackID, hidden, reason)
}
func HideAlbum(cur realm, albumID int, hidden bool, reason string) {
onlyAdmin(cur)
t := rd()
al := getAlbum(t, albumID)
if al == nil {
panic("catalog: unknown album")
}
al.Hidden = hidden
putAlbum(t, al)
moderate(cur, t, "album", albumID, hidden, reason)
}
func HideArtist(cur realm, artistID int, hidden bool, reason string) {
onlyAdmin(cur)
t := rd()
a := getArtist(t, artistID)
if a == nil {
panic("catalog: unknown artist")
}
a.Hidden = hidden
putArtist(t, a)
moderate(cur, t, "artist", artistID, hidden, reason)
}
func HidePlaylist(cur realm, playlistID int, hidden bool, reason string) {
onlyAdmin(cur)
t := rd()
p := getPlaylist(t, playlistID)
if p == nil {
panic("catalog: unknown playlist")
}
p.Hidden = hidden
putPlaylist(t, p)
moderate(cur, t, "playlist", playlistID, hidden, reason)
}
// moderate records the moderator's public reason and saves t.
func moderate(cur realm, t *tx, kind string, id int, hidden bool, reason string) {
mark(t, kind, id, hidden, reason)
save(cur, t)
}
// mark records the moderator's public reason for one item (the caller saves).
func mark(t *tx, kind string, id int, hidden bool, reason string) {
reason = strings.TrimSpace(reason)
k := kind + ":" + text.Itoa(id)
if hidden {
mustText("reason", reason, 4, maxReason)
t.set(cRemoved, k, reason)
} else {
t.del(cRemoved, k)
}
emitEvent("Moderated", "kind", kind, "target", text.Itoa(id), "hidden", strconv.FormatBool(hidden), "reason", reason, "by", "moderator")
}
// maxHideBatch bounds HideSource: 2 writes per artist.
const maxHideBatch = 50
// HideSource hides every artist read from a platform ("audius" or
// "jamendo"), and so all their tracks, for a platform that ends GnoRadio's
// API access. It walks artist ids from `from`, count (1-50) at a time, and
// returns where to go on (0 once past the last artist). One artist opting out
// is a HideArtist. Admin only.
func HideSource(cur realm, kind string, from, count int, reason string) int {
onlyAdmin(cur)
if !isRef(kind) || from < 1 || count < 1 || count > maxHideBatch {
panic("catalog: HideSource(audius|jamendo, from >= 1, count 1-" + text.Itoa(maxHideBatch) + ", reason)")
}
mustText("reason", strings.TrimSpace(reason), 4, maxReason)
t := rd()
last := int(t.count(mArtists))
for id := from; id < from+count && id <= last; id++ {
if a := getArtist(t, id); a != nil && a.Kind == kind {
// An artist that hid itself gets the reason too, so HideOwn cannot show it again;
// one a moderator hid keeps its own reason.
if r, ok := t.get(cRemoved, "artist:"+text.Itoa(id)); a.Hidden && ok && r != "" {
continue
}
if !a.Hidden {
a.Hidden = true
putArtist(t, a)
}
mark(t, "artist", id, true, reason)
}
}
save(cur, t)
if from+count > last {
return 0
}
return from + count
}
// HideOwn hides or shows again the caller's own track, album or artist
// profile ("artist", with the profile's id). The artist can show again only
// what they hid themselves: what the moderator hid stays hidden.
func HideOwn(cur realm, kind string, id int, hidden bool) {
caller := userCaller(cur)
noPayment()
t := rd()
a := getArtist(t, artistOf(t, caller))
if a == nil {
panic("catalog: create your artist profile first")
}
k := kind + ":" + text.Itoa(id)
if reason, ok := t.get(cRemoved, k); ok && reason != "" {
panic("catalog: hidden by the moderator; contact them to restore it")
}
switch kind {
case "track":
tr := getTrack(t, id)
if tr == nil || tr.Artist != a.ID {
panic("catalog: not your track")
}
mustToggle(tr.Hidden, hidden)
tr.Hidden = hidden
putTrack(t, tr)
case "album":
al := getAlbum(t, id)
if al == nil || al.Artist != a.ID {
panic("catalog: not your album")
}
mustToggle(al.Hidden, hidden)
al.Hidden = hidden
putAlbum(t, al)
case "artist":
if id != a.ID {
panic("catalog: not your profile")
}
mustToggle(a.Hidden, hidden)
a.Hidden = hidden
putArtist(t, a)
default:
panic("catalog: kind must be track, album or artist")
}
if hidden {
t.set(cRemoved, k, "")
} else {
t.del(cRemoved, k)
}
save(cur, t)
emitEvent("Moderated", "kind", kind, "target", text.Itoa(id), "hidden", strconv.FormatBool(hidden), "reason", "", "by", "artist")
}
func mustToggle(was, hidden bool) {
if was == hidden {
if hidden {
panic("catalog: already hidden")
}
panic("catalog: already shown")
}
}
// HiddenNote says why a track, album, artist or playlist is hidden, for its
// page: "Removed by moderation: <reason>", "Hidden by the artist.", or "".
func HiddenNote(kind string, id int) string {
reason, ok := rd().get(cRemoved, kind+":"+text.Itoa(id))
switch {
case !ok:
return ""
case reason == "":
return "Hidden by the artist."
}
return "Removed by moderation: " + reason
}
// Verify marks an artist whose identity was checked off-chain.
func Verify(cur realm, artistID int, verified bool) {
onlyAdmin(cur)
t := rd()
a := mustArtist(t, artistID)
a.Verified = verified
putArtist(t, a)
t.del(cClaims, store.Pad(artistID)) // settled by the admin either way
if !verified {
t.del(cProofs, store.Pad(artistID))
}
save(cur, t)
emitEvent("Verified", "artist", text.Itoa(artistID), "verified", strconv.FormatBool(verified))
}
// AllowHost adds or removes an https host that audio and covers may use.
func AllowHost(cur realm, host string, allowed bool) {
onlyAdmin(cur)
host = strings.ToLower(strings.TrimSpace(host))
if !validHost(host) {
panic("catalog: invalid host")
}
t := rd()
if allowed {
t.set(cHosts, host, "1")
} else {
t.del(cHosts, host)
}
save(cur, t)
emitEvent("HostAllowed", "host", host, "allowed", strconv.FormatBool(allowed))
}
promo.gno
package catalog
import (
"gno.land/p/nym-alexiscolin000/gnoradio/store/v0"
"gno.land/p/nym-alexiscolin000/gnoradio/text/v0"
"gno.land/r/nym-alexiscolin000/gnoradio/data"
)
// Promo share: an artist lets a part of each tip go to the listeners who
// brought the tipper, the one who picked the track on the radio and the one
// whose link they followed. It is opt-in: 0% until the artist sets it
// (0..20%), and the tipper sees it before signing. A tipper never pays it to
// themselves: not as the picker, not as the referrer, and not to a
// referrer they name for a track they picked (social.gno, tip). The radio realm alone knows who picked what
// is on air, so the shared tips arrive through RadioTip, which only the
// current radio writer of the data realm may call; it never takes a picker
// from the client.
const (
defaultPromoPct = 0
maxPromoPct = 20
)
// SetPromoShare sets the percent of each tip on the caller's tracks that goes
// to the picker and the referrer (0..20).
func SetPromoShare(cur realm, pct int) {
caller := userCaller(cur)
noPayment()
if pct < 0 || pct > maxPromoPct {
panic("catalog: the promo share is between 0 and 20%")
}
t := rd()
id, _ := ownArtist(t, caller)
t.set(cPromo, store.Pad(id), text.Itoa(pct))
save(cur, t)
emitEvent("PromoShare", "artist", text.Itoa(id), "pct", text.Itoa(pct))
}
// PromoShare returns an artist's promo percent.
func PromoShare(artistID int) int { return promoShare(rd(), artistID) }
func promoShare(t *tx, artistID int) int {
if v, ok := t.get(cPromo, store.Pad(artistID)); ok {
return text.Atoi(v)
}
return defaultPromoPct
}
// RadioTip pays a tip the radio realm received for the listener tipper
// (radio.TipOnAir): the radio has already forwarded total ugnot to this realm
// and names the picker of the slot on air. Only the radio writer may call it.
// It returns what the picker and the referrer received.
func RadioTip(cur realm, trackID, supportPct int, tipper, picker, ref address, total int64) (toPicker, toRef int64) {
onlyRadio(cur)
return tip(cur, tipper, total, trackID, supportPct, picker, ref)
}
// onlyRadio admits the radio realm the data realm names as radio writer
// now, unless the radio role is paused: a paused radio moves no coins
// through the catalog either.
func onlyRadio(cur realm) {
if cur.Previous().PkgPath() != data.Writer("radio") {
panic("catalog: only the GnoRadio radio realm can call this")
}
if data.Paused("radio") {
panic("catalog: the radio is paused")
}
}
// promoShares splits an artist-side amount's promo share between the picker
// and the referrer still eligible ("" when not): half each, the odd ugnot to
// the picker, all of it to one alone.
func promoShares(amt int64, pct int, picker, ref address) (toPicker, toRef int64) {
share := amt * int64(pct) / 100
switch {
case picker != "" && ref != "":
toRef = share / 2
return share - toRef, toRef
case picker != "":
return share, 0
case ref != "":
return 0, share
}
return 0, 0
}
read.gno
package catalog
import (
"strings"
"gno.land/p/nym-alexiscolin000/gnoradio/store/v0"
"gno.land/p/nym-alexiscolin000/gnoradio/text/v0"
"gno.land/r/nym-alexiscolin000/gnoradio/data"
)
// ---- Read API for the other GnoRadio realms (values only) ----
func GenreName(g int) string {
if g < 1 || g > NumGenres {
return ""
}
return genres[g]
}
func TrackCount() int { return int(rd().count(mTracks)) }
func ArtistCount() int { return int(rd().count(mArtists)) }
func AlbumCount() int { return int(rd().count(mAlbums)) }
func PlaylistCount() int { return int(rd().count(mPlaylists)) }
// TrackBrief is what the radio needs; playable is false for an unknown or
// hidden track, or one whose artist is hidden.
func TrackBrief(id int) (artistID, genre int, duration int64, playable_ bool) {
rec := point(cTracks, id)
if rec == "" {
return 0, 0, 0, false
}
a := text.Atoi(store.Field(rec, fArtist))
arec := point(cArtists, a)
return a, text.Atoi(store.Field(rec, fGenre)), text.Atoi64(store.Field(rec, fDuration)),
store.Field(rec, fHidden) == "" && arec != "" && store.Field(arec, aHidden) == ""
}
// TrackBriefFor is TrackBrief and whether addr ("" for nobody) is the
// track's artist or one of its collaborators, from the same reads.
func TrackBriefFor(id int, addr address) (artistID, genre int, duration int64, playable_, own bool) {
rec := point(cTracks, id)
if rec == "" {
return 0, 0, 0, false, false
}
a := text.Atoi(store.Field(rec, fArtist))
arec := point(cArtists, a)
playable_ = store.Field(rec, fHidden) == "" && arec != "" && store.Field(arec, aHidden) == ""
if addr != "" && arec != "" {
// splits are "addr:pct,…" and an address holds no ',' or ':'
sp := store.Field(rec, fSplits)
own = store.Field(arec, aOwner) == addr.String() || sp != "" && strings.Contains(","+sp, ","+addr.String()+":")
}
return a, text.Atoi(store.Field(rec, fGenre)), text.Atoi64(store.Field(rec, fDuration)), playable_, own
}
// PlayableTitle is a track's title, "" unless it is playable (TrackBrief).
func PlayableTitle(id int) string {
rec := point(cTracks, id)
if rec == "" || store.Field(rec, fHidden) != "" {
return ""
}
if arec := point(cArtists, text.Atoi(store.Field(rec, fArtist))); arec == "" || store.Field(arec, aHidden) != "" {
return ""
}
return store.Field(rec, fTitle)
}
func TrackTitle(id int) string {
if rec := point(cTracks, id); rec != "" {
return refLabel(store.Field(rec, fOrigin), store.Field(rec, fTitle), "track")
}
return ""
}
func ArtistName(artistID int) string {
if rec := point(cArtists, artistID); rec != "" {
return refLabel(store.Field(rec, aKind), store.Field(rec, aName), "artist")
}
return ""
}
func ArtistOwner(artistID int) address { return address(artistAt(artistID, aOwner)) }
func ArtistOf(owner address) int { return artistOf(rd(), owner) }
// ArtistPayee is what a payment to an artist checks, from one read: who
// is paid, whether verified, and whether the profile is visible.
func ArtistPayee(id int) (owner address, verified, visible bool) {
rec := point(cArtists, id)
if rec == "" {
return "", false, false
}
return address(store.Field(rec, aOwner)), store.Field(rec, aVerified) == "1", store.Field(rec, aHidden) == ""
}
func ArtistVisible(artistID int) bool {
rec := point(cArtists, artistID)
return rec != "" && store.Field(rec, aHidden) == ""
}
// ---- Value getters for the home realm and tools ----
// GetTrack returns a copy of a track; ok is false if unknown. A pointer's
// empty title reads as its platform ("Audius track").
func GetTrack(id int) (Track, bool) {
if tr := getTrack(rd(), id); tr != nil {
tr.Title = refLabel(tr.Origin, tr.Title, "track")
return *tr, true
}
return Track{}, false
}
func GetArtist(id int) (Artist, bool) {
t := rd()
if a := getArtist(t, id); a != nil {
a.Name = refLabel(a.Kind, a.Name, "artist")
return *withLists(t, a), true
}
return Artist{}, false
}
// ArtistByRef looks a pointer artist up by its platform id ("audius-user:12").
func ArtistByRef(ref string) int {
v, _ := data.Get(cNames, strings.TrimSpace(ref))
return text.Atoi(v)
}
// ArtistByName looks a profile up by its (case-insensitive) name.
func ArtistByName(name string) int {
v, _ := data.Get(cNames, skeleton(strings.TrimSpace(name)))
return text.Atoi(v)
}
func GetAlbum(id int) (Album, bool) {
if a := getAlbum(rd(), id); a != nil {
return *a, true
}
return Album{}, false
}
func GetPlaylist(id int) (Playlist, bool) {
if p := getPlaylist(rd(), id); p != nil {
return *p, true
}
return Playlist{}, false
}
// ReportCount is the number of open (unresolved) reports.
func ReportCount() int { return int(rd().count(mOpen)) }
func GetReport(id int) (ReportInfo, bool) { return getReport(rd(), id) }
// UserStats returns a listener's public counters and playlists. The like
// count reads the listener's own like ranges, one page.
func UserStats(addr address) (likes, follows int, tipped int64, lists []int) {
_, likes = rangePage(cLikes, addr.String(), 0, 0)
u := user(rd(), addr)
return likes, store.Count(u.Follows), u.Tipped, u.Playlists
}
// LikedPage lists a listener's liked track ids, newest tracks first,
// paginated. Likes are keyed by track id, so this is the newest music the
// listener liked, not the order of their likes (that needs an index per like,
// which would add to every like's storage deposit).
func LikedPage(addr address, offset, limit int) []int {
ids, _ := rangePage(cLikes, addr.String(), max0(offset), store.Limit(limit, 100))
return ids
}
// ---- Narrow getters: one field without copying a whole struct ----
// ArtistTrackCount is the number of tracks an artist published.
func ArtistTrackCount(artistID int) int {
tl, _ := lists(rd(), artistID)
return store.Count(tl)
}
// ArtistTrackPage lists an artist's track ids in publishing order, paginated.
func ArtistTrackPage(artistID, offset, limit int) []int {
if offset < 0 {
return nil
}
tl, _ := lists(rd(), artistID)
return store.Page(tl, offset, store.Limit(limit, 100), false)
}
// ArtistBrief returns what a link to an artist needs, without the bio or the
// id lists; ok is false for an unknown artist.
func ArtistBrief(artistID int) (name string, verified, hidden, ok bool) {
rec := point(cArtists, artistID)
if rec == "" {
return "", false, false, false
}
return refLabel(store.Field(rec, aKind), store.Field(rec, aName), "artist"), store.Field(rec, aVerified) != "", store.Field(rec, aHidden) != "", true
}
// PlaylistBrief returns a playlist's header without its track ids.
func PlaylistBrief(id int) (owner address, title string, tracks int, hidden, ok bool) {
rec := rd().val(cPlaylists, store.Pad(id)) // counts the ids without decoding them
if id < 1 || rec == "" {
return "", "", 0, false, false
}
f := store.Fields(rec)
return address(f[0]), f[1], store.Count(f[4]), f[3] != "", true
}
// FollowsPage lists the artist ids a listener follows, paginated.
func FollowsPage(addr address, offset, limit int) []int {
return store.Page(user(rd(), addr).Follows, max0(offset), store.Limit(limit, 100), false)
}
// GenrePage lists the track ids of a genre (hidden ones included), newest first.
func GenrePage(genre, offset, limit int) []int {
if genre < 1 || genre > NumGenres {
return nil
}
ids, _ := rangePage(cGenres, store.Pad(genre), max0(offset), store.Limit(limit, 100))
return ids
}
// GenreCount is the number of tracks filed under a genre.
func GenreCount(genre int) int {
if genre < 1 || genre > NumGenres {
return 0
}
return int(rd().count(mGenre + genre))
}
// TrackPage lists track ids, newest first when newest is true.
// Ids are dense (1..count), so these pages are arithmetic.
func TrackPage(offset, limit int, newest bool) []int {
return seqPage(TrackCount(), offset, limit, newest)
}
func ArtistPage(offset, limit int) []int { return seqPage(ArtistCount(), offset, limit, false) }
func AlbumPage(offset, limit int) []int { return seqPage(AlbumCount(), offset, limit, true) }
func PlaylistPage(offset, limit int) []int { return seqPage(PlaylistCount(), offset, limit, true) }
// ReportPage lists open report ids, newest first.
func ReportPage(offset, limit int) []int {
keys, _ := store.Rows(data.PageAt(cReports, max0(offset), store.Limit(limit, 100), true))
out := make([]int, 0, len(keys))
for _, k := range keys {
out = append(out, text.Atoi(k))
}
return out
}
func seqPage(n, offset, limit int, newest bool) []int {
var out []int
for k := max0(offset); k < n && len(out) < store.Limit(limit, 100); k++ {
if newest {
out = append(out, n-k)
} else {
out = append(out, k+1)
}
}
return out
}
func max0(n int) int {
if n < 0 {
return 0
}
return n
}
func TopLiked() []Rank { return rd().top(topLiked) }
func TopArtists() []Rank { return rd().top(topArtists) }
func TopFans() []Rank { return rd().top(topFans) }
func Admin() address { return adminAddr() }
func PendingAdmin() address { return admin.Pending() } // the address the admin role is offered to, "" if none
func Version() string { return version }
func RightsTerms() string { return rightsTerms }
func HostAllowed(h string) bool { return data.Has(cHosts, strings.ToLower(h)) }
records.gno
package catalog
import (
"strings"
"gno.land/p/nym-alexiscolin000/gnoradio/store/v0"
"gno.land/p/nym-alexiscolin000/gnoradio/text/v0"
)
// Records are store.Rec values: fields behind a length header, so reading a
// field never scans the record. Hot fields come first. Id lists use store's
// JSON-ready width and go straight into the JSON exports. The fields are
// catalog v0's, ordered so the frequent writes touch the first ones.
type Split struct {
To address
Pct int64 // percent of each tip
}
type Artist struct {
ID int
Owner address // "" while unclaimed (curated / Audius / Jamendo)
Kind string // artist | curated | audius | jamendo
Name string
Bio string
Source string // curated: source page; audius / jamendo: platform id (audius-user:<id>, jamendo-artist:<id>)
Joined int64
Tips int64
Followers int
Tracks []int
Albums []int
Verified bool
Hidden bool
}
type Track struct {
ID int
Artist int
Origin string
Title string
Genre int
Duration int64 // seconds
License string
CMO string // none | sacem-nc
Credits string
Audio string // ipfs://… ar://… audius:… jamendo:… https://…
AudioSHA string // sha256 hex, required for https
Cover string
CoverSHA string
SourceURL string
Attribution string
Splits []Split
Album int
Created int64
Likes int
Tips int64
Supporters int
Hidden bool
Early []address // first listeners to like it
}
type Album struct {
ID int
Artist int
Title string
Cover string
CoverSHA string
Year int
Tracks []int
Created int64
Hidden bool
}
type Playlist struct {
ID int
Owner address
Title string
Tracks []int
Updated int64
Hidden bool
}
// User is what a listener writes, so a follow only touches that listener's
// own record. Follows are a sorted packed list (9 bytes each); likes and the
// tipped tracks live apart, per range of 512 track ids.
type User struct {
Follows string // sorted packed artist ids
Tipped int64
Playlists []int
Reports int // open reports filed by this user
}
type ReportInfo struct {
ID int
Kind string // track | album | artist | playlist
Target string
Reason string
By address
At int64
}
// ---- tracks: what the radio reads first, then what likes and tips change ----
// Track record fields. Reading or replacing field i walks the i fields
// before it, so the fields the frequent actions read and change come first.
const (
fArtist = iota
fGenre
fDuration
fHidden
fLikes
fEarly // first listeners to like it, comma-joined
fTips
fSupporters
fAlbum
fCreated
fOrigin
fTitle
fLicense
fCMO
fCredits
fAudio
fAudioSHA
fCover
fCoverSHA
fSource
fAttribution
fSplits // "addr:pct,…"
)
func getTrack(t *tx, id int) *Track {
rec := t.rec(cTracks, id)
if rec == "" {
return nil
}
f := store.Fields(rec)
tr := &Track{
ID: id, Artist: text.Atoi(f[fArtist]), Genre: text.Atoi(f[fGenre]), Duration: text.Atoi64(f[fDuration]), Hidden: f[fHidden] != "",
Likes: text.Atoi(f[fLikes]), Tips: text.Atoi64(f[fTips]), Supporters: text.Atoi(f[fSupporters]), Album: text.Atoi(f[fAlbum]),
Created: text.Atoi64(f[fCreated]), Origin: f[fOrigin], Title: f[fTitle], License: f[fLicense], CMO: f[fCMO],
Credits: f[fCredits], Audio: f[fAudio], AudioSHA: f[fAudioSHA], Cover: f[fCover], CoverSHA: f[fCoverSHA],
SourceURL: f[fSource], Attribution: f[fAttribution],
}
if f[fSplits] != "" {
for _, p := range strings.Split(f[fSplits], ",") {
to, pct, _ := strings.Cut(p, ":")
tr.Splits = append(tr.Splits, Split{To: address(to), Pct: text.Atoi64(pct)})
}
}
if f[fEarly] != "" {
for _, a := range strings.Split(f[fEarly], ",") {
tr.Early = append(tr.Early, address(a))
}
}
return tr
}
func trackRecord(tr *Track) string {
var splits, early []string
for _, s := range tr.Splits {
splits = append(splits, s.To.String()+":"+text.Itoa64(s.Pct))
}
for _, a := range tr.Early {
early = append(early, a.String())
}
return store.Rec(text.Itoa(tr.Artist), text.Itoa(tr.Genre), text.Itoa64(tr.Duration), text.Flag(tr.Hidden), text.Itoa(tr.Likes),
strings.Join(early, ","), text.Itoa64(tr.Tips), text.Itoa(tr.Supporters), text.Itoa(tr.Album), text.Itoa64(tr.Created), tr.Origin,
tr.Title, tr.License, tr.CMO, tr.Credits, tr.Audio, tr.AudioSHA, tr.Cover, tr.CoverSHA, tr.SourceURL,
tr.Attribution, strings.Join(splits, ","))
}
func putTrack(t *tx, tr *Track) { t.setRec(cTracks, tr.ID, trackRecord(tr)) }
// brief reads only what playback needs, without decoding the whole track.
func brief(t *tx, id int) (artist, genre int, dur int64, hidden, ok bool) {
rec := t.rec(cTracks, id)
if rec == "" {
return 0, 0, 0, false, false
}
return text.Atoi(store.Field(rec, fArtist)), text.Atoi(store.Field(rec, fGenre)), text.Atoi64(store.Field(rec, fDuration)), store.Field(rec, fHidden) != "", true
}
// ---- artists: a small head record, the id lists apart ----
// Artist head fields, in the same spirit: what tips and follows read and
// change first. The permanent tickets/nft realm reads aHidden and aName (and
// chunkSize) straight from the data realm: no release may move them.
const (
aHidden = iota
aOwner
aVerified
aTips
aFollowers
aKind
aName
aBio
aSource
aJoined
)
// getArtist returns an artist's head; Tracks and Albums stay empty (see withLists).
func getArtist(t *tx, id int) *Artist {
rec := t.rec(cArtists, id)
if rec == "" {
return nil
}
f := store.Fields(rec)
return &Artist{
ID: id, Hidden: f[aHidden] != "", Owner: address(f[aOwner]), Verified: f[aVerified] != "", Tips: text.Atoi64(f[aTips]),
Followers: text.Atoi(f[aFollowers]), Kind: f[aKind], Name: f[aName], Bio: f[aBio], Source: f[aSource], Joined: text.Atoi64(f[aJoined]),
}
}
func artistRecord(a *Artist) string {
return store.Rec(text.Flag(a.Hidden), a.Owner.String(), text.Flag(a.Verified), text.Itoa64(a.Tips), text.Itoa(a.Followers), a.Kind,
a.Name, a.Bio, a.Source, text.Itoa64(a.Joined))
}
func putArtist(t *tx, a *Artist) { t.setRec(cArtists, a.ID, artistRecord(a)) }
// artistField reads one field of the head ("" for an unknown artist).
func artistField(t *tx, id, i int) string {
if rec := t.rec(cArtists, id); rec != "" {
return store.Field(rec, i)
}
return ""
}
func artistVisible(t *tx, id int) bool {
rec := t.rec(cArtists, id)
return rec != "" && store.Field(rec, aHidden) == ""
}
// lists returns an artist's track and album id lists (made at its first publish).
func lists(t *tx, artistID int) (trackIDs, albumIDs string) {
rec := t.val(cAlists, store.Pad(artistID))
if rec == "" {
return "", ""
}
f := store.Fields(rec)
return f[0], f[1]
}
func setLists(t *tx, artistID int, trackIDs, albumIDs string) {
t.set(cAlists, store.Pad(artistID), store.Rec(trackIDs, albumIDs))
}
// withLists fills an artist head's Tracks and Albums.
func withLists(t *tx, a *Artist) *Artist {
tl, al := lists(t, a.ID)
a.Tracks, a.Albums = store.Ints(tl), store.Ints(al)
return a
}
func artistOf(t *tx, owner address) int { return text.Atoi(t.val(cOwners, owner.String())) }
// ---- albums and playlists ----
func getAlbum(t *tx, id int) *Album {
rec := t.rec(cAlbums, id)
if rec == "" {
return nil
}
f := store.Fields(rec)
return &Album{ID: id, Artist: text.Atoi(f[0]), Title: f[1], Cover: f[2], CoverSHA: f[3], Year: text.Atoi(f[4]),
Created: text.Atoi64(f[5]), Hidden: f[6] != "", Tracks: store.Ints(f[7])}
}
func albumRecord(al *Album) string {
return store.Rec(text.Itoa(al.Artist), al.Title, al.Cover, al.CoverSHA, text.Itoa(al.Year), text.Itoa64(al.Created),
text.Flag(al.Hidden), store.Pack(al.Tracks))
}
func putAlbum(t *tx, al *Album) { t.setRec(cAlbums, al.ID, albumRecord(al)) }
func getPlaylist(t *tx, id int) *Playlist {
if id < 1 {
return nil
}
rec := t.val(cPlaylists, store.Pad(id))
if rec == "" {
return nil
}
f := store.Fields(rec)
return &Playlist{ID: id, Owner: address(f[0]), Title: f[1], Updated: text.Atoi64(f[2]), Hidden: f[3] != "",
Tracks: store.Ints(f[4])}
}
func putPlaylist(t *tx, p *Playlist) {
t.set(cPlaylists, store.Pad(p.ID), store.Rec(p.Owner.String(), p.Title, text.Itoa64(p.Updated), text.Flag(p.Hidden), store.Pack(p.Tracks)))
}
// ---- listeners ----
// user returns a listener's record (an empty one if none); save it with putUser.
func user(t *tx, addr address) *User {
rec := t.val(cUsers, addr.String())
if rec == "" {
return &User{}
}
f := store.Fields(rec)
return &User{Follows: f[0], Tipped: text.Atoi64(f[1]), Playlists: store.Ints(f[2]), Reports: text.Atoi(f[3])}
}
func putUser(t *tx, addr address, u *User) {
t.set(cUsers, addr.String(), store.Rec(u.Follows, text.Itoa64(u.Tipped), store.Pack(u.Playlists), text.Itoa(u.Reports)))
}
// ---- lookups shared by every file ----
func visibleArtist(a *Artist) bool { return a != nil && !a.Hidden }
func playable(t *tx, tr *Track) bool {
return tr != nil && !tr.Hidden && artistVisible(t, tr.Artist)
}
func mustArtist(t *tx, id int) *Artist {
a := getArtist(t, id)
if !visibleArtist(a) {
panic("catalog: unknown artist")
}
return a
}
func mustTrack(t *tx, id int) *Track {
tr := getTrack(t, id)
if !playable(t, tr) {
panic("catalog: unknown track")
}
return tr
}
// ownArtist returns the caller's visible artist profile: its id and head.
func ownArtist(t *tx, caller address) (int, string) {
id := artistOf(t, caller)
arec := t.rec(cArtists, id)
if arec == "" || store.Field(arec, aHidden) != "" {
panic("catalog: create your artist profile first")
}
return id, arec
}
// mayEdit reports whether caller manages artist a: its owner, or the admin
// while the artist is unclaimed.
func mayEdit(caller address, a *Artist) bool {
if a.Owner != "" {
return caller == a.Owner
}
return caller != "" && caller == adminAddr()
}
social.gno
package catalog
import (
"chain"
"chain/banker"
"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/data"
)
// Like records a public like. The first listeners to like a track earn its
// early-listener badge. (Saving a track privately is done in the app, free.)
func Like(cur realm, trackID int) {
caller := userCaller(cur)
noPayment()
// Likes and the early badges are updated in place: the most frequent write
// never decodes the whole track.
t := rd()
rec, arec := playableRec(t, trackID)
if rec == "" {
panic("catalog: unknown track")
}
if address(store.Field(arec, aOwner)) == caller {
panic("catalog: you cannot like your own track")
}
if !t.addID(cLikes, caller.String(), trackID) {
panic("catalog: already liked")
}
n := text.Atoi(store.Field(rec, fLikes)) + 1
rec = store.With(rec, fLikes, text.Itoa(n))
if early := store.Field(rec, fEarly); !hasEarly(early, caller) && (len(early)+1)/(len(caller)+1) < earlyBadges {
if early != "" {
early += ","
}
rec = store.With(rec, fEarly, early+caller.String())
}
t.setRec(cTracks, trackID, rec)
id := text.Itoa(trackID)
t.rank(topLiked, id, int64(n), true)
t.activityOnce("like", caller, id, store.Field(rec, fArtist))
save(cur, t)
emitEvent("Liked", "track", id, "by", caller.String())
}
// hasEarly reports whether a comma-joined address list holds a (addresses
// share one length, so this compares slices instead of scanning bytes).
func hasEarly(list string, a address) bool {
w := len(a) + 1
for p := 0; p+len(a) <= len(list); p += w {
if list[p:p+len(a)] == a.String() {
return true
}
}
return false
}
// dropEarly takes a out of a comma-joined address list.
func dropEarly(list string, a address) string {
var kept []string
for _, x := range strings.Split(list, ",") {
if x != a.String() {
kept = append(kept, x)
}
}
return strings.Join(kept, ",")
}
// Unlike takes a like back, and its early-listener badge with it.
func Unlike(cur realm, trackID int) {
caller := userCaller(cur)
noPayment()
t := rd()
if !t.removeID(cLikes, caller.String(), trackID) {
panic("catalog: not liked")
}
if rec := t.rec(cTracks, trackID); rec != "" {
if n := text.Atoi(store.Field(rec, fLikes)); n > 0 {
rec = store.With(rec, fLikes, text.Itoa(n-1))
t.rank(topLiked, text.Itoa(trackID), int64(n-1), false)
}
// The early-listener badge goes with the like: like and unlike
// cycles keep no badge, and free the slot for a real listener.
if early := store.Field(rec, fEarly); hasEarly(early, caller) {
rec = store.With(rec, fEarly, dropEarly(early, caller))
}
t.setRec(cTracks, trackID, rec)
}
save(cur, t)
emitEvent("Unliked", "track", text.Itoa(trackID), "by", caller.String())
}
// Tip forwards the attached ugnot to the track's artist and collaborators,
// split as declared at publish time, in this same transaction. Only verified
// artists receive tips (verify.gno). Verification proves control of a web
// host or an Audius account, not who the artist is: the proof host is public
// next to every ✓ (ProofHost), and the 72 h claim window (PendingClaims) is
// there to catch an impersonator before tips open.
func Tip(cur realm, trackID int) {
tip(cur, userCaller(cur), paid(), trackID, 0, "", "")
}
// TipWithSupport is Tip plus an optional contribution to GnoRadio: of the
// attached total T, the artist side receives T*100/(100+supportPct) (split as
// in Tip) and the rest goes to the GnoRadio treasury. supportPct is 0..50.
func TipWithSupport(cur realm, trackID int, supportPct int) {
tip(cur, userCaller(cur), paid(), trackID, supportPct, "", "")
}
// tip pays total from this realm's balance for caller. The artist's promo
// share (promo.gno) of the artist side goes to picker and ref, when given and
// neither the tipper nor the artist, and only when the tipper did not pick
// the track themselves; collaborators split what is left.
func tip(cur realm, caller address, total int64, trackID, supportPct int, picker, ref address) (toPicker, toRef int64) {
if supportPct < 0 || supportPct > maxSupportPct {
panic("catalog: supportPct must be between 0 and 50")
}
// The track and artist records are changed in place, as Like does.
t := rd()
if supportPct > 0 && treasury(t) == "" {
panic("catalog: no treasury is set, a tip carries no support share")
}
rec, arec := playableRec(t, trackID)
if rec == "" {
panic("catalog: unknown track")
}
owner := address(store.Field(arec, aOwner))
if owner == "" || store.Field(arec, aVerified) == "" {
panic("catalog: this artist has not verified their profile yet")
}
if owner == caller {
panic("catalog: you cannot tip your own track")
}
if total > maxTip+maxTip/2 {
panic("catalog: a tip is between 0.1 and 1000000 GNOT")
}
amt := total * 100 / int64(100+supportPct)
platform := total - amt
if amt < minTip || amt > maxTip {
panic("catalog: a tip is between 0.1 and 1000000 GNOT")
}
// A tipper who picked the track themselves brings no listener: no promo
// share goes out, neither to the pick nor to a link they name.
selfPicked := picker == caller
if selfPicked || picker == owner || !role.Canonical(picker) || data.IsGnoRadio(picker) {
picker = ""
}
self := cur.Address()
bk := banker.NewBanker(banker.BankerTypeRealmSend, cur)
// This realm holds nothing between transactions: the tip is all it has.
if bk.GetCoins(self).AmountOf(denom) < total {
panic("catalog: the tip did not arrive")
}
if selfPicked || ref == caller || ref == owner || ref == picker || !role.Canonical(ref) || data.IsGnoRadio(ref) {
ref = ""
}
artistID := text.Atoi(store.Field(rec, fArtist))
toPicker, toRef = promoShares(amt, promoShare(t, artistID), picker, ref)
artistSide := amt - toPicker - toRef
rest := artistSide
var paidTo strings.Builder
if splits := store.Field(rec, fSplits); splits != "" {
for _, p := range strings.Split(splits, ",") {
to, pct, _ := strings.Cut(p, ":")
share := artistSide * text.Atoi64(pct) / 100
if share > 0 && !data.IsGnoRadio(address(to)) { // a realm of a later release: the owner keeps it
bk.SendCoins(self, address(to), chain.Coins{{Denom: denom, Amount: share}})
rest -= share
paidTo.WriteString(to + ":" + text.Itoa64(share) + ",")
}
}
}
bk.SendCoins(self, owner, chain.Coins{{Denom: denom, Amount: rest}})
paidTo.WriteString(owner.String() + ":" + text.Itoa64(rest))
if toPicker > 0 {
bk.SendCoins(self, picker, chain.Coins{{Denom: denom, Amount: toPicker}})
}
if toRef > 0 {
bk.SendCoins(self, ref, chain.Coins{{Denom: denom, Amount: toRef}})
}
if platform > 0 {
bk.SendCoins(self, treasury(t), chain.Coins{{Denom: denom, Amount: platform}})
recordSupport(t, caller, platform)
}
rec = store.With(rec, fTips, text.Itoa64(text.Atoi64(store.Field(rec, fTips))+artistSide))
if t.addID(cTipped, caller.String(), trackID) {
rec = store.With(rec, fSupporters, text.Itoa(text.Atoi(store.Field(rec, fSupporters))+1))
}
t.setRec(cTracks, trackID, rec)
artistTips := text.Atoi64(store.Field(arec, aTips)) + artistSide
t.setRec(cArtists, artistID, store.With(arec, aTips, text.Itoa64(artistTips)))
// The tipper's rank and feed line count what reached the artist side: a
// promo share may go back to a second wallet of the tipper's.
u := user(t, caller)
u.Tipped += artistSide
putUser(t, caller, u)
aid, id := store.Field(rec, fArtist), text.Itoa(trackID)
t.rank(topArtists, aid, artistTips, true)
t.rank(topFans, caller.String(), u.Tipped, true)
t.activity("tip", caller, id, aid, text.Itoa64(artistSide))
save(cur, t)
emitEvent("Tipped", "track", id, "by", caller.String(), "amount", text.Itoa64(amt), "paid", paidTo.String(), "support", text.Itoa64(platform),
"picker", picker.String(), "toPicker", text.Itoa64(toPicker), "ref", ref.String(), "toRef", text.Itoa64(toRef))
return toPicker, toRef
}
// ---- Albums ----
// CreateAlbum groups tracks of one artist. The artist (or the admin for an
// unclaimed artist) creates it; trackIDs is "12,13,14" in play order.
func CreateAlbum(cur realm, artistID int, title, cover, coverSHA string, year int, trackIDs string) int {
caller := userCaller(cur)
noPayment()
t := rd()
a := mustArtist(t, artistID)
if !mayEdit(caller, a) {
panic("catalog: only the artist can create its albums")
}
title, cover, coverSHA = strings.TrimSpace(title), strings.TrimSpace(cover), strings.ToLower(strings.TrimSpace(coverSHA))
mustText("title", title, 1, maxTitle)
if cover != "" {
mustMedia("cover", cover, coverSHA, false)
}
if year < 1900 || year > 2100 {
panic("catalog: year must be between 1900 and 2100")
}
ids := parseIDs(trackIDs, maxAlbumTracks)
artistTracks, albumIDs := lists(t, a.ID)
if store.Count(albumIDs) >= maxPerArtist {
panic("catalog: albums per artist limit reached")
}
albumID := int(t.bump(mAlbums, 1))
for _, id := range ids {
tr := mustTrack(t, id)
if tr.Artist != a.ID || tr.Album != 0 {
panic("catalog: track " + text.Itoa(id) + " is not this artist's or already in an album")
}
tr.Album = albumID
putTrack(t, tr)
}
al := &Album{ID: albumID, Artist: a.ID, Title: title, Cover: cover, CoverSHA: coverSHA, Year: year, Tracks: ids, Created: now()}
t.addRec(cAlbums, al.ID, fits(albumRecord(al)))
setLists(t, a.ID, artistTracks, albumIDs+store.Enc(al.ID))
t.activity("album", caller, text.Itoa(al.ID), text.Itoa(a.ID), "0")
save(cur, t)
emitEvent("AlbumCreated", "id", text.Itoa(al.ID), "artist", text.Itoa(a.ID), "title", title)
return al.ID
}
// ---- Playlists ----
// PublishPlaylist makes a public playlist in one signature; trackIDs is
// "12,40,7". Private playlists live in the app and cost nothing.
func PublishPlaylist(cur realm, title, trackIDs string) int {
caller := userCaller(cur)
noPayment()
title = strings.TrimSpace(title)
mustText("title", title, 1, maxTitle)
t := rd()
ids := checkedIDs(t, trackIDs)
u := user(t, caller)
if len(u.Playlists) >= maxUserLists {
panic("catalog: playlists per listener limit reached")
}
p := &Playlist{ID: int(t.bump(mPlaylists, 1)), Owner: caller, Title: title, Tracks: ids, Updated: now()}
u.Playlists = append(u.Playlists, p.ID)
putUser(t, caller, u)
putPlaylist(t, p)
t.activity("playlist", caller, text.Itoa(p.ID), "0", "0")
save(cur, t)
emitEvent("PlaylistPublished", "id", text.Itoa(p.ID), "owner", caller.String(), "tracks", text.Itoa(len(ids)))
return p.ID
}
// UpdatePlaylist replaces a playlist's title and tracks. Owner only.
func UpdatePlaylist(cur realm, playlistID int, title, trackIDs string) {
caller := userCaller(cur)
noPayment()
t := rd()
p := getPlaylist(t, playlistID)
if p == nil || p.Hidden || p.Owner != caller {
panic("catalog: not your playlist")
}
title = strings.TrimSpace(title)
mustText("title", title, 1, maxTitle)
p.Title, p.Tracks, p.Updated = title, checkedIDs(t, trackIDs), now()
putPlaylist(t, p)
save(cur, t)
emitEvent("PlaylistUpdated", "id", text.Itoa(p.ID), "tracks", text.Itoa(len(p.Tracks)))
}
// checkedIDs parses a playlist's track ids. Only the id range and duplicates
// are checked: loading every track would cost a read per id, and hidden or
// removed tracks are skipped when the playlist is read.
func checkedIDs(t *tx, s string) []int {
ids := parseIDs(s, maxListTracks)
for _, id := range ids {
if int64(id) > t.count(mTracks) {
panic("catalog: unknown track " + text.Itoa(id))
}
}
return ids
}
sponsor.gno
package catalog
import (
"chain"
"chain/banker"
"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/data"
)
// Sponsored picks: a verified artist funds a budget that refunds the cost of
// a listener's pick of their track once it has aired in full: the pick's fee
// at the app's 80M gas limit (0.08 GNOT) and its ~1,200-byte deposit (0.12
// GNOT), plus the collect's fee at 40M (0.04 GNOT), less the ~500 bytes of
// deposit the collect frees (0.05 GNOT): about 0.19 GNOT (radio/v1 gas
// filetests). It is a refund, not paid listening: the payout stays near the
// pick cost so throwaway wallets gain nothing by farming it, and the radio
// adds airtime and reputation rules (radio/sponsor.gno). Residual,
// accepted: a script that sets tight gas limits pays less than the 0.2 GNOT
// refund and keeps about 0.05 to 0.1 GNOT a pick, within the quotas (three
// sponsored picks a wallet a day, one per artist, and the budget's daily
// limit, defaultPerDay unless the artist sets one), so a budget drains no
// faster than its daily limit.
//
// The coins sit in the data realm's vault, account "catalog/<P(artist)>",
// never in this realm. The radio reserves the payout when the pick is queued
// (a vault hold); the hold is paid when the pick has aired, released if the
// slot is dropped, and lapses by itself claimDays after the slot ends. The
// funder withdraws the rest at any time with data.VaultWithdraw, whatever
// this realm does: paused, replaced or retired. This realm only keeps the
// artist's settings and stats (catalog/budgets).
//
// A budget has a funding generation, bumped when another wallet funds it
// (the previous funder is refunded, holds included). A reservation carries
// the generation it was made in, and pays or releases only in that one: the
// vault pools an artist's holds per day, so a reservation of an earlier
// funding is never paid from (nor released into) a later listener's hold,
// even when the budget went back to the same funder.
const (
defaultPickPay = 200_000 // ugnot per aired sponsored pick, 0.2 GNOT: the pick and its collect (above)
minPickPay = 10_000
maxPickPay = 500_000 // room for dearer gas, still a refund, never a wage
maxPickPerDay = 100 // the artist's own daily limit
defaultPerDay = 10 // the daily limit unless the artist sets one (0 = this default): a farming script drains a budget slowly
walletPicksDay = 3 // sponsored picks per listener per UTC day, one per artist
claimDays = 7 // a reservation lapses this long after the slot ends
daySecs = 24 * 3600
)
// dataPath is the data realm: its address holds the vault's coins.
const dataPath = "gno.land/r/nym-alexiscolin000/gnoradio/data"
type budget struct {
Pay int64 // per aired sponsored pick, 0 = paused
PerDay int // sponsored picks a day (stored 0 reads as defaultPerDay)
Day int64 // UTC day of Today
Today int
Funded int64
Paid int64
Picks int
Gen int // funding generation (see above)
}
// acct is an artist's vault account.
func acct(artistID int) string { return "catalog/" + store.Pad(artistID) }
func getBudget(t *tx, artistID int) (budget, bool) {
rec, ok := t.get(cBudgets, store.Pad(artistID))
if !ok {
return budget{}, false
}
f := store.Fields(rec)
b := budget{Pay: text.MustAtoi64(f[0]), PerDay: text.MustAtoi(f[1]), Day: text.MustAtoi64(f[2]), Today: text.MustAtoi(f[3]), Funded: text.MustAtoi64(f[4]),
Paid: text.MustAtoi64(f[5]), Picks: text.MustAtoi(f[6]), Gen: text.MustAtoi(store.Field(rec, 7))}
if b.PerDay == 0 {
b.PerDay = defaultPerDay
}
return b, true
}
func putBudget(t *tx, artistID int, b budget) {
t.set(cBudgets, store.Pad(artistID), store.Rec(text.Itoa64(b.Pay), text.Itoa(b.PerDay), text.Itoa64(b.Day), text.Itoa(b.Today),
text.Itoa64(b.Funded), text.Itoa64(b.Paid), text.Itoa(b.Picks), text.Itoa(b.Gen)))
}
func today() int64 { return now() / daySecs }
// lapseDay is the last UTC day a pick ending at end can be paid.
func lapseDay(end int64) int64 { return (end + claimDays*daySecs) / daySecs }
// FundPromo adds the attached ugnot to the caller's sponsored-pick budget in
// the vault. A new budget pays defaultPickPay per aired pick (SetPromoPay
// changes it). If the profile changed hands since the last funding, the
// previous funder gets their whole balance back first, reservations included,
// and the budget starts a new funding generation. The caller's budget must
// then hold at least one refund, or no pick could ever use it.
func FundPromo(cur realm) {
caller := userCaller(cur)
amt := paid()
if amt < minTip || amt > maxTip {
panic("catalog: a promo budget takes 0.1 to 1000000 GNOT")
}
t := rd()
id, arec := ownArtist(t, caller)
if store.Field(arec, aVerified) == "" {
panic("catalog: verify your profile first")
}
b, ok := getBudget(t, id)
if !ok {
b.Pay = defaultPickPay
}
b.Funded += amt
ac := acct(id)
funder, bal, _ := data.VaultInfo(ac)
own := amt // what the caller will have in the budget
if funder == caller {
own += bal
}
if b.Pay > 0 && own < b.Pay {
panic("catalog: fund at least one pick's refund (" + text.Itoa64(b.Pay) + " ugnot)")
}
if funder != caller && funder != "" {
b.Gen++ // every reservation of the previous funding is void
if bal > 0 {
data.VaultRefund(cross(cur), ac)
emitEvent("PromoWithdrawn", "artist", text.Itoa(id), "to", funder.String(), "amount", text.Itoa64(bal))
}
}
putBudget(t, id, b)
// The coins go to the vault before data counts them (data checks it).
banker.NewBanker(banker.BankerTypeRealmSend, cur).SendCoins(cur.Address(), chain.PackageAddress(dataPath), chain.Coins{{Denom: denom, Amount: amt}})
data.VaultCredit(cross(cur), ac, caller, amt)
save(cur, t)
_, bal, _ = data.VaultInfo(ac)
emitEvent("PromoFunded", "artist", text.Itoa(id), "by", caller.String(), "amount", text.Itoa64(amt), "balance", text.Itoa64(bal))
}
// SetPromoPay sets what each aired sponsored pick of the caller's tracks
// refunds (10 000..500 000 ugnot, 0 pauses) and the daily limit (1 to 100,
// 0 = the default, 10).
func SetPromoPay(cur realm, ugnotPerPick int64, perDay int) {
caller := userCaller(cur)
noPayment()
if ugnotPerPick != 0 && (ugnotPerPick < minPickPay || ugnotPerPick > maxPickPay) {
panic("catalog: a sponsored pick refunds 0.01 to 0.5 GNOT (0 pauses)")
}
if perDay < 0 || perDay > maxPickPerDay {
panic("catalog: the daily limit is 1 to 100 picks (0: the default, 10)")
}
t := rd()
id, _ := ownArtist(t, caller)
b, _ := getBudget(t, id)
b.Pay, b.PerDay = ugnotPerPick, perDay
putBudget(t, id, b)
save(cur, t)
emitEvent("PromoPay", "artist", text.Itoa(id), "pay", text.Itoa64(ugnotPerPick), "perDay", text.Itoa(perDay))
}
// PromoReserve reserves the refund of a sponsored pick of trackID by picker
// whose slot ends at end. Only the radio realm may call it (radio.QueueSponsored);
// it panics with the reason when the pick cannot be sponsored. It returns
// the amount reserved and the budget's funding generation, which the radio
// passes back to PromoClaim, PromoClaimable and PromoRelease.
func PromoReserve(cur realm, trackID int, picker address, end int64) (int64, int) {
onlyRadio(cur)
t := rd()
tr := mustTrack(t, trackID)
a := getArtist(t, tr.Artist)
b, _ := getBudget(t, a.ID)
funder, _, free := data.VaultInfo(acct(a.ID))
if a.Hidden || !a.Verified || a.Owner == "" || funder != a.Owner || b.Pay == 0 {
panic("catalog: this artist does not sponsor picks right now")
}
own := picker == a.Owner || !role.Canonical(picker) || data.IsGnoRadio(picker)
for _, s := range tr.Splits {
own = own || s.To == picker
}
if own {
panic("catalog: the artist and collaborators cannot take a sponsored pick")
}
day := today()
if b.Day != day {
b.Day, b.Today = day, 0
}
if b.PerDay > 0 && b.Today >= b.PerDay {
panic("catalog: this artist's sponsored picks for today are taken, pick it normally")
}
if free < b.Pay {
panic("catalog: this artist's promo budget is empty, pick it normally")
}
wd := t.val(cWalletDay, picker.String())
d, list, _ := strings.Cut(wd, "|")
if text.Atoi64(d) != day {
list = ""
}
if strings.Contains(","+list, ","+text.Itoa(a.ID)+",") {
panic("catalog: one sponsored pick per artist a day, pick it normally")
}
if strings.Count(list, ",") >= walletPicksDay {
panic("catalog: three sponsored picks a day, pick normally")
}
t.set(cWalletDay, picker.String(), text.Itoa64(day)+"|"+list+text.Itoa(a.ID)+",")
b.Today++
putBudget(t, a.ID, b)
data.VaultHold(cross(cur), acct(a.ID), b.Pay, lapseDay(end))
save(cur, t)
emitEvent("PromoReserved", "artist", text.Itoa(a.ID), "track", text.Itoa(trackID), "picker", picker.String(), "amount", text.Itoa64(b.Pay))
return b.Pay, b.Gen
}
// PromoClaim pays picker a reservation of funding generation gen once their
// sponsored pick ending at end has aired; the radio realm checks the slot. A
// lapsed or cancelled reservation (the budget was refunded since) pays nothing.
func PromoClaim(cur realm, trackID int, picker address, end, amount int64, gen int) {
onlyRadio(cur)
t := rd()
artistID, _, _, _, _ := brief(t, trackID)
e := lapseDay(end)
if data.VaultDay() > e { // the vault's clock: a pause never makes a refund lapse
panic("catalog: this sponsored pick was not collected within 7 days")
}
b, _ := getBudget(t, artistID)
if amount <= 0 || b.Gen != gen || data.VaultHeld(acct(artistID), e) < amount {
panic("catalog: this sponsorship was cancelled")
}
b.Paid += amount
b.Picks++
putBudget(t, artistID, b)
data.VaultPay(cross(cur), acct(artistID), picker, amount, e)
save(cur, t)
emitEvent("PromoPaid", "artist", text.Itoa(artistID), "track", text.Itoa(trackID), "to", picker.String(), "amount", text.Itoa64(amount))
}
// PromoClaimable reports whether PromoClaim would pay a sponsored pick's
// refund: reserved for end in generation gen, neither lapsed nor cancelled.
func PromoClaimable(trackID int, end, amount int64, gen int) bool {
t := rd()
artistID, _, _, _, _ := brief(t, trackID)
e := lapseDay(end)
b, _ := getBudget(t, artistID)
return data.VaultDay() <= e && amount > 0 && b.Gen == gen && data.VaultHeld(acct(artistID), e) >= amount
}
// PromoRelease returns a reservation to its budget: the slot was dropped or
// cut before it aired in full. A reservation of an earlier funding
// generation than gen's budget was refunded with it: nothing to release. A
// pick that never aired, reserved at reserved (unix; 0 when it partly aired),
// also gives back the daily counts it took, the artist's and picker's, if
// that was today. Radio realm only.
func PromoRelease(cur realm, trackID int, picker address, end, amount, reserved int64, gen int) {
onlyRadio(cur)
t := rd()
artistID, _, _, _, _ := brief(t, trackID)
b, _ := getBudget(t, artistID)
if amount > 0 && b.Gen == gen {
// lapsed or cancelled already: less, or nothing
if amount = data.VaultRelease(cross(cur), acct(artistID), amount, lapseDay(end)); amount > 0 {
emitEvent("PromoReleased", "artist", text.Itoa(artistID), "track", text.Itoa(trackID), "amount", text.Itoa64(amount))
}
}
day := today()
if reserved <= 0 || reserved/daySecs != day {
return
}
if b.Day == day && b.Today > 0 {
b.Today--
putBudget(t, artistID, b)
}
wd := t.val(cWalletDay, picker.String())
if d, list, _ := strings.Cut(wd, "|"); text.Atoi64(d) == day {
t.set(cWalletDay, picker.String(), d+"|"+strings.Replace(","+list, ","+text.Itoa(artistID)+",", ",", 1)[1:])
}
save(cur, t)
}
// PromoOffer is what a sponsored pick of the artist's tracks refunds right
// now (0: none). Picker-specific limits are checked when picking.
func PromoOffer(artistID int) int64 {
t := rd()
return offer(t, getArtist(t, artistID))
}
func offer(t *tx, a *Artist) int64 {
if a == nil {
return 0
}
if a.Hidden || !a.Verified || a.Owner == "" {
return 0
}
b, ok := getBudget(t, a.ID)
if !ok || b.Pay == 0 || b.PerDay > 0 && b.Day == today() && b.Today >= b.PerDay {
return 0
}
if funder, _, free := data.VaultInfo(acct(a.ID)); funder != a.Owner || free < b.Pay {
return 0
}
return b.Pay
}
// PromoJSON is an artist's sponsored-pick budget:
// {"artist","funder","balance","reserved","free","pay","perDay","today","funded","paid","picks","offer"}.
// The funder withdraws "free" with data.VaultWithdraw(acct) where acct is
// "catalog/" and the artist id on 8 digits.
func PromoJSON(artistID int) string {
t := rd()
b, _ := getBudget(t, artistID)
funder, bal, free := data.VaultInfo(acct(artistID))
if b.Day != today() {
b.Today = 0
}
return `{"artist":` + text.Itoa(artistID) + `,"funder":` + text.Str(funder.String()) + `,"balance":` + text.Itoa64(bal) +
`,"reserved":` + text.Itoa64(bal-free) + `,"free":` + text.Itoa64(free) + `,"pay":` + text.Itoa64(b.Pay) + `,"perDay":` + text.Itoa(b.PerDay) +
`,"today":` + text.Itoa(b.Today) + `,"funded":` + text.Itoa64(b.Funded) + `,"paid":` + text.Itoa64(b.Paid) + `,"picks":` + text.Itoa(b.Picks) +
`,"offer":` + text.Itoa64(offer(t, getArtist(t, artistID))) + `}`
}
support.gno
package catalog
import (
"chain"
"chain/banker"
"strings"
"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/data"
)
// GnoRadio's own funding, always on top of what artists receive and always
// visible on-chain: direct support and the optional share added to a tip.
// Every coin is forwarded to the treasury in the same transaction.
// SupportGnoRadio sends the attached ugnot to the GnoRadio treasury.
func SupportGnoRadio(cur realm) {
caller := userCaller(cur)
amt := paid()
if amt < minTip || amt > maxTip {
panic("catalog: support is between 0.1 and 1000000 GNOT")
}
t := rd()
if treasury(t) == "" {
panic("catalog: no treasury is set, GnoRadio takes no support")
}
bk := banker.NewBanker(banker.BankerTypeRealmSend, cur)
bk.SendCoins(cur.Address(), treasury(t), chain.Coins{{Denom: denom, Amount: amt}})
recordSupport(t, caller, amt)
save(cur, t)
emitEvent("Supported", "by", caller.String(), "amount", text.Itoa64(amt))
}
// SetTreasury changes where GnoRadio's support goes; "" (the default) takes none. Admin only.
func SetTreasury(cur realm, to address) {
onlyAdmin(cur)
if to != "" && !role.Canonical(to) { // "" switches support off
panic("catalog: invalid address")
}
if data.IsGnoRadio(to) {
panic("catalog: the treasury cannot be a GnoRadio realm")
}
t := rd()
emitEvent("TreasuryChanged", "from", treasury(t).String(), "to", to.String())
t.set(cConfig, "treasury", to.String())
save(cur, t)
}
// SetMonthlyGoal sets the monthly support goal shown in the app (ugnot). Admin only.
func SetMonthlyGoal(cur realm, ugnot int64) {
onlyAdmin(cur)
if ugnot < 0 || ugnot > maxTip {
panic("catalog: goal out of range")
}
t := rd()
t.set(cConfig, "goal", text.Itoa64(ugnot))
save(cur, t)
emitEvent("MonthlyGoal", "ugnot", text.Itoa64(ugnot))
}
func treasury(t *tx) address { return address(t.val(cConfig, "treasury")) }
func Treasury() address { return treasury(rd()) }
// SupportInfo returns GnoRadio's public funding state for this month.
func SupportInfo() (to address, total int64, supporters int, monthTotal, goal int64) {
t := rd()
return treasury(t), t.count(mSupport), int(t.count(mSupporters)), text.Atoi64(t.val(cMonthly, month(now()))), text.Atoi64(t.val(cConfig, "goal"))
}
func recordSupport(t *tx, by address, amt int64) {
t.bump(mSupport, amt)
s, had := t.get(cSupporters, by.String())
if !had {
t.bump(mSupporters, 1)
}
total := text.Atoi64(s) + amt
t.set(cSupporters, by.String(), text.Itoa64(total))
t.rank(topSupport, by.String(), total, true)
mo := month(now())
t.set(cMonthly, mo, text.Itoa64(text.Atoi64(t.val(cMonthly, mo))+amt))
t.activity("support", by, "0", "0", text.Itoa64(amt))
}
func month(unix int64) string { return time.Unix(unix, 0).UTC().Format("2006-01") }
// Activities returns up to limit entries, newest first.
func Activities(limit int) []Activity {
limit = store.Limit(limit, activitySize)
t := rd()
head := text.Atoi(t.val(cMeta, "head"))
out := make([]Activity, 0, limit)
for i := 1; i <= limit; i++ {
v := t.val(cActivity, store.Pad((head-i+activitySize)%activitySize))
if v == "" {
break // the ring is not full yet
}
f := store.Fields(v)
out = append(out, Activity{Kind: f[0], By: address(f[1]), Track: text.Atoi(f[2]), Artist: text.Atoi(f[3]), Amount: text.Atoi64(f[4]), At: text.Atoi64(f[5])})
}
return out
}
// ActivityJSON returns the activity feed, newest first (limit <= 64).
func ActivityJSON(limit int) string {
var b strings.Builder
b.WriteString("[")
for i, a := range Activities(limit) {
if i > 0 {
b.WriteString(",")
}
b.WriteString(`{"kind":` + text.Str(a.Kind) + `,"by":` + text.Str(a.By.String()) + `,"track":` + text.Itoa(a.Track) +
`,"artist":` + text.Itoa(a.Artist) + `,"amount":` + text.Itoa64(a.Amount) + `,"at":` + text.Itoa64(a.At) + `}`)
}
b.WriteString("]")
return b.String()
}
// SupportJSON returns GnoRadio's public funding state.
func SupportJSON() string {
to, total, supporters, mt, goal := SupportInfo()
var b strings.Builder
b.WriteString(`{"treasury":` + text.Str(to.String()) + `,"total":` + text.Itoa64(total) + `,"supporters":` + text.Itoa(supporters) +
`,"month":` + text.Str(month(now())) + `,"monthTotal":` + text.Itoa64(mt) + `,"goal":` + text.Itoa64(goal) + `,"top":[`)
for i, r := range rd().top(topSupport) {
if i > 0 {
b.WriteString(",")
}
b.WriteString(`{"address":` + text.Str(r.Key) + `,"amount":` + text.Itoa64(r.Value) + `}`)
}
b.WriteString(`]}`)
return b.String()
}
tracks.gno
package catalog
import (
"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"
"gno.land/r/nym-alexiscolin000/gnoradio/data"
)
// Tracks are added and edited through the radio realm only (radio.PublishTrack,
// radio.ImportTrack, radio.EditTrack): it puts a new track in the station
// rotations, and moves an edited one, in the same transaction. The radio
// names the wallet that signed (caller, by); only the radio writer the data
// realm names may call these.
// PublishFor adds a track by caller's own artist profile.
// duration is "m:ss"; cmo is "none" or "sacem-nc"; splits is optional,
// "g1...:30,g1...:15" in percent (the artist keeps at least 10%);
// rights must be "yes" (the caller accepts RightsTerms).
// audio and cover are ipfs://, ar:// or https:// links (an allowed host,
// with the file's sha256).
func PublishFor(cur realm, caller address, title string, genre int, duration, license, cmo, credits, audio, audioSHA, cover, coverSHA, splits, rights string) int {
onlyRadio(cur)
noPayment()
t := rd()
aid, _ := ownArtist(t, caller)
if strings.ToLower(strings.TrimSpace(rights)) != "yes" {
panic("catalog: accept the rights declaration (answer yes)")
}
tr := &Track{Origin: OriginArtist, CMO: "none"}
setInfo(tr, title, genre, duration, credits, true)
mustRefAudio(tr, audio)
setLicense(tr, license, cmo)
setMedia(tr, audio, audioSHA, cover, coverSHA)
tr.Splits = parseSplits(splits, caller)
id := addTrack(t, caller, aid, tr)
save(cur, t)
return id
}
// ImportFor adds a curated (CC0 / CC BY / CC BY-SA / CC BY-NC / CC BY-NC-SA)
// track, or a pointer to an Audius or Jamendo track, to an unclaimed artist.
// by must be the admin. A pointer keeps only what the radio needs (audio
// "audius:<id>" or "jamendo:<id>", genre, duration, licence): title, credits,
// cover, source and attribution stay empty and the app reads them live from
// the platform, whose API terms allow session caching only.
func ImportFor(cur realm, by address, artistID int, title string, genre int, duration, license, credits, audio, audioSHA, cover, coverSHA, sourceURL, attribution string) int {
onlyRadio(cur)
noPayment()
if by == "" || by != adminAddr() {
panic("catalog: admin only")
}
t := rd()
a := mustArtist(t, artistID)
if a.Kind == OriginArtist {
panic("catalog: artists publish their own tracks")
}
tr := &Track{Origin: a.Kind, CMO: "none"}
setInfo(tr, title, genre, duration, credits, false)
mustRefAudio(tr, audio)
if tr.Origin == OriginAudius {
tr.License = AudiusLicense
} else if tr.License = curatedLicense(license); tr.License == "" {
panic("catalog: curated imports must be CC0, CC BY, BY-SA, BY-NC or BY-NC-SA")
}
setMedia(tr, audio, audioSHA, cover, coverSHA)
sourceURL, attribution = strings.TrimSpace(sourceURL), strings.TrimSpace(attribution)
if isRef(tr.Origin) {
if cover != "" || sourceURL != "" || attribution != "" {
panic("catalog: a pointer stores no cover, source or attribution")
}
} else {
if !text.HTTPS(sourceURL, 300) {
panic("catalog: sourceURL must be the track's https page at the source")
}
mustText("attribution", attribution, 2, maxCredits)
}
tr.SourceURL, tr.Attribution = sourceURL, attribution
if isRef(tr.Origin) { // one record per platform track (the key has a '-', no name skeleton does)
if _, dup := t.get(cNames, refKey+tr.Audio); dup {
panic("catalog: this pointer track is already imported (hide it and ReleaseName \"" + refKey + tr.Audio + "\" to import it again)")
}
}
id := addTrack(t, adminAddr(), a.ID, tr)
if isRef(tr.Origin) { // pointers imported before this key existed have none: fine on a fresh chain
t.set(cNames, refKey+tr.Audio, text.Itoa(id))
}
save(cur, t)
return id
}
// EditFor fixes a track's details. Its artist only (the admin while the
// artist is unclaimed): caller is who signed.
func EditFor(cur realm, caller address, trackID int, title string, genre int, duration, credits, audio, audioSHA, cover, coverSHA string) {
onlyRadio(cur)
noPayment()
t := rd()
tr := mustTrack(t, trackID)
a := getArtist(t, tr.Artist)
if !mayEdit(caller, a) {
panic("catalog: only the artist can edit this track")
}
mustRefAudio(tr, audio)
// A pointer keeps its platform id and stores no cover: only its genre,
// duration and (claimed owner) title change.
if isRef(tr.Origin) && (strings.TrimSpace(audio) != tr.Audio || strings.TrimSpace(cover) != "" || strings.TrimSpace(coverSHA) != "") {
panic("catalog: a pointer keeps its audio and stores no cover")
}
oldGenre := tr.Genre
// The owner of a claimed Audius or Jamendo profile may name their own
// tracks: the record then stores the title with the artist's consent.
setInfo(tr, title, genre, duration, credits, a.Owner != "")
if tr.Genre != oldGenre {
t.removeID(cGenres, store.Pad(oldGenre), tr.ID)
t.addID(cGenres, store.Pad(tr.Genre), tr.ID)
t.bump(mGenre+oldGenre, -1)
t.bump(mGenre+tr.Genre, 1)
}
setMedia(tr, audio, audioSHA, cover, coverSHA)
t.setRec(cTracks, tr.ID, fits(trackRecord(tr)))
save(cur, t)
emitEvent("TrackEdited", "id", text.Itoa(tr.ID), "audio", tr.Audio, "duration", text.Itoa64(tr.Duration), "genre", text.Itoa(tr.Genre))
}
func addTrack(t *tx, publisher address, artistID int, tr *Track) int {
trackIDs, albumIDs := lists(t, artistID)
if store.Count(trackIDs) >= maxPerArtist {
panic("catalog: tracks per artist limit reached")
}
t.bump(mGenre+tr.Genre, 1)
tr.ID, tr.Artist, tr.Created = int(t.bump(mTracks, 1)), artistID, now()
t.addRec(cTracks, tr.ID, fits(trackRecord(tr)))
setLists(t, artistID, trackIDs+store.Enc(tr.ID), albumIDs)
t.addID(cGenres, store.Pad(tr.Genre), tr.ID)
t.activity("publish", publisher, text.Itoa(tr.ID), text.Itoa(artistID), "0")
emitEvent("TrackPublished", "id", text.Itoa(tr.ID), "artist", text.Itoa(artistID), "origin", tr.Origin, "genre", text.Itoa(tr.Genre),
"duration", text.Itoa64(tr.Duration), "title", tr.Title, "audio", tr.Audio, "license", tr.License)
return tr.ID
}
// setInfo sets a track's text and timing. An Audius or Jamendo pointer stores
// no title or credits unless named: its claimed artist's owner fills them in.
// Without that, an edit may keep or clear the stored text (a legacy import), never set new text.
func setInfo(tr *Track, title string, genre int, duration, credits string, named bool) {
title, credits = strings.TrimSpace(title), strings.TrimSpace(credits)
switch {
case isRef(tr.Origin) && (title == "" || title == tr.Title) && (credits == "" || credits == tr.Credits): // cleared or unchanged
case isRef(tr.Origin) && !named:
panic("catalog: a pointer stores no title or credits (the app reads them from the platform)")
default:
mustText("title", title, 1, maxTitle)
mustText("credits", credits, 0, maxCredits)
}
if genre < 1 || genre > NumGenres {
panic("catalog: genre must be 1.." + text.Itoa(NumGenres))
}
d, ok := parseClock(duration)
if !ok || d < minDuration || d > maxDuration {
panic("catalog: duration as m:ss, between 0:10 and 20:00")
}
tr.Title, tr.Genre, tr.Duration, tr.Credits = title, genre, d, credits
}
// refKey prefixes a pointer's audio in cNames (the '-' keeps it off every name skeleton).
const refKey = "track-"
// isRef reports whether tracks of this origin are pointers: read live from
// Audius or Jamendo, with no title or credits stored on chain.
func isRef(origin string) bool { return origin == OriginAudius || origin == OriginJamendo }
// mustRefAudio keeps a pointer's audio on its platform ("audius:<id>",
// "jamendo:<id>") and every other track off both.
func mustRefAudio(tr *Track, audio string) {
prefix := strings.TrimSpace(audio)
if i := strings.IndexByte(prefix, ':'); i >= 0 {
prefix = prefix[:i]
}
if isRef(prefix) != isRef(tr.Origin) || isRef(tr.Origin) && prefix != tr.Origin {
panic("catalog: Audius and Jamendo tracks use audio audius:<id> or jamendo:<id>, other tracks neither")
}
}
// refLabel is what gnoweb shows for a pointer's empty title or name: the
// platform it is read from ("Audius track", "Jamendo artist").
func refLabel(origin, stored, what string) string {
if stored != "" || !isRef(origin) {
return stored
}
return strings.ToUpper(origin[:1]) + origin[1:] + " " + what
}
func setLicense(tr *Track, license, cmo string) {
lic := normLicense(license)
if lic == "" {
panic("catalog: unknown license, use one of " + strings.Join(licenses, ", "))
}
cmo = strings.ToLower(strings.TrimSpace(cmo))
switch cmo {
case "", "none":
cmo = "none"
case "sacem-nc":
if !strings.Contains(lic, "-NC") {
panic("catalog: SACEM members may only publish works declared under a CC NC license")
}
default:
panic("catalog: collective society must be none or sacem-nc")
}
tr.License, tr.CMO = lic, cmo
}
func setMedia(tr *Track, audio, audioSHA, cover, coverSHA string) {
audio, audioSHA = strings.TrimSpace(audio), strings.ToLower(strings.TrimSpace(audioSHA))
cover, coverSHA = strings.TrimSpace(cover), strings.ToLower(strings.TrimSpace(coverSHA))
mustMedia("audio", audio, audioSHA, true)
if coverSHA != "" && (cover == "" || !isSHA256(coverSHA)) { // coverSHA goes into the JSON as is
panic("catalog: cover sha256 must be 64 hex characters, with a cover")
}
if cover != "" {
mustMedia("cover", cover, coverSHA, false)
}
tr.Audio, tr.AudioSHA, tr.Cover, tr.CoverSHA = audio, audioSHA, cover, coverSHA
}
// parseSplits reads the collaborators: never the artist, never a GnoRadio realm.
func parseSplits(s string, artist address) []Split {
s = strings.TrimSpace(s)
if s == "" {
return nil
}
parts := strings.Split(s, ",")
if len(parts) > maxSplits {
panic("catalog: at most 4 collaborators")
}
var out []Split
var sum int64
seen := map[string]bool{}
for _, p := range parts {
addrStr, pctStr, ok := strings.Cut(strings.TrimSpace(p), ":")
to := address(strings.TrimSpace(addrStr))
pct, err := strconv.ParseInt(strings.TrimSuffix(strings.TrimSpace(pctStr), "%"), 10, 64)
if !ok || err != nil || !role.Canonical(to) || to == artist || data.IsGnoRadio(to) || seen[to.String()] || pct < 1 || pct > maxSplitPct {
panic("catalog: collaborators as g1...:30,g1...:15 (percent)")
}
seen[to.String()] = true
sum += pct
out = append(out, Split{To: to, Pct: pct})
}
if sum > maxSplitPct {
panic("catalog: collaborators may receive at most 90%")
}
return out
}
validate.gno
package catalog
import (
"strconv"
"strings"
"unicode"
"gno.land/p/nym-alexiscolin000/gnoradio/safe/v0"
"gno.land/p/nym-alexiscolin000/gnoradio/text/v0"
"gno.land/r/nym-alexiscolin000/gnoradio/data"
)
func mustText(field, s string, min, max int) {
if !text.Valid(s, min, max) {
panic("catalog: " + field + " must be " + text.Itoa(min) + "-" + text.Itoa(max) +
" characters: letters, digits, spaces and . , ' - ! ? : / & only")
}
// A report reason may quote what it reports (/moderation masks it).
if field != "reason" && safe.Slur(s) {
panic("catalog: " + field + " holds a slur")
}
}
// validName restricts artist names to ASCII letters and digits plus the
// Latin-1 accented letters, so look-alike names cannot impersonate an artist.
func validName(s string) bool {
if strings.TrimSpace(s) != s || strings.Contains(s, " ") {
return false
}
n, alnum := 0, 0
for _, r := range s {
n++
if (r >= 'a' && r <= 'z') || (r >= 'A' && r <= 'Z') || (r >= '0' && r <= '9') ||
(r >= 0xC0 && r <= 0xFF && r != 0xD7 && r != 0xF7) {
alnum++
continue
}
switch r {
case ' ', '.', '\'', '-', '&':
continue
}
return false
}
// At least one letter or digit, so the reserved skeleton is never empty.
return n >= 2 && n <= 40 && alnum > 0
}
// latin1 folds the Latin-1 letters 0xC0-0xFF (lowercased) to ASCII.
var latin1 = [64]string{
"a", "a", "a", "a", "a", "a", "ae", "c", "e", "e", "e", "e", "i", "i", "i", "i",
"d", "n", "o", "o", "o", "o", "o", "", "o", "u", "u", "u", "u", "y", "th", "ss",
"a", "a", "a", "a", "a", "a", "ae", "c", "e", "e", "e", "e", "i", "i", "i", "i",
"d", "n", "o", "o", "o", "o", "o", "", "o", "u", "u", "u", "u", "y", "th", "y",
}
// skeleton is the key an artist name is reserved under: lowercase, common
// Latin accents stripped, fullwidth letters and digits mapped to ASCII,
// spaces and punctuation dropped and look-alikes folded (i/l/1 → l, 0 → o,
// 3 → e, 4 → a, 5 → s, 7 → t, 9 → g, u → v, rn → m, vv → w, cl → d), so
// "Beyonce", "BEYONCÉ", "Beyonce", "Daft Punk", "DAFT PUNK", "Kanye
// Vvest", "Kanye Uuest", "Clrake" and "9orillaz" collide with the real names.
func skeleton(s string) string {
var b strings.Builder
for _, r := range s {
switch r {
case ' ', '.', '\'', '-', '&', 0x3000:
continue
}
switch {
case r >= 0xFF21 && r <= 0xFF3A:
r = r - 0xFF21 + 'a'
case r >= 0xFF41 && r <= 0xFF5A:
r = r - 0xFF41 + 'a'
case r >= 0xFF10 && r <= 0xFF19:
r = r - 0xFF10 + '0'
}
r = unicode.ToLower(r)
if r >= 0xC0 && r <= 0xFF && latin1[r-0xC0] != "" {
b.WriteString(confusable(latin1[r-0xC0]))
continue
}
b.WriteString(confusable(string(r)))
}
k := strings.ReplaceAll(b.String(), "rn", "m")
k = strings.ReplaceAll(k, "vv", "w")
return strings.ReplaceAll(k, "cl", "d")
}
// confusable folds characters that look alike in common fonts.
func confusable(s string) string {
switch s {
case "i", "1", "|":
return "l"
case "0":
return "o"
case "3":
return "e"
case "4":
return "a"
case "5":
return "s"
case "7":
return "t"
case "9":
return "g"
case "u":
return "v" // before the vv → w fold: "uu" and "vu" pass for w too
}
return s
}
// Reserved names, as skeletons: a name holding a stem anywhere, or one of
// the words as a word, could pass for GnoRadio, its staff, the chain
// (gno.land folds to gnoland), the wallet (Adena) or the audio source
// (Audius). Adena and Audius are prefixes, not stems: refused at the start
// of the name or of any word in it ("AdenaWallet", "Ade-na", "Audius2"),
// while names that only end with them pass ("Pasadena", "La Cadena",
// "Claudius").
var (
reservedStems = []string{skeleton("gnoradio"), skeleton("moderator"), skeleton("moderation"),
skeleton("treasury"), skeleton("administrator"), skeleton("gnoland")}
reservedWords = []string{skeleton("admin"), skeleton("staff"), skeleton("official")}
reservedPrefixes = []string{skeleton("adena"), skeleton("audius")}
)
func reserved(name string) bool {
k := skeleton(name)
for _, s := range reservedStems {
if strings.Contains(k, s) {
return true
}
}
for _, s := range reservedWords {
if strings.Contains(k, s) && anyWord(name, func(w string) bool { return w == s }) {
return true
}
}
for _, s := range reservedPrefixes {
if strings.HasPrefix(k, s) || strings.Contains(k, s) && anyWord(name, func(w string) bool { return strings.HasPrefix(w, s) }) {
return true
}
}
return false
}
// anyWord reports whether the skeleton of a word of name passes ok.
func anyWord(name string, ok func(string) bool) bool {
for _, w := range strings.FieldsFunc(name, func(r rune) bool { return strings.ContainsRune(" .'-&", r) }) {
if ok(skeleton(w)) {
return true
}
}
return false
}
func mustName(s string) {
if !validName(s) {
panic("catalog: artist name must be 2-40 characters: Latin letters (a-z and Latin-1 accents), digits, spaces and . ' - &")
}
if safe.Slur(s) {
panic("catalog: artist name holds a slur")
}
if reserved(s) {
panic("catalog: this artist name is reserved for GnoRadio, gno.land, Adena or Audius")
}
}
func alnum(s string, min, max int) bool {
if len(s) < min || len(s) > max {
return false
}
for _, c := range s {
if (c < 'a' || c > 'z') && (c < 'A' || c > 'Z') && (c < '0' || c > '9') {
return false
}
}
return true
}
func validHost(h string) bool {
if len(h) < 3 || len(h) > 100 || !strings.Contains(h, ".") {
return false
}
for _, c := range h {
if (c < 'a' || c > 'z') && (c < '0' || c > '9') && c != '.' && c != '-' {
return false
}
}
return true
}
// hostOf is the authority of an https link: up to the first / ? or #
// (lower case). It is a plain host only when validHost says so.
func hostOf(url string) string {
rest := strings.TrimPrefix(url, "https://")
if i := strings.IndexAny(rest, "/?#"); i >= 0 {
rest = rest[:i]
}
return strings.ToLower(rest)
}
func isSHA256(s string) bool {
if len(s) != 64 {
return false
}
for _, c := range s {
if (c < '0' || c > '9') && (c < 'a' || c > 'f') {
return false
}
}
return true
}
// mustMedia checks an audio or cover reference:
//
// ipfs://<cid> content-addressed, sha256 optional
// ar://<txid> Arweave, sha256 optional
// audius:<trackId> audio only, streamed through the Audius API
// jamendo:<trackId> audio only, streamed from Jamendo
// https://<host>/… host must be allowed, sha256 required
func mustMedia(field, uri, sha string, audioField bool) {
if sha != "" && !isSHA256(sha) {
panic("catalog: " + field + " sha256 must be 64 hex characters")
}
switch {
case strings.HasPrefix(uri, "ipfs://"):
if !alnum(strings.TrimPrefix(uri, "ipfs://"), 46, 100) {
panic("catalog: " + field + " ipfs:// needs a valid CID")
}
case strings.HasPrefix(uri, "ar://"):
id := strings.TrimPrefix(uri, "ar://")
if len(id) != 43 || !text.URLChars(id) {
panic("catalog: " + field + " ar:// needs a 43-character transaction id")
}
case strings.HasPrefix(uri, "audius:"), strings.HasPrefix(uri, "jamendo:"):
_, id, _ := strings.Cut(uri, ":")
if !audioField || !alnum(id, 1, 32) {
panic("catalog: " + field + " audius:<id> or jamendo:<id> is only valid for audio")
}
case strings.HasPrefix(uri, "https://"):
if !text.HTTPS(uri, 300) || !data.Has(cHosts, hostOf(uri)) {
panic("catalog: " + field + " host is not allowed (ask the admin to add it)")
}
if sha == "" {
panic("catalog: " + field + " over https needs the file's sha256")
}
default:
panic("catalog: " + field + " must be ipfs://, ar://, audius:, jamendo: or an allowed https:// link")
}
}
// normLicense maps loose input ("cc by", "cc-by-4.0", "CC0") to an SPDX id.
func normLicense(s string) string {
s = strings.ToUpper(strings.TrimSpace(s))
s = strings.ReplaceAll(s, " ", "-")
s = strings.ReplaceAll(s, "_", "-")
if s == "CC0" {
s = "CC0-1.0"
}
if strings.HasPrefix(s, "CC-") && !strings.HasSuffix(s, "-4.0") {
s += "-4.0"
}
for _, l := range licenses {
if s == l {
return l
}
}
return ""
}
// parseClock parses "m:ss" (or plain seconds) into seconds.
func parseClock(s string) (int64, bool) {
s = strings.TrimSpace(s)
m, sec, hasColon := strings.Cut(s, ":")
if !hasColon {
if !text.Digits(s) || len(s) > 5 {
return 0, false
}
v, _ := strconv.ParseInt(s, 10, 64)
return v, true
}
if len(m) > 3 || len(sec) != 2 || !text.Digits(m) || !text.Digits(sec) {
return 0, false
}
mv, _ := strconv.ParseInt(m, 10, 64)
sv, _ := strconv.ParseInt(sec, 10, 64)
if sv > 59 {
return 0, false
}
return mv*60 + sv, true
}
// parseIDs parses "12,40,7" into distinct ids, at most max of them.
func parseIDs(s string, max int) []int {
s = strings.TrimSpace(s)
if s == "" {
panic("catalog: list at least one track id")
}
parts := strings.Split(s, ",")
if len(parts) > max {
panic("catalog: at most " + text.Itoa(max) + " tracks")
}
out := make([]int, 0, len(parts))
seen := map[int]bool{}
for _, p := range parts {
p = strings.TrimSpace(p)
n, err := strconv.Atoi(p)
if err != nil || n < 1 || !text.Digits(p) {
panic("catalog: track ids as 12,40,7")
}
if seen[n] {
panic("catalog: duplicate track " + text.Itoa(n))
}
seen[n] = true
out = append(out, n)
}
return out
}
// curatedLicense accepts the redistributable licenses curated imports may
// carry, in any version and national port: CC0-1.0, CC-BY-<v>[-XX],
// CC-BY-SA-<v>[-XX], CC-BY-NC-<v>[-XX], CC-BY-NC-SA-<v>[-XX] (v = 1.0, 2.0, 2.5, 3.0, 4.0). It returns the normalized
// id, or "" when the license is not allowed.
func curatedLicense(s string) string {
s = strings.ToUpper(strings.ReplaceAll(strings.TrimSpace(s), " ", "-"))
if s == "CC0" || s == "CC0-1.0" {
return "CC0-1.0"
}
var rest string
switch {
case strings.HasPrefix(s, "CC-BY-NC-SA-"):
rest = strings.TrimPrefix(s, "CC-BY-NC-SA-")
case strings.HasPrefix(s, "CC-BY-NC-"):
rest = strings.TrimPrefix(s, "CC-BY-NC-")
case strings.HasPrefix(s, "CC-BY-SA-"):
rest = strings.TrimPrefix(s, "CC-BY-SA-")
case strings.HasPrefix(s, "CC-BY-"):
rest = strings.TrimPrefix(s, "CC-BY-")
default:
return ""
}
ver, port, _ := strings.Cut(rest, "-")
switch ver {
case "1.0", "2.0", "2.5", "3.0", "4.0":
default:
return ""
}
if port != "" && (len(port) != 2 || !alnum(port, 2, 2)) {
return ""
}
return s
}
verify.gno
package catalog
import (
"chain/runtime"
"crypto/ed25519"
"encoding/hex"
"strconv"
"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/data"
)
// Automatic verification, paid by the artist. The artist puts a proof line in
// a place only they control (their Audius bio, or /.well-known/gnoradio.txt on
// their own website); the GnoRadio robot reads it and, off-chain and for free,
// signs a certificate (Ed25519, ClaimMessage) valid for a short while. The
// artist submits it with Claim from their own wallet; after claimDelay anyone
// can finalize: the profile goes to that wallet and turns Verified, which
// opens tips and paid tickets. The robot key signs nothing else; the admin can
// revoke it, cancel a pending claim and undo a wrong one. Changing or revoking
// the key voids every claim it started that is still pending, so a stolen key
// is undone in one call; there is no daily cap that one person could use up
// for everyone.
const (
claimDelay = 72 * 3600 // seconds a claim stays public before it counts
certLife = 2 * 3600 // longest validity of a robot certificate, seconds
)
type claim struct {
To address
Proof string
At int64
Gen int // the robot key's generation when the claim was made
}
// ClaimMessage is what the robot signs: the chain, the GnoRadio deployment
// (its data realm, so a staging deployment on the same chain cannot reuse a
// certificate), the profile, the wallet, where the proof was found and until
// when the certificate holds.
func ClaimMessage(artistID int, to address, proof string, expires int64) string {
return "gnoradio-claim|" + runtime.ChainID() + "|" + dataPath + "|" + text.Itoa(artistID) + "|" + to.String() + "|" + proof + "|" + text.Itoa64(expires)
}
// botKey is the robot's Ed25519 public key (empty: verification paused) and
// gen its generation, bumped by SetBot.
func botKey(t *tx) (key []byte, gen int) {
key, _ = hex.DecodeString(t.val(cConfig, "bot"))
return key, text.Atoi(t.val(cConfig, "gen"))
}
func getClaim(t *tx, artistID int) *claim {
rec, ok := t.get(cClaims, store.Pad(artistID))
if !ok {
return nil
}
f := store.Fields(rec)
return &claim{To: address(f[0]), Proof: f[1], At: text.Atoi64(f[2]), Gen: text.Atoi(f[3])}
}
// liveClaim is the pending claim made with the current robot key, if any.
func liveClaim(t *tx, artistID int) *claim {
c := getClaim(t, artistID)
if _, gen := botKey(t); c == nil || c.Gen != gen {
return nil
}
return c
}
// SetBot sets the robot's Ed25519 public key, hex ("" disables it). Every
// pending claim started with the previous key is voided: its artist claims
// again with a fresh certificate. Admin only.
func SetBot(cur realm, pubKeyHex string) {
onlyAdmin(cur)
key, err := hex.DecodeString(pubKeyHex)
if err != nil || (len(key) != 0 && len(key) != 32) {
panic("catalog: the robot key is a 32-byte Ed25519 public key in hex")
}
t := rd()
_, gen := botKey(t)
t.set(cConfig, "bot", hex.EncodeToString(key))
t.set(cConfig, "gen", text.Itoa(gen+1))
save(cur, t)
emitEvent("BotSet", "key", pubKeyHex)
}
// Claim starts the verification of artistID for the caller with the robot's
// certificate (ClaimMessage signed, hex). It replaces any pending claim for the
// artist and restarts the delay. The artist pays its gas.
func Claim(cur realm, artistID int, proof string, expires int64, sigHex string) {
caller := userCaller(cur)
noPayment()
ts := now()
t := rd()
key, gen := botKey(t)
if len(key) == 0 {
panic("catalog: verification is paused")
}
if expires < ts || expires > ts+certLife {
panic("catalog: this certificate has expired, check your page again")
}
// A plain host, so the host shown next to the ✓ is the one the proof
// was read from (no user info, port, or "[email protected]" trick).
if !text.HTTPS(proof, 300) || !validHost(hostOf(proof)) {
panic("catalog: proof must be an https link on a plain host")
}
sig, err := hex.DecodeString(sigHex)
if err != nil || len(sig) != 64 || !ed25519.Verify(key, []byte(ClaimMessage(artistID, caller, proof, expires)), sig) {
panic("catalog: this certificate is not valid for your wallet")
}
a := mustArtist(t, artistID)
mustClaimable(t, a, caller)
mustRobotVerifiable(a)
t.set(cClaims, store.Pad(artistID), store.Rec(caller.String(), proof, text.Itoa64(ts), text.Itoa(gen)))
save(cur, t)
emitEvent("ClaimProposed", "artist", text.Itoa(artistID), "to", caller.String(), "proof", proof)
}
// FinalizeClaim applies a pending claim once claimDelay has passed. Anyone
// can call it, usually the artist from the app.
func FinalizeClaim(cur realm, artistID int) {
noPayment()
t := rd()
c := getClaim(t, artistID)
if c == nil {
panic("catalog: no pending verification for this artist")
}
if _, gen := botKey(t); c.Gen != gen {
panic("catalog: this check was signed by a robot key since replaced, check your page again")
}
if now() < c.At+claimDelay {
panic("catalog: verification completes 72 hours after the check")
}
a := mustArtist(t, artistID)
mustClaimable(t, a, c.To)
t.del(cClaims, store.Pad(artistID))
if a.Owner == "" {
a.Owner = c.To
t.set(cOwners, c.To.String(), text.Itoa(a.ID))
t.activity("claim", c.To, "0", text.Itoa(a.ID), "0")
}
a.Verified = true
putArtist(t, a)
t.set(cProofs, store.Pad(artistID), c.Proof)
save(cur, t)
emitEvent("ArtistClaimed", "id", text.Itoa(a.ID), "owner", c.To.String(), "proof", c.Proof)
}
// CancelClaim drops a pending claim (e.g. the proof page was hijacked). Admin only.
func CancelClaim(cur realm, artistID int) {
onlyAdmin(cur)
t := rd()
if _, ok := t.get(cClaims, store.Pad(artistID)); !ok {
panic("catalog: no pending verification for this artist")
}
t.del(cClaims, store.Pad(artistID))
save(cur, t)
emitEvent("ClaimCancelled", "artist", text.Itoa(artistID))
}
// ResetOwner undoes a wrong claim on an imported profile (e.g. a hijacked
// proof page found too late): the profile is unclaimed again. Self-registered
// profiles keep their owner. Admin only.
func ResetOwner(cur realm, artistID int) {
onlyAdmin(cur)
t := rd()
a := mustArtist(t, artistID)
if a.Kind == OriginArtist || a.Owner == "" {
panic("catalog: only a claimed imported profile can be reset")
}
t.del(cOwners, a.Owner.String())
a.Owner, a.Verified = "", false
if isRef(a.Kind) && !a.Hidden { // a pointer has no name of its own: the claimant's name and bio go too
if old := skeleton(a.Name); old != "" {
if id, ok := t.get(cNames, old); ok && text.Atoi(id) == a.ID {
t.del(cNames, old)
}
}
a.Name, a.Bio = "", ""
}
putArtist(t, a)
t.del(cProofs, store.Pad(artistID))
t.del(cClaims, store.Pad(artistID))
save(cur, t)
emitEvent("OwnerReset", "artist", text.Itoa(artistID))
}
// mustRobotVerifiable refuses the robot's path for a curated profile: it
// carries a real artist's name and tracks that GnoRadio imported, and no
// domain proves who that artist is (neither the import site's operator nor
// any domain an impersonator buys). The moderator assigns it (AssignArtist).
func mustRobotVerifiable(a *Artist) {
if a.Kind == OriginCurated || a.Kind == OriginJamendo { // Jamendo has no bio a robot could read
panic("catalog: an imported profile is verified by the GnoRadio moderator, not with a proof page")
}
}
// mustClaimable: an unowned profile goes to a wallet without a profile; an
// owned one can only be verified for its own wallet.
func mustClaimable(t *tx, a *Artist, to address) {
if a.Hidden {
panic("catalog: this artist is hidden")
}
if a.Verified {
panic("catalog: this artist is already verified")
}
if a.Owner != "" {
if a.Owner != to {
panic("catalog: this profile belongs to another wallet")
}
return
}
if !role.Canonical(to) || artistOf(t, to) != 0 {
panic("catalog: this wallet is invalid or already has an artist profile")
}
}
// ArtistVerified reports whether an artist proved who they are (tips and
// paid tickets need it).
func ArtistVerified(artistID int) bool { return artistAt(artistID, aVerified) == "1" }
// ClaimState is an artist's pending verification: the wallet it goes to and
// when FinalizeClaim may apply it; pending is false when there is none.
func ClaimState(artistID int) (pending bool, to address, readyAt int64) {
if c := liveClaim(rd(), artistID); c != nil {
return true, c.To, c.At + claimDelay
}
return false, "", 0
}
// PendingClaim is a verification on its way: the artist, the wallet it goes
// to, the proof link and when FinalizeClaim may apply it.
type PendingClaim struct {
Artist int
To address
Proof string
ReadyAt int64
}
// PendingClaims lists up to limit (1-100) verifications pending with the
// current robot key, by artist id from offset, and how many claims are
// stored (stale ones included, so offset+limit < total means more). A claim
// stays public for 72 hours before it counts: this is where anyone watches
// them.
func PendingClaims(offset, limit int) (out []PendingClaim, total int) {
t := rd()
_, gen := botKey(t)
keys, recs := store.Rows(data.PageAt(cClaims, max0(offset), store.Limit(limit, 100), false))
for i, k := range keys {
if f := store.Fields(recs[i]); text.Atoi(f[3]) == gen {
out = append(out, PendingClaim{Artist: text.Atoi(k), To: address(f[0]), Proof: f[1], ReadyAt: text.Atoi64(f[2]) + claimDelay})
}
}
return out, data.Size(cClaims)
}
// ProofHost is where a verified artist's proof was found: a host they
// control, not proof of who they are, so show it next to the ✓. It is ""
// when the artist is not verified, or a moderator verified it (Verify,
// AssignArtist).
func ProofHost(artistID int) string {
t := rd()
return proofHost(t, artistID, artistField(t, artistID, aVerified))
}
func proofHost(t *tx, artistID int, verified string) string {
if verified == "" {
return ""
}
if h := hostOf(t.val(cProofs, store.Pad(artistID))); validHost(h) {
return h
}
return "" // a record a later release wrote: show no host rather than a wrong one
}
// ClaimJSON is the verification state of an artist for the app:
// {"verified":b,"proof":"…","pending":b,"to":"…","pendingProof":"…","readyAt":n,"bot":"…"}.
func ClaimJSON(artistID int) string {
t := rd()
out := `{"verified":` + strconv.FormatBool(artistField(t, artistID, aVerified) == "1") + `,"proof":"` + t.val(cProofs, store.Pad(artistID)) + `"`
if c := liveClaim(t, artistID); c != nil {
out += `,"pending":true,"to":"` + c.To.String() + `","pendingProof":"` + c.Proof + `","readyAt":` + text.Itoa64(c.At+claimDelay)
} else {
out += `,"pending":false`
}
key, _ := botKey(t)
return out + `,"bot":` + strconv.FormatBool(len(key) != 0) + `}`
}