mirror of
https://github.com/D-Modem/bbs.git
synced 2026-11-28 17:38:04 -08:00
Deepen the message base: threads, votes, polls, aliases, signatures, groups, retention
For every front end (internal/app), the API and the CLI:
- Threads: from a message, the one it answers (O, PF2) and its whole
thread (T, PF6), replies under what they answer; GET
/messages/{id}/thread.
- Votes: up, down or none on a message (V, PF1), shown by its number;
POST /messages/{id}/vote.
- Polls: a question and 2 to 10 answers posted in an area (L, PF9),
answered (A, PF12) and shown with each answer's share; POST with
"poll", POST /messages/{id}/answer.
- Aliases: a user's alias (checked like a new name, no one's name or
alias) posted under in areas that allow it; the message's From is the
alias everywhere, newsgroup articles included (they used the real
name), while the sysop keeps whose it is.
- Signatures: up to three lines under posts and mail written on the BBS.
- Groups: areas listed by group, with a Group column.
- Retention: an area keeps its newest N messages and/or those of the
last D days, purged hourly and by bbs area purge.
Tested on SQLite, PostgreSQL, MySQL and MariaDB.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01AFQhReUqUc7F5srk2hViqr
This commit is contained in:
22 files changed
+1103
-74
No files matched your search
@@ -13,6 +13,10 @@
|
||||
// bbs [-config FILE] area newsgroup AREA GROUP|-
|
||||
// bbs [-config FILE] news sync [PEER]
|
||||
// bbs [-config FILE] area echo AREA TAG|-
|
||||
// bbs [-config FILE] area group AREA GROUP|-
|
||||
// bbs [-config FILE] area aliases AREA yes|no
|
||||
// bbs [-config FILE] area keep AREA MESSAGES DAYS
|
||||
// bbs [-config FILE] area purge
|
||||
// bbs [-config FILE] fido poll|scan|toss [LINK]
|
||||
// bbs [-config FILE] token add USER [-scope read,post,...] [-expires DAYS] [-name NAME]
|
||||
// bbs [-config FILE] token list [USER]
|
||||
@@ -78,6 +82,10 @@ func usage() {
|
||||
bbs [-config FILE] area newsgroup AREA GROUP|- (- : not a newsgroup)
|
||||
bbs [-config FILE] news sync [PEER] exchange articles with peers now
|
||||
bbs [-config FILE] area echo AREA TAG|- make an area a FidoNet echo (- : not one)
|
||||
bbs [-config FILE] area group AREA GROUP|- list an area under a group (- : none)
|
||||
bbs [-config FILE] area aliases AREA yes|no whether its posters may use their aliases
|
||||
bbs [-config FILE] area keep AREA MESSAGES DAYS keep the newest MESSAGES, for DAYS (0: no limit)
|
||||
bbs [-config FILE] area purge take away what areas keep no more, now
|
||||
bbs [-config FILE] fido poll [LINK] call links (with a host) now
|
||||
bbs [-config FILE] fido scan|toss [LINK] pack new mail, or take in what came
|
||||
bbs [-config FILE] token add USER [-scope read,post,mail,chat,files,sysop]
|
||||
@@ -347,6 +355,21 @@ func serve(cfg *server.Config) int {
|
||||
}
|
||||
go fd.Run(ctx)
|
||||
}
|
||||
go func() {
|
||||
// areas keep what they say (max_msgs, max_days): looked at hourly
|
||||
t := time.NewTicker(time.Hour)
|
||||
defer t.Stop()
|
||||
for {
|
||||
if _, err := b.PurgeAreas(); err != nil {
|
||||
b.Log.Printf("purging: %v", err)
|
||||
}
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
case <-t.C:
|
||||
}
|
||||
}
|
||||
}()
|
||||
if b.Events != nil {
|
||||
go b.Events.Run(ctx)
|
||||
}
|
||||
@@ -559,6 +582,14 @@ func userCmd(cfg *server.Config, args []string) {
|
||||
fmt.Println("done")
|
||||
}
|
||||
|
||||
// limit is n of what, or "no limit".
|
||||
func limit(n int, what string) string {
|
||||
if n == 0 {
|
||||
return "any number of " + what
|
||||
}
|
||||
return strconv.Itoa(n) + " " + what
|
||||
}
|
||||
|
||||
func areaCmd(cfg *server.Config, args []string) {
|
||||
words, flags := split(args)
|
||||
if len(words) == 0 {
|
||||
@@ -586,6 +617,15 @@ func areaCmd(cfg *server.Config, args []string) {
|
||||
if a.ReadReq != "" || a.PostReq != "" {
|
||||
only += fmt.Sprintf(" (read %q, post %q)", a.ReadReq, a.PostReq)
|
||||
}
|
||||
if a.Group != "" {
|
||||
only += " {" + a.Group + "}"
|
||||
}
|
||||
if a.Aliases {
|
||||
only += " (aliases)"
|
||||
}
|
||||
if a.MaxMsgs > 0 || a.MaxDays > 0 {
|
||||
only += fmt.Sprintf(" (keeps %d messages, %d days)", a.MaxMsgs, a.MaxDays)
|
||||
}
|
||||
fmt.Printf("%-20s %5d messages %s%s\n", a.Name, a.Messages, a.Description, only)
|
||||
}
|
||||
case "add":
|
||||
@@ -636,6 +676,58 @@ func areaCmd(cfg *server.Config, args []string) {
|
||||
} else {
|
||||
fmt.Println(a.Name, "is", group)
|
||||
}
|
||||
case "group", "aliases":
|
||||
if len(words) != 3 {
|
||||
usage()
|
||||
}
|
||||
a, err := st.AreaByName(words[1])
|
||||
if err != nil {
|
||||
fatal(fmt.Errorf("%s: %w", words[1], err))
|
||||
}
|
||||
if words[0] == "group" {
|
||||
g := bbs.Clean(words[2], 30)
|
||||
if g == "-" {
|
||||
g = ""
|
||||
}
|
||||
if err := st.SetAreaGroup(a.ID, g); err != nil {
|
||||
fatal(err)
|
||||
}
|
||||
fmt.Printf("%s: group %q\n", a.Name, g)
|
||||
return
|
||||
}
|
||||
on := map[string]bool{"yes": true, "no": false}
|
||||
v, ok := on[strings.ToLower(words[2])]
|
||||
if !ok {
|
||||
usage()
|
||||
}
|
||||
if err := st.SetAreaAliases(a.ID, v); err != nil {
|
||||
fatal(err)
|
||||
}
|
||||
fmt.Printf("%s: aliases %s\n", a.Name, words[2])
|
||||
case "keep":
|
||||
if len(words) != 4 {
|
||||
usage()
|
||||
}
|
||||
a, err := st.AreaByName(words[1])
|
||||
if err != nil {
|
||||
fatal(fmt.Errorf("%s: %w", words[1], err))
|
||||
}
|
||||
msgs, err1 := strconv.Atoi(words[2])
|
||||
days, err2 := strconv.Atoi(words[3])
|
||||
if err1 != nil || err2 != nil || msgs < 0 || days < 0 {
|
||||
fatal(errors.New("keep: MESSAGES and DAYS are numbers, 0 for no limit"))
|
||||
}
|
||||
if err := st.SetAreaKeep(a.ID, msgs, days); err != nil {
|
||||
fatal(err)
|
||||
}
|
||||
fmt.Printf("%s: keeps %s, for %s\n", a.Name, limit(msgs, "messages"), limit(days, "days"))
|
||||
case "purge":
|
||||
b := bbs.New(cfg.Settings, st, log.New(os.Stdout, "", 0))
|
||||
n, err := b.PurgeAreas()
|
||||
if err != nil {
|
||||
fatal(err)
|
||||
}
|
||||
fmt.Printf("%d messages purged\n", n)
|
||||
case "echo":
|
||||
if len(words) != 3 {
|
||||
usage()
|
||||
|
||||
@@ -52,8 +52,16 @@ bbs area add NAME "DESCRIPTION" [-sysop-only]
|
||||
bbs area del NAME # and its messages
|
||||
bbs area newsgroup AREA GROUP # make it a newsgroup (- : no longer)
|
||||
bbs area echo AREA TAG # make it a FidoNet echo (- : no longer)
|
||||
bbs area group AREA GROUP # list it under a group (- : none)
|
||||
bbs area aliases AREA yes|no # whether its posters may use their aliases
|
||||
bbs area keep AREA MESSAGES DAYS # keep the newest MESSAGES, for DAYS (0: no limit)
|
||||
bbs area purge # take away what areas keep no more, now
|
||||
```
|
||||
|
||||
What an area keeps is enforced hourly while the BBS runs (and by `bbs
|
||||
area purge`): beyond its newest `MESSAGES`, and older than `DAYS`,
|
||||
messages go, with their votes and polls.
|
||||
|
||||
A sysop also adds areas from the BBS (`+` in the message areas) and
|
||||
deletes any message. Newsgroups: [Newsgroups and NNTP](Newsgroups-and-NNTP);
|
||||
echoes: [FidoNet](FidoNet).
|
||||
|
||||
@@ -135,7 +135,10 @@ The full-screen editor: its text (wrapping as typed and as given, a word
|
||||
too long for a line, joining lines by Backspace and Delete, moving over
|
||||
line ends, quoting, the line limit), and an SSH caller writing a post
|
||||
with the cursor keys, replying with lines from the quote window and
|
||||
`/S`, then choosing the line editor; the sysop's tools (a sysop watching
|
||||
`/S`, then choosing the line editor; the message base (threads from any
|
||||
message, votes, polls and their answers, aliases (taken names refused),
|
||||
signatures, groups, keeping by count and by age; through internal/app and
|
||||
the API); the sysop's tools (a sysop watching
|
||||
a caller's screen as it is sent, calling them into chat at their next
|
||||
menu, being away when they page; the user editor, statistics, bans, the
|
||||
hack log and events through internal/app; events run, failing, timed
|
||||
|
||||
@@ -71,7 +71,7 @@ Errors are `{"error": "...", "code": "..."}`.
|
||||
| `GET /users`, `/users/{name}` | users | read |
|
||||
| `GET /areas`, `/areas/{id}` | message areas, with your unread | read |
|
||||
| `GET /areas/{id}/messages?after=&limit=&body=no` | messages after an id (200 at most) | read |
|
||||
| `POST /areas/{id}/messages` | post: `{"subject", "body", "reply_to"}` | post |
|
||||
| `POST /areas/{id}/messages` | post: `{"subject", "body", "reply_to", "alias": true, "poll": ["answer", ...]}` | post |
|
||||
| `PUT /areas/{id}/lastread` | mark read up to a message | read |
|
||||
| `GET /messages/{id}` | a message | read |
|
||||
| `GET /mail`, `GET`, `DELETE /mail/{id}` | your inbox; a mail (marked read); delete it | mail |
|
||||
@@ -79,6 +79,8 @@ Errors are `{"error": "...", "code": "..."}`.
|
||||
| `GET /fileareas`, `/fileareas/{id}/files`, `/files/{id}` | file areas and files | files |
|
||||
| `POST /fileareas/{id}/files?name=&description=` | upload: the body is the file | files |
|
||||
| `GET /files/{id}/content` | download (ranges work) | files |
|
||||
| `GET /messages/{id}/thread` | the message's thread from its start, with each one's depth | read |
|
||||
| `POST /messages/{id}/vote`, `POST /messages/{id}/answer` | vote (`{"value": 1}`, -1, 0); answer a poll (`{"answer": 0}`) | post |
|
||||
| `GET /files?q=` or `?since=` | files by words in their names and descriptions, or added since a time (RFC 3339), newest first | files |
|
||||
| `GET /admin/bans`, `DELETE /admin/bans/{ip}` | addresses banned for failed logins; lift a ban | sysop |
|
||||
| `GET /admin/hacklog?lines=` | the hack log's last lines | sysop |
|
||||
|
||||
@@ -28,12 +28,16 @@ Every area is in the new scan until it is taken out: the area's number
|
||||
takes all out. Areas marked `*` are in. The choice is kept with the
|
||||
account.
|
||||
|
||||
Areas a sysop put in groups are listed by group (those in none first),
|
||||
with a Group column.
|
||||
|
||||
## In an area
|
||||
|
||||
The messages a page at a time (Enter for more on a text terminal,
|
||||
PF7/PF8 on a 3270); `*` marks those not read yet. A message's number
|
||||
reads it, even one not on the page. `R` (PF5) reads from the first new
|
||||
one, `P` (PF6) posts.
|
||||
one, `P` (PF6) posts, `L` (PF9) posts a poll: a question and 2 to 10
|
||||
answers, parted by `|`.
|
||||
|
||||
## Reading
|
||||
|
||||
@@ -44,8 +48,24 @@ one, `P` (PF6) posts.
|
||||
| reply in the area | `R` | PF4 |
|
||||
| reply by mail | `M` | PF5 |
|
||||
| delete (yours, or any for the sysop) | `D` | PF9 |
|
||||
| vote it up or down (or take your vote back) | `V` | PF1 |
|
||||
| the thread: every message from the one it began with, replies under what they answer | `T` | PF6 |
|
||||
| the message this answers | `O` | PF2 |
|
||||
| answer a poll (again: your answer changes) | `A` | PF12 |
|
||||
| back | `Q` | PF3 |
|
||||
|
||||
A message's votes show by its number (`+3 -1`), a poll's answers under
|
||||
its text with each one's share, yours marked `*`.
|
||||
|
||||
## Aliases and signatures
|
||||
|
||||
On the profile, `I` sets an alias and `G` a signature (up to three
|
||||
lines). In an area whose sysop allows aliases, posting asks whether to
|
||||
post under the alias: the message is from the alias (in newsgroups and
|
||||
echoes too), while the sysop still knows whose it is. An alias is
|
||||
checked like a new user's name and may not be anyone's name or alias.
|
||||
The signature goes under every post and mail written on the BBS.
|
||||
|
||||
Reading in an area marks it read up to there. Reading what *To you* or
|
||||
*Find* found does not: the new scan still finds those messages new.
|
||||
|
||||
|
||||
@@ -788,3 +788,48 @@ func TestEventsAndAvailable(t *testing.T) {
|
||||
t.Errorf("nothing said: %d", code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestVotesPollsThreads(t *testing.T) {
|
||||
s := setup(t, Settings{})
|
||||
alice, bob, sys := s.login("alice", "alicepass1"), s.login("bob", "bobpass123"), s.login("sysop", "sysoppass1")
|
||||
if code, m, _ := s.do("PATCH", "/api/v1/admin/areas/1", sys, map[string]any{"group": "Local", "aliases": true,
|
||||
"max_messages": 500, "max_days": 90}); code != 200 || m["group"] != "Local" || m["aliases"] != true || m["max_messages"] != 500.0 {
|
||||
t.Fatalf("area: %d %v", code, m)
|
||||
}
|
||||
if code, _, _ := s.do("PATCH", "/api/v1/admin/areas/1", sys, map[string]any{"max_days": -1}); code != 400 {
|
||||
t.Errorf("negative days: %d", code)
|
||||
}
|
||||
if code, _, _ := s.do("POST", "/api/v1/areas/1/messages", alice, map[string]any{"subject": "x", "body": "y", "alias": true}); code != 400 {
|
||||
t.Errorf("an alias alice has not: %d", code)
|
||||
}
|
||||
u, _ := s.b.Store.UserByName("alice")
|
||||
s.b.Store.SetAlias(u.ID, "Night Owl")
|
||||
code, m, _ := s.do("POST", "/api/v1/areas/1/messages", alice, map[string]any{"subject": "Lunch?", "body": "Where?",
|
||||
"alias": true, "poll": []string{"Here", "There"}})
|
||||
if code != 201 || m["from"] != "Night Owl" {
|
||||
t.Fatalf("poll: %d %v", code, m)
|
||||
}
|
||||
id := int(m["id"].(float64))
|
||||
_, m, _ = s.do("POST", "/api/v1/areas/1/messages", bob, map[string]any{"subject": "Re: Lunch?", "body": "Here", "reply_to": id})
|
||||
reply := int(m["id"].(float64))
|
||||
if code, _, _ := s.do("POST", fmt.Sprintf("/api/v1/messages/%d/vote", id), alice, map[string]any{"value": 1}); code != 400 {
|
||||
t.Errorf("own vote: %d", code)
|
||||
}
|
||||
if code, m, _ := s.do("POST", fmt.Sprintf("/api/v1/messages/%d/vote", id), bob, map[string]any{"value": 1}); code != 200 ||
|
||||
m["votes"].(map[string]any)["up"] != 1.0 {
|
||||
t.Errorf("vote: %d %v", code, m)
|
||||
}
|
||||
if code, m, _ := s.do("POST", fmt.Sprintf("/api/v1/messages/%d/answer", id), bob, map[string]any{"answer": 1}); code != 200 ||
|
||||
m["poll"].(map[string]any)["mine"] != 1.0 {
|
||||
t.Errorf("answer: %d %v", code, m)
|
||||
}
|
||||
for _, bad := range []map[string]any{{"answer": 2}, {}} {
|
||||
if code, _, _ := s.do("POST", fmt.Sprintf("/api/v1/messages/%d/answer", id), bob, bad); code != 400 {
|
||||
t.Errorf("answer %v: %d", bad, code)
|
||||
}
|
||||
}
|
||||
if code, _, l := s.do("GET", fmt.Sprintf("/api/v1/messages/%d/thread", reply), alice, nil); code != 200 || len(l) != 2 ||
|
||||
l[1].(map[string]any)["depth"] != 1.0 {
|
||||
t.Errorf("thread: %d %v", code, l)
|
||||
}
|
||||
}
|
||||
+30
-22
@@ -33,7 +33,10 @@ var ops = []op{
|
||||
{"GET", "/api/v1/areas/{id}/messages", "Messages after an id (?after=, ?limit= up to 200, ?body=no)", "read", "", "MessagePage", 200},
|
||||
{"POST", "/api/v1/areas/{id}/messages", "Post a message", "post", "NewMessage", "Message", 201},
|
||||
{"PUT", "/api/v1/areas/{id}/lastread", "Mark read up to a message", "read", "LastRead", "Area", 200},
|
||||
{"GET", "/api/v1/messages/{id}", "A message", "read", "", "Message", 200},
|
||||
{"GET", "/api/v1/messages/{id}", "A message (its votes and poll too)", "read", "", "Message", 200},
|
||||
{"GET", "/api/v1/messages/{id}/thread", "The message's thread from its start, with each one's depth", "read", "", "Thread", 200},
|
||||
{"POST", "/api/v1/messages/{id}/vote", "Vote on a message: 1, -1 or 0", "post", "Vote", "Message", 200},
|
||||
{"POST", "/api/v1/messages/{id}/answer", "Answer a poll (the answer's index)", "post", "Answer", "Message", 200},
|
||||
{"GET", "/api/v1/mail", "Your inbox", "mail", "", "Messages", 200},
|
||||
{"GET", "/api/v1/mail/{id}", "A mail of yours (marked read)", "mail", "", "Message", 200},
|
||||
{"DELETE", "/api/v1/mail/{id}", "Delete a mail of yours", "mail", "", "", 204},
|
||||
@@ -56,7 +59,7 @@ var ops = []op{
|
||||
{"POST", "/api/v1/admin/users", "Add a user", "sysop", "NewUser", "User", 201},
|
||||
{"PATCH", "/api/v1/admin/users/{name}", "Lock, unlock, make sysop, set password, location, level or flags", "sysop", "PatchUser", "User", 200},
|
||||
{"POST", "/api/v1/admin/areas", "Add a message area", "sysop", "NewArea", "Area", 201},
|
||||
{"PATCH", "/api/v1/admin/areas/{id}", "Set an area's newsgroup, echo tag or access requirements (\"\": none)", "sysop", "PatchArea", "Area", 200},
|
||||
{"PATCH", "/api/v1/admin/areas/{id}", "Set an area's newsgroup, echo tag, access requirements (\"\": none), group, aliases, or how much it keeps", "sysop", "PatchArea", "Area", 200},
|
||||
{"POST", "/api/v1/admin/nodes/{n}/kick", "Throw a caller off", "sysop", "", "", 204},
|
||||
{"GET", "/api/v1/admin/bans", "Addresses banned for failed logins, and until when", "sysop", "", "Bans", 200},
|
||||
{"DELETE", "/api/v1/admin/bans/{ip}", "Lift a ban", "sysop", "", "", 204},
|
||||
@@ -90,27 +93,32 @@ func ref(name string) map[string]any { return map[string]any{"$ref": "#/componen
|
||||
func arr(name string) map[string]any { return map[string]any{"type": "array", "items": ref(name)} }
|
||||
|
||||
var schemas = map[string]any{
|
||||
"Error": obj(map[string]any{"error": str, "code": str}, "error", "code"),
|
||||
"Login": obj(map[string]any{"name": str, "password": str, "scopes": str}, "name", "password"),
|
||||
"Session": obj(map[string]any{"token": str, "expires": date, "user": str, "scopes": map[string]any{"type": "array", "items": str}}),
|
||||
"System": obj(map[string]any{"name": str, "sysop": str, "location": str, "motd": str, "users": num, "messages": num, "areas": num, "online": num, "features": map[string]any{"type": "object"}}),
|
||||
"Node": obj(map[string]any{"node": num, "user": str, "via": str, "since": date, "doing": str, "terminal": str}),
|
||||
"Nodes": arr("Node"),
|
||||
"User": obj(map[string]any{"name": str, "location": str, "sysop": boo, "created": date, "last_login": date, "calls": num, "posts": num, "node": num, "locked": boo, "level": num, "flags": str, "about": str}),
|
||||
"Users": arr("User"),
|
||||
"Me": obj(map[string]any{"user": ref("User"), "unread_mail": num, "access": map[string]any{"type": "object"}, "prefs": ref("Prefs"), "scopes": map[string]any{"type": "array", "items": str}}),
|
||||
"PatchMe": obj(map[string]any{"location": str, "about": str, "old_password": str, "new_password": str, "prefs": ref("Prefs")}),
|
||||
"Prefs": map[string]any{"type": "object", "description": "settings: ansi, utf8, sixel, rip (on, off), width (40, 80), editor (full, line); \"\" forgets one", "additionalProperties": str},
|
||||
"SSHKey": obj(map[string]any{"id": num, "type": str, "fingerprint": str, "comment": str, "key": str, "created": date, "last_used": date}),
|
||||
"SSHKeys": arr("SSHKey"),
|
||||
"NewSSHKey": obj(map[string]any{"key": str}, "key"),
|
||||
"Tokens": map[string]any{"type": "array", "items": obj(map[string]any{"id": num, "name": str, "scopes": map[string]any{"type": "array", "items": str}, "session": boo, "created": date, "expires": date, "last_used": date, "current": boo})},
|
||||
"Area": obj(map[string]any{"id": num, "name": str, "description": str, "sysop_only": boo, "newsgroup": str, "echo_tag": str, "messages": num, "first_id": num, "last_id": num, "unread": num, "last_read": num, "can_post": boo, "read_require": str, "post_require": str}),
|
||||
"Areas": arr("Area"),
|
||||
"Message": obj(map[string]any{"id": num, "area": num, "from": str, "to": str, "subject": str, "body": str, "reply_to": num, "created": date, "message_id": str, "ftn_msgid": str, "read": boo}),
|
||||
"Error": obj(map[string]any{"error": str, "code": str}, "error", "code"),
|
||||
"Login": obj(map[string]any{"name": str, "password": str, "scopes": str}, "name", "password"),
|
||||
"Session": obj(map[string]any{"token": str, "expires": date, "user": str, "scopes": map[string]any{"type": "array", "items": str}}),
|
||||
"System": obj(map[string]any{"name": str, "sysop": str, "location": str, "motd": str, "users": num, "messages": num, "areas": num, "online": num, "features": map[string]any{"type": "object"}}),
|
||||
"Node": obj(map[string]any{"node": num, "user": str, "via": str, "since": date, "doing": str, "terminal": str}),
|
||||
"Nodes": arr("Node"),
|
||||
"User": obj(map[string]any{"name": str, "location": str, "sysop": boo, "created": date, "last_login": date, "calls": num, "posts": num, "node": num, "locked": boo, "level": num, "flags": str, "about": str}),
|
||||
"Users": arr("User"),
|
||||
"Me": obj(map[string]any{"user": ref("User"), "unread_mail": num, "access": map[string]any{"type": "object"}, "prefs": ref("Prefs"), "scopes": map[string]any{"type": "array", "items": str}}),
|
||||
"PatchMe": obj(map[string]any{"location": str, "about": str, "old_password": str, "new_password": str, "prefs": ref("Prefs")}),
|
||||
"Prefs": map[string]any{"type": "object", "description": "settings: ansi, utf8, sixel, rip (on, off), width (40, 80), editor (full, line); \"\" forgets one", "additionalProperties": str},
|
||||
"SSHKey": obj(map[string]any{"id": num, "type": str, "fingerprint": str, "comment": str, "key": str, "created": date, "last_used": date}),
|
||||
"SSHKeys": arr("SSHKey"),
|
||||
"NewSSHKey": obj(map[string]any{"key": str}, "key"),
|
||||
"Tokens": map[string]any{"type": "array", "items": obj(map[string]any{"id": num, "name": str, "scopes": map[string]any{"type": "array", "items": str}, "session": boo, "created": date, "expires": date, "last_used": date, "current": boo})},
|
||||
"Area": obj(map[string]any{"id": num, "name": str, "description": str, "sysop_only": boo, "newsgroup": str, "echo_tag": str, "messages": num, "first_id": num, "last_id": num, "unread": num, "last_read": num, "can_post": boo, "read_require": str, "post_require": str, "group": str, "aliases": boo, "max_messages": num, "max_days": num}),
|
||||
"Areas": arr("Area"),
|
||||
"Message": obj(map[string]any{"id": num, "area": num, "from": str, "to": str, "subject": str, "body": str, "reply_to": num, "created": date, "message_id": str, "ftn_msgid": str, "read": boo,
|
||||
"votes": obj(map[string]any{"up": num, "down": num, "mine": num}),
|
||||
"poll": obj(map[string]any{"answers": map[string]any{"type": "array", "items": str}, "counts": map[string]any{"type": "array", "items": num}, "mine": num})}),
|
||||
"Messages": arr("Message"),
|
||||
"MessagePage": obj(map[string]any{"messages": arr("Message"), "next": str}),
|
||||
"NewMessage": obj(map[string]any{"to": str, "subject": str, "body": str, "reply_to": num}, "subject", "body"),
|
||||
"NewMessage": obj(map[string]any{"to": str, "subject": str, "body": str, "reply_to": num, "alias": boo, "poll": map[string]any{"type": "array", "items": str}}, "subject", "body"),
|
||||
"Thread": map[string]any{"type": "array", "items": obj(map[string]any{"message": ref("Message"), "depth": num})},
|
||||
"Vote": obj(map[string]any{"value": num}, "value"),
|
||||
"Answer": obj(map[string]any{"answer": num}, "answer"),
|
||||
"LastRead": obj(map[string]any{"id": num}, "id"),
|
||||
"Sent": obj(map[string]any{"sent": boo}),
|
||||
"FileAreas": map[string]any{"type": "array", "items": obj(map[string]any{"id": num, "name": str, "description": str, "sysop_upload": boo, "files": num, "can_upload": boo})},
|
||||
@@ -132,7 +140,7 @@ var schemas = map[string]any{
|
||||
"NewUser": obj(map[string]any{"name": str, "password": str, "location": str, "sysop": boo}, "name", "password"),
|
||||
"PatchUser": obj(map[string]any{"locked": boo, "sysop": boo, "password": str, "location": str, "level": num, "flags": str}),
|
||||
"NewArea": obj(map[string]any{"name": str, "description": str, "sysop_only": boo}, "name"),
|
||||
"PatchArea": obj(map[string]any{"newsgroup": str, "echo_tag": str, "read_require": str, "post_require": str}),
|
||||
"PatchArea": obj(map[string]any{"newsgroup": str, "echo_tag": str, "read_require": str, "post_require": str, "group": str, "aliases": boo, "max_messages": num, "max_days": num}),
|
||||
"EventStream": map[string]any{"type": "string", "description": "text/event-stream: events welcome, said, emoted, joined, left, private, paged, notice, mail; data is the Event of proto/bbs.proto in its JSON"},
|
||||
"Object": map[string]any{"type": "object"},
|
||||
}
|
||||
|
||||
+163
-26
@@ -36,12 +36,15 @@ func (s *Server) routes() map[string]route {
|
||||
"GET /api/v1/users/{name}": {scope: "read", h: s.user},
|
||||
"GET /api/v1/callers": {scope: "read", h: s.callers},
|
||||
|
||||
"GET /api/v1/areas": {scope: "read", h: s.areas},
|
||||
"GET /api/v1/areas/{id}": {scope: "read", h: s.area},
|
||||
"GET /api/v1/areas/{id}/messages": {scope: "read", h: s.messages},
|
||||
"POST /api/v1/areas/{id}/messages": {scope: "post", h: s.post},
|
||||
"PUT /api/v1/areas/{id}/lastread": {scope: "read", h: s.lastRead},
|
||||
"GET /api/v1/messages/{id}": {scope: "read", h: s.message},
|
||||
"GET /api/v1/areas": {scope: "read", h: s.areas},
|
||||
"GET /api/v1/areas/{id}": {scope: "read", h: s.area},
|
||||
"GET /api/v1/areas/{id}/messages": {scope: "read", h: s.messages},
|
||||
"POST /api/v1/areas/{id}/messages": {scope: "post", h: s.post},
|
||||
"PUT /api/v1/areas/{id}/lastread": {scope: "read", h: s.lastRead},
|
||||
"GET /api/v1/messages/{id}": {scope: "read", h: s.message},
|
||||
"GET /api/v1/messages/{id}/thread": {scope: "read", h: s.thread},
|
||||
"POST /api/v1/messages/{id}/vote": {scope: "post", h: s.vote},
|
||||
"POST /api/v1/messages/{id}/answer": {scope: "post", h: s.answerPoll},
|
||||
|
||||
"GET /api/v1/mail": {scope: "mail", h: s.mail},
|
||||
"GET /api/v1/mail/{id}": {scope: "mail", h: s.mailOne},
|
||||
@@ -152,20 +155,38 @@ type areaJSON struct {
|
||||
CanPost bool `json:"can_post"`
|
||||
ReadReq string `json:"read_require,omitempty"`
|
||||
PostReq string `json:"post_require,omitempty"`
|
||||
Group string `json:"group,omitempty"`
|
||||
Aliases bool `json:"aliases,omitempty"`
|
||||
MaxMsgs int `json:"max_messages,omitempty"`
|
||||
MaxDays int `json:"max_days,omitempty"`
|
||||
}
|
||||
|
||||
type messageJSON struct {
|
||||
ID int64 `json:"id"`
|
||||
Area int64 `json:"area,omitempty"`
|
||||
From string `json:"from"`
|
||||
To string `json:"to"`
|
||||
Subject string `json:"subject"`
|
||||
Body string `json:"body,omitempty"`
|
||||
ReplyTo int64 `json:"reply_to,omitempty"`
|
||||
Created time.Time `json:"created"`
|
||||
MessageID string `json:"message_id,omitempty"`
|
||||
FTNMsgID string `json:"ftn_msgid,omitempty"`
|
||||
Read *bool `json:"read,omitempty"` // mail
|
||||
ID int64 `json:"id"`
|
||||
Area int64 `json:"area,omitempty"`
|
||||
From string `json:"from"`
|
||||
To string `json:"to"`
|
||||
Subject string `json:"subject"`
|
||||
Body string `json:"body,omitempty"`
|
||||
ReplyTo int64 `json:"reply_to,omitempty"`
|
||||
Created time.Time `json:"created"`
|
||||
MessageID string `json:"message_id,omitempty"`
|
||||
FTNMsgID string `json:"ftn_msgid,omitempty"`
|
||||
Read *bool `json:"read,omitempty"` // mail
|
||||
Votes *votesJSON `json:"votes,omitempty"`
|
||||
Poll *pollJSON `json:"poll,omitempty"`
|
||||
}
|
||||
|
||||
type votesJSON struct {
|
||||
Up int `json:"up"`
|
||||
Down int `json:"down"`
|
||||
Mine int `json:"mine"`
|
||||
}
|
||||
|
||||
type pollJSON struct {
|
||||
Answers []string `json:"answers"`
|
||||
Counts []int `json:"counts"`
|
||||
Mine int `json:"mine"` // -1: not answered
|
||||
}
|
||||
|
||||
func msgOut(m *store.Message, body bool) messageJSON {
|
||||
@@ -509,7 +530,8 @@ func (s *Server) areaOut(r *http.Request, a *store.Area) areaJSON {
|
||||
unread, _ := s.B.Store.NewCount(u.ID, a.ID)
|
||||
last, _ := s.B.Store.LastRead(u.ID, a.ID)
|
||||
return areaJSON{a.ID, a.Name, a.Description, a.SysopOnly, a.Newsgroup, a.EchoTag, a.Messages,
|
||||
a.FirstID, a.LastID, unread, last, s.B.CanPost(u, a), a.ReadReq, a.PostReq}
|
||||
a.FirstID, a.LastID, unread, last, s.B.CanPost(u, a), a.ReadReq, a.PostReq,
|
||||
a.Group, a.Aliases, a.MaxMsgs, a.MaxDays}
|
||||
}
|
||||
|
||||
func (s *Server) areas(w http.ResponseWriter, r *http.Request) {
|
||||
@@ -574,11 +596,12 @@ func (s *Server) messages(w http.ResponseWriter, r *http.Request) {
|
||||
writeJSON(w, http.StatusOK, resp)
|
||||
}
|
||||
|
||||
func (s *Server) message(w http.ResponseWriter, r *http.Request) {
|
||||
// readable is the path's message, if the user may read its area.
|
||||
func (s *Server) readable(w http.ResponseWriter, r *http.Request) *store.Message {
|
||||
id, ok := pathID(r, "id")
|
||||
if !ok {
|
||||
fail(w, http.StatusNotFound, "no such message")
|
||||
return
|
||||
return nil
|
||||
}
|
||||
m, err := s.B.Store.Message(id)
|
||||
if err == nil {
|
||||
@@ -588,9 +611,96 @@ func (s *Server) message(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
if err != nil {
|
||||
fail(w, http.StatusNotFound, "no such message")
|
||||
return nil
|
||||
}
|
||||
return m
|
||||
}
|
||||
|
||||
func (s *Server) message(w http.ResponseWriter, r *http.Request) {
|
||||
m := s.readable(w, r)
|
||||
if m == nil {
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, msgOut(m, true))
|
||||
j := msgOut(m, true)
|
||||
u := whoOf(r).user
|
||||
if up, down, mine, err := s.B.Store.Votes(m.ID, u.ID); err == nil && up+down+mine != 0 {
|
||||
j.Votes = &votesJSON{up, down, mine}
|
||||
}
|
||||
if ans, counts, mine, err := s.B.Store.Poll(m.ID, u.ID); err == nil && ans != nil {
|
||||
j.Poll = &pollJSON{ans, counts, mine}
|
||||
}
|
||||
writeJSON(w, http.StatusOK, j)
|
||||
}
|
||||
|
||||
// vote: {"value": 1, -1 or 0}
|
||||
func (s *Server) vote(w http.ResponseWriter, r *http.Request) {
|
||||
m := s.readable(w, r)
|
||||
if m == nil {
|
||||
return
|
||||
}
|
||||
var req struct {
|
||||
Value int `json:"value"`
|
||||
}
|
||||
if !s.decode(w, r, &req) {
|
||||
return
|
||||
}
|
||||
u := whoOf(r).user
|
||||
if req.Value < -1 || req.Value > 1 || req.Value != 0 && m.FromID == u.ID {
|
||||
fail(w, http.StatusBadRequest, "value is 1, -1 or 0, and not on your own message")
|
||||
return
|
||||
}
|
||||
if err := s.B.Store.Vote(m.ID, u.ID, req.Value); err != nil {
|
||||
fail(w, http.StatusInternalServerError, err.Error())
|
||||
return
|
||||
}
|
||||
s.message(w, r)
|
||||
}
|
||||
|
||||
// answerPoll: {"answer": the answer's index}
|
||||
func (s *Server) answerPoll(w http.ResponseWriter, r *http.Request) {
|
||||
m := s.readable(w, r)
|
||||
if m == nil {
|
||||
return
|
||||
}
|
||||
var req struct {
|
||||
Answer *int `json:"answer"`
|
||||
}
|
||||
if !s.decode(w, r, &req) {
|
||||
return
|
||||
}
|
||||
u := whoOf(r).user
|
||||
ans, _, _, err := s.B.Store.Poll(m.ID, u.ID)
|
||||
if err != nil || ans == nil {
|
||||
fail(w, http.StatusBadRequest, "that message is no poll")
|
||||
return
|
||||
}
|
||||
if req.Answer == nil || *req.Answer < 0 || *req.Answer >= len(ans) {
|
||||
fail(w, http.StatusBadRequest, fmt.Sprintf("answer is 0 to %d", len(ans)-1))
|
||||
return
|
||||
}
|
||||
if err := s.B.Store.PollVote(m.ID, u.ID, *req.Answer); err != nil {
|
||||
fail(w, http.StatusInternalServerError, err.Error())
|
||||
return
|
||||
}
|
||||
s.message(w, r)
|
||||
}
|
||||
|
||||
// thread: the message's thread, from its start, with each one's depth
|
||||
func (s *Server) thread(w http.ResponseWriter, r *http.Request) {
|
||||
m := s.readable(w, r)
|
||||
if m == nil {
|
||||
return
|
||||
}
|
||||
ms, depth, err := s.B.Store.Thread(m)
|
||||
if err != nil {
|
||||
fail(w, http.StatusInternalServerError, err.Error())
|
||||
return
|
||||
}
|
||||
out := []map[string]any{}
|
||||
for i, x := range ms {
|
||||
out = append(out, map[string]any{"message": msgOut(x, false), "depth": depth[i]})
|
||||
}
|
||||
writeJSON(w, http.StatusOK, out)
|
||||
}
|
||||
|
||||
func (s *Server) post(w http.ResponseWriter, r *http.Request) {
|
||||
@@ -599,10 +709,12 @@ func (s *Server) post(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
var req struct {
|
||||
To string `json:"to"`
|
||||
Subject string `json:"subject"`
|
||||
Body string `json:"body"`
|
||||
ReplyTo int64 `json:"reply_to"`
|
||||
To string `json:"to"`
|
||||
Subject string `json:"subject"`
|
||||
Body string `json:"body"`
|
||||
ReplyTo int64 `json:"reply_to"`
|
||||
Alias bool `json:"alias"`
|
||||
Poll []string `json:"poll"`
|
||||
}
|
||||
if !s.decode(w, r, &req) {
|
||||
return
|
||||
@@ -617,7 +729,8 @@ func (s *Server) post(w http.ResponseWriter, r *http.Request) {
|
||||
fail(w, http.StatusForbidden, "only the sysop posts here")
|
||||
return
|
||||
}
|
||||
id, err := s.agent(r).Post(a, req.To, req.Subject, lines(req.Body), req.ReplyTo)
|
||||
id, err := s.agent(r).PostWith(a, req.To, req.Subject, lines(req.Body), req.ReplyTo,
|
||||
bbs.PostOpts{Alias: req.Alias, Poll: req.Poll})
|
||||
if err != nil {
|
||||
fail(w, http.StatusBadRequest, err.Error())
|
||||
return
|
||||
@@ -1147,6 +1260,10 @@ func (s *Server) patchArea(w http.ResponseWriter, r *http.Request) {
|
||||
EchoTag *string `json:"echo_tag"`
|
||||
ReadReq *string `json:"read_require"`
|
||||
PostReq *string `json:"post_require"`
|
||||
Group *string `json:"group"`
|
||||
Aliases *bool `json:"aliases"`
|
||||
MaxMsgs *int `json:"max_messages"`
|
||||
MaxDays *int `json:"max_days"`
|
||||
}
|
||||
if !s.decode(w, r, &req) {
|
||||
return
|
||||
@@ -1191,6 +1308,26 @@ func (s *Server) patchArea(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
}
|
||||
if req.Group != nil {
|
||||
s.B.Store.SetAreaGroup(a.ID, bbs.Clean(*req.Group, 30))
|
||||
}
|
||||
if req.Aliases != nil {
|
||||
s.B.Store.SetAreaAliases(a.ID, *req.Aliases)
|
||||
}
|
||||
if req.MaxMsgs != nil || req.MaxDays != nil {
|
||||
msgs, days := a.MaxMsgs, a.MaxDays
|
||||
if req.MaxMsgs != nil {
|
||||
msgs = *req.MaxMsgs
|
||||
}
|
||||
if req.MaxDays != nil {
|
||||
days = *req.MaxDays
|
||||
}
|
||||
if msgs < 0 || days < 0 {
|
||||
fail(w, http.StatusBadRequest, "max_messages and max_days are 0 (no limit) or more")
|
||||
return
|
||||
}
|
||||
s.B.Store.SetAreaKeep(a.ID, msgs, days)
|
||||
}
|
||||
a, _ = s.B.Store.Area(a.ID)
|
||||
writeJSON(w, http.StatusOK, s.areaOut(r, a))
|
||||
}
|
||||
|
||||
@@ -400,6 +400,55 @@ func TestSysopTools(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestMessageBase(t *testing.T) {
|
||||
b, alice, sysop := setup(t)
|
||||
gen, _ := b.Store.AreaByName("General")
|
||||
b.Store.SetAreaAliases(gen.ID, true)
|
||||
tech, _ := b.Store.CreateArea("Tech", "Machines", false)
|
||||
b.Store.SetAreaGroup(tech.ID, "Hobbies")
|
||||
f := run(t, b, alice,
|
||||
// an alias and a signature
|
||||
"P", "alias", map[string]string{"alias": "Night Owl"},
|
||||
"signature", map[string]string{"1": "-- alice", "2": "at the keys"}, view.Back,
|
||||
// a post as the alias, a poll, a reply
|
||||
"M", view.Choice{Action: view.Pick, Row: 0}, // General: ungrouped, first
|
||||
view.Choice{Action: "post"}, true, draft{"All", "Hello", []string{"First."}},
|
||||
view.Choice{Action: "poll"}, map[string]string{"q": "Tea or coffee?", "a": "Tea | Coffee | "}, false,
|
||||
view.Choice{Action: view.Pick, Row: 0}, "reply", false, draft{"Night Owl", "Re: Hello", []string{"Me too."}},
|
||||
view.Back, view.Choice{Action: view.Back}, view.Choice{Action: view.Back})
|
||||
has(t, "screens", f.shown, "table Message areas: |General|Talk|0|; Hobbies|Tech|Machines|0|")
|
||||
has(t, "said", f.said, "Posted as #1.")
|
||||
has(t, "said", f.said, "Posted as #2.")
|
||||
has(t, "said", f.said, "Posted as #3.")
|
||||
m, _ := b.Store.Message(1)
|
||||
if m.From != "Night Owl" || m.FromID != alice.User().ID || !strings.HasSuffix(m.Body, "First.\n\n-- alice\nat the keys") {
|
||||
t.Errorf("as the alias: %+v", m)
|
||||
}
|
||||
if r, _ := b.Store.Message(3); r.From != "alice" || r.ReplyTo != 1 {
|
||||
t.Errorf("the reply: %+v", r)
|
||||
}
|
||||
|
||||
// the sysop: the reply's original, its thread, a vote, the poll answered
|
||||
f = run(t, b, sysop,
|
||||
"M", view.Choice{Action: view.Pick, Row: 0},
|
||||
view.Choice{Action: view.Pick, Row: -1, Num: "3"}, "original", "vote", "U", "thread",
|
||||
view.Choice{Action: view.Pick, Row: 1}, "quit",
|
||||
view.Choice{Action: view.Pick, Row: -1, Num: "2"},
|
||||
"answer", view.Choice{Action: view.Pick, Row: 1}, view.Back,
|
||||
view.Choice{Action: view.Back}, view.Choice{Action: view.Back})
|
||||
has(t, "screens", f.shown, "message Hello: First.")
|
||||
has(t, "screens", f.shown, "table Thread: Hello: Night Owl|Hello|")
|
||||
has(t, "screens", f.shown, "; alice| Re: Hello|")
|
||||
has(t, "screens", f.shown, "message Tea or coffee?: Tea or coffee?")
|
||||
has(t, "said", f.said, "Your answer is counted.")
|
||||
if up, _, _, _ := b.Store.Votes(1, 0); up != 1 {
|
||||
t.Errorf("votes up %d", up)
|
||||
}
|
||||
if _, counts, _, _ := b.Store.Poll(2, 0); counts[1] != 1 {
|
||||
t.Errorf("poll %v", counts)
|
||||
}
|
||||
}
|
||||
|
||||
func TestMailAndWho(t *testing.T) {
|
||||
b, alice, sysop := setup(t)
|
||||
f := run(t, b, alice,
|
||||
|
||||
+195
-6
@@ -3,6 +3,7 @@ package app
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"sort"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
@@ -19,6 +20,12 @@ func (s *Session) areas() error {
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
// by group (those in none first), then as they were
|
||||
sort.SliceStable(areas, func(i, j int) bool { return areas[i].Group < areas[j].Group })
|
||||
grouped := false
|
||||
for _, a := range areas {
|
||||
grouped = grouped || a.Group != ""
|
||||
}
|
||||
t := &view.Table{Title: "Message areas", Empty: "There are no message areas yet.",
|
||||
Pick: "Area number",
|
||||
Columns: []view.Column{{Title: "Area", Width: 20}, {Title: "Description", Width: 36, Wide: true},
|
||||
@@ -35,8 +42,15 @@ func (s *Session) areas() error {
|
||||
if a.New > 0 {
|
||||
nw = strconv.Itoa(a.New)
|
||||
}
|
||||
t.Rows = append(t.Rows, view.Row{Num: strconv.Itoa(i + 1), Mark: a.New > 0,
|
||||
Cells: []string{a.Name, a.Description, strconv.Itoa(a.Messages), nw}})
|
||||
cells := []string{a.Name, a.Description, strconv.Itoa(a.Messages), nw}
|
||||
if grouped {
|
||||
cells = append([]string{a.Group}, cells...)
|
||||
}
|
||||
t.Rows = append(t.Rows, view.Row{Num: strconv.Itoa(i + 1), Mark: a.New > 0, Cells: cells})
|
||||
}
|
||||
if grouped {
|
||||
t.Columns = append([]view.Column{{Title: "Group", Width: 12}}, t.Columns...)
|
||||
t.Columns[2].Width = 24 // the description gives way
|
||||
}
|
||||
c, err := s.UI.Table(t)
|
||||
if err != nil {
|
||||
@@ -155,7 +169,8 @@ func (s *Session) area(a *store.Area) error {
|
||||
{Title: "Date", Width: 11, Wide: true}},
|
||||
Actions: []view.Action{{ID: "new", Label: "Read new", Key: 'R', PF: 5}}}
|
||||
if s.B.CanPost(s.User, a) {
|
||||
t.Actions = append(t.Actions, view.Action{ID: "post", Label: "Post", Key: 'P', PF: 6})
|
||||
t.Actions = append(t.Actions, view.Action{ID: "post", Label: "Post", Key: 'P', PF: 6},
|
||||
view.Action{ID: "poll", Label: "New poll", Key: 'L', PF: 9, Short: "Poll"})
|
||||
}
|
||||
for _, m := range ms {
|
||||
t.Rows = append(t.Rows, view.Row{Num: strconv.FormatInt(m.ID, 10), Mark: m.ID > last,
|
||||
@@ -186,6 +201,12 @@ func (s *Session) area(a *store.Area) error {
|
||||
return err
|
||||
}
|
||||
}
|
||||
case "poll":
|
||||
if s.B.CanPost(s.User, a) {
|
||||
if err := s.newPoll(a); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
case view.Pick:
|
||||
var m *store.Message
|
||||
if c.Row >= 0 {
|
||||
@@ -236,7 +257,18 @@ func (s *Session) read(a *store.Area, m *store.Message) (bool, error) {
|
||||
s.N.Doing("Reading " + a.Name)
|
||||
s.B.Store.SetLastRead(s.User.ID, a.ID, m.ID)
|
||||
canDelete := s.User.Sysop || s.User.ID == m.FromID
|
||||
vm := message(m, fmt.Sprintf("%s #%d", a.Name, m.ID))
|
||||
where := fmt.Sprintf("%s #%d", a.Name, m.ID)
|
||||
if up, down, _, err := s.B.Store.Votes(m.ID, s.User.ID); err == nil && up+down > 0 {
|
||||
where += fmt.Sprintf(" (+%d -%d)", up, down)
|
||||
}
|
||||
vm := message(m, where)
|
||||
answers, counts, mine, err := s.B.Store.Poll(m.ID, s.User.ID)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
if answers != nil {
|
||||
vm.Body += pollText(answers, counts, mine)
|
||||
}
|
||||
vm.Actions = []view.Action{{ID: "next", Label: "Next", Key: 'N', PF: 11},
|
||||
{ID: "prev", Label: "Previous", Key: 'P', PF: 10, Short: "Prev"}}
|
||||
if s.B.CanPost(s.User, a) {
|
||||
@@ -246,6 +278,14 @@ func (s *Session) read(a *store.Area, m *store.Message) (bool, error) {
|
||||
if canDelete {
|
||||
vm.Actions = append(vm.Actions, view.Action{ID: "delete", Label: "Delete", Key: 'D', PF: 9, Short: "Del"})
|
||||
}
|
||||
if answers != nil {
|
||||
vm.Actions = append(vm.Actions, view.Action{ID: "answer", Label: "Answer the poll", Key: 'A', PF: 12, Short: "Answer"})
|
||||
}
|
||||
vm.Actions = append(vm.Actions, view.Action{ID: "vote", Label: "Vote", Key: 'V', PF: 1},
|
||||
view.Action{ID: "thread", Label: "Thread", Key: 'T', PF: 6})
|
||||
if m.ReplyTo != 0 {
|
||||
vm.Actions = append(vm.Actions, view.Action{ID: "original", Label: "Original", Key: 'O', PF: 2, Short: "Orig"})
|
||||
}
|
||||
vm.Quit = "quit"
|
||||
act, err := s.UI.Message(vm)
|
||||
if err != nil {
|
||||
@@ -281,6 +321,29 @@ func (s *Session) read(a *store.Area, m *store.Message) (bool, error) {
|
||||
bbs.Quote(m.From, m.Body, 8), 0); err != nil {
|
||||
return false, err
|
||||
}
|
||||
case "original":
|
||||
o, err := s.B.Store.Message(m.ReplyTo)
|
||||
if err != nil || o.AreaID != a.ID {
|
||||
s.UI.Say(view.Plain, "The message this answers is gone.")
|
||||
continue
|
||||
}
|
||||
m = o
|
||||
case "thread":
|
||||
t, err := s.thread(a, m)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
if t != nil {
|
||||
m = t
|
||||
}
|
||||
case "vote":
|
||||
if err := s.vote(m); err != nil {
|
||||
return false, err
|
||||
}
|
||||
case "answer":
|
||||
if err := s.answerPoll(m, answers, mine); err != nil {
|
||||
return false, err
|
||||
}
|
||||
case "delete":
|
||||
if !canDelete {
|
||||
continue
|
||||
@@ -301,14 +364,140 @@ func (s *Session) read(a *store.Area, m *store.Message) (bool, error) {
|
||||
}
|
||||
}
|
||||
|
||||
// pollText is a poll's answers and votes, under a message's text.
|
||||
func pollText(answers []string, counts []int, mine int) string {
|
||||
total := 0
|
||||
for _, c := range counts {
|
||||
total += c
|
||||
}
|
||||
var b strings.Builder
|
||||
b.WriteString("\n\n--- Poll: " + strconv.Itoa(total) + " votes\n")
|
||||
for i, a := range answers {
|
||||
pct := 0
|
||||
if total > 0 {
|
||||
pct = counts[i] * 100 / total
|
||||
}
|
||||
mark := " "
|
||||
if i == mine {
|
||||
mark = "*"
|
||||
}
|
||||
bar := strings.Repeat("#", pct/5)
|
||||
fmt.Fprintf(&b, "%s%2d. %-30s %3d%% %s\n", mark, i+1, bbs.Trunc(a, 30), pct, bar)
|
||||
}
|
||||
if mine >= 0 {
|
||||
b.WriteString("(* your answer)\n")
|
||||
}
|
||||
return b.String()
|
||||
}
|
||||
|
||||
// thread: the messages of m's thread, one to read (nil: none)
|
||||
func (s *Session) thread(a *store.Area, m *store.Message) (*store.Message, error) {
|
||||
ms, depth, err := s.B.Store.Thread(m)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
t := &view.Table{Title: "Thread: " + ms[0].Subject, Pick: "Number to read",
|
||||
Columns: []view.Column{{Title: "From", Width: 16}, {Title: "Subject", Width: 40},
|
||||
{Title: "Date", Width: 11, Wide: true}}}
|
||||
for i, x := range ms {
|
||||
indent := strings.Repeat(" ", min(depth[i], 8))
|
||||
t.Rows = append(t.Rows, view.Row{Num: strconv.FormatInt(x.ID, 10), Mark: x.ID == m.ID,
|
||||
Cells: []string{x.From, indent + x.Subject, x.Created.Format("01-02 15:04")}})
|
||||
}
|
||||
c, err := s.UI.Table(t)
|
||||
if err != nil || c.Action != view.Pick || c.Row < 0 {
|
||||
return nil, err
|
||||
}
|
||||
return ms[c.Row], nil
|
||||
}
|
||||
|
||||
// vote: the caller's vote on a message
|
||||
func (s *Session) vote(m *store.Message) error {
|
||||
k, err := s.UI.Menu(&view.Menu{Title: "Your vote on #" + strconv.FormatInt(m.ID, 10), Items: []view.Item{
|
||||
{Key: "U", Label: "Up"}, {Key: "D", Label: "Down"}, {Key: "N", Label: "No vote"}, {Key: "Q", Label: "Back"}}})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
v, ok := map[string]int{"U": 1, "D": -1, "N": 0}[strings.ToUpper(k)]
|
||||
if !ok {
|
||||
return nil
|
||||
}
|
||||
if m.FromID == s.User.ID && v != 0 {
|
||||
s.UI.Say(view.Plain, "Not on your own message.")
|
||||
return nil
|
||||
}
|
||||
return s.B.Store.Vote(m.ID, s.User.ID, v)
|
||||
}
|
||||
|
||||
// answerPoll: the caller's answer to a poll
|
||||
func (s *Session) answerPoll(m *store.Message, answers []string, mine int) error {
|
||||
t := &view.Table{Title: m.Subject, Pick: "Your answer", Columns: []view.Column{{Title: "Answer"}}}
|
||||
for i, a := range answers {
|
||||
t.Rows = append(t.Rows, view.Row{Num: strconv.Itoa(i + 1), Mark: i == mine, Cells: []string{a}})
|
||||
}
|
||||
c, err := s.UI.Table(t)
|
||||
if err != nil || c.Action != view.Pick || c.Row < 0 {
|
||||
return err
|
||||
}
|
||||
if err := s.B.Store.PollVote(m.ID, s.User.ID, c.Row); err != nil {
|
||||
return err
|
||||
}
|
||||
s.UI.Say(view.Good, "Your answer is counted.")
|
||||
return nil
|
||||
}
|
||||
|
||||
// newPoll: a poll posted in an area
|
||||
func (s *Session) newPoll(a *store.Area) error {
|
||||
v, ok, err := s.UI.Form(&view.Form{Title: "A poll in " + a.Name, Submit: "Post", Fields: []view.Field{
|
||||
{Name: "q", Label: "Question", Width: bbs.MaxSubjectLen},
|
||||
{Name: "a", Label: "Answers", Prompt: "Answers, parted by | (2 to 10): ", Width: 400}}})
|
||||
if err != nil || !ok || strings.TrimSpace(v["q"]) == "" {
|
||||
return err
|
||||
}
|
||||
answers := strings.Split(v["a"], "|")
|
||||
alias, err := s.asAlias(a)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
id, err := s.N.PostWith(a, "All", v["q"], []string{v["q"]}, 0, bbs.PostOpts{Poll: answers, Alias: alias})
|
||||
if err != nil {
|
||||
s.UI.Say(view.Bad, capital(err.Error())+".")
|
||||
return nil
|
||||
}
|
||||
s.UI.Say(view.Good, fmt.Sprintf("Posted as #%d.", id))
|
||||
return nil
|
||||
}
|
||||
|
||||
// asAlias asks whether to post under the caller's alias, where the area
|
||||
// takes aliases and they have one.
|
||||
func (s *Session) asAlias(a *store.Area) (bool, error) {
|
||||
u := s.refresh()
|
||||
if !a.Aliases || u.Alias == "" {
|
||||
return false, nil
|
||||
}
|
||||
return s.UI.Confirm("Post as "+u.Alias+"?", false)
|
||||
}
|
||||
|
||||
// signed is a body with the caller's signature under it.
|
||||
func (s *Session) signed(body []string) []string {
|
||||
if sig := s.User.Signature; sig != "" {
|
||||
body = append(append(body, ""), strings.Split(sig, "\n")...)
|
||||
}
|
||||
return body
|
||||
}
|
||||
|
||||
// post: a message to an area
|
||||
func (s *Session) post(a *store.Area, to, subject string, quote []string, replyTo int64) error {
|
||||
s.N.Doing("Writing in " + a.Name)
|
||||
alias, err := s.asAlias(a)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
var id int64
|
||||
sent, err := s.UI.Edit(&view.Draft{Title: "Post in " + a.Name, To: to, Subject: subject, Quote: quote,
|
||||
Send: func(to, subject string, body []string) error {
|
||||
var err error
|
||||
id, err = s.N.Post(a, to, subject, body, replyTo)
|
||||
id, err = s.N.PostWith(a, to, subject, s.signed(body), replyTo, bbs.PostOpts{Alias: alias})
|
||||
return err
|
||||
}})
|
||||
if err == nil && sent {
|
||||
@@ -331,7 +520,7 @@ func (s *Session) compose(to, subject string, quote []string, replyTo int64) err
|
||||
return nil
|
||||
},
|
||||
Send: func(to, subject string, body []string) error {
|
||||
return s.N.SendMail(to, subject, body, replyTo)
|
||||
return s.N.SendMail(to, subject, s.signed(body), replyTo)
|
||||
}}
|
||||
if s.B.Netmail != nil {
|
||||
d.ToHint = "user name, or Name@zone:net/node for FidoNet"
|
||||
|
||||
+58
-1
@@ -232,7 +232,15 @@ func (s *Session) profile() error {
|
||||
if u.About != "" {
|
||||
p.Lines = append(p.Lines, view.V("About:", u.About))
|
||||
}
|
||||
p.Actions = append(p.Actions, view.Action{ID: "about", Label: "About you", Key: 'Y', PF: 4, Short: "About"})
|
||||
if u.Alias != "" {
|
||||
p.Lines = append(p.Lines, view.V("Alias:", u.Alias))
|
||||
}
|
||||
if u.Signature != "" {
|
||||
p.Lines = append(p.Lines, view.V("Signature:", strings.ReplaceAll(u.Signature, "\n", " / ")))
|
||||
}
|
||||
p.Actions = append(p.Actions, view.Action{ID: "about", Label: "About you", Key: 'Y', PF: 4, Short: "About"},
|
||||
view.Action{ID: "alias", Label: "Alias", Key: 'I', PF: 2},
|
||||
view.Action{ID: "signature", Label: "Signature", Key: 'G', PF: 1, Short: "Sig"})
|
||||
if s.UI.Kind() == Text {
|
||||
mode := "off"
|
||||
if s.expert() {
|
||||
@@ -282,6 +290,55 @@ func (s *Session) profile() error {
|
||||
return err
|
||||
}
|
||||
}
|
||||
case "alias":
|
||||
v, ok, err := s.UI.Form(&view.Form{Title: "Your alias", Submit: "Save", Fields: []view.Field{
|
||||
{Name: "alias", Label: "Alias", Prompt: "An alias to post under where areas allow (Enter keeps it, - clears it): ",
|
||||
Width: bbs.MaxNameLen, Value: u.Alias}}})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
alias := strings.TrimSpace(v["alias"])
|
||||
if alias == "-" {
|
||||
alias = ""
|
||||
}
|
||||
if alias != "" {
|
||||
if msg := s.N.CheckNewName(alias); msg != "" {
|
||||
s.UI.Say(view.Bad, msg)
|
||||
continue
|
||||
}
|
||||
}
|
||||
switch err := s.B.Store.SetAlias(u.ID, alias); {
|
||||
case errors.Is(err, store.ErrExists):
|
||||
s.UI.Say(view.Bad, "That is someone's name or alias.")
|
||||
case err != nil:
|
||||
return err
|
||||
}
|
||||
case "signature":
|
||||
v, ok, err := s.UI.Form(&view.Form{Title: "Your signature", Submit: "Save",
|
||||
Intro: []view.Line{view.L("Up to three lines, put under your posts and mail; - clears it.")},
|
||||
Fields: []view.Field{{Name: "1", Label: "Line 1", Width: 70}, {Name: "2", Label: "Line 2", Width: 70},
|
||||
{Name: "3", Label: "Line 3", Width: 70}}})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
var ls []string
|
||||
for _, k := range []string{"1", "2", "3"} {
|
||||
if l := bbs.Clean(v[k], 70); l != "" {
|
||||
ls = append(ls, l)
|
||||
}
|
||||
}
|
||||
if len(ls) == 1 && ls[0] == "-" {
|
||||
ls = nil
|
||||
}
|
||||
if err := s.B.Store.SetSignature(u.ID, strings.Join(ls, "\n")); err != nil {
|
||||
return err
|
||||
}
|
||||
case "expert":
|
||||
v := "on"
|
||||
if s.expert() {
|
||||
|
||||
+43
-2
@@ -524,17 +524,51 @@ func (b *BBS) MOTDText() string {
|
||||
|
||||
// Post cleans and posts a message.
|
||||
func (n *Node) Post(a *store.Area, to, subject string, body []string, replyTo int64) (int64, error) {
|
||||
return n.PostWith(a, to, subject, body, replyTo, PostOpts{})
|
||||
}
|
||||
|
||||
// PostOpts are a post's choices: under the poster's alias (where the area
|
||||
// allows), a poll's answers.
|
||||
type PostOpts struct {
|
||||
Alias bool
|
||||
Poll []string
|
||||
}
|
||||
|
||||
// MaxPollAnswers is the most answers a poll has.
|
||||
const MaxPollAnswers = 10
|
||||
|
||||
// PostWith is Post with choices.
|
||||
func (n *Node) PostWith(a *store.Area, to, subject string, body []string, replyTo int64, o PostOpts) (int64, error) {
|
||||
u := n.User()
|
||||
if u == nil {
|
||||
return 0, errors.New("not logged in")
|
||||
}
|
||||
var answers []string
|
||||
for _, p := range o.Poll {
|
||||
if p = Clean(p, 60); p != "" {
|
||||
answers = append(answers, p)
|
||||
}
|
||||
}
|
||||
if o.Poll != nil && (len(answers) < 2 || len(answers) > MaxPollAnswers) {
|
||||
return 0, fmt.Errorf("a poll has 2 to %d answers", MaxPollAnswers)
|
||||
}
|
||||
from := u.Name
|
||||
if o.Alias {
|
||||
if !a.Aliases {
|
||||
return 0, errors.New("this area takes no aliases")
|
||||
}
|
||||
if u.Alias == "" {
|
||||
return 0, errors.New("you have no alias (set one in your profile)")
|
||||
}
|
||||
from = u.Alias
|
||||
}
|
||||
if !n.b.CanPost(u, a) {
|
||||
if a.SysopOnly {
|
||||
return 0, errors.New("only the sysop posts here")
|
||||
}
|
||||
return 0, errors.New("your access does not allow posting here")
|
||||
}
|
||||
m := &store.Message{AreaID: a.ID, FromID: u.ID, From: u.Name,
|
||||
m := &store.Message{AreaID: a.ID, FromID: u.ID, From: from,
|
||||
To: Clean(to, MaxNameLen), Subject: Clean(subject, MaxSubjectLen),
|
||||
Body: CleanBody(body), ReplyTo: replyTo}
|
||||
if m.To == "" {
|
||||
@@ -548,9 +582,16 @@ func (n *Node) Post(a *store.Area, to, subject string, body []string, replyTo in
|
||||
}
|
||||
n.b.MakeArticle(u, a, m)
|
||||
id, err := n.b.Store.Post(m)
|
||||
if err == nil && answers != nil {
|
||||
err = n.b.Store.SetPoll(id, answers)
|
||||
}
|
||||
if err == nil {
|
||||
n.b.Stats.Posts.Add(1)
|
||||
n.b.Log.Printf("node %d: %s posted #%d in %s", n.Num, u.Name, id, a.Name)
|
||||
as := ""
|
||||
if o.Alias {
|
||||
as = " as " + from
|
||||
}
|
||||
n.b.Log.Printf("node %d: %s posted #%d in %s%s", n.Num, u.Name, id, a.Name, as)
|
||||
}
|
||||
return id, err
|
||||
}
|
||||
|
||||
@@ -55,7 +55,7 @@ func (b *BBS) MakeArticle(u *store.User, a *store.Area, m *store.Message) {
|
||||
}
|
||||
}
|
||||
m.MessageID = news.NewMessageID(ns.Domain)
|
||||
art := news.New(news.Local{Name: u.Name, Address: localPart(u.Name) + "@" + ns.Domain,
|
||||
art := news.New(news.Local{Name: m.From, Address: localPart(m.From) + "@" + ns.Domain,
|
||||
Group: a.Newsgroup, Subject: m.Subject, Body: m.Body, References: refs,
|
||||
MessageID: m.MessageID, PathHost: ns.PathHost, Organization: ns.Organization})
|
||||
m.Raw = art.Bytes()
|
||||
|
||||
@@ -125,3 +125,27 @@ func (b *BBS) SetSysopAvailable(on bool) {
|
||||
b.sysopAway.Store(!on)
|
||||
b.Log.Printf("the sysop is %s", map[bool]string{true: "available for chat", false: "not available for chat"}[on])
|
||||
}
|
||||
|
||||
// PurgeAreas takes away the messages each area keeps no more (its
|
||||
// max_msgs, max_days); how many went.
|
||||
func (b *BBS) PurgeAreas() (int, error) {
|
||||
as, err := b.Store.Areas()
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
total := 0
|
||||
for _, a := range as {
|
||||
if a.MaxMsgs == 0 && a.MaxDays == 0 {
|
||||
continue
|
||||
}
|
||||
n, err := b.Store.Purge(a)
|
||||
if err != nil {
|
||||
return total, fmt.Errorf("%s: %w", a.Name, err)
|
||||
}
|
||||
if n > 0 {
|
||||
b.Log.Printf("purged %d messages from %s", n, a.Name)
|
||||
}
|
||||
total += n
|
||||
}
|
||||
return total, nil
|
||||
}
|
||||
@@ -50,12 +50,12 @@ func TestShared3270(t *testing.T) {
|
||||
d.expect("Area number, [N]ew scan, [T]o you, [F]ind, [S]can setup, [+] add area, [Q]uit: ")
|
||||
d.send("1\r")
|
||||
d.expect("Hello from a 3270")
|
||||
d.expect("Number to read, [R]ead new, [P]ost, [Q]uit: ")
|
||||
d.expect("Number to read, [R]ead new, [P]ost, [L] New poll, [Q]uit: ")
|
||||
d.send("1\r")
|
||||
d.expect("A line of the body.")
|
||||
d.expect("[N]ext, [P]revious, [R]eply, [M]ail reply, [D]elete, [Q]uit: ")
|
||||
d.expect("[N]ext, [P]revious, [R]eply, [M]ail reply, [D]elete, [V]ote, [T]hread, [Q]uit: ")
|
||||
d.send("Q")
|
||||
d.expect("[P]ost, [Q]uit: ")
|
||||
d.expect("[P]ost, [L] New poll, [Q]uit: ")
|
||||
d.send("Q\r")
|
||||
d.expect("[+] add area, [Q]uit: ")
|
||||
d.send("Q\r")
|
||||
|
||||
@@ -21,7 +21,7 @@ func TestFullScreenEditor(t *testing.T) {
|
||||
d.send("M")
|
||||
d.expect("[Q]uit: ")
|
||||
d.send("1\r")
|
||||
d.expect("[P]ost, [Q]uit: ")
|
||||
d.expect("[P]ost, [L] New poll, [Q]uit: ")
|
||||
d.send("P\r")
|
||||
d.expect("To [All]: ")
|
||||
d.send("\r")
|
||||
@@ -39,7 +39,7 @@ func TestFullScreenEditor(t *testing.T) {
|
||||
}
|
||||
|
||||
// a reply: the quote window, a line taken from it, the line editor's /S
|
||||
d.expect("[P]ost, [Q]uit: ")
|
||||
d.expect("[P]ost, [L] New poll, [Q]uit: ")
|
||||
d.send("1\r")
|
||||
d.expect("[R]eply")
|
||||
d.send("R")
|
||||
|
||||
@@ -216,7 +216,7 @@ func TestLoginAndPost(t *testing.T) {
|
||||
d.send("M")
|
||||
d.expect("[Q]uit: ")
|
||||
d.send("1\r")
|
||||
d.expect("[P]ost, [Q]uit: ")
|
||||
d.expect("[P]ost, [L] New poll, [Q]uit: ")
|
||||
d.send("P\r")
|
||||
d.expect("To [All]: ")
|
||||
d.send("\r")
|
||||
|
||||
@@ -8,7 +8,7 @@ import (
|
||||
)
|
||||
|
||||
// copyOrder is the tables in an order their references allow.
|
||||
var copyOrder = []string{"users", "areas", "messages", "lastread", "scan_off", "mail", "file_areas", "files",
|
||||
var copyOrder = []string{"users", "areas", "messages", "votes", "poll_answers", "poll_votes", "lastread", "scan_off", "mail", "file_areas", "files",
|
||||
"history", "peer_groups", "peer_push", "netmail_out", "api_tokens", "ssh_keys", "script_data", "calls"}
|
||||
|
||||
var columnPat = regexp.MustCompile(`(?m)^\s*("?\w+"?)\s+(\{\w+\})`)
|
||||
|
||||
@@ -0,0 +1,220 @@
|
||||
package store
|
||||
|
||||
import (
|
||||
"database/sql"
|
||||
"errors"
|
||||
"time"
|
||||
)
|
||||
|
||||
// The message base's depth: areas' groups, aliases and how long messages
|
||||
// are kept; threads; votes and polls; users' aliases and signatures.
|
||||
|
||||
// SetAreaGroup puts an area in a group ("": none).
|
||||
func (s *Store) SetAreaGroup(id int64, group string) error {
|
||||
return s.exec1(`UPDATE areas SET grp = ? WHERE id = ?`, group, id)
|
||||
}
|
||||
|
||||
// SetAreaAliases says whether an area's posters may use their aliases.
|
||||
func (s *Store) SetAreaAliases(id int64, on bool) error {
|
||||
return s.exec1(`UPDATE areas SET aliases = ? WHERE id = ?`, on, id)
|
||||
}
|
||||
|
||||
// SetAreaKeep says how many messages an area keeps, and for how many days
|
||||
// (0: no limit).
|
||||
func (s *Store) SetAreaKeep(id int64, msgs, days int) error {
|
||||
return s.exec1(`UPDATE areas SET max_msgs = ?, max_days = ? WHERE id = ?`, msgs, days, id)
|
||||
}
|
||||
|
||||
// Purge takes away an area's messages beyond what it keeps: more than its
|
||||
// newest MaxMsgs, older than MaxDays. How many went.
|
||||
func (s *Store) Purge(a *Area) (int, error) {
|
||||
n := 0
|
||||
if a.MaxDays > 0 {
|
||||
res, err := s.db.Exec(`DELETE FROM messages WHERE area_id = ? AND created < ?`,
|
||||
a.ID, time.Now().AddDate(0, 0, -a.MaxDays).Unix())
|
||||
if err != nil {
|
||||
return n, err
|
||||
}
|
||||
k, _ := res.RowsAffected()
|
||||
n += int(k)
|
||||
}
|
||||
if a.MaxMsgs > 0 {
|
||||
var last int64
|
||||
err := s.db.QueryRow(`SELECT id FROM messages WHERE area_id = ? ORDER BY id DESC LIMIT 1 OFFSET ?`,
|
||||
a.ID, a.MaxMsgs).Scan(&last)
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
return n, nil
|
||||
}
|
||||
if err != nil {
|
||||
return n, err
|
||||
}
|
||||
res, err := s.db.Exec(`DELETE FROM messages WHERE area_id = ? AND id <= ?`, a.ID, last)
|
||||
if err != nil {
|
||||
return n, err
|
||||
}
|
||||
k, _ := res.RowsAffected()
|
||||
n += int(k)
|
||||
}
|
||||
return n, nil
|
||||
}
|
||||
|
||||
// Thread is the messages of m's thread, in its area: from the message it
|
||||
// all began with, each followed by its replies (depth: how far down).
|
||||
func (s *Store) Thread(m *Message) ([]*Message, []int, error) {
|
||||
// up to the start (within the area, at most 1000 steps)
|
||||
root := m
|
||||
for i := 0; i < 1000 && root.ReplyTo != 0; i++ {
|
||||
p, err := s.Message(root.ReplyTo)
|
||||
if errors.Is(err, ErrNotFound) || err == nil && p.AreaID != m.AreaID {
|
||||
break
|
||||
}
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
root = p
|
||||
}
|
||||
var out []*Message
|
||||
var depth []int
|
||||
seen := map[int64]bool{}
|
||||
var walk func(m *Message, d int) error
|
||||
walk = func(m *Message, d int) error {
|
||||
if seen[m.ID] || len(out) >= 1000 {
|
||||
return nil
|
||||
}
|
||||
seen[m.ID] = true
|
||||
out, depth = append(out, m), append(depth, d)
|
||||
kids, err := s.messageList(`SELECT `+msgCols+` FROM messages WHERE reply_to = ? AND area_id = ? ORDER BY id`,
|
||||
m.ID, m.AreaID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
for _, k := range kids {
|
||||
if err := walk(k, d+1); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
return out, depth, walk(root, 0)
|
||||
}
|
||||
|
||||
// Vote sets a user's vote on a message: 1 up, -1 down, 0 none.
|
||||
func (s *Store) Vote(msg, user int64, value int) error {
|
||||
if value == 0 {
|
||||
_, err := s.db.Exec(`DELETE FROM votes WHERE message_id = ? AND user_id = ?`, msg, user)
|
||||
return err
|
||||
}
|
||||
_, err := s.db.Exec(`INSERT INTO votes (message_id, user_id, value) VALUES (?, ?, ?)
|
||||
ON CONFLICT (message_id, user_id) DO UPDATE SET value = excluded.value`, msg, user, value)
|
||||
return err
|
||||
}
|
||||
|
||||
// Votes are a message's votes up and down, and the user's (1, -1 or 0).
|
||||
func (s *Store) Votes(msg, user int64) (up, down, mine int, err error) {
|
||||
rows, err := s.db.Query(`SELECT user_id, value FROM votes WHERE message_id = ?`, msg)
|
||||
if err != nil {
|
||||
return 0, 0, 0, err
|
||||
}
|
||||
defer rows.Close()
|
||||
for rows.Next() {
|
||||
var u int64
|
||||
var v int
|
||||
if err := rows.Scan(&u, &v); err != nil {
|
||||
return 0, 0, 0, err
|
||||
}
|
||||
if v > 0 {
|
||||
up++
|
||||
} else {
|
||||
down++
|
||||
}
|
||||
if u == user {
|
||||
mine = v
|
||||
}
|
||||
}
|
||||
return up, down, mine, rows.Err()
|
||||
}
|
||||
|
||||
// SetPoll makes a message a poll with these answers.
|
||||
func (s *Store) SetPoll(msg int64, answers []string) error {
|
||||
tx, err := s.db.Begin()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer tx.Rollback()
|
||||
for i, a := range answers {
|
||||
if _, err := tx.Exec(`INSERT INTO poll_answers (message_id, idx, text) VALUES (?, ?, ?)`, msg, i, a); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return tx.Commit()
|
||||
}
|
||||
|
||||
// Poll is a message's poll: its answers, each one's votes, and the
|
||||
// user's answer (-1: none). No answers: the message is no poll.
|
||||
func (s *Store) Poll(msg, user int64) (answers []string, counts []int, mine int, err error) {
|
||||
rows, err := s.db.Query(`SELECT text FROM poll_answers WHERE message_id = ? ORDER BY idx`, msg)
|
||||
if err != nil {
|
||||
return nil, nil, -1, err
|
||||
}
|
||||
for rows.Next() {
|
||||
var t string
|
||||
if err := rows.Scan(&t); err != nil {
|
||||
rows.Close()
|
||||
return nil, nil, -1, err
|
||||
}
|
||||
answers = append(answers, t)
|
||||
}
|
||||
rows.Close()
|
||||
mine = -1
|
||||
if len(answers) == 0 {
|
||||
return nil, nil, -1, nil
|
||||
}
|
||||
counts = make([]int, len(answers))
|
||||
rows, err = s.db.Query(`SELECT user_id, idx FROM poll_votes WHERE message_id = ?`, msg)
|
||||
if err != nil {
|
||||
return nil, nil, -1, err
|
||||
}
|
||||
defer rows.Close()
|
||||
for rows.Next() {
|
||||
var u int64
|
||||
var i int
|
||||
if err := rows.Scan(&u, &i); err != nil {
|
||||
return nil, nil, -1, err
|
||||
}
|
||||
if i >= 0 && i < len(counts) {
|
||||
counts[i]++
|
||||
}
|
||||
if u == user {
|
||||
mine = i
|
||||
}
|
||||
}
|
||||
return answers, counts, mine, rows.Err()
|
||||
}
|
||||
|
||||
// PollVote is a user's answer to a poll (again: their answer changes).
|
||||
func (s *Store) PollVote(msg, user int64, idx int) error {
|
||||
_, err := s.db.Exec(`INSERT INTO poll_votes (message_id, user_id, idx) VALUES (?, ?, ?)
|
||||
ON CONFLICT (message_id, user_id) DO UPDATE SET idx = excluded.idx`, msg, user, idx)
|
||||
return err
|
||||
}
|
||||
|
||||
// SetAlias sets a user's alias ("": none); ErrExists if it is another's
|
||||
// name or alias.
|
||||
func (s *Store) SetAlias(id int64, alias string) error {
|
||||
if alias != "" {
|
||||
var n int
|
||||
if err := s.db.QueryRow(`SELECT COUNT(*) FROM users WHERE id <> ? AND (name = ? OR LOWER(alias) = LOWER(?))`,
|
||||
id, alias, alias).Scan(&n); err != nil {
|
||||
return err
|
||||
}
|
||||
if n > 0 {
|
||||
return ErrExists
|
||||
}
|
||||
}
|
||||
return s.exec1(`UPDATE users SET alias = ? WHERE id = ?`, alias, id)
|
||||
}
|
||||
|
||||
// SetSignature sets a user's signature.
|
||||
func (s *Store) SetSignature(id int64, sig string) error {
|
||||
return s.exec1(`UPDATE users SET signature = ? WHERE id = ?`, sig, id)
|
||||
}
|
||||
@@ -29,7 +29,9 @@ CREATE TABLE IF NOT EXISTS users (
|
||||
dl_count {int} NOT NULL DEFAULT 0,
|
||||
prefs {str} NOT NULL DEFAULT '',
|
||||
downloads {int} NOT NULL DEFAULT 0,
|
||||
about {str} NOT NULL DEFAULT ''
|
||||
about {str} NOT NULL DEFAULT '',
|
||||
alias {str} NOT NULL DEFAULT '',
|
||||
signature {str} NOT NULL DEFAULT ''
|
||||
)`, `
|
||||
CREATE TABLE IF NOT EXISTS areas (
|
||||
id {id},
|
||||
@@ -39,7 +41,11 @@ CREATE TABLE IF NOT EXISTS areas (
|
||||
newsgroup {key},
|
||||
echotag {key},
|
||||
read_req {str} NOT NULL DEFAULT '',
|
||||
post_req {str} NOT NULL DEFAULT ''
|
||||
post_req {str} NOT NULL DEFAULT '',
|
||||
grp {str} NOT NULL DEFAULT '',
|
||||
aliases {bool} NOT NULL DEFAULT FALSE,
|
||||
max_msgs {int} NOT NULL DEFAULT 0,
|
||||
max_days {int} NOT NULL DEFAULT 0
|
||||
)`, `
|
||||
CREATE TABLE IF NOT EXISTS messages (
|
||||
id {id},
|
||||
@@ -75,6 +81,24 @@ CREATE TABLE IF NOT EXISTS script_data (
|
||||
value {text} NOT NULL,
|
||||
PRIMARY KEY (script, user_id, name)
|
||||
)`, `
|
||||
CREATE TABLE IF NOT EXISTS votes (
|
||||
message_id {int} NOT NULL REFERENCES messages(id) ON DELETE CASCADE,
|
||||
user_id {int} NOT NULL,
|
||||
value {int} NOT NULL,
|
||||
PRIMARY KEY (message_id, user_id)
|
||||
)`, `
|
||||
CREATE TABLE IF NOT EXISTS poll_answers (
|
||||
message_id {int} NOT NULL REFERENCES messages(id) ON DELETE CASCADE,
|
||||
idx {int} NOT NULL,
|
||||
text {str} NOT NULL,
|
||||
PRIMARY KEY (message_id, idx)
|
||||
)`, `
|
||||
CREATE TABLE IF NOT EXISTS poll_votes (
|
||||
message_id {int} NOT NULL REFERENCES messages(id) ON DELETE CASCADE,
|
||||
user_id {int} NOT NULL,
|
||||
idx {int} NOT NULL,
|
||||
PRIMARY KEY (message_id, user_id)
|
||||
)`, `
|
||||
CREATE TABLE IF NOT EXISTS calls (
|
||||
id {id},
|
||||
user_id {int} NOT NULL,
|
||||
@@ -176,6 +200,7 @@ var indexes = []struct {
|
||||
unique bool
|
||||
}{
|
||||
{"messages_area", "messages", "area_id, id", false},
|
||||
{"messages_reply", "messages", "reply_to", false},
|
||||
{"mail_to", "mail", "to_id, id", false},
|
||||
{"files_uploader", "files", "uploader_id, created", false},
|
||||
{"areas_newsgroup", "areas", "newsgroup", true},
|
||||
@@ -214,6 +239,12 @@ var added = []struct{ table, column, decl string }{
|
||||
{"files", "long_desc", "{text}"},
|
||||
{"users", "downloads", "{int} NOT NULL DEFAULT 0"},
|
||||
{"users", "about", "{str} NOT NULL DEFAULT ''"},
|
||||
{"users", "alias", "{str} NOT NULL DEFAULT ''"},
|
||||
{"users", "signature", "{str} NOT NULL DEFAULT ''"},
|
||||
{"areas", "grp", "{str} NOT NULL DEFAULT ''"},
|
||||
{"areas", "aliases", "{bool} NOT NULL DEFAULT FALSE"},
|
||||
{"areas", "max_msgs", "{int} NOT NULL DEFAULT 0"},
|
||||
{"areas", "max_days", "{int} NOT NULL DEFAULT 0"},
|
||||
}
|
||||
|
||||
// migrate makes the schema, or brings an older database up to it.
|
||||
|
||||
+10
-4
@@ -50,6 +50,8 @@ type User struct {
|
||||
// files downloaded ever, and uploaded (the files there now)
|
||||
Downloads, Uploads int
|
||||
About string // a line about themselves
|
||||
Alias string // a name they may post under where an area allows ("": none)
|
||||
Signature string // lines put under what they write
|
||||
}
|
||||
|
||||
// Area is a message area.
|
||||
@@ -62,6 +64,10 @@ type Area struct {
|
||||
PostReq string // and to post
|
||||
Newsgroup string // its newsgroup ("": not one)
|
||||
EchoTag string // its FidoNet echo ("": not one)
|
||||
Group string // the group it is listed under ("": none)
|
||||
Aliases bool // its posters may use their aliases
|
||||
MaxMsgs int // the newest kept (0: all)
|
||||
MaxDays int // the days a message is kept (0: for ever)
|
||||
Messages int
|
||||
FirstID int64
|
||||
LastID int64
|
||||
@@ -190,7 +196,7 @@ func HashPassword(pw string) (string, error) {
|
||||
}
|
||||
|
||||
const userCols = `id, name, password, location, sysop, locked, created, last_login, logins, posts,
|
||||
level, flags, time_day, time_used, dl_day, dl_count, prefs, downloads, about,
|
||||
level, flags, time_day, time_used, dl_day, dl_count, prefs, downloads, about, alias, signature,
|
||||
(SELECT COUNT(*) FROM files WHERE files.uploader_id = users.id)`
|
||||
|
||||
func scanUser(row interface{ Scan(...any) error }) (*User, string, error) {
|
||||
@@ -199,7 +205,7 @@ func scanUser(row interface{ Scan(...any) error }) (*User, string, error) {
|
||||
var created, last int64
|
||||
err := row.Scan(&u.ID, &u.Name, &pw, &u.Location, &u.Sysop, &u.Locked,
|
||||
&created, &last, &u.Logins, &u.Posts, &u.Level, &u.Flags, &u.TimeDay, &u.TimeUsed, &u.DLDay, &u.DLCount, &u.Prefs,
|
||||
&u.Downloads, &u.About, &u.Uploads)
|
||||
&u.Downloads, &u.About, &u.Alias, &u.Signature, &u.Uploads)
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
return nil, "", ErrNotFound
|
||||
}
|
||||
@@ -359,7 +365,7 @@ func (s *Store) DeleteArea(id int64) error {
|
||||
}
|
||||
|
||||
const areaQuery = `SELECT a.id, a.name, a.description, a.sysop_only, COALESCE(a.newsgroup, ''), COALESCE(a.echotag, ''),
|
||||
a.read_req, a.post_req,
|
||||
a.read_req, a.post_req, a.grp, a.aliases, a.max_msgs, a.max_days,
|
||||
(SELECT COUNT(*) FROM messages m WHERE m.area_id = a.id),
|
||||
(SELECT COALESCE(MIN(m.id), 0) FROM messages m WHERE m.area_id = a.id),
|
||||
(SELECT COALESCE(MAX(m.id), 0) FROM messages m WHERE m.area_id = a.id)
|
||||
@@ -367,7 +373,7 @@ const areaQuery = `SELECT a.id, a.name, a.description, a.sysop_only, COALESCE(a.
|
||||
|
||||
func scanArea(row interface{ Scan(...any) error }) (*Area, error) {
|
||||
var a Area
|
||||
err := row.Scan(&a.ID, &a.Name, &a.Description, &a.SysopOnly, &a.Newsgroup, &a.EchoTag, &a.ReadReq, &a.PostReq, &a.Messages,
|
||||
err := row.Scan(&a.ID, &a.Name, &a.Description, &a.SysopOnly, &a.Newsgroup, &a.EchoTag, &a.ReadReq, &a.PostReq, &a.Group, &a.Aliases, &a.MaxMsgs, &a.MaxDays, &a.Messages,
|
||||
&a.FirstID, &a.LastID)
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
return nil, ErrNotFound
|
||||
|
||||
@@ -420,3 +420,100 @@ func TestScriptData(t *testing.T) {
|
||||
t.Errorf("a deleted user's: %d", n)
|
||||
}
|
||||
}
|
||||
|
||||
func TestMessageBaseDepth(t *testing.T) {
|
||||
s := open(t)
|
||||
u, _ := s.CreateUser("alice", "password1", "", false)
|
||||
b, _ := s.CreateUser("bob", "password1", "", false)
|
||||
a, _ := s.CreateArea("General", "", false)
|
||||
post := func(subject string, reply int64, ago time.Duration) int64 {
|
||||
id, err := s.Post(&Message{AreaID: a.ID, FromID: u.ID, From: "alice", To: "All", Subject: subject, Body: "x", ReplyTo: reply})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if ago > 0 {
|
||||
s.db.Exec(`UPDATE messages SET created = ? WHERE id = ?`, time.Now().Add(-ago).Unix(), id)
|
||||
}
|
||||
return id
|
||||
}
|
||||
root := post("Start", 0, 0)
|
||||
r1 := post("Re: Start", root, 0)
|
||||
post("Other", 0, 0)
|
||||
r2 := post("Re: Re: Start", r1, 0)
|
||||
r3 := post("Re: Start again", root, 0)
|
||||
m, _ := s.Message(r2)
|
||||
thread, depth, err := s.Thread(m)
|
||||
var got []string
|
||||
for i, m := range thread {
|
||||
got = append(got, fmt.Sprintf("%d:%s", depth[i], m.Subject))
|
||||
}
|
||||
if err != nil || strings.Join(got, ",") != "0:Start,1:Re: Start,2:Re: Re: Start,1:Re: Start again" {
|
||||
t.Errorf("thread %v %v", got, err)
|
||||
}
|
||||
_ = r3
|
||||
|
||||
// votes
|
||||
s.Vote(root, u.ID, 1)
|
||||
s.Vote(root, b.ID, -1)
|
||||
s.Vote(root, b.ID, 1)
|
||||
if up, down, mine, err := s.Votes(root, b.ID); up != 2 || down != 0 || mine != 1 || err != nil {
|
||||
t.Errorf("votes %d %d %d %v", up, down, mine, err)
|
||||
}
|
||||
s.Vote(root, b.ID, 0)
|
||||
if up, _, mine, _ := s.Votes(root, b.ID); up != 1 || mine != 0 {
|
||||
t.Errorf("unvoted %d %d", up, mine)
|
||||
}
|
||||
|
||||
// a poll
|
||||
p := post("Tea or coffee?", 0, 0)
|
||||
if ans, _, _, _ := s.Poll(root, u.ID); ans != nil {
|
||||
t.Error("not a poll")
|
||||
}
|
||||
s.SetPoll(p, []string{"Tea", "Coffee"})
|
||||
s.PollVote(p, u.ID, 1)
|
||||
s.PollVote(p, b.ID, 0)
|
||||
s.PollVote(p, b.ID, 1)
|
||||
if ans, counts, mine, err := s.Poll(p, b.ID); len(ans) != 2 || counts[0] != 0 || counts[1] != 2 || mine != 1 || err != nil {
|
||||
t.Errorf("poll %v %v %d %v", ans, counts, mine, err)
|
||||
}
|
||||
|
||||
// aliases and signatures
|
||||
if err := s.SetAlias(u.ID, "Bob"); err != ErrExists {
|
||||
t.Errorf("another's name: %v", err)
|
||||
}
|
||||
if err := s.SetAlias(u.ID, "Night Owl"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := s.SetAlias(b.ID, "night owl"); err != ErrExists {
|
||||
t.Errorf("another's alias: %v", err)
|
||||
}
|
||||
s.SetSignature(u.ID, "-- alice\nat the keys")
|
||||
if x, _ := s.UserByID(u.ID); x.Alias != "Night Owl" || x.Signature != "-- alice\nat the keys" {
|
||||
t.Errorf("user %+v", x)
|
||||
}
|
||||
|
||||
// groups and keeping
|
||||
s.SetAreaGroup(a.ID, "Local")
|
||||
s.SetAreaAliases(a.ID, true)
|
||||
s.SetAreaKeep(a.ID, 3, 0)
|
||||
a, _ = s.Area(a.ID)
|
||||
if a.Group != "Local" || !a.Aliases || a.MaxMsgs != 3 {
|
||||
t.Errorf("area %+v", a)
|
||||
}
|
||||
n, err := s.Purge(a)
|
||||
if err != nil || n != 3 || a.Messages != 6 {
|
||||
t.Errorf("purged %d %v (of %d)", n, err, a.Messages)
|
||||
}
|
||||
if _, err := s.Message(root); err != ErrNotFound {
|
||||
t.Error("the oldest kept")
|
||||
}
|
||||
old := post("Old", 0, 40*24*time.Hour)
|
||||
s.SetAreaKeep(a.ID, 0, 30)
|
||||
a, _ = s.Area(a.ID)
|
||||
if n, _ := s.Purge(a); n != 1 {
|
||||
t.Errorf("by age: %d", n)
|
||||
}
|
||||
if _, err := s.Message(old); err != ErrNotFound {
|
||||
t.Error("an old one kept")
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user