app/parsers.go

v1.5.8
skunky-art/app/parsers.go history · blame · raw

553 lines · 16671 bytes · executable

  1package app
  2
  3import (
  4	"encoding/json"
  5	"net/url"
  6	"path"
  7	"strconv"
  8	"strings"
  9	"time"
 10
 11	"github.com/krazywarez/devianter"
 12	"golang.org/x/net/html"
 13)
 14
 15// ParseComments renders a comment thread, nesting replies under the comment they
 16// answer. It returns a placeholder message rather than failing if the upstream
 17// fetch errored.
 18func (s skunkyart) ParseComments(c devianter.Comments, daError devianter.Error) string {
 19	if daError.RAW != nil {
 20		return esc(T(s.Lang, "comments.failed"))
 21	}
 22
 23	var cmmts strings.Builder
 24	replied := make(map[int]string)
 25
 26	cmmts.WriteString("<details><summary>")
 27	cmmts.WriteString(esc(T(s.Lang, "deviation.comments")))
 28	cmmts.WriteString(": <b>")
 29	cmmts.WriteString(strconv.Itoa(c.Total))
 30	cmmts.WriteString("</b></summary>")
 31	for _, x := range c.Thread {
 32		replied[x.ID] = x.User.Username
 33		cmmts.WriteString(`<div class="msg`)
 34		if x.Parent > 0 {
 35			cmmts.WriteString(` reply`)
 36		}
 37		cmmts.WriteString(`"><p id="`)
 38		cmmts.WriteString(strconv.Itoa(x.ID))
 39		cmmts.WriteString(`"><img src="`)
 40		cmmts.WriteString(esc(URLBuilder(s.Host, "media", "emojitar", x.User.Username, "?type=a")))
 41		cmmts.WriteString(`" width="30px" height="30px" alt="`)
 42		cmmts.WriteString(esc(x.User.Username))
 43		cmmts.WriteString(`"><a href="`)
 44		cmmts.WriteString(esc(URLBuilder(s.Host, "group_user", "?q=", x.User.Username, "&type=a")))
 45		cmmts.WriteString(`"><b`)
 46		cmmts.WriteString(` class="`)
 47		if x.User.Banned {
 48			cmmts.WriteString(`banned`)
 49		}
 50		if x.Author {
 51			cmmts.WriteString(`author`)
 52		}
 53		cmmts.WriteString(`">`)
 54		cmmts.WriteString(esc(x.User.Username))
 55		cmmts.WriteString("</b></a> ")
 56
 57		if x.Parent > 0 {
 58			cmmts.WriteString(" ")
 59			cmmts.WriteString(esc(T(s.Lang, "comments.reply_to")))
 60			cmmts.WriteString(` <a href="`)
 61			cmmts.WriteString(esc(s._pth))
 62			cmmts.WriteString("#")
 63			cmmts.WriteString(strconv.Itoa(x.Parent))
 64			cmmts.WriteString(`">`)
 65			if replied[x.Parent] == "" {
 66				cmmts.WriteString("???")
 67			} else {
 68				cmmts.WriteString(esc(replied[x.Parent]))
 69			}
 70			cmmts.WriteString("</a>")
 71		}
 72		cmmts.WriteString(" [")
 73		cmmts.WriteString(x.Posted.UTC().String())
 74		cmmts.WriteString("]<p>")
 75
 76		cmmts.WriteString(ParseDescription(s.Host, x.TextContent))
 77		cmmts.WriteString("<p>👍: ")
 78		cmmts.WriteString(strconv.Itoa(x.Likes))
 79		cmmts.WriteString(" ⏩: ")
 80		cmmts.WriteString(strconv.Itoa(x.Replies))
 81		cmmts.WriteString("</p></div>\n")
 82	}
 83	cmmts.WriteString(s.NavBase(DeviationList{
 84		Pages: 0,
 85		More:  c.HasMore,
 86	}))
 87	cmmts.WriteString("</details>")
 88	return cmmts.String()
 89}
 90
 91// VisibleDeviation reports whether a deviation may be shown by this instance.
 92//
 93// Both the HTML listing and the JSON API ask this, deliberately: an API that
 94// returned what the pages hide would leak exactly what hide-ai and the NSFW
 95// setting exist to withhold, and a second copy of the rule is a second thing to
 96// forget to update.
 97func VisibleDeviation(d *devianter.Deviation) bool {
 98	if d.AI && CFG.HideAI {
 99		return false
100	}
101	return !d.NSFW || CFG.Nsfw
102}
103
104// DeviationList renders devs as an HTML grid, or as an Atom feed when the
105// request asked for one and allowAtom permits it. NSFW entries are dropped
106// unless the instance allows them. Passing content adds a navigation bar.
107func (s skunkyart) DeviationList(devs []devianter.Deviation, allowAtom bool, content ...DeviationList) string {
108	if s.Atom && s.Page > 1 {
109		s.ReturnHTTPError(400)
110		return ""
111	}
112
113	atom := allowAtom && s.Atom
114	var listContent strings.Builder
115	var newest time.Time // the latest entry, for the feed's own <updated>
116
117	for i, l := 0, len(devs); i < l; i++ {
118		data := &devs[i]
119		if !VisibleDeviation(data) {
120			continue
121		}
122		item := s.listItem(data)
123		if atom {
124			s.Writer.Header().Add("Content-Type", "application/atom+xml")
125			if published := s.writeAtomEntry(&listContent, data, item); published.After(newest) {
126				newest = published
127			}
128		} else {
129			s.writeGridEntry(&listContent, data, item)
130		}
131	}
132
133	if atom {
134		feed := s.atomFeed(devs, listContent.String(), newest)
135		wr(s.Writer, feed)
136		return feed
137	}
138
139	var list strings.Builder
140	list.WriteString(`<div class="content">`)
141	list.WriteString(listContent.String())
142	list.WriteString("</div>")
143	if content != nil {
144		list.WriteString(s.NavBase(content[0]))
145	}
146	return list.String()
147}
148
149// listEntry holds one deviation's values for a list, escaped once: the same
150// values go into both the HTML grid and the Atom feed, and html.EscapeString
151// produces entities XML accepts too.
152type listEntry struct {
153	author, title, postURL, preview, fullview string
154}
155
156func (s skunkyart) listItem(data *devianter.Deviation) listEntry {
157	return listEntry{
158		author:   esc(data.Author.Username),
159		title:    esc(data.Title),
160		postURL:  esc(ConvertDeviantArtURLToSkunkyArt(s.Host, data.Url)),
161		preview:  esc(ParseMedia(s.Host, data.Media, 320)),
162		fullview: esc(ParseMedia(s.Host, data.Media)),
163	}
164}
165
166// writeAtomEntry writes one feed entry and returns its published time.
167func (s skunkyart) writeAtomEntry(b *strings.Builder, data *devianter.Deviation, item listEntry) time.Time {
168	// The entry id is the post's URL here: Atom wants an IRI, and a
169	// bare number is not one. Timestamps are RFC 3339, the only form
170	// the format allows.
171	entryURL := esc(URLBuilder(s.Host, "post", data.Author.Username, "atom-"+strconv.Itoa(data.ID)))
172	published := data.PublishedTime.UTC()
173	b.WriteString(`<entry><author><name>`)
174	b.WriteString(item.author)
175	b.WriteString(`</name></author><title>`)
176	b.WriteString(item.title)
177	b.WriteString(`</title><link rel="alternate" type="text/html" href="`)
178	b.WriteString(entryURL)
179	b.WriteString(`"/><id>`)
180	b.WriteString(entryURL)
181	b.WriteString(`</id><published>`)
182	b.WriteString(published.Format(time.RFC3339))
183	b.WriteString(`</published><updated>`)
184	b.WriteString(published.Format(time.RFC3339))
185	b.WriteString(`</updated>`)
186	b.WriteString(`<media:group><media:title>`)
187	b.WriteString(item.title)
188	b.WriteString(`</media:title><media:thumbnail url="`)
189	b.WriteString(item.preview)
190	b.WriteString(`"/></media:group><content type="xhtml"><div xmlns="http://www.w3.org/1999/xhtml"><a href="`)
191	b.WriteString(item.postURL)
192	b.WriteString(`"><img src="`)
193	b.WriteString(item.fullview)
194	b.WriteString(`"/></a><p>`)
195	b.WriteString(ParseDescription(s.Host, data.TextContent))
196	b.WriteString(`</p></div></content></entry>`)
197	return published
198}
199
200func (s skunkyart) writeGridEntry(b *strings.Builder, data *devianter.Deviation, item listEntry) {
201	b.WriteString(`<div class="block">`)
202	if item.fullview != "" && item.preview != "" {
203		b.WriteString(`<a title="` + esc(T(s.Lang, "deviation.open")) + `" href="`)
204		b.WriteString(item.fullview)
205		b.WriteString(`"><img loading="lazy" src="`)
206		b.WriteString(item.preview)
207		b.WriteString(`" width="15%" alt="`)
208		b.WriteString(item.author)
209		b.WriteString(" - ")
210		b.WriteString(item.title)
211		b.WriteString(`"></a>`)
212	} else {
213		b.WriteString("<h1>[ " + esc(T(s.Lang, "list.text")) + " ]</h1>")
214	}
215	b.WriteString(`<br><a href="`)
216	b.WriteString(item.postURL)
217	b.WriteString(`">`)
218	b.WriteString(item.author)
219	b.WriteString(" - ")
220	b.WriteString(item.title)
221
222	if data.NSFW {
223		b.WriteString(` [<span class="nsfw">NSFW</span>]`)
224	}
225	if data.AI {
226		b.WriteString(" [🤖]")
227	}
228	if data.DD {
229		b.WriteString(` [<span class="dd">DD</span>]`)
230	}
231
232	b.WriteString("</a></div>")
233}
234
235// atomFeed wraps the entries in an Atom feed for this request.
236func (s skunkyart) atomFeed(devs []devianter.Deviation, entries string, newest time.Time) string {
237	var list strings.Builder
238	list.WriteString(`<?xml version="1.0" encoding="UTF-8"?><feed xmlns:media="http://search.yahoo.com/mrss/" xmlns="http://www.w3.org/2005/Atom">`)
239
240	list.WriteString(`<title>`)
241	switch {
242	case s.Type == 0:
243		list.WriteString("Daily Deviations")
244	case s.Type == 'g' && len(devs) != 0:
245		list.WriteString(esc(devs[0].Author.Username))
246	default:
247		list.WriteString("SkunkyArt")
248	}
249	list.WriteString(`</title>`)
250
251	// Atom requires a feed id and updated time; readers reject a feed
252	// without them. The id is the feed's own URL on this instance.
253	feedURL := esc(s.Host + s._pth + "?" + s.Args.Encode())
254	if newest.IsZero() {
255		newest = time.Now().UTC()
256	}
257	list.WriteString(`<id>`)
258	list.WriteString(feedURL)
259	list.WriteString(`</id><updated>`)
260	list.WriteString(newest.Format(time.RFC3339))
261	list.WriteString(`</updated><link rel="self" type="application/atom+xml" href="`)
262	list.WriteString(feedURL)
263	list.WriteString(`"/>`)
264
265	list.WriteString(`<link rel="alternate" href="`)
266	list.WriteString(esc(s.Host))
267	list.WriteString(`"/>`)
268
269	list.WriteString(entries)
270
271	list.WriteString("</feed>")
272	return list.String()
273}
274
275/* DESCRIPTION/COMMENT PARSER */
276
277// emoticonURL maps an e.deviantart.net emoticon image URL to this instance's
278// emote route, by the file's base name without its extension, which is what
279// devianter.AEmedia takes. Anything else yields "".
280func emoticonURL(host, raw string) string {
281	u, err := url.Parse(raw)
282	if err != nil || u.Host != "e.deviantart.net" {
283		return ""
284	}
285	name := path.Base(u.Path)
286	name = strings.TrimSuffix(name, path.Ext(name))
287	if name == "" || name == "." || name == "/" {
288		return ""
289	}
290	return URLBuilder(host, "media", "emojitar", name, "?type=e")
291}
292
293// text is one styled run within a description: the rendered HTML, the raw source
294// it came from, and the offsets it spans in the original block.
295type text struct {
296	Txt    string
297	TxtRaw string
298	From   int
299	To     int
300}
301
302// ParseDescription renders a DeviantArt description into HTML, handling both the
303// Draft.js-style JSON payload and the plain HTML markup DeviantArt returns, and
304// rewriting embedded links and artwork references to point at this instance.
305// host is the request's scheme and host, as taken by URLBuilder.
306//
307// Three formats arrive: the current editor's document JSON (a "document"
308// key), handled by renderDocument; the older Draft.js JSON ("blocks" and
309// "entityMap"), handled below and kept for the posts that still carry it; and
310// plain HTML markup from before either.
311func ParseDescription(host string, dscr devianter.Text) string {
312	if doc, ok := parseDocument(dscr.Html.Markup); ok {
313		return renderDocument(host, doc)
314	}
315
316	description, dl := dscr.Html.Markup, len(dscr.Html.Markup)
317	if dl != 0 && description[0] == '{' && description[dl-1] == '}' {
318		return renderDraftJS(host, description)
319	}
320	if dl != 0 {
321		return renderMarkupHTML(host, description)
322	}
323	return ""
324}
325
326// tagBuilder wraps content in each tag in turn, innermost first.
327func tagBuilder(content string, tags ...string) string {
328	for _, tag := range tags {
329		var htm strings.Builder
330		htm.WriteString("<")
331		htm.WriteString(tag)
332		htm.WriteString(">")
333		htm.WriteString(content)
334		htm.WriteString("</")
335		htm.WriteString(tag)
336		htm.WriteString(">")
337		content = htm.String()
338	}
339	return content
340}
341
342type draftBlock struct {
343	Text              string `json:"text"`
344	Type              string `json:"type"`
345	InlineStyleRanges []struct {
346		Offset int    `json:"offset"`
347		Length int    `json:"length"`
348		Style  string `json:"style"`
349	} `json:"inlineStyleRanges"`
350	EntityRanges []struct {
351		Offset int `json:"offset"`
352		Length int `json:"length"`
353		Key    int `json:"key"`
354	} `json:"entityRanges"`
355	Data struct {
356		TextAlignment string `json:"textAlignment"`
357	} `json:"data"`
358}
359
360type draftDescription struct {
361	Blocks    []draftBlock `json:"blocks"`
362	EntityMap map[string]struct {
363		Type string `json:"type"`
364		Data struct {
365			URL    string `json:"url"`
366			Config struct {
367				// "aligment" is DeviantArt's own spelling; do not correct it.
368				Aligment string `json:"aligment"`
369				Width    int    `json:"width"`
370			} `json:"config"`
371			Data devianter.Deviation `json:"data"`
372		} `json:"data"`
373	} `json:"entityMap"`
374}
375
376// renderDraftJS renders the older Draft.js description JSON.
377func renderDraftJS(host, description string) string {
378	var descr draftDescription
379	e := json.Unmarshal([]byte(description), &descr)
380	try(e)
381
382	entities := make(map[int]devianter.Deviation)
383	urls := make(map[int]string)
384	for n, x := range descr.EntityMap {
385		num, _ := strconv.Atoi(n)
386		if x.Data.URL != "" {
387			urls[num] = deleteTrackingFromURL(x.Data.URL)
388		}
389		entities[num] = x.Data.Data
390	}
391
392	var parsedDescription strings.Builder
393	for _, x := range descr.Blocks {
394		styles := draftStyles(x)
395		switch x.Type {
396		case "atomic":
397			if len(x.EntityRanges) != 0 {
398				writeDraftArtwork(&parsedDescription, host, entities[x.EntityRanges[0].Key])
399			}
400		case "unstyled":
401			writeDraftText(&parsedDescription, x, styles, urls)
402		}
403		parsedDescription.WriteString("<br>")
404	}
405	return parsedDescription.String()
406}
407
408// draftStyles renders each inline style range of a block as tagged text.
409func draftStyles(x draftBlock) []text {
410	styles := make([]text, len(x.InlineStyleRanges))
411	if len(x.InlineStyleRanges) == 0 {
412		return styles
413	}
414	var tags = make(map[int][]string)
415	for n, rngs := range x.InlineStyleRanges {
416		style := &styles[n]
417		switch rngs.Style {
418		case "BOLD":
419			rngs.Style = "b"
420		case "UNDERLINE":
421			rngs.Style = "u"
422		case "ITALIC":
423			rngs.Style = "i"
424		}
425		style.From = rngs.Offset
426		style.To = rngs.Offset + rngs.Length
427		ft := style.From * style.To
428		tags[ft] = append(tags[ft], rngs.Style)
429	}
430	for n := range styles {
431		style := &styles[n]
432		style.TxtRaw = x.Text[style.From:style.To]
433		style.Txt = tagBuilder(esc(style.TxtRaw), tags[style.From*style.To]...)
434	}
435	return styles
436}
437
438// writeDraftArtwork writes an embedded deviation as a linked thumbnail.
439func writeDraftArtwork(b *strings.Builder, host string, d devianter.Deviation) {
440	b.WriteString(`<a href="`)
441	b.WriteString(esc(ConvertDeviantArtURLToSkunkyArt(host, d.Url)))
442	b.WriteString(`"><img width="50%" src="`)
443	b.WriteString(esc(ParseMedia(host, d.Media)))
444	b.WriteString(`" alt="`)
445	b.WriteString(esc(d.Author.Username))
446	b.WriteString(" - ")
447	b.WriteString(esc(d.Title))
448	b.WriteString(`" title="`)
449	b.WriteString(esc(d.Author.Username))
450	b.WriteString(" - ")
451	b.WriteString(esc(d.Title))
452	b.WriteString(`"></a>`)
453}
454
455// writeDraftText writes an unstyled block with its styled ranges and link.
456func writeDraftText(b *strings.Builder, x draftBlock, styles []text, urls map[int]string) {
457	l := len(styles)
458	if l == 0 {
459		b.WriteString(esc(x.Text))
460		return
461	}
462	for n, r := range styles {
463		var tag string
464		if x.Type == "header-two" {
465			tag = "h2"
466		}
467
468		b.WriteString(esc(x.Text[:r.From]))
469		if len(urls) != 0 && len(x.EntityRanges) != 0 {
470			ra := &x.EntityRanges[0]
471
472			b.WriteString(`<a target="_blank" href="`)
473			b.WriteString(esc(urls[ra.Key]))
474			b.WriteString(`">`)
475			b.WriteString(r.Txt)
476			b.WriteString(`</a>`)
477		} else if l > n+1 {
478			b.WriteString(r.Txt)
479		}
480		b.WriteString(tagBuilder(tag, esc(x.Text[r.To:])))
481	}
482}
483
484// renderMarkupHTML renders plain HTML markup, keeping links, DeviantArt
485// emoticons, and a few bare formatting tags.
486func renderMarkupHTML(host, markup string) string {
487	var parsedDescription strings.Builder
488	for tt := html.NewTokenizer(strings.NewReader(markup)); ; {
489		switch tt.Next() {
490		case html.ErrorToken:
491			return parsedDescription.String()
492		case html.CommentToken, html.DoctypeToken:
493			// No renderable content; skip.
494		case html.StartTagToken, html.EndTagToken, html.SelfClosingTagToken:
495			writeMarkupTag(&parsedDescription, host, tt, tt.Token())
496		case html.TextToken:
497			parsedDescription.WriteString(esc(string(tt.Text())))
498		}
499	}
500}
501
502func writeMarkupTag(b *strings.Builder, host string, tt *html.Tokenizer, token html.Token) {
503	switch token.Data {
504	case "a":
505		for _, a := range token.Attr {
506			if a.Key == "href" {
507				url := deleteTrackingFromURL(a.Val)
508				b.WriteString(`<a target="_blank" href="`)
509				b.WriteString(esc(url))
510				b.WriteString(`">`)
511				b.WriteString(esc(GetValueOfTag(tt)))
512				b.WriteString("</a> ")
513			}
514		}
515	case "img":
516		writeEmoticon(b, host, token)
517	case "br", "li", "ul", "p", "b":
518		// The bare tag, not token.String(): that would carry over
519		// whatever attributes DeviantArt's markup put on it.
520		if token.Type == html.EndTagToken {
521			b.WriteString("</")
522		} else {
523			b.WriteString("<")
524		}
525		b.WriteString(token.Data)
526		b.WriteString(">")
527	case "div":
528		b.WriteString("<p> ")
529	}
530}
531
532// writeEmoticon carries over DeviantArt's emoticons, served through this
533// instance; any other image is dropped.
534func writeEmoticon(b *strings.Builder, host string, token html.Token) {
535	var uri, title string
536	for _, a := range token.Attr {
537		switch a.Key {
538		case "src":
539			uri = emoticonURL(host, a.Val)
540		case "title":
541			title = a.Val
542		}
543	}
544	if uri != "" {
545		b.WriteString(`<img src="`)
546		b.WriteString(esc(uri))
547		b.WriteString(`" alt="`)
548		b.WriteString(esc(title))
549		b.WriteString(`" title="`)
550		b.WriteString(esc(title))
551		b.WriteString(`">`)
552	}
553}