1package groups
2
3import (
4 "std"
5 "strconv"
6 "time"
7
8 "gno.land/p/demo/avl"
9)
10
11type GroupID uint64
12
13func (gid GroupID) String() string {
14 return strconv.Itoa(int(gid))
15}
16
17type Group struct {
18 id GroupID
19 url string
20 name string
21 lastMemberID MemberID
22 members avl.Tree
23 creator std.Address
24 createdAt time.Time
25}
26
27func newGroup(url string, name string, creator std.Address) *Group {
28 if !reName.MatchString(name) {
29 panic("invalid name: " + name)
30 }
31 if gGroupsByName.Has(name) {
32 panic("Group with such name already exists")
33 }
34 return &Group{
35 id: incGetGroupID(),
36 url: url,
37 name: name,
38 creator: creator,
39 members: avl.Tree{},
40 createdAt: time.Now(),
41 }
42}
43
44func (group *Group) newMember(id MemberID, address std.Address, weight int, metadata string) *Member {
45 if group.members.Has(address.String()) {
46 panic("this member for this group already exists")
47 }
48 return &Member{
49 id: id,
50 address: address,
51 weight: weight,
52 metadata: metadata,
53 createdAt: time.Now(),
54 }
55}
56
57func (group *Group) HasPermission(addr std.Address, perm Permission) bool {
58 if group.creator != addr {
59 return false
60 }
61 return isValidPermission(perm)
62}
63
64func (group *Group) RenderGroup() string {
65 str := "Group ID: " + groupIDKey(group.id) + "\n\n" +
66 "Group Name: " + group.name + "\n\n" +
67 "Group Creator: " + usernameOf(group.creator) + "\n\n" +
68 "Group createdAt: " + group.createdAt.String() + "\n\n" +
69 "Group Last MemberID: " + memberIDKey(group.lastMemberID) + "\n\n"
70
71 str += "Group Members: \n\n"
72 group.members.Iterate("", "", func(key string, value interface{}) bool {
73 member := value.(*Member)
74 str += member.getMemberStr()
75 return false
76 })
77 return str
78}
79
80func (group *Group) deleteGroup() {
81 gidkey := groupIDKey(group.id)
82 _, gGroupsRemoved := gGroups.Remove(gidkey)
83 if !gGroupsRemoved {
84 panic("group does not exist with id " + group.id.String())
85 }
86 gGroupsByName.Remove(group.name)
87}
88
89func (group *Group) deleteMember(mid MemberID) {
90 gidkey := groupIDKey(group.id)
91 if !gGroups.Has(gidkey) {
92 panic("group does not exist with id " + group.id.String())
93 }
94
95 g := getGroup(group.id)
96 midkey := memberIDKey(mid)
97 g.members.Remove(midkey)
98}
group.gno
2.18 Kb ยท 98 lines