Playground
boards.gno
package boards2
import (
"gno.land/p/gnoland/boards/exts/permissions/v0"
"gno.land/p/gnoland/boards/v0"
"gno.land/p/moul/realmpath/v0"
"gno.land/p/moul/txlink/v0"
"gno.land/p/nt/bptree/v0"
)
const (
realmPkgPath = "gno.land/r/gnoland/boards2/v0"
gRealmPath = "/r/gnoland/boards2/v0"
)
var (
// RealmLink contains Boards2 realm link.
// It can be used to generate board TX links from other realms.
RealmLink = txlink.Realm(realmPkgPath)
// RequiredAccountAmount contains the required account amount for open board interactions.
// The amount requirement is not applied to members that were invited to an open board.
// Amount is defined as ugnot.
RequiredAccountAmount = int64(3_000_000_000)
// Notice contains an optional message that is displayed globally within the realm.
Notice string
// Help contains optional Markdown with Boards2 realm help.
Help string
)
// TODO: Refactor globals in favor of a cleaner pattern
var (
gListedBoardsByID bptree.BPTree // string(id) -> *boards.Board
gInviteRequests bptree.BPTree // string(board id) -> *bptree.BPTree(address -> time.Time)
gBannedUsers bptree.BPTree // string(board id) -> *bptree.BPTree(address -> time.Time)
gLocked struct {
realm bool
realmMembers bool
}
)
var (
gBoards = boards.NewStorage()
gBoardsSequence = boards.NewIdentifierGenerator()
gPerms = initRealmPermissions("g1skl80cuz8zq3lul9pgz5pc35l2pfzgxgfpsqkx") // GovDAO T1 multisig
)
// initRealmPermissions returns the default realm permissions.
func initRealmPermissions(owners ...address) boards.Permissions {
perms := permissions.New(
permissions.UseSingleUserRole(),
permissions.WithSuperRole(RoleOwner),
)
perms.AddRole(RoleAdmin, PermissionBoardCreate)
for _, owner := range owners {
perms.SetUserRoles(owner, RoleOwner)
}
perms.ValidateFunc(PermissionBoardCreate, validateBasicBoardCreate)
perms.ValidateFunc(PermissionMemberInvite, validateBasicMemberInvite)
perms.ValidateFunc(PermissionRoleChange, validateBasicRoleChange)
return perms
}
// getInviteRequests returns invite requests for a board.
func getInviteRequests(boardID boards.ID) (_ *bptree.BPTree, found bool) {
v := gInviteRequests.Get(boardID.Key())
if v == nil {
return nil, false
}
return v.(*bptree.BPTree), true
}
// getBannedUsers returns banned users within a board.
func getBannedUsers(boardID boards.ID) (_ *bptree.BPTree, found bool) {
v := gBannedUsers.Get(boardID.Key())
if v == nil {
return nil, false
}
return v.(*bptree.BPTree), true
}
// mustGetBoardByName returns a board or panics when it's not found.
func mustGetBoardByName(name string) *boards.Board {
board, found := gBoards.GetByName(name)
if !found {
panic("board does not exist with name: " + name)
}
return board
}
// mustGetBoard returns a board or panics when it's not found.
func mustGetBoard(id boards.ID) *boards.Board {
board, found := gBoards.Get(id)
if !found {
panic("board does not exist with ID: " + id.String())
}
return board
}
// getThread returns a board thread.
func getThread(board *boards.Board, threadID boards.ID) (*boards.Post, bool) {
thread, found := board.Threads.Get(threadID)
if !found {
// When thread is not found search it within hidden threads
meta := board.Meta.(*BoardMeta)
thread, found = meta.HiddenThreads.Get(threadID)
}
return thread, found
}
// getReply returns a thread comment or reply.
func getReply(thread *boards.Post, replyID boards.ID) (*boards.Post, bool) {
meta := thread.Meta.(*ThreadMeta)
return meta.AllReplies.Get(replyID)
}
// mustGetThread returns a thread or panics when it's not found.
func mustGetThread(board *boards.Board, threadID boards.ID) *boards.Post {
thread, found := getThread(board, threadID)
if !found {
panic("thread does not exist with ID: " + threadID.String())
}
return thread
}
// mustGetReply returns a reply or panics when it's not found.
func mustGetReply(thread *boards.Post, replyID boards.ID) *boards.Post {
reply, found := getReply(thread, replyID)
if !found {
panic("reply does not exist with ID: " + replyID.String())
}
return reply
}
func mustGetPermissions(bid boards.ID) boards.Permissions {
if bid != 0 {
board := mustGetBoard(bid)
return board.Permissions
}
return gPerms
}
func parseRealmPath(path string) *realmpath.Request {
// Make sure request is using current realm path so paths can be parsed during Render
r := realmpath.Parse(path)
r.Realm = string(RealmLink)
return r
}
doc.gno
// Boards2 is a social discussion forum for open communication and community-driven conversations. // // Users can start discussions by creating or reposting threads and then submitting comments or replies // to other user comments. // // Discussions happen within different boards, where each board is an independent self managed community. // // Boards2 allows users to create two types of boards: // - Invite Only: Only invited users (members) can create threads, reposts and comments. // - Open: Anyone with a specific amount of GNOT in their account can create threads, reposts and comments. package boards2
flag.gno
package boards2
import (
"strconv"
"gno.land/p/gnoland/boards/v0"
"gno.land/p/nt/bptree/v0"
)
// DefaultFlaggingThreshold defines the default number of flags that hides flaggable items.
const DefaultFlaggingThreshold = 1
var gFlaggingThresholds bptree.BPTree // string(board ID) -> int
// flagItem adds a flag to a post.
// Returns whether flag count threshold is reached and post can be hidden.
// Panics if flag count threshold was already reached.
func flagItem(post *boards.Post, user address, reason string, threshold int) bool {
if post.Flags.Size() >= threshold {
panic("flag count threshold exceeded: " + strconv.Itoa(threshold))
}
if post.Flags.Exists(user) {
panic("post has been already flagged by " + user.String())
}
post.Flags.Add(boards.Flag{
User: user,
Reason: reason,
})
return post.Flags.Size() == threshold
}
func getFlaggingThreshold(bid boards.ID) int {
if v := gFlaggingThresholds.Get(bid.String()); v != nil {
return v.(int)
}
return DefaultFlaggingThreshold
}
format.gno
package boards2
import (
"strconv"
"strings"
"gno.land/p/gnoland/boards/v0"
"gno.land/p/moul/md/v0"
"gno.land/p/nt/markdown/foreign/v0"
"gno.land/r/sys/users"
)
const dateFormat = "2006-01-02 3:04pm MST"
func padLeft(s string, length int) string {
if len(s) >= length {
return s
}
return strings.Repeat(" ", length-len(s)) + s
}
func padZero(u64 uint64, length int) string {
s := strconv.Itoa(int(u64))
if len(s) >= length {
return s
}
return strings.Repeat("0", length-len(s)) + s
}
func indentBody(indent string, body string) string {
var (
res string
lines = strings.Split(body, "\n")
)
for i, line := range lines {
if i > 0 {
// Add two spaces to keep newlines within Markdown
res += " \n"
}
res += indent + line
}
return res
}
// indentForeignBody is the single "render a user body" operation: it
// sandboxes the body in a <gno-foreign> block, indents it like
// indentBody, AND charges one unit against the per-render budget — so
// wrapping and budget-accounting can't drift apart (the *int signals
// the mutation). The body renders inside the sandbox: its block
// structure (headings, blockquotes, lists, columns, alerts) is
// contained and cannot hijack realm chrome, so boards no longer needs
// the write-time markdown blacklist. The opener survives the "> "
// comment indentation at any depth (goldmark strips the "> " prefix
// before the block parser runs).
func indentForeignBody(indent, body string, budget *int) string {
*budget-- // one <gno-foreign> block
return indentBody(indent, foreign.Foreign(body))
}
func summaryOf(text string, length int) string {
lines := strings.SplitN(text, "\n", 2)
line := lines[0]
if len(line) > length {
line = line[:(length-3)] + "..."
} else if len(lines) > 1 {
line = line + "..."
}
return line
}
func userLink(addr address) string {
if u := users.ResolveAddress(addr); u != nil {
return md.UserLink(u.Name())
}
return md.UserLink(addr.String())
}
func getRoleBadge(post *boards.Post) string {
if post == nil || post.Board == nil || post.Board.Permissions == nil {
return ""
}
perms := post.Board.Permissions
creator := post.Creator
// Check roles in order of priority
if perms.HasRole(creator, RoleOwner) {
return " `owner`"
}
if perms.HasRole(creator, RoleAdmin) {
return " `admin`"
}
if perms.HasRole(creator, RoleModerator) {
return " `mod`"
}
return ""
}
gnomod.toml
module = "gno.land/r/gnoland/boards2/v0" gno = "0.9" [addpkg] creator = "g1edq4dugw0sgat4zxcw9xardvuydqf6cgleuc8p"
hub.gno
// The `hub.gno` file exposes safe, read-only views over the realm's
// persistent state.
//
// Note for future maintainers: these reads perform no caller
// authorization, so do not graft user-identity gating onto them.
package boards2
import (
hubexts "gno.land/p/gnoland/boards/exts/hub/v0"
"gno.land/p/gnoland/boards/v0"
)
// Safe view types are defined in the hub extensions package and
// re-exported here so callers can keep using them via this realm.
type (
Board = hubexts.Board
Comment = hubexts.Comment
Flag = hubexts.Flag
Member = hubexts.Member
Thread = hubexts.Thread
)
// GetBoard returns a safe board.
func GetBoard(id uint64) (Board, bool) {
b, found := gBoards.Get(boards.ID(id))
if !found {
return Board{}, false
}
return hubexts.NewSafeBoard(b), true
}
// GetThread returns a safe board thread.
func GetThread(boardID, threadID uint64) (Thread, bool) {
t, found := getBoardThread(boardID, threadID)
if !found {
return Thread{}, false
}
return hubexts.NewSafeThread(t), true
}
// GetComment returns a safe thread comment or reply.
// `commentID` can be the ID of a top level comment or of a nested reply.
func GetComment(boardID, threadID, commentID uint64) (Comment, bool) {
c, found := getComment(boardID, threadID, commentID)
if !found {
return Comment{}, false
}
return hubexts.NewSafeComment(c), true
}
// GetBoards returns a list with all boards.
// To reverse iterate use a negative count.
func GetBoards(start, count int) []Board {
var boards_ []Board
gBoards.Iterate(start, count, func(b *boards.Board) bool {
boards_ = append(boards_, hubexts.NewSafeBoard(b))
return false
})
return boards_
}
// GetThreads returns a list with threads of a board.
// To reverse iterate use a negative count.
// A board without thread storage has no threads, so nil is returned.
func GetThreads(boardID uint64, start, count int) []Thread {
b, found := gBoards.Get(boards.ID(boardID))
if !found || b.Threads == nil {
return nil
}
var threads []Thread
b.Threads.Iterate(start, count, func(thread *boards.Post) bool {
threads = append(threads, hubexts.NewSafeThread(thread))
return false
})
return threads
}
// GetMembers returns a list with the members of a board.
// A zero `boardID` refers to the realm, so the realm admin users are returned.
// A non permissioned board has no members, so nil is returned.
func GetMembers(boardID uint64, start, count int) []Member {
perms := gPerms
if boardID != 0 {
b, found := gBoards.Get(boards.ID(boardID))
if !found {
return nil
}
perms = b.Permissions
}
if perms == nil {
return nil
}
var members []Member
perms.IterateUsers(start, count, func(u boards.User) bool {
members = append(members, hubexts.NewSafeMember(u))
return false
})
return members
}
// GetReposts returns a list with repost of a board thread.
// To reverse iterate use a negative count.
// A repost is not included when its destination thread has been deleted,
// so the total accessible results can be shorter than the thread's RepostCount(),
// and a single call can return fewer than count results.
// (The reason for the discrepancy is that the start index can be large,
// and this function cannot scan all reposts up to the start index to
// resolve the discrepancy.)
func GetReposts(boardID, threadID uint64, start, count int) []Thread {
t, found := getBoardThread(boardID, threadID)
if !found {
return nil
}
var reposts []Thread
t.Reposts.Iterate(start, count, func(rBoardID, rRepostID boards.ID) bool {
r, found := getBoardThread(uint64(rBoardID), uint64(rRepostID))
if found {
reposts = append(reposts, hubexts.NewSafeThread(r))
}
return false
})
return reposts
}
// GetFlags returns a list with thread or comment moderation flags.
// To reverse iterate use a negative count.
// Thread flags are returned when `commentID` is zero, or the flags of the
// comment or reply with that ID are returned otherwise.
func GetFlags(boardID, threadID, commentID uint64, start, count int) []Flag {
var storage boards.FlagStorage
if commentID == 0 {
t, found := getBoardThread(boardID, threadID)
if !found {
return nil
}
storage = t.Flags
} else {
c, found := getComment(boardID, threadID, commentID)
if !found {
return nil
}
storage = c.Flags
}
var flags []Flag
storage.Iterate(start, count, func(f boards.Flag) bool {
flags = append(flags, hubexts.NewSafeFlag(f))
return false
})
return flags
}
// GetComments returns a list with top-level comments of a thread.
// To reverse iterate use a negative count.
func GetComments(boardID, threadID uint64, start, count int) []Comment {
t, found := getBoardThread(boardID, threadID)
if !found {
return nil
}
var comments []Comment
// Replies only has direct replies.
t.Replies.Iterate(start, count, func(comment *boards.Post) bool {
comments = append(comments, hubexts.NewSafeComment(comment))
return false
})
return comments
}
// GetReplies returns a list with the direct replies of a comment or reply.
// To reverse iterate use a negative count.
// `commentID` can be the ID of a top level comment or of a nested reply.
func GetReplies(boardID, threadID, commentID uint64, start, count int) []Comment {
c, found := getComment(boardID, threadID, commentID)
if !found {
return nil
}
var replies []Comment
c.Replies.Iterate(start, count, func(comment *boards.Post) bool {
replies = append(replies, hubexts.NewSafeComment(comment))
return false
})
return replies
}
// getBoardThread returns a board thread from their IDs.
func getBoardThread(boardID, threadID uint64) (*boards.Post, bool) {
b, found := gBoards.Get(boards.ID(boardID))
if !found {
return nil, false
}
return getThread(b, boards.ID(threadID))
}
// getComment returns a thread comment or reply from their IDs.
// It searches the thread's flat index of all comments and replies, so
// nested replies are addressable by ID and not only top level comments.
func getComment(boardID, threadID, commentID uint64) (*boards.Post, bool) {
t, found := getBoardThread(boardID, threadID)
if !found {
return nil, false
}
return getReply(t, boards.ID(commentID))
}
meta.gno
package boards2
import "gno.land/p/gnoland/boards/v0"
// BoardMeta defines a type for board metadata.
type BoardMeta struct {
// HiddenThreads contains hidden board threads.
HiddenThreads boards.PostStorage
}
// ThreadMeta defines a type for thread metadata.
type ThreadMeta struct {
// AllReplies contains all existing thread comments and replies.
AllReplies boards.PostStorage
}
permissions.gno
package boards2
import (
"gno.land/p/gnoland/boards/exts/permissions/v0"
"gno.land/p/gnoland/boards/v0"
)
// List of Boards2 member roles.
const (
RoleOwner boards.Role = "owner"
RoleAdmin = "admin"
RoleModerator = "moderator"
RoleGuest = "guest"
)
// PermissionCustom defines an initial value for custom board permissions.
// When a board defines custom permissions it must starts from a value
// greater or equal than PermissionCustom.
//
// Custom permissions definition example:
//
// const (
// PermissionCustom1 boards.Permission = iota + boards2.PermissionCustom
// PermissionCustom2
// PermissionCustom3
// )
const PermissionCustom boards.Permission = 200
// List of Boards2 permissions.
const (
PermissionBoardCreate boards.Permission = iota
PermissionBoardFlaggingUpdate
PermissionBoardFreeze
PermissionBoardRename
PermissionMemberInvite
PermissionMemberInviteRevoke
PermissionMemberRemove
PermissionPermissionsUpdate
PermissionRealmHelpChange
PermissionRealmLock
PermissionRealmNotice
PermissionAccountRequiredAmountChange
PermissionReplyCreate
PermissionReplyDelete
PermissionReplyFlag
PermissionRoleChange
PermissionThreadCreate
PermissionThreadDelete
PermissionThreadEdit
PermissionThreadFlag
PermissionThreadFreeze
PermissionThreadRepost
PermissionUserBan
PermissionUserUnban
)
func createBasicBoardPermissions(owner address) *permissions.Permissions {
perms := permissions.New(
permissions.UseSingleUserRole(),
permissions.WithSuperRole(RoleOwner),
)
perms.AddRole(
RoleAdmin,
PermissionBoardRename,
PermissionBoardFlaggingUpdate,
PermissionMemberInvite,
PermissionMemberInviteRevoke,
PermissionMemberRemove,
PermissionThreadCreate,
PermissionThreadEdit,
PermissionThreadDelete,
PermissionThreadRepost,
PermissionThreadFlag,
PermissionThreadFreeze,
PermissionReplyCreate,
PermissionReplyDelete,
PermissionReplyFlag,
PermissionRoleChange,
PermissionUserBan,
PermissionUserUnban,
)
perms.AddRole(
RoleModerator,
PermissionThreadCreate,
PermissionThreadEdit,
PermissionThreadRepost,
PermissionThreadFlag,
PermissionReplyCreate,
PermissionReplyFlag,
PermissionUserBan,
PermissionUserUnban,
)
perms.AddRole(
RoleGuest,
PermissionThreadCreate,
PermissionThreadRepost,
PermissionReplyCreate,
)
perms.SetUserRoles(owner, RoleOwner)
perms.ValidateFunc(PermissionBoardRename, validateBasicBoardRename)
perms.ValidateFunc(PermissionMemberInvite, validateBasicMemberInvite)
perms.ValidateFunc(PermissionRoleChange, validateBasicRoleChange)
return perms
}
func createOpenBoardPermissions(owner address) *permissions.Permissions {
perms := permissions.New(
permissions.UseSingleUserRole(),
permissions.WithSuperRole(RoleOwner),
)
perms.SetPublicPermissions(
PermissionThreadCreate,
PermissionThreadRepost,
PermissionReplyCreate,
)
perms.AddRole(
RoleAdmin,
PermissionBoardRename,
PermissionBoardFlaggingUpdate,
PermissionMemberInvite,
PermissionMemberInviteRevoke,
PermissionMemberRemove,
PermissionThreadCreate,
PermissionThreadEdit,
PermissionThreadDelete,
PermissionThreadRepost,
PermissionThreadFlag,
PermissionThreadFreeze,
PermissionReplyCreate,
PermissionReplyDelete,
PermissionReplyFlag,
PermissionRoleChange,
PermissionUserBan,
PermissionUserUnban,
)
perms.AddRole(
RoleModerator,
PermissionThreadCreate,
PermissionThreadEdit,
PermissionThreadRepost,
PermissionThreadFlag,
PermissionReplyCreate,
PermissionReplyFlag,
PermissionUserBan,
PermissionUserUnban,
)
perms.AddRole(
RoleGuest,
PermissionThreadCreate,
PermissionThreadRepost,
PermissionReplyCreate,
)
perms.SetUserRoles(owner, RoleOwner)
perms.ValidateFunc(PermissionBoardRename, validateOpenBoardRename)
perms.ValidateFunc(PermissionMemberInvite, validateOpenMemberInvite)
perms.ValidateFunc(PermissionRoleChange, validateOpenRoleChange)
perms.ValidateFunc(PermissionThreadCreate, validateOpenThreadCreate)
perms.ValidateFunc(PermissionReplyCreate, validateOpenReplyCreate)
return perms
}
permissions_validators_basic.gno
package boards2
import (
"errors"
"gno.land/p/gnoland/boards/v0"
"gno.land/r/sys/users"
)
// validateBasicBoardCreate validates PermissionBoardCreate.
//
// Expected `args` values:
// 1. Caller address
// 2. Board name
// 3. Board ID
// 4. Is board listed
// 5. Is board open
func validateBasicBoardCreate(perms boards.Permissions, args boards.Args) error {
caller, ok := args[0].(address)
if !ok {
return errors.New("expected a valid caller address")
}
name, ok := args[1].(string)
if !ok {
return errors.New("expected board name to be a string")
}
open, ok := args[4].(bool)
if !ok {
return errors.New("expected board open flag to be a boolean")
}
if open && !perms.HasRole(caller, RoleOwner) {
return errors.New("only owners can create open boards")
}
if err := checkBoardNameIsNotAddress(name); err != nil {
return err
}
if err := checkBoardNameBelongsToAddress(caller, name); err != nil {
return err
}
return nil
}
// validateBasicBoardRename validates PermissionBoardRename.
//
// Expected `args` values:
// 1. Caller address
// 2. Board ID
// 3. Current board name
// 4. New board name
func validateBasicBoardRename(_ boards.Permissions, args boards.Args) error {
caller, ok := args[0].(address)
if !ok {
return errors.New("expected a valid caller address")
}
newName, ok := args[3].(string)
if !ok {
return errors.New("expected new board name to be a string")
}
if err := checkBoardNameIsNotAddress(newName); err != nil {
return err
}
if err := checkBoardNameBelongsToAddress(caller, newName); err != nil {
return err
}
return nil
}
// validateBasicMemberInvite validates PermissionMemberInvite.
//
// Expected `args` values:
// 1. Caller address
// 2. Board ID
// 3. Invites
func validateBasicMemberInvite(perms boards.Permissions, args boards.Args) error {
caller, ok := args[0].(address)
if !ok {
return errors.New("expected a valid caller address")
}
invites, ok := args[2].([]Invite)
if !ok {
return errors.New("expected valid user invites")
}
// Make sure that only owners invite other owners
callerIsOwner := perms.HasRole(caller, RoleOwner)
for _, v := range invites {
if v.Role == RoleOwner && !callerIsOwner {
return errors.New("only owners are allowed to invite other owners")
}
}
return nil
}
// validateBasicRoleChange validates PermissionRoleChange.
//
// Expected `args` values:
// 1. Caller address
// 2. Board ID
// 3. Member address
// 4. Role
func validateBasicRoleChange(perms boards.Permissions, args boards.Args) error {
caller, ok := args[0].(address)
if !ok {
return errors.New("expected a valid caller address")
}
// Owners and Admins can change roles.
// Admins should not be able to assign or remove the Owner role from members.
if perms.HasRole(caller, RoleAdmin) {
role, ok := args[3].(boards.Role)
if !ok {
return errors.New("expected a valid member role")
}
if role == RoleOwner {
return errors.New("admins are not allowed to promote members to Owner")
} else {
member, ok := args[2].(address)
if !ok {
return errors.New("expected a valid member address")
}
if perms.HasRole(member, RoleOwner) {
return errors.New("admins are not allowed to remove the Owner role")
}
}
}
return nil
}
func checkBoardNameIsNotAddress(s string) error {
if address(s).IsValid() {
return errors.New("addresses are not allowed as board name")
}
return nil
}
func checkBoardNameBelongsToAddress(owner address, name string) error {
// When the board name is the name of a registered user
// check that caller is the owner of the name.
user, _ := users.ResolveName(name)
if user != nil && user.Addr() != owner {
return errors.New("board name is a user name registered to a different user")
}
return nil
}
permissions_validators_open.gno
package boards2
import (
"chain/banker"
"errors"
"gno.land/p/gnoland/boards/v0"
"gno.land/p/nt/ufmt/v0"
)
// validateOpenBoardRename validates PermissionBoardRename.
//
// Expected `args` values:
// 1. Caller address
// 2. Board ID
// 3. Current board name
// 4. New board name
func validateOpenBoardRename(_ boards.Permissions, args boards.Args) error {
caller, ok := args[0].(address)
if !ok {
return errors.New("expected a valid caller address")
}
newName, ok := args[3].(string)
if !ok {
return errors.New("expected new board name to be a string")
}
if err := checkBoardNameIsNotAddress(newName); err != nil {
return err
}
if err := checkBoardNameBelongsToAddress(caller, newName); err != nil {
return err
}
return nil
}
// validateOpenMemberInvite validates PermissionMemberInvite.
//
// Expected `args` values:
// 1. Caller address
// 2. Board ID
// 3. Invites
func validateOpenMemberInvite(perms boards.Permissions, args boards.Args) error {
caller, ok := args[0].(address)
if !ok {
return errors.New("expected a valid caller address")
}
invites, ok := args[2].([]Invite)
if !ok {
return errors.New("expected valid user invites")
}
// Make sure that only owners invite other owners
callerIsOwner := perms.HasRole(caller, RoleOwner)
for _, v := range invites {
if v.Role == RoleOwner && !callerIsOwner {
return errors.New("only owners are allowed to invite other owners")
}
}
return nil
}
// validateOpenRoleChange validates PermissionRoleChange.
//
// Expected `args` values:
// 1. Caller address
// 2. Board ID
// 3. Member address
// 4. Role
func validateOpenRoleChange(perms boards.Permissions, args boards.Args) error {
caller, ok := args[0].(address)
if !ok {
return errors.New("expected a valid caller address")
}
// Owners and Admins can change roles.
// Admins should not be able to assign or remove the Owner role from members.
if perms.HasRole(caller, RoleAdmin) {
role, ok := args[3].(boards.Role)
if !ok {
return errors.New("expected a valid member role")
}
if role == RoleOwner {
return errors.New("admins are not allowed to promote members to Owner")
} else {
member, ok := args[2].(address)
if !ok {
return errors.New("expected a valid member address")
}
if perms.HasRole(member, RoleOwner) {
return errors.New("admins are not allowed to remove the Owner role")
}
}
}
return nil
}
// validateOpenThreadCreate validates PermissionThreadCreate.
//
// Expected `args` values:
// 1. Caller address
// 2. Board ID
// 3. Thread ID
// 4. Title
// 5. Body
func validateOpenThreadCreate(perms boards.Permissions, args boards.Args) error {
caller, ok := args[0].(address)
if !ok {
return errors.New("expected a valid caller address")
}
// Owners and admins can create threads without special requirements
if perms.HasRole(caller, RoleOwner) || perms.HasRole(caller, RoleAdmin) {
return nil
}
// Require non members to have some GNOT in their accounts
if err := checkAccountHasAmount(caller, RequiredAccountAmount); err != nil {
return ufmt.Errorf("caller is not allowed to create threads: %s", err)
}
return nil
}
// validateOpenReplyCreate validates PermissionReplyCreate.
//
// Expected `args` values:
// 1. Caller address
// 2. Board ID
// 3. Thread ID
// 4. Parent ID
// 5. Reply ID
// 6. Body
func validateOpenReplyCreate(perms boards.Permissions, args boards.Args) error {
caller, ok := args[0].(address)
if !ok {
return errors.New("expected a valid caller address")
}
// All board members can reply
if perms.HasUser(caller) {
return nil
}
// Require non members to have some GNOT in their accounts
if err := checkAccountHasAmount(caller, RequiredAccountAmount); err != nil {
return ufmt.Errorf("caller is not allowed to comment: %s", err)
}
return nil
}
func checkAccountHasAmount(addr address, amount int64) error {
bnk := banker.NewReadonlyBanker()
if bnk.GetCoin(addr, "ugnot") < RequiredAccountAmount {
amount = amount / 1_000_000 // ugnot -> GNOT
return ufmt.Errorf("account amount is lower than %d GNOT", amount)
}
return nil
}
public.gno
package boards2
import (
"chain"
"chain/runtime/unsafe"
"regexp"
"strconv"
"strings"
"time"
"gno.land/p/gnoland/boards/v0"
)
const (
// MaxBoardNameLength defines the maximum length allowed for board names.
MaxBoardNameLength = 50
// MaxThreadTitleLength defines the maximum length allowed for thread titles.
MaxThreadTitleLength = 100
// MaxThreadBodyLength defines the maximum length allowed for thread bodies.
// 40,000 mirrors Reddit's self-post body cap.
MaxThreadBodyLength = 40000
// MaxReplyLength defines the maximum length allowed for replies.
// 10,000 mirrors Reddit's comment cap.
MaxReplyLength = 10000
)
var reBoardName = regexp.MustCompile(`(?i)^[a-z]+[a-z0-9_\-]{2,50}$`)
// SetHelp sets or updates boards realm help content.
func SetHelp(cur realm, content string) {
content = strings.TrimSpace(content)
caller := cur.Previous().Address()
args := boards.Args{content}
gPerms.WithPermission(caller, PermissionRealmHelpChange, args, func() {
Help = content
})
}
// SetRequiredAccountAmount sets the required account amount to interact as a non member with open boards.
// Amount must be given as ugnot.
// The amount requirement is not applied to members that were invited to an open board.
func SetRequiredAccountAmount(cur realm, amount int64) {
if amount < 0 {
panic("invalid amount")
}
caller := cur.Previous().Address()
args := boards.Args{amount}
gPerms.WithPermission(caller, PermissionAccountRequiredAmountChange, args, func() {
RequiredAccountAmount = amount
chain.Emit(
"RequiredAccountAmountChanged",
"caller", caller.String(),
"amount", strconv.FormatInt(amount, 10),
)
})
}
// SetPermissions sets a permissions implementation for boards2 realm or a board.
func SetPermissions(cur realm, boardID boards.ID, p boards.Permissions) {
assertRealmIsNotLocked()
assertBoardExists(boardID)
if p == nil {
panic("permissions is required")
}
caller := cur.Previous().Address()
args := boards.Args{boardID}
gPerms.WithPermission(caller, PermissionPermissionsUpdate, args, func() {
assertRealmIsNotLocked()
// When board ID is zero it means that realm permissions are being updated
if boardID == 0 {
gPerms = p
chain.Emit(
"RealmPermissionsChanged",
"caller", caller.String(),
)
return
}
// Otherwise update the permissions of a single board
board := mustGetBoard(boardID)
board.Permissions = p
chain.Emit(
"BoardPermissionsChanged",
"caller", caller.String(),
"boardID", board.ID.String(),
)
})
}
// SetRealmNotice sets a notice to be displayed globally within the realm.
// An empty message removes the realm notice.
func SetRealmNotice(cur realm, message string) {
message = strings.TrimSpace(message)
caller := cur.Previous().Address()
args := boards.Args{message}
gPerms.WithPermission(caller, PermissionRealmNotice, args, func() {
Notice = message
chain.Emit(
"RealmNoticeChanged",
"caller", caller.String(),
"message", message,
)
})
}
// GetBoardIDFromName searches a board by name and returns its ID.
func GetBoardIDFromName(_ realm, name string) (_ boards.ID, found bool) {
board, found := gBoards.GetByName(name)
if !found {
return 0, false
}
return board.ID, true
}
// BoardCount returns the total number of boards.
func BoardCount() int {
return gBoards.Size()
}
// CreateBoard creates a new board.
//
// Listed boards are included in the realm's list of boards.
// Open boards allow anyone to create threads and comment.
func CreateBoard(cur realm, name string, listed, open bool) boards.ID {
assertRealmIsNotLocked()
name = strings.TrimSpace(name)
assertIsValidBoardName(name)
assertBoardNameNotExists(name)
caller := cur.Previous().Address()
id := gBoardsSequence.Next()
board := boards.New(id)
args := boards.Args{caller, name, board.ID, listed, open}
gPerms.WithPermission(caller, PermissionBoardCreate, args, func() {
assertRealmIsNotLocked()
assertBoardNameNotExists(name)
board.Name = name
board.Creator = caller
board.Meta = &BoardMeta{
HiddenThreads: boards.NewPostStorage(),
}
if open {
board.Permissions = createOpenBoardPermissions(caller)
} else {
board.Permissions = createBasicBoardPermissions(caller)
}
if err := gBoards.Add(board); err != nil {
panic(err)
}
// Listed boards are also indexed separately for easier iteration and pagination
if listed {
gListedBoardsByID.Set(board.ID.Key(), board)
}
chain.Emit(
"BoardCreated",
"caller", caller.String(),
"boardID", board.ID.String(),
"name", name,
)
})
return board.ID
}
// RenameBoard changes the name of an existing board.
//
// A history of previous board names is kept when boards are renamed.
// Because of that boards are also accessible using previous name(s).
func RenameBoard(cur realm, name, newName string) {
assertRealmIsNotLocked()
newName = strings.TrimSpace(newName)
assertIsValidBoardName(newName)
assertBoardNameNotExists(newName)
board := mustGetBoardByName(name)
assertBoardIsNotFrozen(board)
caller := cur.Previous().Address()
args := boards.Args{caller, board.ID, name, newName}
board.Permissions.WithPermission(caller, PermissionBoardRename, args, func() {
assertRealmIsNotLocked()
assertBoardNameNotExists(newName)
board.Aliases = append(board.Aliases, board.Name)
board.Name = newName
board.UpdatedAt = time.Now()
// Index board for the new name keeping previous indexes for older names
gBoards.Add(board)
chain.Emit(
"BoardRenamed",
"caller", caller.String(),
"boardID", board.ID.String(),
"name", name,
"newName", newName,
)
})
}
// CreateThread creates a new thread within a board.
func CreateThread(cur realm, boardID boards.ID, title, body string) boards.ID {
assertRealmIsNotLocked()
title = strings.TrimSpace(title)
assertTitleIsValid(title)
assertThreadBodyIsValid(body)
caller := cur.Previous().Address()
assertUserIsNotBanned(boardID, caller)
board := mustGetBoard(boardID)
assertBoardIsNotFrozen(board)
thread := boards.MustNewThread(board, caller, title, body)
args := boards.Args{caller, board.ID, thread.ID, title, body}
board.Permissions.WithPermission(caller, PermissionThreadCreate, args, func() {
assertRealmIsNotLocked()
assertUserIsNotBanned(board.ID, caller)
thread.Meta = &ThreadMeta{
AllReplies: boards.NewPostStorage(),
}
if err := board.Threads.Add(thread); err != nil {
panic(err)
}
chain.Emit(
"ThreadCreated",
"caller", caller.String(),
"boardID", board.ID.String(),
"threadID", thread.ID.String(),
"title", title,
)
})
return thread.ID
}
// CreateReply creates a new comment or reply within a thread.
//
// The value of `replyID` is only required when creating a reply of another reply.
func CreateReply(cur realm, boardID, threadID, replyID boards.ID, body string) boards.ID {
assertRealmIsNotLocked()
body = strings.TrimSpace(body)
assertReplyBodyIsValid(body)
caller := cur.Previous().Address()
assertUserIsNotBanned(boardID, caller)
board := mustGetBoard(boardID)
assertBoardIsNotFrozen(board)
thread := mustGetThread(board, threadID)
assertThreadIsVisible(thread)
assertThreadIsNotFrozen(thread)
// By default consider that reply's parent is the thread.
// Or when replyID is assigned use that reply as the parent.
parent := thread
if replyID > 0 {
parent = mustGetReply(thread, replyID)
if parent.Hidden || parent.Readonly {
panic("replying to a hidden or frozen reply is not allowed")
}
}
reply := boards.MustNewReply(parent, caller, body)
args := boards.Args{caller, board.ID, thread.ID, parent.ID, reply.ID, body}
board.Permissions.WithPermission(caller, PermissionReplyCreate, args, func() {
assertRealmIsNotLocked()
// Add reply to its parent
if err := parent.Replies.Add(reply); err != nil {
panic(err)
}
// Always add reply to the thread so it contains all comments and replies.
// Comment and reply only contains direct replies.
meta := thread.Meta.(*ThreadMeta)
if err := meta.AllReplies.Add(reply); err != nil {
panic(err)
}
chain.Emit(
"ReplyCreate",
"caller", caller.String(),
"boardID", board.ID.String(),
"threadID", thread.ID.String(),
"replyID", reply.ID.String(),
)
})
return reply.ID
}
// CreateRepost reposts a thread into another board.
func CreateRepost(cur realm, boardID, threadID, destinationBoardID boards.ID, title, body string) boards.ID {
assertRealmIsNotLocked()
title = strings.TrimSpace(title)
assertTitleIsValid(title)
assertThreadBodyIsValid(body)
caller := cur.Previous().Address()
assertUserIsNotBanned(destinationBoardID, caller)
dst := mustGetBoard(destinationBoardID)
assertBoardIsNotFrozen(dst)
board := mustGetBoard(boardID)
thread := mustGetThread(board, threadID)
assertThreadIsVisible(thread)
repost := boards.MustNewRepost(thread, dst, caller)
args := boards.Args{caller, board.ID, thread.ID, dst.ID, repost.ID, title, body}
dst.Permissions.WithPermission(caller, PermissionThreadRepost, args, func() {
assertRealmIsNotLocked()
repost.Title = title
repost.Body = strings.TrimSpace(body)
repost.Meta = &ThreadMeta{
AllReplies: boards.NewPostStorage(),
}
if err := dst.Threads.Add(repost); err != nil {
panic(err)
}
if err := thread.Reposts.Add(repost); err != nil {
panic(err)
}
chain.Emit(
"Repost",
"caller", caller.String(),
"boardID", board.ID.String(),
"threadID", thread.ID.String(),
"destinationBoardID", dst.ID.String(),
"repostID", repost.ID.String(),
"title", title,
)
})
return repost.ID
}
// DeleteThread deletes a thread from a board.
//
// Threads can be deleted by the users who created them or otherwise by users with special permissions.
func DeleteThread(cur realm, boardID, threadID boards.ID) {
assertRealmIsNotLocked()
caller := cur.Previous().Address()
board := mustGetBoard(boardID)
assertUserIsNotBanned(boardID, caller)
isRealmOwner := gPerms.HasRole(caller, RoleOwner) // TODO: Add DeleteThread filetest cases for realm owners
if !isRealmOwner {
assertBoardIsNotFrozen(board)
}
thread := mustGetThread(board, threadID)
deleteThread := func() {
board.Threads.Remove(thread.ID)
chain.Emit(
"ThreadDeleted",
"caller", caller.String(),
"boardID", board.ID.String(),
"threadID", thread.ID.String(),
)
}
// Thread can be directly deleted by user that created it.
// It can also be deleted by realm owners, to be able to delete inappropriate content.
// TODO: Discuss and decide if realm owners should be able to delete threads.
if isRealmOwner || caller == thread.Creator {
deleteThread()
return
}
args := boards.Args{caller, board.ID, thread.ID}
board.Permissions.WithPermission(caller, PermissionThreadDelete, args, func() {
assertRealmIsNotLocked()
deleteThread()
})
}
// DeleteReply deletes a reply from a thread.
//
// Replies can be deleted by the users who created them or otherwise by users with special permissions.
// Soft deletion is used when the deleted reply contains sub replies, in which case the reply content
// is replaced by a text informing that reply has been deleted to avoid deleting sub-replies.
func DeleteReply(cur realm, boardID, threadID, replyID boards.ID) {
assertRealmIsNotLocked()
caller := cur.Previous().Address()
board := mustGetBoard(boardID)
assertUserIsNotBanned(boardID, caller)
thread := mustGetThread(board, threadID)
reply := mustGetReply(thread, replyID)
isRealmOwner := gPerms.HasRole(caller, RoleOwner) // TODO: Add DeleteReply filetest cases for realm owners
if !isRealmOwner {
assertBoardIsNotFrozen(board)
assertThreadIsNotFrozen(thread)
assertReplyIsVisible(reply)
}
deleteReply := func() {
// Soft delete comment/reply by changing its body when
// it contains replies, otherwise hard delete it.
if reply.Replies.Size() > 0 {
reply.Body = "⚠ This comment has been deleted"
reply.UpdatedAt = time.Now()
} else {
// Remove reply from the flat thread index.
meta := thread.Meta.(*ThreadMeta)
reply, removed := meta.AllReplies.Remove(replyID)
if !removed {
panic("reply not found")
}
// Remove reply from its parent's direct-children list too. A
// direct thread reply's parent is the thread itself; a nested
// reply's parent is another reply (resolved via the flat index).
// Missing the thread-parent case left a ghost in thread.Replies
// (rendered in the threaded view, with a stale reply count).
if reply.ParentID == thread.ID {
thread.Replies.Remove(replyID)
} else if parent, found := meta.AllReplies.Get(reply.ParentID); found {
parent.Replies.Remove(replyID)
}
}
chain.Emit(
"ReplyDeleted",
"caller", caller.String(),
"boardID", board.ID.String(),
"threadID", thread.ID.String(),
"replyID", reply.ID.String(),
)
}
// Reply can be directly deleted by user that created it.
// It can also be deleted by realm owners, to be able to delete inappropriate content.
// TODO: Discuss and decide if realm owners should be able to delete replies.
if isRealmOwner || caller == reply.Creator {
deleteReply()
return
}
args := boards.Args{caller, board.ID, thread.ID, reply.ID}
board.Permissions.WithPermission(caller, PermissionReplyDelete, args, func() {
assertRealmIsNotLocked()
deleteReply()
})
}
// EditThread updates the title and body of a thread.
//
// Threads can be updated by the users who created them or otherwise by users with special permissions.
func EditThread(cur realm, boardID, threadID boards.ID, title, body string) {
assertRealmIsNotLocked()
title = strings.TrimSpace(title)
assertTitleIsValid(title)
assertThreadBodyIsValid(body)
board := mustGetBoard(boardID)
assertBoardIsNotFrozen(board)
caller := cur.Previous().Address()
assertUserIsNotBanned(boardID, caller)
thread := mustGetThread(board, threadID)
assertThreadIsNotFrozen(thread)
body = strings.TrimSpace(body)
if !boards.IsRepost(thread) {
assertBodyIsNotEmpty(body)
}
editThread := func() {
thread.Title = title
thread.Body = body
thread.UpdatedAt = time.Now()
chain.Emit(
"ThreadEdited",
"caller", caller.String(),
"boardID", board.ID.String(),
"threadID", thread.ID.String(),
"title", title,
)
}
if caller == thread.Creator {
editThread()
return
}
args := boards.Args{caller, board.ID, thread.ID, title, body}
board.Permissions.WithPermission(caller, PermissionThreadEdit, args, func() {
assertRealmIsNotLocked()
editThread()
})
}
// EditReply updates the body of a comment or reply.
//
// Replies can be updated only by the users who created them.
func EditReply(cur realm, boardID, threadID, replyID boards.ID, body string) {
assertRealmIsNotLocked()
body = strings.TrimSpace(body)
assertReplyBodyIsValid(body)
board := mustGetBoard(boardID)
assertBoardIsNotFrozen(board)
caller := cur.Previous().Address()
assertUserIsNotBanned(boardID, caller)
thread := mustGetThread(board, threadID)
assertThreadIsNotFrozen(thread)
reply := mustGetReply(thread, replyID)
assertReplyIsVisible(reply)
if caller != reply.Creator {
panic("only the reply creator is allowed to edit it")
}
reply.Body = body
reply.UpdatedAt = time.Now()
chain.Emit(
"ReplyEdited",
"caller", caller.String(),
"boardID", board.ID.String(),
"threadID", thread.ID.String(),
"replyID", reply.ID.String(),
"body", body,
)
}
// RemoveMember removes a member from the realm or a board.
//
// Board ID is only required when removing a member from board.
func RemoveMember(cur realm, boardID boards.ID, member address) {
assertMembersUpdateIsEnabled(boardID)
assertMemberAddressIsValid(member)
perms := mustGetPermissions(boardID)
origin := unsafe.OriginCaller()
caller := cur.Previous().Address()
removeMember := func() {
if !perms.RemoveUser(member) {
panic("member not found")
}
chain.Emit(
"MemberRemoved",
"caller", caller.String(),
"origin", origin.String(), // When origin and caller match it means self removal
"boardID", boardID.String(),
"member", member.String(),
)
}
// Members can remove themselves without permission
if origin == member {
removeMember()
return
}
args := boards.Args{boardID, member}
perms.WithPermission(caller, PermissionMemberRemove, args, func() {
assertMembersUpdateIsEnabled(boardID)
removeMember()
})
}
// IsMember checks if a user is a member of the realm or a board.
//
// Board ID is only required when checking if a user is a member of a board.
func IsMember(boardID boards.ID, user address) bool {
assertUserAddressIsValid(user)
if boardID != 0 {
board := mustGetBoard(boardID)
assertBoardIsNotFrozen(board)
}
perms := mustGetPermissions(boardID)
return perms.HasUser(user)
}
// HasMemberRole checks if a realm or board member has a specific role assigned.
//
// Board ID is only required when checking a member of a board.
func HasMemberRole(boardID boards.ID, member address, role boards.Role) bool {
assertMemberAddressIsValid(member)
if boardID != 0 {
board := mustGetBoard(boardID)
assertBoardIsNotFrozen(board)
}
perms := mustGetPermissions(boardID)
return perms.HasRole(member, role)
}
// ChangeMemberRole changes the role of a realm or board member.
//
// Board ID is only required when changing the role for a member of a board.
func ChangeMemberRole(cur realm, boardID boards.ID, member address, role boards.Role) {
assertMemberAddressIsValid(member)
assertMembersUpdateIsEnabled(boardID)
if role == "" {
role = RoleGuest
}
perms := mustGetPermissions(boardID)
caller := cur.Previous().Address()
args := boards.Args{caller, boardID, member, role}
perms.WithPermission(caller, PermissionRoleChange, args, func() {
assertMembersUpdateIsEnabled(boardID)
perms.SetUserRoles(member, role)
chain.Emit(
"RoleChanged",
"caller", caller.String(),
"boardID", boardID.String(),
"member", member.String(),
"newRole", string(role),
)
})
}
func assertMemberAddressIsValid(member address) {
if !member.IsValid() {
panic("invalid member address: " + member.String())
}
}
func assertUserAddressIsValid(user address) {
if !user.IsValid() {
panic("invalid user address: " + user.String())
}
}
func assertBoardExists(id boards.ID) {
if id == 0 { // ID zero is used to refer to the realm
return
}
if _, found := gBoards.Get(id); !found {
panic("board not found: " + id.String())
}
}
func assertBoardIsNotFrozen(b *boards.Board) {
if b.Readonly {
panic("board is frozen")
}
}
func assertIsValidBoardName(name string) {
size := len(name)
if size == 0 {
panic("board name is empty")
}
if size < 3 {
panic("board name is too short, minimum length is 3 characters")
}
if size > MaxBoardNameLength {
n := strconv.Itoa(MaxBoardNameLength)
panic("board name is too long, maximum allowed is " + n + " characters")
}
if !reBoardName.MatchString(name) {
panic("board name must start with a letter and have letters, numbers, \"-\" and \"_\"")
}
}
func assertThreadIsNotFrozen(t *boards.Post) {
if t.Readonly {
panic("thread is frozen")
}
}
func assertNameIsNotEmpty(name string) {
if name == "" {
panic("name is empty")
}
}
func assertTitleIsValid(title string) {
if title == "" {
panic("title is empty")
}
if len(title) > MaxThreadTitleLength {
n := strconv.Itoa(MaxThreadTitleLength)
panic("title is too long, maximum allowed is " + n + " characters")
}
}
func assertBodyIsNotEmpty(body string) {
if body == "" {
panic("body is empty")
}
}
func assertBoardNameNotExists(name string) {
name = strings.ToLower(name)
if _, found := gBoards.GetByName(name); found {
panic("board already exists")
}
}
func assertThreadExists(b *boards.Board, threadID boards.ID) {
if _, found := getThread(b, threadID); !found {
panic("thread not found: " + threadID.String())
}
}
func assertReplyExists(thread *boards.Post, replyID boards.ID) {
if _, found := getReply(thread, replyID); !found {
panic("reply not found: " + replyID.String())
}
}
func assertThreadIsVisible(thread *boards.Post) {
if thread.Hidden {
panic("thread is hidden")
}
}
func assertReplyIsVisible(thread *boards.Post) {
if thread.Hidden {
panic("reply is hidden")
}
}
func assertThreadBodyIsValid(body string) {
if len(body) > MaxThreadBodyLength {
n := strconv.Itoa(MaxThreadBodyLength)
panic("thread body is too long, maximum allowed is " + n + " characters")
}
}
func assertReplyBodyIsValid(body string) {
assertBodyIsNotEmpty(body)
if len(body) > MaxReplyLength {
n := strconv.Itoa(MaxReplyLength)
panic("reply is too long, maximum allowed is " + n + " characters")
}
// No markdown-structure or gno-form blacklist here: reply bodies
// render inside a <gno-foreign> sandbox (see indentForeignBody),
// which contains block structure and omits forms at render time.
}
func assertMembersUpdateIsEnabled(boardID boards.ID) {
if boardID != 0 {
assertRealmIsNotLocked()
} else {
assertRealmMembersAreNotLocked()
}
}
public_ban.gno
package boards2
import (
"chain"
"strings"
"time"
"gno.land/p/gnoland/boards/v0"
"gno.land/p/nt/bptree/v0"
)
// Constants for different banning periods.
const (
BanDay = uint(24)
BanWeek = BanDay * 7
BanYear = BanDay * 365
)
// Ban bans a user from a board for a period of time.
// Only invited guest members and external users can be banned.
// Banning board owners, admins and moderators is not allowed.
func Ban(cur realm, boardID boards.ID, user address, hours uint, reason string) {
assertAddressIsValid(user)
if hours == 0 {
panic("ban period in hours is required")
}
reason = strings.TrimSpace(reason)
if reason == "" {
panic("ban reason is required")
}
board := mustGetBoard(boardID)
caller := cur.Previous().Address()
until := time.Now().Add(time.Minute * 60 * time.Duration(hours))
args := boards.Args{boardID, user, until, reason}
board.Permissions.WithPermission(caller, PermissionUserBan, args, func() {
// When banning invited members make sure they are guests, otherwise
// disallow banning. Only guest or external users can be banned.
if board.Permissions.HasUser(user) && !board.Permissions.HasRole(user, RoleGuest) {
panic("owner, admin and moderator banning is not allowed")
}
banned, found := getBannedUsers(boardID)
if !found {
banned = bptree.NewBPTree32()
gBannedUsers.Set(boardID.Key(), banned)
}
banned.Set(user.String(), until)
chain.Emit(
"UserBanned",
"bannedBy", caller.String(),
"boardID", board.ID.String(),
"user", user.String(),
"until", until.Format(time.RFC3339),
"reason", reason,
)
})
}
// Unban unbans a user from a board.
func Unban(cur realm, boardID boards.ID, user address, reason string) {
assertAddressIsValid(user)
board := mustGetBoard(boardID)
caller := cur.Previous().Address()
args := boards.Args{boardID, user, reason}
board.Permissions.WithPermission(caller, PermissionUserUnban, args, func() {
banned, found := getBannedUsers(boardID)
if !found || !banned.Has(user.String()) {
panic("user is not banned")
}
banned.Remove(user.String())
chain.Emit(
"UserUnbanned",
"bannedBy", caller.String(),
"boardID", board.ID.String(),
"user", user.String(),
"reason", reason,
)
})
}
// IsBanned checks if a user is banned from a board.
func IsBanned(boardID boards.ID, user address) bool {
banned, found := getBannedUsers(boardID)
return found && banned.Has(user.String())
}
func assertAddressIsValid(addr address) {
if !addr.IsValid() {
panic("invalid address: " + addr.String())
}
}
func assertUserIsNotBanned(boardID boards.ID, user address) {
banned, found := getBannedUsers(boardID)
if !found {
return
}
v := banned.Get(user.String())
if v == nil {
return
}
until := v.(time.Time)
if time.Now().Before(until) {
panic(user.String() + " is banned until " + until.Format(dateFormat))
}
}
public_flag.gno
package boards2
import (
"chain"
"strconv"
"strings"
"gno.land/p/gnoland/boards/v0"
)
// SetFlaggingThreshold sets the number of flags required to hide a thread or comment.
//
// Threshold is only applicable within the board where it's setted.
func SetFlaggingThreshold(cur realm, boardID boards.ID, threshold int) {
if threshold < 1 {
panic("invalid flagging threshold")
}
assertRealmIsNotLocked()
board := mustGetBoard(boardID)
assertBoardIsNotFrozen(board)
caller := cur.Previous().Address()
args := boards.Args{board.ID, threshold}
board.Permissions.WithPermission(caller, PermissionBoardFlaggingUpdate, args, func() {
assertRealmIsNotLocked()
gFlaggingThresholds.Set(boardID.String(), threshold)
chain.Emit(
"FlaggingThresholdUpdated",
"caller", caller.String(),
"boardID", board.ID.String(),
"threshold", strconv.Itoa(threshold),
)
})
}
// GetFlaggingThreshold returns the number of flags required to hide a thread or comment within a board.
func GetFlaggingThreshold(boardID boards.ID) int {
assertBoardExists(boardID)
return getFlaggingThreshold(boardID)
}
// FlagThread adds a new flag to a thread.
//
// Flagging requires special permissions and hides the thread when
// the number of flags reaches a pre-defined flagging threshold.
func FlagThread(cur realm, boardID, threadID boards.ID, reason string) {
reason = strings.TrimSpace(reason)
if reason == "" {
panic("flagging reason is required")
}
caller := cur.Previous().Address()
board := mustGetBoard(boardID)
isRealmOwner := gPerms.HasRole(caller, RoleOwner)
if !isRealmOwner {
assertRealmIsNotLocked()
assertBoardIsNotFrozen(board)
}
thread, found := getThread(board, threadID)
if !found {
panic("thread not found")
}
if thread.Hidden {
panic("flagging hidden threads is not allowed")
}
flagThread := func() {
if thread.Hidden {
panic("flagged thread is already hidden")
}
// Hide thread when flagging threshold is reached.
// Realm owners can hide with a single flag.
hide := flagItem(thread, caller, reason, getFlaggingThreshold(board.ID))
if hide || isRealmOwner {
// Remove thread from the list of visible threads
thread, removed := board.Threads.Remove(threadID)
if !removed {
panic("thread not found")
}
// Mark thread as hidden to avoid rendering content
thread.Hidden = true
// Keep track of hidden the thread to be able to restore it after moderation disputes
meta := board.Meta.(*BoardMeta)
meta.HiddenThreads.Add(thread)
}
chain.Emit(
"ThreadFlagged",
"caller", caller.String(),
"boardID", board.ID.String(),
"threadID", thread.ID.String(),
"reason", reason,
)
}
// Realm owners should be able to flag without permissions even when board is frozen
if isRealmOwner {
flagThread()
return
}
args := boards.Args{caller, board.ID, thread.ID, reason}
board.Permissions.WithPermission(caller, PermissionThreadFlag, args, func() {
flagThread()
})
}
// FlagReply adds a new flag to a comment or reply.
//
// Flagging requires special permissions and hides the comment or reply
// when the number of flags reaches a pre-defined flagging threshold.
func FlagReply(cur realm, boardID, threadID, replyID boards.ID, reason string) {
reason = strings.TrimSpace(reason)
if reason == "" {
panic("flagging reason is required")
}
caller := cur.Previous().Address()
board := mustGetBoard(boardID)
isRealmOwner := gPerms.HasRole(caller, RoleOwner)
if !isRealmOwner {
assertRealmIsNotLocked()
assertBoardIsNotFrozen(board)
}
thread := mustGetThread(board, threadID)
reply := mustGetReply(thread, replyID)
if reply.Hidden {
panic("flagging hidden comments or replies is not allowed")
}
flagReply := func() {
if reply.Hidden {
panic("flagged comment or reply is already hidden")
}
hide := flagItem(reply, caller, reason, getFlaggingThreshold(board.ID))
if hide || isRealmOwner {
reply.Hidden = true
}
chain.Emit(
"ReplyFlagged",
"caller", caller.String(),
"boardID", board.ID.String(),
"threadID", thread.ID.String(),
"replyID", reply.ID.String(),
"reason", reason,
)
}
// Realm owners should be able to flag without permissions even when board is frozen
if isRealmOwner {
flagReply()
return
}
args := boards.Args{caller, board.ID, thread.ID, reply.ID, reason}
board.Permissions.WithPermission(caller, PermissionReplyFlag, args, func() {
flagReply()
})
}
public_freeze.gno
package boards2
import (
"chain"
"strconv"
"gno.land/p/gnoland/boards/v0"
)
// FreezeBoard freezes a board so no more threads and comments can be created or modified.
func FreezeBoard(cur realm, boardID boards.ID) {
setBoardReadonly(0, cur, boardID, true)
}
// UnfreezeBoard removes frozen status from a board.
func UnfreezeBoard(cur realm, boardID boards.ID) {
setBoardReadonly(0, cur, boardID, false)
}
// IsBoardFrozen checks if a board has been frozen.
func IsBoardFrozen(boardID boards.ID) bool {
board := mustGetBoard(boardID)
return board.Readonly
}
// FreezeThread freezes a thread so thread cannot be replied, modified or deleted.
//
// Fails if board is frozen.
func FreezeThread(cur realm, boardID, threadID boards.ID) {
setThreadReadonly(0, cur, boardID, threadID, true)
}
// UnfreezeThread removes frozen status from a thread.
//
// Fails if board is frozen.
func UnfreezeThread(cur realm, boardID, threadID boards.ID) {
setThreadReadonly(0, cur, boardID, threadID, false)
}
// IsThreadFrozen checks if a thread has been frozen.
//
// Returns true if board is frozen.
func IsThreadFrozen(boardID, threadID boards.ID) bool {
board := mustGetBoard(boardID)
thread := mustGetThread(board, threadID)
return board.Readonly || thread.Readonly
}
func setBoardReadonly(_ int, rlm realm, boardID boards.ID, readonly bool) {
if !rlm.IsCurrent() {
panic("unauthorized: rlm is not the caller's live cur")
}
assertRealmIsNotLocked()
board := mustGetBoard(boardID)
if readonly {
assertBoardIsNotFrozen(board)
}
caller := rlm.Previous().Address()
args := boards.Args{caller, board.ID, readonly}
board.Permissions.WithPermission(caller, PermissionBoardFreeze, args, func() {
assertRealmIsNotLocked()
board.Readonly = readonly
chain.Emit(
"BoardFreeze",
"caller", caller.String(),
"boardID", board.ID.String(),
"frozen", strconv.FormatBool(readonly),
)
})
}
func setThreadReadonly(_ int, rlm realm, boardID, threadID boards.ID, readonly bool) {
if !rlm.IsCurrent() {
panic("unauthorized: rlm is not the caller's live cur")
}
assertRealmIsNotLocked()
board := mustGetBoard(boardID)
assertBoardIsNotFrozen(board)
thread := mustGetThread(board, threadID)
if readonly {
assertThreadIsNotFrozen(thread)
}
caller := rlm.Previous().Address()
args := boards.Args{caller, board.ID, thread.ID, readonly}
board.Permissions.WithPermission(caller, PermissionThreadFreeze, args, func() {
assertRealmIsNotLocked()
thread.Readonly = readonly
chain.Emit(
"ThreadFreeze",
"caller", caller.String(),
"boardID", board.ID.String(),
"threadID", thread.ID.String(),
"frozen", strconv.FormatBool(readonly),
)
})
}
public_invite.gno
package boards2
import (
"chain"
"strings"
"time"
"gno.land/p/gnoland/boards/v0"
"gno.land/p/nt/bptree/v0"
)
// Invite contains a user invitation.
type Invite struct {
// User is the user to invite.
User address
// Role is the optional role to assign to the user.
Role boards.Role
}
// InviteMember adds a member to the realm or to a board.
//
// A role can optionally be specified to be assigned to the new member.
func InviteMember(cur realm, boardID boards.ID, user address, role boards.Role) {
inviteMembers(0, cur, boardID, Invite{
User: user,
Role: role,
})
}
// InviteMembers adds one or more members to the realm or to a board.
//
// Board ID is only required when inviting a member to a specific board.
func InviteMembers(cur realm, boardID boards.ID, invites ...Invite) {
inviteMembers(0, cur, boardID, invites...)
}
// RequestInvite request to be invited to a board.
func RequestInvite(cur realm, boardID boards.ID) {
assertMembersUpdateIsEnabled(boardID)
if !cur.Previous().IsUser() {
panic("caller must be user")
}
// TODO: Request a fee (returned on accept) or registered user to avoid spam?
// WARNING: if a fee is added via unsafe.OriginSend(), the guard above
// must be tightened to IsUserCall() — IsUser() accepts maketx-run
// ephemeral realms which can consume the origin-send envelope before
// calling us, bypassing the fee. See
// docs/resources/effective-gno.md#verifying-inbound-coin-payments.
// TODO: Make open invite requests optional (per board)
board := mustGetBoard(boardID)
user := cur.Previous().Address()
if board.Permissions.HasUser(user) {
panic("caller is already a member")
}
invitee := user.String()
requests, found := getInviteRequests(boardID)
if !found {
requests = bptree.NewBPTree32()
requests.Set(invitee, time.Now())
gInviteRequests.Set(boardID.Key(), requests)
return
}
if requests.Has(invitee) {
panic("invite request already exists")
}
requests.Set(invitee, time.Now())
}
// AcceptInvite accepts a board invite request.
func AcceptInvite(cur realm, boardID boards.ID, user address) {
assertMembersUpdateIsEnabled(boardID)
assertInviteRequestExists(boardID, user)
board := mustGetBoard(boardID)
if board.Permissions.HasUser(user) {
panic("user is already a member")
}
caller := cur.Previous().Address()
invite := Invite{
User: user,
Role: RoleGuest,
}
args := boards.Args{caller, boardID, []Invite{invite}}
board.Permissions.WithPermission(caller, PermissionMemberInvite, args, func() {
assertMembersUpdateIsEnabled(boardID)
invitee := user.String()
requests, found := getInviteRequests(boardID)
if !found || !requests.Has(invitee) {
panic("invite request not found")
}
if board.Permissions.HasUser(user) {
panic("user is already a member")
}
board.Permissions.SetUserRoles(user)
requests.Remove(invitee)
chain.Emit(
"MembersInvited",
"invitedBy", caller.String(),
"boardID", board.ID.String(),
"members", user.String()+":"+string(RoleGuest), // TODO: Support optional role assign
)
})
}
// RevokeInvite revokes a board invite request.
func RevokeInvite(cur realm, boardID boards.ID, user address) {
assertInviteRequestExists(boardID, user)
board := mustGetBoard(boardID)
caller := cur.Previous().Address()
args := boards.Args{boardID, user, RoleGuest}
board.Permissions.WithPermission(caller, PermissionMemberInviteRevoke, args, func() {
invitee := user.String()
requests, found := getInviteRequests(boardID)
if !found || !requests.Has(invitee) {
panic("invite request not found")
}
requests.Remove(invitee)
chain.Emit(
"InviteRevoked",
"revokedBy", caller.String(),
"boardID", board.ID.String(),
"user", user.String(),
)
})
}
func inviteMembers(_ int, rlm realm, boardID boards.ID, invites ...Invite) {
if !rlm.IsCurrent() {
panic("unauthorized: rlm is not the caller's live cur")
}
if len(invites) == 0 {
panic("one or more user invites are required")
}
assertMembersUpdateIsEnabled(boardID)
assertNoDuplicatedInvites(invites)
perms := mustGetPermissions(boardID)
caller := rlm.Previous().Address()
args := boards.Args{caller, boardID, invites}
perms.WithPermission(caller, PermissionMemberInvite, args, func() {
assertMembersUpdateIsEnabled(boardID)
users := make([]string, len(invites))
for _, v := range invites {
assertMemberAddressIsValid(v.User)
if perms.HasUser(v.User) {
panic("user is already a member: " + v.User.String())
}
// NOTE: Permissions implementation should check that role is valid
perms.SetUserRoles(v.User, v.Role)
users = append(users, v.User.String()+":"+string(v.Role))
}
chain.Emit(
"MembersInvited",
"invitedBy", caller.String(),
"boardID", boardID.String(),
"members", strings.Join(users, ","),
)
})
}
func assertInviteRequestExists(boardID boards.ID, user address) {
invitee := user.String()
requests, found := getInviteRequests(boardID)
if !found || !requests.Has(invitee) {
panic("invite request not found")
}
}
func assertNoDuplicatedInvites(invites []Invite) {
if len(invites) == 1 {
return
}
seen := make(map[address]struct{}, len(invites))
for _, v := range invites {
if _, found := seen[v.User]; found {
panic("duplicated invite: " + v.User.String())
}
seen[v.User] = struct{}{}
}
}
public_lock.gno
package boards2
import (
"chain"
"strconv"
"gno.land/p/gnoland/boards/v0"
)
// LockRealm locks the realm making it readonly.
//
// WARNING: Realm can't be unlocked once locked.
//
// Realm can also be locked without locking realm members.
// Realm members can be locked when locking the realm or afterwards.
// This is relevant for two reasons, one so that members can be modified after the lock.
// The other is for realm owners, who can delete threads and comments after the lock.
func LockRealm(cur realm, lockRealmMembers bool) {
assertRealmMembersAreNotLocked()
// If realm members are not being locked assert that realm is not locked.
// Members can be locked after locking the realm, in a second `LockRealm` call.
if !lockRealmMembers {
assertRealmIsNotLocked()
}
caller := cur.Previous().Address()
gPerms.WithPermission(caller, PermissionRealmLock, boards.Args{}, func() {
gLocked.realm = true
gLocked.realmMembers = lockRealmMembers
chain.Emit(
"RealmLocked",
"caller", caller.String(),
"lockRealmMembers", strconv.FormatBool(lockRealmMembers),
)
})
}
// IsRealmLocked checks if boards realm has been locked.
func IsRealmLocked() bool {
return gLocked.realm
}
// AreRealmMembersLocked checks if realm members have been locked.
func AreRealmMembersLocked() bool {
return gLocked.realmMembers
}
func assertRealmIsNotLocked() { // TODO: Add filtests for locked realm case to all public functions
if gLocked.realm {
panic("realm is locked")
}
}
func assertRealmMembersAreNotLocked() { // TODO: Add filtests for locked members case to all public member functions
if gLocked.realmMembers {
panic("realm and members are locked")
}
}
render.gno
package boards2
import (
"net/url"
"strconv"
"strings"
"time"
"gno.land/p/gnoland/boards/v0"
"gno.land/p/jeronimoalbi/mdform/v0"
"gno.land/p/jeronimoalbi/pager/v0"
"gno.land/p/leon/svgbtn/v0"
"gno.land/p/moul/md/v0"
"gno.land/p/moul/mdtable/v0"
"gno.land/p/nt/markdown/foreign/v0"
"gno.land/p/nt/mux/v0"
)
const (
pageSizeDefault = 6
pageSizeReplies = 10
// pageSizeFlat is the page size of the flat "all comments" view (?flat=1).
// Each comment renders exactly one <gno-foreign> block (no recursion); with
// the OP (and any repost-source body) the per-page total stays well under
// maxRenderedBodies, so a flat page can't hit the render cap.
pageSizeFlat = 50
)
// maxRenderedBodies caps user bodies wrapped in <gno-foreign> per page
// render, kept a margin under gnoweb's per-render foreign-block cap
// (foreign.MaxBlocksPerRender, sourced from chain/markdown so it can't
// drift from the renderer). On reaching it the tree stops descending
// and shows a truncation notice instead of letting the renderer blank
// comments past the cap. The margin absorbs the OP, repost source
// bodies, and chrome.
//
// Computed lazily (a func, not a package-level var) so it tracks the
// native cap across chain upgrades: a var initializer runs once at
// realm-init and persists, freezing a stale value if the underlying
// MaxBlocksPerRender ever changes; recomputing per render re-reads it.
func maxRenderedBodies() int {
return foreign.MaxBlocksPerRender() - 10
}
// sortToggleLink builds the asc/desc sort-toggle link for path. The label
// names the DESTINATION order (what you get by clicking), not the order you're
// currently viewing, and ?page= is reset since page N of one order is a
// different slice in the other. It reports whether the CURRENT order is
// descending, so callers can drive their own (signed-count or reverse-iterate)
// pagination. Other query params (e.g. flat=1) are preserved.
func sortToggleLink(path string) (link string, desc bool) {
r := parseRealmPath(path)
desc = r.Query.Get("order") == "desc"
r.Query.Del("page")
if desc {
r.Query.Set("order", "asc")
return md.Link("oldest first", r.String()), true
}
r.Query.Set("order", "desc")
return md.Link("newest first", r.String()), false
}
const menuManageBoard = "manageBoard"
var (
createBoardURI = gRealmPath + ":create-board"
adminUsersURI = gRealmPath + ":admin-users"
helpURI = gRealmPath + ":help"
)
func Render(path string) string {
var (
b strings.Builder
router = mux.NewRouter()
)
router.HandleFunc("", renderBoardsList)
router.HandleFunc("help", renderHelp)
router.HandleFunc("admin-users", renderMembers)
router.HandleFunc("create-board", renderCreateBoard)
router.HandleFunc("{board}", renderBoard)
router.HandleFunc("{board}/members", renderMembers)
router.HandleFunc("{board}/invites", renderInvites)
router.HandleFunc("{board}/banned-users", renderBannedUsers)
router.HandleFunc("{board}/create-thread", renderCreateThread)
router.HandleFunc("{board}/invite-member", renderInviteMember)
router.HandleFunc("{board}/{thread}", renderThread)
router.HandleFunc("{board}/{thread}/flag", renderFlagPost)
router.HandleFunc("{board}/{thread}/flagging-reasons", renderFlaggingReasonsPost)
router.HandleFunc("{board}/{thread}/reply", renderReplyPost)
router.HandleFunc("{board}/{thread}/edit", renderEditThread)
router.HandleFunc("{board}/{thread}/repost", renderRepostThread)
router.HandleFunc("{board}/{thread}/{reply}", renderReply)
router.HandleFunc("{board}/{thread}/{reply}/flag", renderFlagPost)
router.HandleFunc("{board}/{thread}/{reply}/flagging-reasons", renderFlaggingReasonsPost)
router.HandleFunc("{board}/{thread}/{reply}/reply", renderReplyPost)
router.HandleFunc("{board}/{thread}/{reply}/edit", renderEditReply)
router.NotFoundHandler = func(res *mux.ResponseWriter, _ *mux.Request) {
res.Write(md.Blockquote("Path not found"))
}
// Render common realm header before resolving render path
if Notice != "" {
b.WriteString(infoAlert("Notice", Notice))
}
// Render view for current path
b.WriteString(router.Render(path))
return b.String()
}
func renderHelp(res *mux.ResponseWriter, _ *mux.Request) {
res.Write(md.H1("Boards Help"))
if Help != "" {
res.Write(Help)
return
}
link := RealmLink.Call("SetHelp", "content", "")
res.Write(md.H3("Help content has not been uploaded"))
res.Write("Do you want to " + md.Link("upload boards help", link) + "?")
}
func renderBoardsList(res *mux.ResponseWriter, req *mux.Request) {
res.Write(md.H1("Boards"))
renderBoardListMenu(res, req)
res.Write(md.HorizontalRule())
if gListedBoardsByID.Size() == 0 {
res.Write(md.H3("Currently there are no boards"))
res.Write("Be the first to " + md.Link("create a new board", createBoardURI) + "!")
return
}
p := newClampedPager(req.RawPath, gListedBoardsByID.Size(), pageSizeDefault)
render := func(_ string, v any) bool {
board := v.(*boards.Board)
userLink := userLink(board.Creator)
date := board.CreatedAt.Format(dateFormat)
res.Write(md.H6(md.Link(board.Name, makeBoardURI(board))))
res.Write("Created by " + userLink + " on " + date + ", #" + board.ID.String() + " \n")
status := strconv.Itoa(board.Threads.Size()) + " threads"
if board.Readonly {
status += ", read-only"
}
res.Write(md.Bold(status) + "\n\n")
return false
}
res.Write("Sort by: ")
link, desc := sortToggleLink(req.RawPath)
res.Write(link + "\n\n")
if desc {
gListedBoardsByID.ReverseIterateByOffset(p.Offset(), p.PageSize(), render)
} else {
gListedBoardsByID.IterateByOffset(p.Offset(), p.PageSize(), render)
}
if p.HasPages() {
res.Write(md.HorizontalRule())
res.Write(pager.Picker(p))
}
}
func renderBoardListMenu(res *mux.ResponseWriter, req *mux.Request) {
res.Write(md.Link("Create Board", createBoardURI))
res.Write(" • ")
res.Write(md.Link("List Admin Users", adminUsersURI))
res.Write(" • ")
res.Write(md.Link("Help", helpURI))
res.Write("\n\n")
}
func renderCreateBoard(res *mux.ResponseWriter, _ *mux.Request) {
form := mdform.New("exec", "CreateBoard")
form.Input(
"name",
"placeholder", "Board name",
"required", "true",
)
form.Radio(
"listed",
"true",
"checked", "true",
"description", "Should board be publicly listed?",
)
form.Radio(
"listed",
"false",
)
form.Radio(
"open",
"true",
"description", "Should anyone be allowed to create threads and comments?",
)
form.Radio(
"open",
"false",
"checked", "true",
)
res.Write(md.H1("Boards: Create Board"))
res.Write(md.Link("← Back to boards", gRealmPath) + "\n\n")
res.Write(
md.Paragraph(
"Boards are by default listed by the realm but they can optionally " +
"be created so they are only found by their URL.",
),
)
res.Write(
md.Paragraph(
"They can also be created to be open so anyone is allowed to create " +
"new threads and also to comment on any thread within the open board.",
),
)
res.Write(form.String())
res.Write("\n\n**Done?** " + svgbtn.ButtonWithRadius(136, 32, 4, "#E2E2E2", "#54595D", "Return to boards", gRealmPath) + "\n")
}
func renderMembers(res *mux.ResponseWriter, req *mux.Request) {
boardID := boards.ID(0)
perms := gPerms
name := req.GetVar("board")
if name != "" {
board, found := gBoards.GetByName(name)
if !found {
res.Write(md.H3("Board not found"))
return
}
boardID = board.ID
perms = board.Permissions
res.Write(md.H1(board.Name + " Members"))
res.Write(md.H3("These are the board members"))
} else {
res.Write(md.H1("Admin Users"))
res.Write(md.H3("These are the admin users of the realm"))
}
// Create a pager with a small page size to reduce
// the number of username lookups per page.
p := newClampedPager(req.RawPath, perms.UsersCount(), pageSizeDefault)
table := mdtable.Table{
Headers: []string{"Member", "Role", "Actions"},
}
perms.IterateUsers(p.Offset(), p.PageSize(), func(u boards.User) bool {
actions := []string{
md.Link("remove", RealmLink.Call(
"RemoveMember",
"boardID", boardID.String(),
"member", u.Address.String(),
)),
md.Link("change role", RealmLink.Call(
"ChangeMemberRole",
"boardID", boardID.String(),
"member", u.Address.String(),
"role", "",
)),
}
table.Append([]string{
userLink(u.Address),
rolesToString(u.Roles),
strings.Join(actions, " • "),
})
return false
})
res.Write(table.String())
if p.HasPages() {
res.Write("\n" + pager.Picker(p))
}
}
func renderInvites(res *mux.ResponseWriter, req *mux.Request) {
name := req.GetVar("board")
board, found := gBoards.GetByName(name)
if !found {
res.Write(md.H3("Board not found"))
return
}
res.Write(md.H1(board.Name + " Invite Requests"))
requests, found := getInviteRequests(board.ID)
if !found || requests.Size() == 0 {
res.Write(md.H3("Board has no invite requests"))
return
}
p := newClampedPager(req.RawPath, requests.Size(), pageSizeDefault)
table := mdtable.Table{
Headers: []string{"User", "Request Date", "Actions"},
}
res.Write(md.H3("These users have requested to be invited to the board"))
requests.ReverseIterateByOffset(p.Offset(), p.PageSize(), func(addr string, v any) bool {
actions := []string{
md.Link("accept", RealmLink.Call(
"AcceptInvite",
"boardID", board.ID.String(),
"user", addr,
)),
md.Link("revoke", RealmLink.Call(
"RevokeInvite",
"boardID", board.ID.String(),
"user", addr,
)),
}
table.Append([]string{
userLink(address(addr)),
v.(time.Time).Format(dateFormat),
strings.Join(actions, " • "),
})
return false
})
res.Write(table.String())
if p.HasPages() {
res.Write("\n" + pager.Picker(p))
}
}
func renderBannedUsers(res *mux.ResponseWriter, req *mux.Request) {
name := req.GetVar("board")
board, found := gBoards.GetByName(name)
if !found {
res.Write(md.H3("Board not found"))
return
}
res.Write(md.H1(board.Name + " Banned Users"))
banned, found := getBannedUsers(board.ID)
if !found || banned.Size() == 0 {
res.Write(md.H3("Board has no banned users"))
return
}
p := newClampedPager(req.RawPath, banned.Size(), pageSizeDefault)
table := mdtable.Table{
Headers: []string{"User", "Banned Until", "Actions"},
}
res.Write(md.H3("These users have been banned from the board"))
banned.ReverseIterateByOffset(p.Offset(), p.PageSize(), func(addr string, v any) bool {
table.Append([]string{
userLink(address(addr)),
v.(time.Time).Format(dateFormat),
md.Link("unban", RealmLink.Call(
"Unban",
"boardID", board.ID.String(),
"user", addr,
"reason", "",
)),
})
return false
})
res.Write(table.String())
if p.HasPages() {
res.Write("\n" + pager.Picker(p))
}
}
func infoAlert(title, msg string) string {
header := strings.TrimSpace("[!INFO] " + title)
return md.Blockquote(header + "\n" + msg)
}
func rolesToString(roles []boards.Role) string {
if len(roles) == 0 {
return ""
}
names := make([]string, len(roles))
for i, r := range roles {
names[i] = string(r)
}
return strings.Join(names, ", ")
}
func menuURL(name string) string {
// TODO: Menu URL works because no other GET arguments are being used
return "?menu=" + name
}
func getCurrentMenu(rawURL string) string {
_, rawQuery, found := strings.Cut(rawURL, "?")
if !found {
return ""
}
query, _ := url.ParseQuery(rawQuery)
return query.Get("menu")
}
render_board.gno
package boards2
import (
"strings"
"gno.land/p/gnoland/boards/v0"
"gno.land/p/jeronimoalbi/mdform/v0"
"gno.land/p/jeronimoalbi/pager/v0"
"gno.land/p/moul/md/v0"
"gno.land/p/nt/mdalert/v0"
"gno.land/p/nt/mux/v0"
)
func renderBoard(res *mux.ResponseWriter, req *mux.Request) {
name := req.GetVar("board")
board, found := gBoards.GetByName(name)
if !found {
res.Write(md.H3("The board you are looking for does not exist"))
res.Write("Do you want to " + md.Link("create a new board", createBoardURI) + "?")
return
}
creatorLink := userLink(board.Creator)
date := board.CreatedAt.Format(dateFormat)
res.Write(md.H1(md.Link("Boards", gRealmPath) + " › " + board.Name))
if board.Readonly {
res.Write(
mdalert.Warning("Info", "Creating new threads and commenting are disabled within this board") + "\n",
)
}
res.Write("Created by " + creatorLink + " on " + date + ", #" + board.ID.String())
res.Write(" \n" + renderBoardMenu(board, req))
res.Write(md.HorizontalRule())
if board.Threads.Size() == 0 {
res.Write(md.H3("This board doesn't have any threads"))
if !board.Readonly {
startConversationLink := md.Link("start a new conversation", makeCreateThreadURI(board))
res.Write("Do you want to " + startConversationLink + " in this board?")
}
return
}
p := newClampedPager(req.RawPath, board.Threads.Size(), pageSizeDefault)
render := func(thread *boards.Post) bool {
res.Write(renderThreadSummary(thread) + "\n")
return false
}
res.Write("Sort by: ")
link, desc := sortToggleLink(req.RawPath)
res.Write(link + "\n\n")
count := p.PageSize()
if desc {
count = -count // Reverse iterate
}
board.Threads.Iterate(p.Offset(), count, render)
if p.HasPages() {
res.Write(md.HorizontalRule())
res.Write(pager.Picker(p))
}
}
// renderSubMenu renders a sub-menu with a distinct visual pattern.
func renderSubMenu(items []string) string {
if len(items) == 0 {
return ""
}
return "└─ " + strings.Join(items, " • ") + "\n"
}
func renderBoardMenu(board *boards.Board, req *mux.Request) string {
var (
b strings.Builder
boardMembersURL = makeBoardURI(board) + "/members"
)
if board.Readonly {
b.WriteString(md.Link("List Members", boardMembersURL))
b.WriteString(" • ")
b.WriteString(md.Link("Unfreeze Board", makeUnfreezeBoardURI(board)))
b.WriteString("\n")
} else {
b.WriteString("↳ ")
b.WriteString(md.Link("Create Thread", makeCreateThreadURI(board)))
b.WriteString(" • ")
b.WriteString(md.Link("Request Invite", makeRequestInviteURI(board)))
b.WriteString(" • ")
menu := getCurrentMenu(req.RawPath)
if menu == menuManageBoard {
b.WriteString(md.Bold("Manage Board"))
} else {
b.WriteString(md.Link("Manage Board", menuURL(menuManageBoard)))
}
b.WriteString(" \n")
if menu == menuManageBoard {
subMenuItems := []string{
md.Link("Invite Member", makeInviteMemberURI(board)),
md.Link("List Invite Requests", makeBoardURI(board)+"/invites"),
md.Link("List Members", boardMembersURL),
md.Link("List Banned Users", makeBoardURI(board)+"/banned-users"),
md.Link("Freeze Board", makeFreezeBoardURI(board)),
}
b.WriteString(renderSubMenu(subMenuItems))
}
}
b.WriteString("\n")
return b.String()
}
func renderInviteMember(res *mux.ResponseWriter, req *mux.Request) {
name := req.GetVar("board")
board, found := gBoards.GetByName(name)
if !found {
res.Write("Board not found")
return
}
form := mdform.New("exec", "InviteMember")
form.Input(
"boardID",
"placeholder", "Board ID",
"value", board.ID.String(),
"readonly", "true",
)
form.Input(
"user",
"placeholder", "Address",
"required", "true",
)
form.Select(
"role",
string(RoleOwner),
)
form.Select(
"role",
string(RoleAdmin),
)
form.Select(
"role",
string(RoleModerator),
)
form.Select(
"role",
string(RoleGuest),
"selected", "true",
)
res.Write(md.H1(board.Name + ": Invite Member"))
res.Write(
md.Paragraph(
"Both open and invite only boards can have multiple members with different roles within a "+
"board, where members can have a single role at a time.",
) +
md.Paragraph(
"Boards are independent communities which could apply different permissions per role than "+
"other boards, but generally Boards2 supports four roles, _owner_, _admin_, _moderator_ "+
"and _guest_.",
) +
md.Paragraph(
"Member will be added to "+md.Link(board.Name, makeBoardURI(board))+" board.",
),
)
res.Write(form.String())
}
render_post.gno
package boards2
import (
"strconv"
"strings"
"gno.land/p/gnoland/boards/v0"
"gno.land/p/jeronimoalbi/mdform/v0"
"gno.land/p/leon/svgbtn/v0"
"gno.land/p/moul/md/v0"
"gno.land/p/moul/mdtable/v0"
"gno.land/p/nt/markdown/foreign/v0"
"gno.land/p/nt/mdalert/v0"
"gno.land/p/nt/mux/v0"
"gno.land/p/nt/ufmt/v0"
)
// renderPost renders a post and (unless it's a leaf or capped) its replies.
// desc is the page's sort order, forwarded so a comment's nested inline
// children (renderSubReplies) match the order of the view they appear in. It
// is unused for the top-level/re-root call (path != "" routes to
// renderTopLevelReplies, which derives the order from the path); those
// callers pass false.
func renderPost(post *boards.Post, path, indent string, levels int, budget *int, desc bool) string {
var b strings.Builder
// Thread reposts might not have a title, if so get title from source thread
title := post.Title
if boards.IsRepost(post) && title == "" {
if board, ok := gBoards.Get(post.OriginalBoardID); ok {
if src, ok := getThread(board, post.ParentID); ok {
title = src.Title
}
}
}
if title != "" { // Replies don't have a title
b.WriteString(md.H2(md.EscapeText(title)))
}
b.WriteString(indent + "\n")
b.WriteString(renderPostContent(post, indent, levels, budget))
if post.Replies.Size() == 0 {
return b.String()
}
// In practice this only fires for the re-rooted view's context-parent,
// which renderPostInner renders with an explicit levels==0. The thread
// recursion does levels-1 in BOTH renderPost and renderTopLevelReplies/
// renderSubReplies, so levels drops by 2 per nesting level and skips 0 —
// i.e. levels does NOT bound depth in the thread view; the render budget
// and the per-node breadth cap (renderSubReplies) are the real bounds.
if levels == 0 {
b.WriteString(indent + "\n")
return b.String()
}
if path != "" {
b.WriteString(renderTopLevelReplies(post, path, indent, levels-1, budget))
} else {
b.WriteString(renderSubReplies(post, indent, levels-1, budget, desc))
}
return b.String()
}
func renderPostContent(post *boards.Post, indent string, levels int, budget *int) string {
var b strings.Builder
// Author and date header
creatorLink := userLink(post.Creator)
roleBadge := getRoleBadge(post)
date := post.CreatedAt.Format(dateFormat)
b.WriteString(indent)
b.WriteString(md.Bold(creatorLink) + roleBadge + " · " + date)
if !boards.IsThread(post) {
b.WriteString(" " + md.Link("#"+post.ID.String(), makeReplyURI(post)))
}
b.WriteString(" \n")
// Flagged comment should be hidden, but replies still visible (see: #3480)
// Flagged threads will be hidden by render function caller.
if post.Hidden {
link := md.Link("inappropriate", makeFlaggingReasonsURI(post))
b.WriteString(indentBody(indent, "⚠ Reply is hidden as it has been flagged as "+link))
b.WriteString("\n")
return b.String()
}
srcContent, srcPost := renderSourcePost(post, indent, budget)
if boards.IsRepost(post) && srcPost != nil {
msg := ufmt.Sprintf(
"Original thread is %s \nCreated by %s on %s",
md.Link(srcPost.Title, makeThreadURI(srcPost)),
userLink(srcPost.Creator),
srcPost.CreatedAt.Format(dateFormat),
)
b.WriteString(mdalert.New(mdalert.TypeInfo, "Thread Repost", msg, true).String())
b.WriteString("\n")
}
// Render repost body before original thread's body
if post.Body != "" {
b.WriteString(indentForeignBody(indent, post.Body, budget) + "\n")
if srcContent != "" {
// Add extra line to separate repost content from original thread content
b.WriteString("\n")
}
}
b.WriteString(srcContent)
// Add a newline to separate source deleted message from repost body content
if boards.IsRepost(post) && srcPost == nil && len(post.Body) > 0 {
b.WriteString("\n\n")
}
// Split thread content and actions
if boards.IsThread(post) && !boards.IsRepost(post) {
b.WriteString("\n")
}
// Action buttons
b.WriteString(indent)
if !boards.IsThread(post) { // is comment
b.WriteString(" \n")
b.WriteString(indent)
}
actions := []string{
md.Link("Flag", makeFlagURI(post)),
}
if boards.IsThread(post) {
repostAction := md.Link("Repost", makeCreateRepostURI(post))
if post.Reposts.Size() > 0 {
repostAction += " [" + strconv.Itoa(post.Reposts.Size()) + "]"
}
actions = append(actions, repostAction)
}
isReadonly := post.Readonly || post.Board.Readonly
// A reply doesn't carry the thread's frozen flag (FreezeThread sets
// Readonly on the thread post only), so check the enclosing thread too —
// otherwise a frozen thread's replies show Reply/Edit/Delete links that
// the backend rejects. Mirrors the IsReadonly helper (board || thread).
if !isReadonly && !boards.IsThread(post) {
if t, ok := getThread(post.Board, post.ThreadID); ok {
isReadonly = t.Readonly
}
}
if !isReadonly {
replyLabel := "Reply"
if boards.IsThread(post) {
replyLabel = "Comment"
}
replyAction := md.Link(replyLabel, makeCreateReplyURI(post))
// Add reply count if any
if post.Replies.Size() > 0 {
replyAction += " [" + strconv.Itoa(post.Replies.Size()) + "]"
}
actions = append(
actions,
replyAction,
md.Link("Edit", makeEditPostURI(post)),
md.Link("Delete", makeDeletePostURI(post)),
)
}
if levels == 0 {
switch {
case boards.IsThread(post):
actions = append(actions, md.Link("Show all Replies", makeThreadURI(post)))
case post.Replies.Size() > 0:
// Reached at levels==0 — in practice the re-rooted view's
// context-parent (see renderPost). It still has replies below, so
// re-root here (Reddit/HN "continue this thread") to keep the
// subtree drillable instead of bouncing to the thread root.
actions = append(actions, md.Link("Continue this thread →", makeReplyURI(post)))
}
}
b.WriteString("↳ " + strings.Join(actions, " • ") + "\n")
return b.String()
}
func renderPostInner(post *boards.Post, path string) string {
if boards.IsThread(post) {
return ""
}
var (
s string
threadID = post.ThreadID
thread, _ = getThread(post.Board, threadID)
budget = maxRenderedBodies()
)
// Fully render parent if it's not a repost.
if !boards.IsRepost(post) {
parentID := post.ParentID
parent := thread
if thread.ID != parentID {
parent, _ = getReply(thread, parentID)
}
s += renderPost(parent, "", "", 0, &budget, false) + "\n"
}
// Pass the reply's own path so renderPost routes to renderTopLevelReplies
// and paginates this comment's direct replies (the re-root has its own
// ?page= — no collision with the thread view, which is a different path).
// desc=false: order is derived from path by renderTopLevelReplies.
s += renderPost(post, path, "> ", 5, &budget, false)
return s
}
func renderSourcePost(post *boards.Post, indent string, budget *int) (string, *boards.Post) {
if !boards.IsRepost(post) {
return "", nil
}
indent += "> "
// TODO: figure out a way to decouple posts from a global storage.
board, ok := gBoards.Get(post.OriginalBoardID)
if !ok {
// TODO: Boards can't be deleted so this might be redundant
return indentBody(indent, "⚠ Source board has been deleted"), nil
}
srcPost, ok := getThread(board, post.ParentID)
if !ok {
return indentBody(indent, "⚠ Source post has been deleted"), nil
}
if srcPost.Hidden {
return indentBody(indent, "⚠ Source post has been flagged as inappropriate"), nil
}
return indentForeignBody(indent, srcPost.Body, budget) + "\n\n", srcPost
}
func renderFlagPost(res *mux.ResponseWriter, req *mux.Request) {
name := req.GetVar("board")
board, found := gBoards.GetByName(name)
if !found {
res.Write("Board not found")
return
}
// Thread ID must always be available
rawID := req.GetVar("thread")
threadID, err := strconv.Atoi(rawID)
if err != nil {
res.Write("Invalid thread ID: " + md.EscapeText(rawID))
return
}
thread, found := getThread(board, boards.ID(threadID))
if !found {
res.Write("Thread not found")
return
}
// Parse reply ID when post is a reply
var reply *boards.Post
rawID = req.GetVar("reply")
isReply := rawID != ""
if isReply {
replyID, err := strconv.Atoi(rawID)
if err != nil {
res.Write("Invalid reply ID: " + md.EscapeText(rawID))
return
}
reply, _ = getReply(thread, boards.ID(replyID))
if reply == nil {
res.Write("Reply not found")
return
}
}
exec := "FlagThread"
if isReply {
exec = "FlagReply"
}
form := mdform.New("exec", exec)
form.Input(
"boardID",
"placeholder", "Board ID",
"value", board.ID.String(),
"readonly", "true",
)
form.Input(
"threadID",
"placeholder", "Thread ID",
"value", thread.ID.String(),
"readonly", "true",
)
if isReply {
form.Input(
"replyID",
"placeholder", "Reply ID",
"value", reply.ID.String(),
"readonly", "true",
)
}
form.Input(
"reason",
"placeholder", "Flagging Reason",
)
// Breadcrumb navigation
backLink := md.Link("← Back to thread", makeThreadURI(thread))
if isReply {
res.Write(md.H1(board.Name + ": Flag Comment"))
} else {
res.Write(md.H1(board.Name + ": Flag Thread"))
}
res.Write(backLink + "\n\n")
res.Write(
md.Paragraph(
"Thread or comment moderation is done through flagging, which is usually done "+
"by board members with the moderator role, though other roles could also potentially flag.",
) +
md.Paragraph(
"Flagging relies on a configurable threshold, which by default is of one flag, that when "+
"reached leads to the flagged thread or comment to be hidden.",
) +
md.Paragraph(
"Flagging thresholds can be different within each board.",
),
)
if isReply {
res.Write(
md.Paragraph(
ufmt.Sprintf(
"⚠ You are flagging a %s from %s ⚠",
md.Link("comment", makeReplyURI(reply)),
userLink(reply.Creator),
),
),
)
} else {
res.Write(
md.Paragraph(
ufmt.Sprintf(
"⚠ You are flagging the thread: %s ⚠",
md.Link(thread.Title, makeThreadURI(thread)),
),
),
)
}
res.Write(form.String())
res.Write("\n\n**Done?** " + svgbtn.ButtonWithRadius(136, 32, 4, "#E2E2E2", "#54595D", "Return to thread", makeThreadURI(thread)) + "\n")
}
func renderFlaggingReasonsPost(res *mux.ResponseWriter, req *mux.Request) {
name := req.GetVar("board")
board, found := gBoards.GetByName(name)
if !found {
res.Write("Board not found")
return
}
// Thread ID must always be available
rawID := req.GetVar("thread")
threadID, err := strconv.Atoi(rawID)
if err != nil {
res.Write("Invalid thread ID: " + md.EscapeText(rawID))
return
}
thread, found := getThread(board, boards.ID(threadID))
if !found {
res.Write("Thread not found")
return
}
flags := thread.Flags
// Parse reply ID when post is a reply
var reply *boards.Post
rawID = req.GetVar("reply")
isReply := rawID != ""
if isReply {
replyID, err := strconv.Atoi(rawID)
if err != nil {
res.Write("Invalid reply ID: " + md.EscapeText(rawID))
return
}
reply, found = getReply(thread, boards.ID(replyID))
if !found {
res.Write("Reply not found")
return
}
flags = reply.Flags
}
table := mdtable.Table{
Headers: []string{"Moderator", "Reason"},
}
flags.Iterate(0, flags.Size(), func(f boards.Flag) bool {
// f.Reason is user-supplied (only trimmed at write); escape it so a
// flag reason can't inject markdown (links/images) or HTML into the
// reasons table. md.EscapeText leaves '|' for mdtable to escape.
table.Append([]string{userLink(f.User), md.EscapeText(f.Reason)})
return false
})
// Breadcrumb navigation
backLink := md.Link("← Back to thread", makeThreadURI(thread))
res.Write(md.H1("Flagging Reasons"))
res.Write(backLink + "\n\n")
if isReply {
res.Write(
md.Paragraph(
ufmt.Sprintf(
"Moderation flags for a %s submitted by %s",
md.Link("comment", makeReplyURI(reply)),
userLink(reply.Creator),
),
),
)
} else {
res.Write(
md.Paragraph(
// Intentionally hide flagged thread title
ufmt.Sprintf("Moderation flags for %s", md.Link("thread", makeThreadURI(thread))),
),
)
}
res.Write(table.String())
}
func renderReplyPost(res *mux.ResponseWriter, req *mux.Request) {
name := req.GetVar("board")
board, found := gBoards.GetByName(name)
if !found {
res.Write("Board not found")
return
}
// Thread ID must always be available
rawID := req.GetVar("thread")
threadID, err := strconv.Atoi(rawID)
if err != nil {
res.Write("Invalid thread ID: " + md.EscapeText(rawID))
return
}
thread, found := board.Threads.Get(boards.ID(threadID))
if !found {
res.Write("Thread not found")
return
}
// Parse reply ID when post is a reply
var reply *boards.Post
rawID = req.GetVar("reply")
isReply := rawID != ""
if isReply {
replyID, err := strconv.Atoi(rawID)
if err != nil {
res.Write("Invalid reply ID: " + md.EscapeText(rawID))
return
}
reply, _ = getReply(thread, boards.ID(replyID))
if reply == nil {
res.Write("Reply not found")
return
}
}
form := mdform.New("exec", "CreateReply")
form.Input(
"boardID",
"placeholder", "Board ID",
"value", board.ID.String(),
"readonly", "true",
)
form.Input(
"threadID",
"placeholder", "Thread ID",
"value", thread.ID.String(),
"readonly", "true",
)
if isReply {
form.Input(
"replyID",
"placeholder", "Reply ID",
"value", reply.ID.String(),
"readonly", "true",
)
} else {
form.Input(
"replyID",
"placeholder", "Reply ID",
"value", "0",
"readonly", "true",
)
}
form.Textarea(
"body",
"placeholder", "Comment",
"required", "true",
)
// Breadcrumb navigation
backLink := md.Link("← Back to thread", makeThreadURI(thread))
if isReply {
res.Write(md.H1(board.Name + ": Reply"))
res.Write(backLink + "\n\n")
res.Write(
md.Paragraph(ufmt.Sprintf("Replying to a comment posted by %s:", userLink(reply.Creator))) +
foreign.ForeignWithLabel("Quoted comment", reply.Body),
)
} else {
res.Write(md.H1(board.Name + ": Comment"))
res.Write(backLink + "\n\n")
res.Write(
md.Paragraph(
ufmt.Sprintf("Commenting on the thread: %s", md.Link(thread.Title, makeThreadURI(thread))),
),
)
}
res.Write(form.String())
res.Write("\n\n**Done?** " + svgbtn.ButtonWithRadius(136, 32, 4, "#E2E2E2", "#54595D", "Return to thread", makeThreadURI(thread)) + "\n")
}
render_reply.gno
package boards2
import (
"strconv"
"strings"
"gno.land/p/gnoland/boards/v0"
"gno.land/p/jeronimoalbi/mdform/v0"
"gno.land/p/jeronimoalbi/pager/v0"
"gno.land/p/leon/svgbtn/v0"
"gno.land/p/moul/md/v0"
"gno.land/p/nt/mux/v0"
"gno.land/p/nt/ufmt/v0"
)
func renderReply(res *mux.ResponseWriter, req *mux.Request) {
name := req.GetVar("board")
board, found := gBoards.GetByName(name)
if !found {
res.Write("Board not found")
return
}
rawID := req.GetVar("thread")
threadID, err := strconv.Atoi(rawID)
if err != nil {
res.Write("Invalid thread ID: " + md.EscapeText(rawID))
return
}
rawID = req.GetVar("reply")
replyID, err := strconv.Atoi(rawID)
if err != nil {
res.Write("Invalid reply ID: " + md.EscapeText(rawID))
return
}
thread, found := getThread(board, boards.ID(threadID))
if !found {
res.Write("Thread not found")
return
}
reply, found := getReply(thread, boards.ID(replyID))
if !found {
res.Write("Reply not found")
return
}
// Call render even for hidden replies to display children.
// Original comment content will be hidden under the hood.
// See: #3480
res.Write(renderPostInner(reply, req.RawPath))
}
// newClampedPager builds a pager, clamping an out-of-range, zero, negative,
// or malformed ?page= to the last valid page instead of erroring. pager.New
// rejects page==0, page>pageCount, and non-numeric pages with
// ErrInvalidPageNumber, which the callers would otherwise surface as a panic
// (aborting the whole render) or an error page in place of the list. A
// NEGATIVE page is not rejected by pager.New (it only checks ==0 and
// >pageCount), so it must be caught here too — otherwise it renders a broken
// "page -N of M" picker with both arrows disabled. Triggers on a stale deep
// link after deletions, or a hand-edited URL.
func newClampedPager(path string, size, pageSize int) pager.Pager {
p, err := pager.New(path, size, pager.WithPageSize(pageSize))
if err == nil && p.Page() >= 1 {
return p
}
// Re-parse without ?page= to get a valid page-1 pager and read the real
// page count, then jump to the last page when there is more than one.
r := parseRealmPath(path)
r.Query.Del("page")
first, ferr := pager.New(r.String(), size, pager.WithPageSize(pageSize))
if ferr != nil {
// A page-less path is valid for every current route, so this is
// unreachable today; fall back to the original pager rather than
// asserting the invariant with a panic that would abort the render.
return p
}
if last := first.PageCount(); last > 1 {
r.Query.Set("page", strconv.Itoa(last))
if clamped, e := pager.New(r.String(), size, pager.WithPageSize(pageSize)); e == nil {
return clamped
}
}
return first
}
func renderTopLevelReplies(post *boards.Post, path, indent string, levels int, budget *int) string {
p := newClampedPager(path, post.Replies.Size(), pageSizeReplies)
link, desc := sortToggleLink(path)
var (
b strings.Builder
commentsIndent = indent + "> "
truncated bool
)
render := func(reply *boards.Post) bool {
if *budget <= 0 {
truncated = true
return true // stop: render budget exhausted (see maxRenderedBodies)
}
// Forward the page order so this reply's nested children match it.
b.WriteString(indent + "\n" + renderPost(reply, "", commentsIndent, levels-1, budget, desc))
return false
}
b.WriteString("\n" + md.HorizontalRule() + "Sort by: " + link + "\n")
count := p.PageSize()
if desc {
count = -count // Reverse iterate
}
post.Replies.Iterate(p.Offset(), count, render)
if truncated {
b.WriteString(indent + "\n" + commentsIndent + "_Some replies not shown — " +
md.Link("view all comments", makeThreadFlatURI(post)) + "._\n")
}
// Suppress the page picker when the budget truncated this page: later
// replies in the page were skipped, so the offset-based "next page" would
// jump past them. The flat link above is the complete, reachable view.
if !truncated && p.HasPages() {
b.WriteString(md.HorizontalRule())
b.WriteString(pager.Picker(p))
}
return b.String()
}
func renderSubReplies(post *boards.Post, indent string, levels int, budget *int, desc bool) string {
var (
b strings.Builder
commentsIndent = indent + "> "
truncated bool
)
// Cap inline children at pageSizeReplies. A nested reply list can't have
// its own pager (it would collide with the page's ?page=), so instead of
// dumping every child here a comment with more links to its own re-rooted
// view, which paginates them. Keeps every view bounded to <=pageSizeReplies
// children per post. count's sign follows the page order so the inline
// children match the view they appear in (desc → the newest ones).
count := pageSizeReplies
if desc {
count = -count
}
post.Replies.Iterate(0, count, func(reply *boards.Post) bool {
if *budget <= 0 {
truncated = true
return true // stop: render budget exhausted (see maxRenderedBodies)
}
b.WriteString(indent + "\n" + renderPost(reply, "", commentsIndent, levels-1, budget, desc))
return false
})
notice := func(text, uri string) {
b.WriteString(indent + "\n" + commentsIndent + md.Link(text, uri) + "\n")
}
switch {
case truncated:
// Budget exhausted: the whole-thread flat view is the reachable backstop.
notice("More replies — view all comments", makeThreadFlatURI(post))
case post.Replies.Size() > pageSizeReplies:
// Breadth cap hit: re-root at this comment to page the rest, carrying
// the page's sort order so the re-root opens the same way (its first
// page then matches the newest-first children shown inline here).
uri := makeReplyURI(post)
if desc {
uri += "?order=desc"
}
notice("View all "+strconv.Itoa(post.Replies.Size())+" replies", uri)
}
return b.String()
}
func renderEditReply(res *mux.ResponseWriter, req *mux.Request) {
name := req.GetVar("board")
board, found := gBoards.GetByName(name)
if !found {
res.Write("Board not found")
return
}
rawID := req.GetVar("thread")
threadID, err := strconv.Atoi(rawID)
if err != nil {
res.Write("Invalid thread ID: " + md.EscapeText(rawID))
return
}
rawID = req.GetVar("reply")
replyID, err := strconv.Atoi(rawID)
if err != nil {
res.Write("Invalid reply ID: " + md.EscapeText(rawID))
return
}
thread, found := getThread(board, boards.ID(threadID))
if !found {
res.Write("Thread not found")
return
}
reply, found := getReply(thread, boards.ID(replyID))
if !found {
res.Write("Reply not found")
return
}
form := mdform.New("exec", "EditReply")
form.Input(
"boardID",
"placeholder", "Board ID",
"value", board.ID.String(),
"readonly", "true",
)
form.Input(
"threadID",
"placeholder", "Thread ID",
"value", thread.ID.String(),
"readonly", "true",
)
form.Input(
"replyID",
"placeholder", "Reply ID",
"value", reply.ID.String(),
"readonly", "true",
)
form.Textarea(
"body",
"placeholder", "Comment",
"value", reply.Body,
"required", "true",
)
res.Write(md.H1(board.Name + ": Edit Comment"))
res.Write(md.Link("← Back to thread", makeThreadURI(thread)) + "\n\n")
res.Write(
md.Paragraph(
ufmt.Sprintf("Editing a comment from the thread: %s", md.Link(thread.Title, makeThreadURI(thread))),
),
)
res.Write(form.String())
res.Write("\n\n**Done?** " + svgbtn.ButtonWithRadius(136, 32, 4, "#E2E2E2", "#54595D", "Return to thread", makeThreadURI(thread)) + "\n")
}
render_thread.gno
package boards2
import (
"strconv"
"strings"
"gno.land/p/gnoland/boards/v0"
"gno.land/p/jeronimoalbi/mdform/v0"
"gno.land/p/jeronimoalbi/pager/v0"
"gno.land/p/leon/svgbtn/v0"
"gno.land/p/moul/md/v0"
"gno.land/p/nt/mux/v0"
"gno.land/p/nt/ufmt/v0"
)
// maxFlatIndentDepth caps the blockquote nesting in the flat comment view so
// deep reply chains stay readable; comments deeper than this still render,
// just at the capped indent.
const maxFlatIndentDepth = 6
func renderThread(res *mux.ResponseWriter, req *mux.Request) {
name := req.GetVar("board")
board, found := gBoards.GetByName(name)
if !found {
res.Write("Board not found")
return
}
rawID := req.GetVar("thread")
threadID, err := strconv.Atoi(rawID)
if err != nil {
res.Write("Invalid thread ID: " + md.EscapeText(rawID))
return
}
thread, found := getThread(board, boards.ID(threadID))
if !found {
res.Write("Thread not found")
return
}
if thread.Hidden {
link := md.Link("inappropriate", makeFlaggingReasonsURI(thread))
res.Write("⚠ Thread has been flagged as " + link)
return
}
res.Write(md.H1(md.Link("Boards", gRealmPath) + " › " + md.Link(board.Name, makeBoardURI(board))))
budget := maxRenderedBodies()
if parseRealmPath(req.RawPath).Query.Get("flat") != "" {
res.Write(renderThreadFlat(thread, req.RawPath, &budget))
return
}
res.Write(renderPost(thread, req.RawPath, "", 5, &budget, false))
}
// renderThreadFlat renders every comment in the thread as a single flat,
// depth-indented, paginated list backed by ThreadMeta.AllReplies (the index
// that already holds every reply at every depth). Unlike the recursive
// threaded view — which bounds work with the render budget and truncates a
// large subtree — this view is reachable to the very last comment: each
// comment renders one <gno-foreign> block (no recursion), so a fixed page
// size (pageSizeFlat) plus the OP stays well under the budget regardless of
// nesting, and the pager always advances. ?order=desc shows newest first, so
// its page 1 is the latest comments.
func renderThreadFlat(thread *boards.Post, path string, budget *int) string {
var b strings.Builder
// The OP for context (its body only; no replies — levels 0).
b.WriteString(renderPost(thread, "", "", 0, budget, false))
meta, ok := thread.Meta.(*ThreadMeta)
if !ok || meta.AllReplies.Size() == 0 {
return b.String()
}
all := meta.AllReplies
p := newClampedPager(path, all.Size(), pageSizeFlat)
b.WriteString("\n" + md.HorizontalRule())
b.WriteString(md.Link("← Threaded view", makeThreadURI(thread)) + " · All " +
strconv.Itoa(all.Size()) + " comments — sort by: ")
// sortToggleLink preserves flat=1, so the toggle stays in the flat view.
link, desc := sortToggleLink(path)
b.WriteString(link + "\n")
count := p.PageSize()
if desc {
count = -count // reverse iterate: newest first
}
all.Iterate(p.Offset(), count, func(reply *boards.Post) bool {
if *budget <= 0 {
// Unreachable while pageSizeFlat << maxRenderedBodies; a backstop
// in case a chain upgrade drops the native cap below one page.
return true
}
indent := flatIndent(thread, reply)
b.WriteString(indent + "\n" + renderPost(reply, "", indent, 0, budget, false))
return false
})
if p.HasPages() {
b.WriteString(md.HorizontalRule())
b.WriteString(pager.Picker(p))
}
return b.String()
}
// flatIndent returns the blockquote indent for a reply in the flat view,
// derived from its depth below the thread root (depth 1 = a direct reply to
// the thread), capped at maxFlatIndentDepth.
func flatIndent(thread *boards.Post, reply *boards.Post) string {
depth := 1
pid := reply.ParentID
for pid != thread.ID && pid != 0 && depth < maxFlatIndentDepth {
parent, ok := getReply(thread, pid)
if !ok {
break
}
depth++
pid = parent.ParentID
}
return strings.Repeat("> ", depth)
}
func renderThreadSummary(thread *boards.Post) string {
var (
b strings.Builder
postURI = makeThreadURI(thread)
summary = summaryOf(thread.Title, 80)
creatorLink = userLink(thread.Creator)
roleBadge = getRoleBadge(thread)
date = thread.CreatedAt.Format(dateFormat)
)
byline := "Created by "
if boards.IsRepost(thread) {
summary += ` ⟳`
byline = "Reposted by "
}
b.WriteString(md.H6(md.Link(summary, postURI)))
b.WriteString(byline + creatorLink + roleBadge + " on " + date + " \n")
status := []string{
strconv.Itoa(thread.Replies.Size()) + " replies",
strconv.Itoa(thread.Reposts.Size()) + " reposts",
}
b.WriteString(md.Bold(strings.Join(status, " • ")) + "\n")
return b.String()
}
func renderCreateThread(res *mux.ResponseWriter, req *mux.Request) {
name := req.GetVar("board")
board, found := gBoards.GetByName(name)
if !found {
res.Write("Board not found")
return
}
form := mdform.New("exec", "CreateThread")
form.Input(
"boardID",
"placeholder", "Board ID",
"value", board.ID.String(),
"readonly", "true",
)
form.Input(
"title",
"placeholder", "Title",
"required", "true",
)
form.Textarea(
"body",
"placeholder", "Content",
"rows", "10",
"required", "true",
)
res.Write(md.H1(board.Name + ": Create Thread"))
res.Write(md.Link("← Back to board", makeBoardURI(board)) + "\n\n")
res.Write(
md.Paragraph(
ufmt.Sprintf("Thread will be created in the board: %s", md.Link(board.Name, makeBoardURI(board))),
),
)
res.Write(form.String())
res.Write("\n\n**Done?** " + svgbtn.ButtonWithRadius(136, 32, 4, "#E2E2E2", "#54595D", "Return to board", makeBoardURI(board)) + "\n")
}
func renderEditThread(res *mux.ResponseWriter, req *mux.Request) {
name := req.GetVar("board")
board, found := gBoards.GetByName(name)
if !found {
res.Write("Board not found")
return
}
rawID := req.GetVar("thread")
threadID, err := strconv.Atoi(rawID)
if err != nil {
res.Write("Invalid thread ID: " + md.EscapeText(rawID))
return
}
thread, found := getThread(board, boards.ID(threadID))
if !found {
res.Write("Thread not found")
return
}
form := mdform.New("exec", "EditThread")
form.Input(
"boardID",
"placeholder", "Board ID",
"value", board.ID.String(),
"readonly", "true",
)
form.Input(
"threadID",
"placeholder", "Thread ID",
"value", thread.ID.String(),
"readonly", "true",
)
form.Input(
"title",
"placeholder", "Title",
"value", thread.Title,
"required", "true",
)
form.Textarea(
"body",
"placeholder", "Content",
"rows", "10",
"value", thread.Body,
"required", "true",
)
res.Write(md.H1(board.Name + ": Edit Thread"))
res.Write(md.Link("← Back to thread", makeThreadURI(thread)) + "\n\n")
res.Write(
md.Paragraph("Editing " + md.Link(thread.Title, makeThreadURI(thread))),
)
res.Write(form.String())
res.Write("\n\n**Done?** " + svgbtn.ButtonWithRadius(136, 32, 4, "#E2E2E2", "#54595D", "Return to thread", makeThreadURI(thread)) + "\n")
}
func renderRepostThread(res *mux.ResponseWriter, req *mux.Request) {
name := req.GetVar("board")
board, found := gBoards.GetByName(name)
if !found {
res.Write("Board not found")
return
}
rawID := req.GetVar("thread")
threadID, err := strconv.Atoi(rawID)
if err != nil {
res.Write("Invalid thread ID: " + md.EscapeText(rawID))
return
}
thread, found := getThread(board, boards.ID(threadID))
if !found {
res.Write("Thread not found")
return
}
form := mdform.New("exec", "CreateRepost")
form.Input(
"boardID",
"placeholder", "Board ID",
"value", board.ID.String(),
"readonly", "true",
)
form.Input(
"threadID",
"placeholder", "Thread ID",
"value", thread.ID.String(),
"readonly", "true",
)
form.Input(
"destinationBoardID",
"type", mdform.InputTypeNumber,
"placeholder", "Board ID where to repost",
"required", "true",
)
form.Input(
"title",
"value", thread.Title,
"placeholder", "Title",
"required", "true",
)
form.Textarea(
"body",
"placeholder", "Content",
"rows", "10",
)
res.Write(md.H1(board.Name + ": Repost Thread"))
res.Write(md.Link("← Back to thread", makeThreadURI(thread)) + "\n\n")
res.Write(
md.Paragraph(
"Threads can be reposted to other open boards or boards where you are a member " +
"and are allowed to create new threads.",
),
)
res.Write(
md.Paragraph(
ufmt.Sprintf("Reposting the thread: %s.", md.Link(thread.Title, makeThreadURI(thread))),
),
)
res.Write(form.String())
res.Write("\n\n**Done?** " + svgbtn.ButtonWithRadius(136, 32, 4, "#E2E2E2", "#54595D", "Return to thread", makeThreadURI(thread)) + "\n")
}
uris_board.gno
package boards2
import (
"net/url"
"strings"
"gno.land/p/gnoland/boards/v0"
)
func makeBoardURI(b *boards.Board) string {
path := strings.TrimPrefix(string(RealmLink), "gno.land")
return path + ":" + url.PathEscape(b.Name)
}
func makeFreezeBoardURI(b *boards.Board) string {
return RealmLink.Call(
"FreezeBoard",
"boardID", b.ID.String(),
)
}
func makeUnfreezeBoardURI(b *boards.Board) string {
return RealmLink.Call(
"UnfreezeBoard",
"boardID", b.ID.String(),
"threadID", "",
"replyID", "",
)
}
func makeInviteMemberURI(b *boards.Board) string {
return makeBoardURI(b) + "/invite-member"
}
func makeCreateThreadURI(b *boards.Board) string {
return makeBoardURI(b) + "/create-thread"
}
func makeRequestInviteURI(b *boards.Board) string {
return RealmLink.Call(
"RequestInvite",
"boardID", b.ID.String(),
)
}
uris_post.gno
package boards2
import (
"gno.land/p/gnoland/boards/v0"
)
func makeThreadURI(p *boards.Post) string {
if boards.IsThread(p) {
return makeBoardURI(p.Board) + "/" + p.ID.String()
}
// When post is a reply use the parent thread ID
return makeBoardURI(p.Board) + "/" + p.ThreadID.String()
}
// makeThreadFlatURI links to the thread's flat "all comments" view. Works for
// a thread or any reply within it (makeThreadURI resolves to the thread).
func makeThreadFlatURI(p *boards.Post) string {
return makeThreadURI(p) + "?flat=1"
}
func makeReplyURI(p *boards.Post) string {
return makeBoardURI(p.Board) + "/" + p.ThreadID.String() + "/" + p.ID.String()
}
func makeCreateReplyURI(p *boards.Post) string {
if boards.IsThread(p) {
return makeThreadURI(p) + "/reply"
}
return makeReplyURI(p) + "/reply"
}
func makeCreateRepostURI(p *boards.Post) string {
return makeThreadURI(p) + "/repost"
}
func makeDeletePostURI(p *boards.Post) string {
if boards.IsThread(p) {
return RealmLink.Call(
"DeleteThread",
"boardID", p.Board.ID.String(),
"threadID", p.ThreadID.String(),
)
}
return RealmLink.Call(
"DeleteReply",
"boardID", p.Board.ID.String(),
"threadID", p.ThreadID.String(),
"replyID", p.ID.String(),
)
}
func makeEditPostURI(p *boards.Post) string {
if boards.IsThread(p) {
return makeThreadURI(p) + "/edit"
}
return makeReplyURI(p) + "/edit"
}
func makeFlagURI(p *boards.Post) string {
if boards.IsThread(p) {
return makeThreadURI(p) + "/flag"
}
return makeReplyURI(p) + "/flag"
}
func makeFlaggingReasonsURI(p *boards.Post) string {
if boards.IsThread(p) {
return makeThreadURI(p) + "/flagging-reasons"
}
return makeReplyURI(p) + "/flagging-reasons"
}