-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathblossom.go
More file actions
419 lines (353 loc) · 10.2 KB
/
Copy pathblossom.go
File metadata and controls
419 lines (353 loc) · 10.2 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
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
package main
import (
"context"
"crypto/sha256"
"fmt"
"io"
"log"
"net/http"
"os"
"path/filepath"
"regexp"
"strings"
"sync"
"time"
"fiatjaf.com/nostr"
)
var blossomURLRegex = regexp.MustCompile(`https?://[^/\s]+/([a-fA-F0-9]{64})(?:\.[a-zA-Z0-9]+)?`)
var ownerBlossomTrackingFile string
var ownerBlossomMutex sync.Mutex
func initOwnerBlossomTracking() {
ownerBlossomTrackingFile = filepath.Join(config.DBPath, "owner_blossom")
if _, err := os.Stat(ownerBlossomTrackingFile); os.IsNotExist(err) {
log.Println("🗂️ Bootstrapping owner Blossom file tracking")
bootstrapOwnerBlossomFiles()
} else {
log.Println("🗂️ Owner Blossom tracking file found")
}
}
func bootstrapOwnerBlossomFiles() {
hashSet := make(map[string]bool)
filesFound := 0
if entries, err := os.ReadDir(config.BlossomAssetsPath); err == nil {
for _, entry := range entries {
if !entry.IsDir() {
filename := entry.Name()
if !strings.HasSuffix(filename, ".tmp") && len(filename) == 64 {
if _, err := filepath.Match("[a-fA-F0-9]*", filename); err == nil {
hashSet[filename] = true
filesFound++
}
}
}
}
log.Printf("🗂️ Found %d existing owner Blossom files in assets directory", filesFound)
} else {
log.Printf("Warning: Could not read assets directory: %v", err)
}
ownerPK, err := nostr.PubKeyFromHex(config.OwnerPubkey)
if err != nil {
log.Printf("Error parsing owner pubkey: %v", err)
return
}
missingFiles := make(map[string][]string)
eventHashes := 0
for event := range store.QueryEvents(nostr.Filter{Authors: []nostr.PubKey{ownerPK}}, 0) {
hashes := extractBlossomHashes(event.Content)
for _, hash := range hashes {
eventHashes++
if !hashSet[hash] {
matches := blossomURLRegex.FindAllString(event.Content, -1)
for _, url := range matches {
if strings.Contains(url, hash) {
missingFiles[hash] = append(missingFiles[hash], url)
break
}
}
}
hashSet[hash] = true
}
}
log.Printf("🔍 Found %d Blossom hashes in %d owner events", eventHashes, len(hashSet)-filesFound)
downloaded := 0
failed := 0
for hash, urls := range missingFiles {
for _, url := range urls {
if err := downloadBlossomFile(url, hash, false); err == nil {
downloaded++
log.Printf("✅ Downloaded missing owner file: %s", hash[:16]+"...")
break
} else {
failed++
log.Printf("❌ Failed to download owner file: %s - %s", urls, err)
}
}
}
if len(missingFiles) > 0 {
log.Printf("📥 Download results: %d succeeded, %d failed", downloaded, failed)
}
file, err := os.Create(ownerBlossomTrackingFile)
if err != nil {
log.Printf("Error creating owner Blossom tracking file: %v", err)
return
}
defer file.Close()
for hash := range hashSet {
file.WriteString(hash + "\n")
}
log.Printf("📝 Bootstrapped %d total owner Blossom files (%d existing + %d from events)", len(hashSet), filesFound, len(hashSet)-filesFound)
}
func extractBlossomHashes(content string) []string {
matches := blossomURLRegex.FindAllStringSubmatch(content, -1)
var hashes []string
for _, match := range matches {
if len(match) > 1 {
hashes = append(hashes, match[1])
}
}
return hashes
}
func trackOwnerBlossomFile(hash string) {
ownerBlossomMutex.Lock()
defer ownerBlossomMutex.Unlock()
file, err := os.OpenFile(ownerBlossomTrackingFile, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
if err != nil {
log.Printf("Error opening owner Blossom tracking file: %v", err)
return
}
defer file.Close()
if _, err := file.WriteString(hash + "\n"); err != nil {
log.Printf("Error writing to owner Blossom tracking file: %v", err)
}
}
func isFileAlreadyDownloaded(hash string) bool {
filePath := filepath.Join(config.BlossomAssetsPath, hash)
_, err := os.Stat(filePath)
return !os.IsNotExist(err)
}
func downloadBlossomFile(url, hash string, enforceMaxSize bool) error {
if isFileAlreadyDownloaded(hash) {
return nil
}
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
req, err := http.NewRequestWithContext(ctx, "GET", url, nil)
if err != nil {
return err
}
resp, err := http.DefaultClient.Do(req)
if err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return fmt.Errorf("HTTP %d: %s", resp.StatusCode, resp.Status)
}
if enforceMaxSize && resp.ContentLength > 0 {
maxSize := int64(config.MaxFileSizeMB * 1024 * 1024)
if resp.ContentLength > maxSize {
return fmt.Errorf("file too large: %d bytes (max %d MB)", resp.ContentLength, config.MaxFileSizeMB)
}
}
tempFile := filepath.Join(config.BlossomAssetsPath, hash+".tmp")
file, err := os.Create(tempFile)
if err != nil {
return err
}
defer func() {
file.Close()
os.Remove(tempFile)
}()
hasher := sha256.New()
var written int64
if enforceMaxSize {
maxSize := int64(config.MaxFileSizeMB * 1024 * 1024)
limitedReader := io.LimitReader(resp.Body, maxSize+1)
teeReader := io.TeeReader(limitedReader, hasher)
written, err = io.Copy(file, teeReader)
if err != nil {
return err
}
if written > maxSize {
return fmt.Errorf("file too large: %d bytes (max %d MB)", written, config.MaxFileSizeMB)
}
} else {
teeReader := io.TeeReader(resp.Body, hasher)
written, err = io.Copy(file, teeReader)
if err != nil {
return err
}
}
calculatedHash := fmt.Sprintf("%x", hasher.Sum(nil))
if calculatedHash != hash {
return fmt.Errorf("hash mismatch: expected %s, got %s", hash, calculatedHash)
}
file.Close()
finalPath := filepath.Join(config.BlossomAssetsPath, hash)
if err := os.Rename(tempFile, finalPath); err != nil {
return err
}
log.Printf("📥 Downloaded Blossom file: %s (%d bytes)", hash[:16]+"...", written)
return nil
}
func getUserWriteRelays(authorPubkey string) []string {
ctx := context.Background()
timeout, cancel := context.WithTimeout(ctx, 5*time.Second)
defer cancel()
pk, err := nostr.PubKeyFromHex(authorPubkey)
if err != nil {
return nil
}
filter := nostr.Filter{
Authors: []nostr.PubKey{pk},
Kinds: []nostr.Kind{nostr.KindRelayListMetadata},
Limit: 1,
}
var relayListEvent nostr.Event
var found bool
for event := range store.QueryEvents(filter, 1) {
if !found || event.CreatedAt > relayListEvent.CreatedAt {
relayListEvent = event
found = true
}
}
if !found {
for ev := range pool.FetchMany(timeout, seedRelays, filter, nostr.SubscriptionOptions{}) {
if !found || ev.CreatedAt > relayListEvent.CreatedAt {
relayListEvent = ev.Event
found = true
saveEvent(ev.Event)
}
}
}
if !found {
return nil
}
var writeRelays []string
for tag := range relayListEvent.Tags.FindAll("r") {
if len(tag) >= 2 && tag[1] != "" {
if len(tag) < 3 || tag[2] == "" || tag[2] == "write" {
writeRelays = append(writeRelays, tag[1])
}
}
}
return writeRelays
}
func tryDownloadFromServers(servers []string, hash string, enforceMaxSize bool) bool {
for _, server := range servers {
url := fmt.Sprintf("%s/%s", server, hash)
if err := downloadBlossomFile(url, hash, enforceMaxSize); err == nil {
log.Printf("✅ Downloaded from server: %s", server)
return true
}
}
return false
}
func downloadFromAltBlossomServers(authorPubkey string, hash string, enforceMaxSize bool) bool {
ctx := context.Background()
timeout, cancel := context.WithTimeout(ctx, 15*time.Second)
defer cancel()
pk, err := nostr.PubKeyFromHex(authorPubkey)
if err != nil {
return false
}
serverFilter := nostr.Filter{
Authors: []nostr.PubKey{pk},
Kinds: []nostr.Kind{10063},
Limit: 1,
}
var serverListEvent nostr.Event
var found bool
for event := range store.QueryEvents(serverFilter, 1) {
if !found || event.CreatedAt > serverListEvent.CreatedAt {
serverListEvent = event
found = true
}
}
if found {
servers := extractServersFromEvent(serverListEvent)
if len(servers) > 0 {
log.Printf("🔍 Trying servers from local DB for %s", authorPubkey[:8]+"...")
if tryDownloadFromServers(servers, hash, enforceMaxSize) {
return true
}
}
}
found = false
for ev := range pool.FetchMany(timeout, seedRelays, serverFilter, nostr.SubscriptionOptions{}) {
if !found || ev.CreatedAt > serverListEvent.CreatedAt {
serverListEvent = ev.Event
found = true
}
}
if found {
saveEvent(serverListEvent)
servers := extractServersFromEvent(serverListEvent)
if len(servers) > 0 {
log.Printf("🔍 Trying servers from seedRelays for %s", authorPubkey[:8]+"...")
if tryDownloadFromServers(servers, hash, enforceMaxSize) {
return true
}
}
}
writeRelays := getUserWriteRelays(authorPubkey)
if len(writeRelays) > 0 {
log.Printf("🔍 Searching user's write relays for %s server list", authorPubkey[:8]+"...")
found = false
for ev := range pool.FetchMany(timeout, writeRelays, serverFilter, nostr.SubscriptionOptions{}) {
if !found || ev.CreatedAt > serverListEvent.CreatedAt {
serverListEvent = ev.Event
found = true
}
}
if found {
saveEvent(serverListEvent)
servers := extractServersFromEvent(serverListEvent)
if len(servers) > 0 {
log.Printf("🔍 Trying servers from user's write relays for %s", authorPubkey[:8]+"...")
if tryDownloadFromServers(servers, hash, enforceMaxSize) {
return true
}
}
}
}
return false
}
func extractServersFromEvent(event nostr.Event) []string {
var servers []string
for tag := range event.Tags.FindAll("server") {
if len(tag) >= 2 && tag[1] != "" {
servers = append(servers, tag[1])
}
}
return servers
}
func processBlossomBackup(event nostr.Event) {
if !config.BackupBlossomMedia {
return
}
matches := blossomURLRegex.FindAllString(event.Content, -1)
if len(matches) == 0 {
return
}
go func() {
isOwnerEvent := event.PubKey.Hex() == config.OwnerPubkey
for _, originalURL := range matches {
hashMatches := blossomURLRegex.FindStringSubmatch(originalURL)
if len(hashMatches) < 2 {
continue
}
hash := hashMatches[1]
if isFileAlreadyDownloaded(hash) {
continue
}
if err := downloadBlossomFile(originalURL, hash, !isOwnerEvent); err == nil {
continue
}
log.Printf("🔄 Original URL %s failed, trying author's fallback servers", originalURL)
if !downloadFromAltBlossomServers(event.PubKey.Hex(), hash, !isOwnerEvent) {
log.Printf("⚠️ Failed to download Blossom file %s from all available sources", hash[:16]+"...")
}
}
}()
}