This repository has been archived by the owner on Aug 21, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathsave.go
71 lines (63 loc) · 2.05 KB
/
save.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
package main
import (
"database/sql"
"encoding/json"
"errors"
"fmt"
"strings"
"github.com/fiatjaf/go-nostr"
)
func (relay *ExpensiveRelay) SaveEvent(evt *nostr.Event) error {
// disallow large contents
if len(evt.Content) > 10000 {
return errors.New("event content too large")
}
// check if user is registered
var registered bool
if err := relay.db.Get(®istered, `
SELECT true FROM registered_users
WHERE pubkey = $1 AND registered_at IS NOT NULL
`, evt.PubKey); err != nil {
if err == sql.ErrNoRows {
return fmt.Errorf("%s not registered", evt.PubKey)
} else {
return fmt.Errorf("error reading users table: %w", err)
}
} else if !registered {
return fmt.Errorf("%s's invoice was not paid", evt.PubKey)
}
// react to different kinds of events
switch evt.Kind {
case nostr.KindSetMetadata:
// delete past set_metadata events from this user
relay.db.Exec(`DELETE FROM event WHERE pubkey = $1 AND kind = 0`, evt.PubKey)
case nostr.KindRecommendServer:
// delete past recommend_server events equal to this one
relay.db.Exec(`DELETE FROM event WHERE pubkey = $1 AND kind = 2 AND content = $2`,
evt.PubKey, evt.Content)
case nostr.KindContactList:
// delete past contact lists from this same pubkey
relay.db.Exec(`DELETE FROM event WHERE pubkey = $1 AND kind = 3`, evt.PubKey)
default:
// delete all but the 10 most recent ones
relay.db.Exec(`DELETE FROM event WHERE pubkey = $1 AND kind = $2 AND created_at < (
SELECT created_at FROM event WHERE pubkey = $1
ORDER BY created_at DESC OFFSET 10 LIMIT 1
)`,
evt.PubKey, evt.Kind)
}
// insert
tagsj, _ := json.Marshal(evt.Tags)
_, err := relay.db.Exec(`
INSERT INTO event (id, pubkey, created_at, kind, tags, content, sig)
VALUES ($1, $2, $3, $4, $5, $6, $7)
`, evt.ID, evt.PubKey, evt.CreatedAt.Unix(), evt.Kind, tagsj, evt.Content, evt.Sig)
if err != nil {
if strings.Index(err.Error(), "UNIQUE") != -1 {
// already exists
return nil
}
return fmt.Errorf("failed to save event from %s", evt.PubKey)
}
return nil
}