app/util.go
508 lines · 15029 bytes · executable
1package app
2
3import (
4 "context"
5 "encoding/json"
6 "fmt"
7 htmlesc "html"
8 "html/template"
9 "io"
10 "net/http"
11 "net/url"
12 "os"
13 "skunkyart/static"
14 "strconv"
15 "strings"
16 "time"
17
18 "github.com/krazywarez/devianter"
19 "golang.org/x/net/html"
20)
21
22/* INTERNAL */
23
24// wr writes s to w. A write error here means the client went away mid-response,
25// which a handler cannot act on, so it is deliberately discarded.
26func wr(w io.Writer, s string) {
27 _, _ = io.WriteString(w, s)
28}
29
30// exit is a variable so a test can observe a fatal path without ending the
31// test binary.
32var exit = func(msg string, code int) {
33 println(msg)
34 os.Exit(code)
35}
36
37func try(e error) {
38 if e != nil {
39 println(e.Error())
40 }
41}
42func tryWithExitStatus(err error, code int) {
43 if err != nil {
44 exit(err.Error(), code)
45 }
46}
47
48// esc escapes s for use as HTML text or inside a quoted attribute. The Go-built
49// fragments bypass html/template's contextual escaping because they are handed
50// to it as template.HTML, so every DeviantArt-supplied string they contain has
51// to be escaped here instead.
52func esc(s string) string {
53 return htmlesc.EscapeString(s)
54}
55
56// restore swallows a panic in the calling goroutine so that one bad parse cannot
57// take the whole process down. The panic is logged rather than dropped silently.
58func restore() {
59 if r := recover(); r != nil {
60 println("recovered from panic:", fmt.Sprint(r))
61 }
62}
63
64var instances []byte
65
66// About is the instance list and settings shown in the frontend, refreshed by
67// RefreshInstances.
68var About instanceAbout
69
70// RefreshInstances re-fetches the published instance list every hour, forever.
71// Run it in its own goroutine; fetch failures are logged and retried next cycle.
72func RefreshInstances() {
73 for {
74 func() {
75 defer restore()
76 instances = Download("https://gitbay.org/krz/skunky-art/raw/main/instances.json").Body
77 try(json.Unmarshal(instances, &About))
78 }()
79 time.Sleep(1 * time.Hour)
80 }
81}
82
83// instanceAbout is the instance metadata exposed to the frontend and the API.
84type instanceAbout struct {
85 Proxy bool `json:"proxy"`
86 Nsfw bool `json:"nsfw"`
87 HideAI bool `json:"hide-ai"`
88 Theme string `json:"theme"`
89 Instances []settings `json:"instances"`
90}
91
92type skunkyart struct {
93 Writer http.ResponseWriter
94 _pth string
95
96 Args url.Values
97 Page int
98 Type rune
99 Atom bool
100
101 // Lang is the catalogue chosen for this request, resolved once in the
102 // handler so every template and helper agrees on one answer.
103 Lang string
104
105 // Host is the scheme and host this request arrived on, e.g.
106 // "https://art.example.com". It is per-request rather than global because
107 // concurrent requests can arrive on different hosts and ports.
108 Host string
109
110 BasePath, Endpoint string
111 Query, QueryRaw string
112
113 API API
114 Version string
115
116 // The template.HTML fields hold fragments the Go builders already
117 // escaped, so html/template inserts them as-is. Everything typed string is
118 // escaped by the template at the point of use.
119 Templates struct {
120 About instanceAbout
121
122 SomeList template.HTML
123 DDStrips template.HTML
124 Deviation struct {
125 Post devianter.Post
126 Description template.HTML
127 Related template.HTML
128 StringTime string
129 Tags template.HTML
130 Comments template.HTML
131 }
132
133 GroupUser groupUserPage
134 Search struct {
135 Content devianter.Search
136 List template.HTML
137 }
138 }
139}
140
141// groupUserPage is the data the group/user page template renders.
142type groupUserPage struct {
143 GR devianter.GRuser
144 Admins template.HTML
145 Group bool
146 CreationDate string
147
148 About struct {
149 A devianter.About
150
151 DescriptionFormatted template.HTML
152 Interests, Social template.HTML
153 Comments template.HTML
154 BG string
155 BGMeta devianter.Deviation
156 }
157
158 Gallery struct {
159 Folders template.HTML
160 Pages int
161 List template.HTML
162 }
163}
164
165// pageTemplates is every page template parsed once per language, by
166// ParseTemplates. One set per language because T is bound at parse time, so
167// templates ask for a key and never have to know which catalogue answered.
168var pageTemplates = map[string]*template.Template{}
169
170// ParseTemplates parses static/html once for each loaded language. Call it at
171// startup after LoadLanguages; a template that does not parse exits the
172// process, since it would otherwise be a 500 on every request for that page.
173func ParseTemplates() {
174 langs := Languages()
175 if len(langs) == 0 {
176 langs = []string{DefaultLang}
177 }
178 for _, lang := range langs {
179 tmp := template.New("").Funcs(template.FuncMap{
180 "T": func(key string) string { return T(lang, key) },
181 })
182 tmp, err := tmp.ParseFS(static.Templates, "html/*")
183 if err != nil {
184 exit("templates: "+err.Error(), 1)
185 return
186 }
187 pageTemplates[lang] = tmp
188 }
189}
190
191// ExecuteTemplate renders the named page template with data in the request's
192// language, responding 500 if the templates were never parsed.
193func (s skunkyart) ExecuteTemplate(file, _ string, data any) {
194 tmp := pageTemplates[s.Lang]
195 if tmp == nil {
196 tmp = pageTemplates[DefaultLang]
197 }
198 if tmp == nil {
199 s.Writer.WriteHeader(500)
200 wr(s.Writer, "templates not parsed")
201 return
202 }
203 var buf strings.Builder
204 try(tmp.ExecuteTemplate(&buf, file, &data))
205 wr(s.Writer, buf.String())
206}
207
208// URLBuilder joins strs into an absolute instance URL, prefixing host and the
209// configured URI and inserting slashes between path segments but not before
210// query separators. host is the request's own scheme and host: passing the
211// wrong one emits links to another origin, which the instance's own
212// Content-Security-Policy then blocks.
213func URLBuilder(host string, strs ...string) string {
214 var str strings.Builder
215 l := len(strs)
216 str.WriteString(host)
217 str.WriteString(CFG.URI)
218 for n, x := range strs {
219 str.WriteString(x)
220 if n := n + 1; n < l && len(strs[n]) != 0 && (strs[n][0] != '?' && strs[n][0] != '&') && (x[0] != '?' && x[0] != '&') {
221 str.WriteString("/")
222 }
223 }
224 return str.String()
225}
226
227// Error responds 502 with the error DeviantArt reported upstream. Only the
228// first line is shown: a WAF block arrives as a whole HTML page, which is
229// neither readable nor safe to echo.
230func (s skunkyart) Error(dAerr devianter.Error) {
231 s.Writer.Header().Del("Cache-Control")
232
233 // A shed request is not an upstream failure: the instance is busy and the
234 // client should come back shortly rather than treat the page as broken.
235 if strings.Contains(dAerr.Error, errUpstreamBusy.Error()) {
236 s.Writer.Header().Set("Retry-After", "5")
237 s.ReturnHTTPError(http.StatusServiceUnavailable)
238 return
239 }
240 s.Writer.WriteHeader(502)
241
242 reason, _, _ := strings.Cut(dAerr.Error, "\n")
243
244 var msg strings.Builder
245 msg.WriteString(`<html><link rel="stylesheet" href="`)
246 msg.WriteString(URLBuilder(s.Host, "stylesheet"))
247 msg.WriteString(`" /><h3>` + esc(T(s.Lang, "error.upstream")) + ` — '`)
248 msg.WriteString(esc(reason))
249 msg.WriteString("'</h3></html>")
250
251 wr(s.Writer, msg.String())
252}
253
254// ReturnHTTPError responds with a styled error page for the given status.
255func (s skunkyart) ReturnHTTPError(status int) {
256 // A failed upstream fetch reports status 0, and WriteHeader panics on any
257 // code outside 1xx-5xx. Treat anything unusable as a gateway failure.
258 if status < 100 || status > 599 {
259 status = http.StatusBadGateway
260 }
261 s.Writer.Header().Del("Cache-Control")
262 s.Writer.WriteHeader(status)
263
264 var msg strings.Builder
265 msg.WriteString(`<html><link rel="stylesheet" href="`)
266 msg.WriteString(URLBuilder(s.Host, "stylesheet"))
267 msg.WriteString(`" /><h1>`)
268 msg.WriteString(strconv.Itoa(status))
269 msg.WriteString(" - ")
270 msg.WriteString(http.StatusText(status))
271 msg.WriteString("</h1></html>")
272
273 wr(s.Writer, msg.String())
274}
275
276// SetFilename sets the Content-Disposition filename for the response.
277func (s skunkyart) SetFilename(name string) {
278 var filename strings.Builder
279 filename.WriteString(`filename="`)
280 filename.WriteString(name)
281 filename.WriteString(`"`)
282 s.Writer.Header().Add("Content-Disposition", filename.String())
283}
284
285// Downloaded is the result of a Download. A Status of 0 means the request never
286// completed, in which case Body and Headers are empty.
287type Downloaded struct {
288 Headers http.Header
289 Status int
290 Body []byte
291}
292
293// Download fetches urlString with the configured User-Agent, routing through
294// download-proxy when one is set. Every failure path returns the zero
295// Downloaded, so callers must check Status before trusting Body or Headers.
296func Download(urlString string) (d Downloaded) {
297 cli := &http.Client{}
298 if CFG.DownloadProxy != "" {
299 u, err := url.Parse(CFG.DownloadProxy)
300 if err != nil {
301 try(err)
302 return
303 }
304 cli.Transport = ProxiedTransport(u)
305 }
306
307 ctx, cancel := context.WithTimeout(context.Background(), downloadTimeout)
308 defer cancel()
309
310 req, err := http.NewRequestWithContext(ctx, http.MethodGet, urlString, nil)
311 if err != nil {
312 try(err)
313 return
314 }
315 req.Header.Set("User-Agent", CFG.UserAgent)
316
317 resp, err := cli.Do(req)
318 if err != nil {
319 try(err)
320 return
321 }
322 defer func() { try(resp.Body.Close()) }()
323
324 b, err := io.ReadAll(resp.Body)
325 if err != nil {
326 try(err)
327 return
328 }
329
330 d.Body = b
331 d.Status = resp.StatusCode
332 d.Headers = resp.Header
333 return
334}
335
336/* PARSING HELPERS */
337
338// wixmpMedia splits a wixmp CDN URL into the pieces the media proxy takes:
339// the variable hostname label, the path without its leading slash, and the
340// signing token. ok is false for anything that is not wixmp media.
341func wixmpMedia(raw string) (subdomain, path, token string, ok bool) {
342 u, err := url.Parse(raw)
343 if err != nil || !strings.HasPrefix(u.Host, "images-wixmp-") || !strings.HasSuffix(u.Host, ".wixmp.com") {
344 return "", "", "", false
345 }
346 subdomain = strings.TrimSuffix(strings.TrimPrefix(u.Host, "images-wixmp-"), ".wixmp.com")
347 return subdomain, strings.TrimPrefix(u.Path, "/"), u.Query().Get("token"), true
348}
349
350// proxiedMediaURL is the instance URL that serves raw through the media proxy,
351// with the token and a download filename as query parameters, or "" when raw is
352// not wixmp media. host is the request's scheme and host, as taken by URLBuilder.
353func proxiedMediaURL(host, raw, filename string) string {
354 subdomain, path, token, ok := wixmpMedia(raw)
355 if !ok {
356 return ""
357 }
358 q := url.Values{}
359 if token != "" {
360 q.Set("token", token)
361 }
362 if filename != "" {
363 q.Set("filename", filename)
364 }
365 return URLBuilder(host, "media", "file", subdomain, path) + "?" + q.Encode()
366}
367
368// ParseMedia returns the URL to serve for media: a link back through this
369// instance's media proxy when proxying is on, or DeviantArt's own URL when it is
370// off. An optional thumb width selects a thumbnail instead of the full image.
371// host is the request's scheme and host, as taken by URLBuilder.
372func ParseMedia(host string, media devianter.Media, thumb ...int) string {
373 mediaURL, filename := devianter.UrlFromMedia(media, thumb...)
374 if mediaURL == "" || !CFG.Proxy {
375 return mediaURL
376 }
377 if filename == "" {
378 filename = "image.gif"
379 }
380 return proxiedMediaURL(host, mediaURL, filename)
381}
382
383// ConvertDeviantArtURLToSkunkyArt rewrites a deviantart.com post link, in the
384// www.deviantart.com/<author>/art/<name> or <author>.deviantart.com/art/<name>
385// form, into the equivalent link on this instance. It returns "" for anything
386// else, including sta.sh links. host is the request's scheme and host, as
387// taken by URLBuilder.
388func ConvertDeviantArtURLToSkunkyArt(host, raw string) string {
389 u, err := url.Parse(raw)
390 if err != nil || !strings.HasSuffix(u.Host, "deviantart.com") {
391 return ""
392 }
393 parts := strings.Split(strings.Trim(u.Path, "/"), "/")
394 switch {
395 case len(parts) == 3 && parts[1] == "art" && parts[0] != "stash":
396 return URLBuilder(host, "post", parts[0], parts[2])
397 case len(parts) == 2 && parts[0] == "art" && u.Host != "www.deviantart.com":
398 return URLBuilder(host, "post", strings.TrimSuffix(u.Host, ".deviantart.com"), parts[1])
399 }
400 return ""
401}
402
403// BuildUserPlate renders the small avatar-and-username block linking to a user's
404// about page. host is the request's scheme and host, as taken by URLBuilder.
405func BuildUserPlate(host, name string) string {
406 var htm strings.Builder
407 htm.WriteString(`<div class="user-plate"><img src="`)
408 htm.WriteString(esc(URLBuilder(host, "media", "emojitar", name, "?type=a")))
409 htm.WriteString(`" alt="`)
410 htm.WriteString(esc(name))
411 htm.WriteString(`"><a href="`)
412 htm.WriteString(esc(URLBuilder(host, "group_user", "?type=about&q=", name)))
413 htm.WriteString(`">`)
414 htm.WriteString(esc(name))
415 htm.WriteString(`</a></div>`)
416 return htm.String()
417}
418
419// GetValueOfTag returns the text of the tokenizer's next token, or an empty
420// string if that token is not text.
421func GetValueOfTag(t *html.Tokenizer) string {
422 if t.Next() == html.TextToken {
423 return string(t.Text())
424 }
425 return ""
426}
427
428// DeviationList describes the pagination state of a list of artworks: how many
429// pages exist, and whether another page follows the current one.
430type DeviationList struct {
431 Pages int
432 More bool
433}
434
435// NavBase renders the page navigation bar for a list.
436func (s skunkyart) NavBase(c DeviationList) string {
437 var list strings.Builder
438
439 list.WriteString("<br>")
440 p := s.Page
441
442 if p > 1 {
443 s.writeNavLink(&list, "<= "+esc(T(s.Lang, "nav.prev"))+" |", p-1, false)
444 } else {
445 p = 1
446 }
447
448 // The window runs to the last page or the current one, whichever is further
449 // out. Callers that cannot count pages pass Pages: 0 — the comment list on an
450 // artwork is one — and bounding purely by Pages then ended the loop before
451 // i reached 1, so page one rendered no numbers at all. With nothing before it
452 // to link back to and no further page to link on, the whole panel came out as
453 // a bare <br>.
454 last := max(c.Pages, p)
455
456 for i, x := p-6, 0; (i <= last && i <= p+6) && x < 12; i++ {
457 if i > 0 {
458 s.writeNavLink(&list, strconv.Itoa(i), i, i == p)
459 x++
460 }
461 }
462
463 if c.More {
464 s.writeNavLink(&list, "| "+esc(T(s.Lang, "nav.next"))+" =>", p+1, false)
465 }
466
467 return list.String()
468}
469
470// writeNavLink writes a link to page labelled msg, or just the page number
471// when it is the current page.
472func (s skunkyart) writeNavLink(list *strings.Builder, msg string, page int, onpage bool) {
473 if onpage {
474 list.WriteString(strconv.Itoa(page))
475 list.WriteString(" ")
476 return
477 }
478 list.WriteString(`<a href="`)
479 list.WriteString(esc(s._pth))
480 list.WriteString(s.pageQuery(page))
481 list.WriteString(`">`)
482 list.WriteString(msg)
483 list.WriteString("</a> ")
484}
485
486// pageQuery is the query string for page, carrying over the request's type,
487// search, folder, and comments arguments.
488func (s skunkyart) pageQuery(page int) string {
489 var q strings.Builder
490 q.WriteString(`?p=`)
491 q.WriteString(strconv.Itoa(page))
492 if s.Type != 0 {
493 q.WriteString("&type=")
494 q.WriteRune(s.Type)
495 }
496 if s.Query != "" {
497 q.WriteString("&q=")
498 q.WriteString(esc(s.Query))
499 }
500 if f := s.Args.Get("folder"); f != "" {
501 q.WriteString("&folder=")
502 q.WriteString(esc(f))
503 }
504 if s.Args.Get("comments") != "" {
505 q.WriteString("&comments=1")
506 }
507 return q.String()
508}