-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathmain.go
More file actions
289 lines (250 loc) · 8 KB
/
Copy pathmain.go
File metadata and controls
289 lines (250 loc) · 8 KB
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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
package main
import (
"context"
"database/sql"
"flag"
"fmt"
"io"
"log"
"net/http"
"os"
"strconv"
"time"
"github.com/fiatjaf/khatru"
"github.com/fiatjaf/khatru/policies"
"github.com/joho/godotenv"
"github.com/nbd-wtf/go-nostr"
)
var ctx = context.Background()
var pool = nostr.NewSimplePool(ctx)
var repository *NostrRepository
var relays = []string{
"wss://relay.lexingtonbitcoin.org",
"wss://nostr.600.wtf",
"wss://nostr.hexhex.online",
"wss://wot.utxo.one",
"wss://nostrelites.org",
"wss://wot.nostr.party",
"wss://wot.puhcho.me",
"wss://wot.girino.org",
"wss://relay.beeola.me",
"wss://zap.watch",
"wss://wot.yeghro.site",
"wss://wot.innovativecerebrum.ai",
"wss://wot.swarmstr.com",
"wss://wot.azzamo.net",
"wss://satsage.xyz",
"wss://wot.sandwich.farm",
"wss://wons.calva.dev",
"wss://wot.shaving.kiwi",
"wss://wot.tealeaf.dev",
"wss://wot.dtonon.com",
"wss://wot.relay.vanderwarker.family",
"wss://wot.zacoos.com",
"wss://nos.lol",
"wss://nostr.mom",
"wss://purplepag.es",
"wss://purplerelay.com",
"wss://relay.damus.io",
"wss://relay.nostr.band",
"wss://relay.snort.social",
"wss://relayable.org",
"wss://relay.primal.net",
"wss://relay.nostr.bg",
"wss://no.str.cr",
"wss://nostr21.com",
"wss://nostrue.com",
"wss://relay.siamstr.com",
}
var db *sql.DB
var art = `
█████╗ ██╗ ██████╗ ██████╗ ██████╗ ███████╗██╗ █████╗ ██╗ ██╗
██╔══██╗██║ ██╔════╝ ██╔═══██╗ ██╔══██╗██╔════╝██║ ██╔══██╗╚██╗ ██╔╝
███████║██║ ██║ ███╗██║ ██║ ██████╔╝█████╗ ██║ ███████║ ╚████╔╝
██╔══██║██║ ██║ ██║██║ ██║ ██╔══██╗██╔══╝ ██║ ██╔══██║ ╚██╔╝
██║ ██║███████╗╚██████╔╝╚██████╔╝ ██║ ██║███████╗███████╗██║ ██║ ██║
╚═╝ ╚═╝╚══════╝ ╚═════╝ ╚═════╝ ╚═╝ ╚═╝╚══════╝╚══════╝╚═╝ ╚═╝ ╚═╝
`
func main() {
err := godotenv.Load()
if err != nil {
log.Fatalf("Error loading .env file")
}
nostr.InfoLogger = log.New(io.Discard, "", 0)
green := "\033[32m"
reset := "\033[0m"
fmt.Println(green + art + reset)
importFlag := flag.Bool("import", false, "Run the importNotes function after initializing relays")
flag.Parse()
conn, err := getDBConnection()
if err != nil {
log.Fatalf("Error getting db connection: %v", err)
}
defer conn.Close()
db = conn
repository = NewNostrRepository(db)
weightInteractionsWithAuthor = getWeightFloat64("WEIGHT_INTERACTIONS_WITH_AUTHOR")
weightCommentsGlobal = getWeightFloat64("WEIGHT_COMMENTS_GLOBAL")
weightReactionsGlobal = getWeightFloat64("WEIGHT_REACTIONS_GLOBAL")
weightZapsGlobal = getWeightFloat64("WEIGHT_ZAPS_GLOBAL")
weightRecency = getWeightFloat64("WEIGHT_RECENCY")
viralThreshold = getWeightFloat64("VIRAL_THRESHOLD")
viralNoteDampening = getWeightFloat64("VIRAL_NOTE_DAMPENING")
decayRate = getWeightFloat64("DECAY_RATE")
purgeMonthsStr := os.Getenv("PURGE_MONTHS")
if purgeMonthsStr == "" {
log.Fatal("PURGE_MONTHS environment variable is not set")
}
purgeMonths, err := strconv.Atoi(purgeMonthsStr)
if err != nil {
log.Fatalf("Invalid PURGE_MONTHS value: %v\n", err)
}
if *importFlag {
log.Println("📦 importing notes")
importNotes(nostr.KindArticle)
importNotes(20) // KindImage
importNotes(nostr.KindTextNote)
importNotes(nostr.KindReaction)
importNotes(nostr.KindZap)
log.Println("📦 done importing notes. Please restart relay")
return
}
go subscribeAll()
go purgeData(purgeMonths)
go func() {
refreshViralNotes(ctx) // Immediate refresh when the application starts
go refreshViralNotesPeriodically(ctx) // Start the periodic refresh
}()
relay := khatru.NewRelay()
relay.Info.Description = os.Getenv("RELAY_DESCRIPTION")
relay.Info.Name = os.Getenv("RELAY_NAME")
relay.Info.PubKey = os.Getenv("RELAY_PUBKEY")
relay.Info.Software = "https://github.com/bitvora/algo-relay"
relay.Info.Version = "0.1.1"
relay.Info.Icon = os.Getenv("RELAY_ICON")
relay.RejectConnection = append(relay.RejectConnection,
policies.ConnectionRateLimiter(
10,
time.Minute*1,
10,
),
)
relay.RejectFilter = append(relay.RejectFilter,
policies.FilterIPRateLimiter(
10,
time.Second*10,
10,
),
)
relay.OnConnect = append(relay.OnConnect, func(ctx context.Context) {
khatru.RequestAuth(ctx)
})
relay.RejectFilter = append(relay.RejectFilter, func(ctx context.Context, filter nostr.Filter) (bool, string) {
authenticatedUser := khatru.GetAuthed(ctx)
if authenticatedUser == "" {
return true, "auth-required: this query requires you to be authenticated"
}
if len(filter.Authors) > 0 {
return true, "this relay is only for algorithmic feeds"
}
return false, ""
})
relay.RejectEvent = append(relay.RejectEvent, func(ctx context.Context, event *nostr.Event) (bool, string) {
return true, "you cannot publish to this relay"
})
relay.QueryEvents = append(relay.QueryEvents, func(ctx context.Context, filter nostr.Filter) (chan *nostr.Event, error) {
ch := make(chan *nostr.Event)
copyFilter := filter
authenticatedUser := khatru.GetAuthed(ctx)
go func() {
defer close(ch)
limit := copyFilter.Limit
if limit == 0 {
limit = 50
}
kinds := copyFilter.Kinds
var kind int
if len(kinds) == 0 {
kind = nostr.KindTextNote
} else {
kind = kinds[0]
}
events, err := GetUserFeed(ctx, authenticatedUser, limit, kind)
fmt.Println("getting events of kind:", kind)
if err != nil {
log.Println("Error fetching most reacted posts:", err)
return
}
for _, event := range events {
ch <- &event
}
}()
return ch, nil
})
log.Println("🚀 Relay started on port 3334")
mux := relay.Router()
mux.HandleFunc("/", handleHomePage)
mux.HandleFunc("/dashboard.html", handleDashboardPage)
mux.HandleFunc("/api/top-authors", handleTopAuthorsAPI)
mux.HandleFunc("/auth", handleAuth)
mux.HandleFunc("/api/settings", handleUserSettings)
mux.HandleFunc("/api/user-metrics", handleUserMetricsAPI)
err = http.ListenAndServe(":3334", relay)
if err != nil {
log.Fatal(err)
}
mux.Handle("/static/", http.StripPrefix("/static/", http.FileServer(http.Dir("./static"))))
mux.HandleFunc("/", handleHomePage)
log.Printf("listening at http://0.0.0.0:3334")
http.ListenAndServe("0.0.0.0:3334", relay)
}
func subscribeAll() {
now := nostr.Now()
filters := nostr.Filters{{
Kinds: []int{
nostr.KindTextNote,
nostr.KindReaction,
nostr.KindZap,
nostr.KindFollowList,
nostr.KindArticle,
20, // KindImage
},
Since: &now,
}}
for ev := range pool.SubMany(ctx, relays, filters) {
err := repository.SaveNostrEvent(ev.Event)
if err != nil {
continue
}
}
}
func loadEnv() {
err := godotenv.Load()
if err != nil {
log.Fatalf("Error loading .env file: %v", err)
}
}
func purgeData(months int) {
ticker := time.NewTicker(24 * time.Hour)
defer ticker.Stop()
for {
select {
case <-ticker.C:
repository := NewNostrRepository(db)
log.Println("Starting data purge...")
if err := repository.PurgeCommentsOlderThan(months); err != nil {
log.Printf("Error purging comments: %v\n", err)
}
if err := repository.PurgeNotesOlderThan(months); err != nil {
log.Printf("Error purging posts: %v\n", err)
}
if err := repository.PurgeReactionsOlderThan(months); err != nil {
log.Printf("Error purging reactions: %v\n", err)
}
if err := repository.PurgeZapsOlderThan(months); err != nil {
log.Printf("Error purging zaps: %v\n", err)
}
log.Println("Data purge completed.")
}
}
}