-
Notifications
You must be signed in to change notification settings - Fork 23
/
render_event.go
471 lines (423 loc) · 14.1 KB
/
render_event.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
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
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
package main
import (
_ "embed"
"encoding/hex"
"encoding/json"
"fmt"
"html"
"html/template"
"net/http"
"net/url"
"regexp"
"strings"
"github.com/nbd-wtf/go-nostr"
"github.com/nbd-wtf/go-nostr/nip19"
"github.com/pelletier/go-toml"
)
func renderEvent(w http.ResponseWriter, r *http.Request) {
code := r.URL.Path[1:] // hopefully a nip19 code
// it's the homepage
if code == "" {
renderHomepage(w, r)
return
}
if strings.HasPrefix(code, "nostr:") {
// remove the "nostr:" prefix
http.Redirect(w, r, "/"+code[6:], http.StatusFound)
return
}
// decode the nip19 code we've received
prefix, decoded, err := nip19.Decode(code)
if err != nil {
// if it's a 32-byte hex assume it's an event id
if _, err := hex.DecodeString(code); err == nil && len(code) == 64 {
redirectNevent, _ := nip19.EncodeEvent(code, []string{}, "")
http.Redirect(w, r, "/"+redirectNevent, http.StatusFound)
return
}
// otherwise error
w.Header().Set("Cache-Control", "max-age=60")
errorPage := &ErrorPage{
Errors: err.Error(),
}
errorPage.TemplateText()
w.WriteHeader(http.StatusNotFound)
ErrorTemplate.Render(w, errorPage)
return
}
// render npub and nprofile using a separate function
if strings.HasPrefix(code, "npub") || strings.HasPrefix(code, "nprofile") {
// it's a profile
renderProfile(w, r, code)
return
}
// get data for this event
data, err := grabData(r.Context(), code, false)
if err != nil {
w.Header().Set("Cache-Control", "max-age=60")
errorPage := &ErrorPage{
Errors: err.Error(),
}
errorPage.TemplateText()
w.WriteHeader(http.StatusNotFound)
ErrorTemplate.Render(w, errorPage)
return
}
// if the result is a kind:0 render this as a profile
if data.event.Kind == 0 {
renderProfile(w, r, data.npub)
return
}
// if we originally got a note code or an nevent with no hints
// augment the URL to point to an nevent with hints -- redirect
if p, ok := decoded.(nostr.EventPointer); (ok && p.Author == "" && len(p.Relays) == 0) || prefix == "note" {
http.Redirect(w, r, "/"+data.nevent, http.StatusFound)
return
}
// from here onwards we know we're rendering an event
fmt.Println(r.URL.Path, "#/", r.Header.Get("user-agent"))
// gather page style from user-agent
style := getPreviewStyle(r)
// gather host
host := r.Header.Get("X-Forwarded-Host")
if host == "" {
host = r.Host
}
var subject string
var summary string
for _, tag := range data.event.Tags {
if tag[0] == "subject" || tag[0] == "title" {
subject = tag[1]
}
if tag[0] == "summary" {
summary = tag[1]
}
}
useTextImage := false
if data.event.Kind == 1 || data.event.Kind == 30023 {
if data.image == "" && data.video == "" && len(data.event.Content) > 133 {
useTextImage = true
}
if style == StyleTwitter {
useTextImage = true
}
}
if tgiv := r.URL.Query().Get("tgiv"); tgiv == "true" || (style == StyleTelegram && tgiv != "false") {
// do telegram instant preview (only works on telegram mobile apps, not desktop)
if data.event.Kind == 30023 || // do it for longform articles
(data.event.Kind == 1 && len(data.event.Content) > 650) || // or very long notes
(data.parentLink != "") || // or notes that are replies (so we can navigate to them from telegram)
(strings.Contains(data.content, "nostr:")) || // or notes that quote other stuff (idem)
// or shorter notes that should be using text-to-image stuff but are not because they have video or images
(data.event.Kind == 1 && len(data.event.Content)-len(data.image) > 133 && !useTextImage) {
data.templateId = TelegramInstantView
useTextImage = false
}
} else if style == StyleSlack || style == StyleDiscord {
useTextImage = false
}
title := ""
if data.event.Kind >= 30000 && data.event.Kind < 40000 {
tValue := "~"
for _, tag := range data.event.Tags {
if tag[0] == "t" {
tValue = tag[1]
break
}
}
title = fmt.Sprintf("%s: %s", kindNames[data.event.Kind], tValue)
} else if kindName, ok := kindNames[data.event.Kind]; ok {
title = kindName
} else {
title = fmt.Sprintf("kind:%d event", data.event.Kind)
}
if subject != "" {
title += " (" + subject + ")"
}
title += " by " + data.authorShort
seenOnRelays := ""
if len(data.relays) > 0 {
seenOnRelays = fmt.Sprintf("seen on %s", strings.Join(data.relays, ", "))
}
textImageURL := ""
description := ""
if useTextImage {
textImageURL = fmt.Sprintf("https://%s/njump/image/%s?%s", host, code, r.URL.RawQuery)
if subject != "" {
if seenOnRelays != "" {
description = fmt.Sprintf("%s -- %s", subject, seenOnRelays)
} else {
description = subject
}
} else {
description = seenOnRelays
}
} else if summary != "" {
description = summary
} else {
// if content is valid JSON, parse that and print as TOML for easier readability
var parsedJson any
if err := json.Unmarshal([]byte(data.event.Content), &parsedJson); err == nil {
if t, err := toml.Marshal(parsedJson); err == nil && len(t) > 0 {
description = string(t)
}
} else {
// otherwise replace npub/nprofiles with names and trim length
description = replaceUserReferencesWithNames(r.Context(), []string{data.event.Content})[0]
if len(description) > 240 {
description = description[:240]
}
}
}
// titleizedContent
titleizedContent := strings.TrimSpace(
strings.Replace(
strings.Replace(
replaceUserReferencesWithNames(r.Context(), []string{data.event.Content})[0],
"\r\n", " ", -1),
"\n", " ", -1,
),
)
// Remove image/video urls
urlRegex := regexp.MustCompile(`(https?)://[^\s/$.?#]+\.(?i:jpg|jpeg|png|gif|bmp|mp4|mov|avi|mkv|webm|ogg)`)
titleizedContent = urlRegex.ReplaceAllString(titleizedContent, "")
if titleizedContent == "" {
titleizedContent = title
}
if len(titleizedContent) > 85 {
words := strings.Fields(titleizedContent)
titleizedContent = ""
for _, word := range words {
if len(titleizedContent)+len(word)+1 <= 85 { // +1 for space
if titleizedContent != "" {
titleizedContent += " "
}
titleizedContent += word
} else {
break
}
}
titleizedContent = titleizedContent + " ..."
}
// content massaging
for index, value := range data.event.Tags {
placeholderTag := "#[" + fmt.Sprintf("%d", index) + "]"
nreplace := ""
if value[0] == "p" {
nreplace, _ = nip19.EncodePublicKey(value[1])
} else if value[0] == "e" {
nreplace, _ = nip19.EncodeEvent(value[1], []string{}, "")
} else {
continue
}
data.content = strings.ReplaceAll(data.content, placeholderTag, "nostr:"+nreplace)
}
if data.event.Kind == 30023 || data.event.Kind == 30024 {
data.content = mdToHTML(data.content, data.templateId == TelegramInstantView)
} else {
// first we run basicFormatting, which turns URLs into their appropriate HTML tags
data.content = basicFormatting(html.EscapeString(data.content), true, false)
// then we render quotes as HTML, which will also apply basicFormatting to all the internal quotes
data.content = renderQuotesAsHTML(r.Context(), data.content, data.templateId == TelegramInstantView)
// we must do this because inside <blockquotes> we must treat <img>s differently when telegram_instant_view
}
w.Header().Set("Content-Type", "text/html")
if data.templateId == TelegramInstantView {
w.Header().Set("Cache-Control", "no-cache")
} else if len(data.content) != 0 {
w.Header().Set("Cache-Control", "max-age=604800")
} else {
w.Header().Set("Cache-Control", "max-age=60")
}
// oembed discovery
oembed := ""
if data.templateId == Note {
oembed = (&url.URL{
Scheme: "https",
Host: host,
Path: "/services/oembed",
RawQuery: (url.Values{
"url": {fmt.Sprintf("https://%s/%s", host, code)},
}).Encode(),
}).String()
w.Header().Add("Link", "<"+oembed+"&format=json>; rel=\"alternate\"; type=\"application/json+oembed\"")
w.Header().Add("Link", "<"+oembed+"&format=xml>; rel=\"alternate\"; type=\"text/xml+oembed\"")
}
detailsData := DetailsPartial{
HideDetails: true,
CreatedAt: data.createdAt,
KindDescription: data.kindDescription,
KindNIP: data.kindNIP,
EventJSON: eventToHTML(data.event),
Kind: data.event.Kind,
SeenOn: data.relays,
Npub: data.npub,
Nprofile: data.nprofile,
// kind-specific stuff
FileMetadata: data.kind1063Metadata,
LiveEvent: data.kind30311Metadata,
}
opengraph := OpenGraphPartial{
BigImage: textImageURL,
Image: data.image,
Video: data.video,
VideoType: data.videoType,
ProxiedImage: "https://" + host + "/njump/proxy?src=" + data.image,
Superscript: data.authorLong,
Subscript: title,
Text: strings.TrimSpace(description),
}
switch data.templateId {
case TelegramInstantView:
err = TelegramInstantViewTemplate.Render(w, &TelegramInstantViewPage{
Video: data.video,
VideoType: data.videoType,
Image: data.image,
Summary: template.HTML(summary),
Content: template.HTML(data.content),
Description: description,
Subject: subject,
Metadata: data.metadata,
AuthorLong: data.authorLong,
CreatedAt: data.createdAt,
ParentLink: data.parentLink,
})
case Note:
if style == StyleTwitter {
// twitter only uses one title, so we ensure it is this
// we can't set this for other platforms as some will reuse stuff from twitter-specific tags
opengraph.SingleTitle = "by " + data.authorShort + " at " + humanDate(data.event.CreatedAt)
}
if opengraph.BigImage == "" && style != StyleTwitter && strings.HasSuffix(opengraph.Text, opengraph.Image) {
// if a note is mostly about an image, we should prefer to display the image in a big card
// this works, for example, in telegram, and it may work in other places --
// but we can't do this on twitter because when twitter sees a big image it hides all the text and title
// also twitter images only work if they're proxied and for now we're not proxying this
opengraph.Text = opengraph.Text[0 : len(opengraph.Text)-len(opengraph.Image)]
opengraph.BigImage = opengraph.Image
}
enhancedCode := data.nevent
if data.naddr != "" {
enhancedCode = data.naddr
}
err = NoteTemplate.Render(w, &NotePage{
OpenGraphPartial: opengraph,
HeadCommonPartial: HeadCommonPartial{
IsProfile: false,
Oembed: oembed,
TailwindDebugStuff: tailwindDebugStuff,
NaddrNaked: data.naddrNaked,
NeventNaked: data.neventNaked,
},
DetailsPartial: detailsData,
ClientsPartial: ClientsPartial{
Clients: generateClientList(style, enhancedCode, data.event),
},
Content: template.HTML(data.content),
CreatedAt: data.createdAt,
Metadata: data.metadata,
Npub: data.npub,
NpubShort: data.npubShort,
ParentLink: data.parentLink,
Subject: subject,
TitleizedContent: titleizedContent,
})
case FileMetadata:
opengraph.Image = data.kind1063Metadata.DisplayImage()
err = FileMetadataTemplate.Render(w, &FileMetadataPage{
OpenGraphPartial: opengraph,
HeadCommonPartial: HeadCommonPartial{
IsProfile: false,
TailwindDebugStuff: tailwindDebugStuff,
NaddrNaked: data.naddrNaked,
NeventNaked: data.neventNaked,
},
DetailsPartial: detailsData,
ClientsPartial: ClientsPartial{
Clients: generateClientList(style, data.nevent, data.event),
},
CreatedAt: data.createdAt,
Metadata: data.metadata,
Npub: data.npub,
NpubShort: data.npubShort,
Style: style,
Subject: subject,
TitleizedContent: titleizedContent,
Alt: data.alt,
FileMetadata: *data.kind1063Metadata,
IsImage: data.kind1063Metadata.IsImage(),
IsVideo: data.kind1063Metadata.IsVideo(),
})
case LiveEvent:
opengraph.Image = data.kind30311Metadata.Image
err = LiveEventTemplate.Render(w, &LiveEventPage{
OpenGraphPartial: opengraph,
HeadCommonPartial: HeadCommonPartial{
IsProfile: false,
TailwindDebugStuff: tailwindDebugStuff,
NaddrNaked: data.naddrNaked,
NeventNaked: data.neventNaked,
},
DetailsPartial: detailsData,
ClientsPartial: ClientsPartial{
Clients: generateClientList(style, data.naddr, data.event),
},
CreatedAt: data.createdAt,
Metadata: data.metadata,
Npub: data.npub,
NpubShort: data.npubShort,
Style: style,
Subject: subject,
TitleizedContent: titleizedContent,
Alt: data.alt,
LiveEvent: *data.kind30311Metadata,
})
case LiveEventMessage:
// opengraph.Image = data.kind1311Metadata.Image
err = LiveEventMessageTemplate.Render(w, &LiveEventMessagePage{
OpenGraphPartial: opengraph,
HeadCommonPartial: HeadCommonPartial{
IsProfile: false,
TailwindDebugStuff: tailwindDebugStuff,
NaddrNaked: data.naddrNaked,
NeventNaked: data.neventNaked,
},
DetailsPartial: detailsData,
ClientsPartial: ClientsPartial{
Clients: generateClientList(style, data.naddr, data.event),
},
Content: template.HTML(data.content),
CreatedAt: data.createdAt,
Metadata: data.metadata,
Npub: data.npub,
NpubShort: data.npubShort,
ParentLink: data.parentLink,
Style: style,
Subject: subject,
TitleizedContent: titleizedContent,
Alt: data.alt,
LiveEventMessage: *data.kind1311Metadata,
})
case Other:
detailsData.HideDetails = false // always open this since we know nothing else about the event
err = OtherTemplate.Render(w, &OtherPage{
HeadCommonPartial: HeadCommonPartial{
IsProfile: false,
TailwindDebugStuff: tailwindDebugStuff,
NaddrNaked: data.naddrNaked,
NeventNaked: data.neventNaked,
},
DetailsPartial: detailsData,
Alt: data.alt,
Kind: data.event.Kind,
KindDescription: data.kindDescription,
})
default:
log.Error().Int("templateId", int(data.templateId)).Msg("no way to render")
http.Error(w, "tried to render an unsupported template at render_event.go", 500)
}
if err != nil {
log.Error().Err(err).Msg("error rendering tmpl")
}
return
}