app/wrapper.go

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

460 lines · 15066 bytes · executable

  1package app
  2
  3import (
  4	"crypto/sha1" //nolint:gosec // G505: SHA-1 is a cache-key hash here, not a security primitive
  5	"html/template"
  6	"maps"
  7	"net/url"
  8	"regexp"
  9	"strconv"
 10	"strings"
 11	"time"
 12
 13	"github.com/krazywarez/devianter"
 14	"golang.org/x/net/html"
 15)
 16
 17// devianter calls behind variables so tests can count and script them.
 18var (
 19	fetchDeviation = devianter.GetDeviation
 20	fetchComments  = devianter.GetComments
 21	fetchProfile   = func(name string) (devianter.GRuser, devianter.Error, error) {
 22		g := devianter.Group{Name: name}
 23		return g.Get()
 24	}
 25	fetchGallery = func(g devianter.Group, page, folderid int) (devianter.Group, devianter.Error, error) {
 26		return g.Gallery(page, folderid)
 27	}
 28	fetchFavourites = func(g devianter.Group, page int, all bool, folderid int) (devianter.Group, devianter.Error) {
 29		return g.Favourites(page, all, folderid)
 30	}
 31)
 32
 33// groupSearchURL is the DeviantArt group search page for query, paged ten
 34// results at a time. page counts from 1; 0 means the first page too.
 35func groupSearchURL(query string, page int) string {
 36	var url strings.Builder
 37	url.WriteString("https://www.deviantart.com/groups/?q=")
 38	url.WriteString(query)
 39	if page > 1 {
 40		url.WriteString("&offset=")
 41		url.WriteString(strconv.Itoa(10 * (page - 1)))
 42	}
 43	return url.String()
 44}
 45
 46// commentsOrLink renders a comment thread only when the request asked for it
 47// with ?comments=1, and otherwise a link that does. A thread is a second
 48// upstream call on every post and profile view, and most viewers never open
 49// it. total is shown in the link when it is known (0 or more).
 50func (s skunkyart) commentsOrLink(id, cursor string, kind, total int) template.HTML {
 51	if s.Args.Get("comments") != "" {
 52		return template.HTML(s.ParseComments(fetchComments(id, cursor, s.Page, kind))) //nolint:gosec // G203: ParseComments escapes its input
 53	}
 54
 55	args := url.Values{}
 56	maps.Copy(args, s.Args)
 57	args.Del("p")
 58	args.Set("comments", "1")
 59
 60	var link strings.Builder
 61	link.WriteString(`<p><a href="`)
 62	link.WriteString(esc(s._pth + "?" + args.Encode()))
 63	link.WriteString(`">`)
 64	link.WriteString(esc(T(s.Lang, "deviation.comments")))
 65	if total >= 0 {
 66		link.WriteString(" (")
 67		link.WriteString(strconv.Itoa(total))
 68		link.WriteString(")")
 69	}
 70	link.WriteString("</a></p>")
 71	return template.HTML(link.String()) //nolint:gosec // G203: escaped above
 72}
 73
 74// GRUser renders a group or user page: the about tab, the gallery, or favourites,
 75// selected by the request's type argument.
 76func (s skunkyart) GRUser() {
 77	if len(s.Query) < 1 {
 78		s.ReturnHTTPError(400)
 79		return
 80	}
 81
 82	var g devianter.Group
 83	var daError devianter.Error
 84	g.Name = s.Query
 85	var err error
 86	s.Templates.GroupUser.GR, daError, err = fetchProfile(s.Query)
 87	try(err)
 88	if daError.RAW != nil {
 89		s.Error(daError)
 90		return
 91	}
 92
 93	group := &s.Templates.GroupUser
 94
 95	switch s.Type {
 96	case 'a':
 97		s.Atom = false
 98		for _, x := range group.GR.Gruser.Page.Modules {
 99			switch x.Name {
100			case "about", "group_about":
101				s.fillAbout(group, x.ModuleData.GroupAbout, x.ModuleData.About)
102			case "cover_deviation":
103				group.About.BGMeta = x.ModuleData.CoverDeviation.Deviation
104				group.About.BGMeta.Url = ConvertDeviantArtURLToSkunkyArt(s.Host, group.About.BGMeta.Url)
105				group.About.BG = ParseMedia(s.Host, group.About.BGMeta.Media)
106			case "group_admins":
107				var htm strings.Builder
108				for _, z := range x.ModuleData.GroupAdmins.Results {
109					htm.WriteString(BuildUserPlate(s.Host, z.User.Username))
110				}
111				group.Admins += template.HTML(htm.String()) //nolint:gosec // G203: BuildUserPlate escapes its input
112			}
113		}
114	case 'g', 'f':
115		if s.Page == 0 {
116			s.Page++
117		}
118		if !s.fillGallery(group, g) {
119			return
120		}
121	default:
122		s.ReturnHTTPError(400)
123	}
124
125	if !s.Atom {
126		s.ExecuteTemplate("gruser.htm", "html", &s)
127	}
128}
129
130// fillAbout fills the about tab from a group's or a user's about module.
131func (s skunkyart) fillAbout(group *groupUserPage, groupAbout devianter.GroupAbout, about devianter.About) {
132	if group.GR.Owner.Group {
133		group.Group = true
134		group.CreationDate = groupAbout.FoundatedAt.UTC().String()
135		group.About.DescriptionFormatted = template.HTML(ParseDescription(s.Host, groupAbout.Description)) //nolint:gosec // G203: ParseDescription escapes its input
136	} else {
137		group.About.A = about
138		group.CreationDate = time.Unix(time.Now().Unix()-about.RegDate, 0).UTC().String()
139		group.About.DescriptionFormatted = template.HTML(ParseDescription(s.Host, about.Description)) //nolint:gosec // G203: ParseDescription escapes its input
140		group.About.Social += profileLinks(about)
141		group.About.Interests += profileInterests(about)
142	}
143	group.About.Comments = s.commentsOrLink(strconv.Itoa(group.GR.Gruser.ID), "", 4, -1)
144}
145
146func profileLinks(about devianter.About) template.HTML {
147	var out template.HTML
148	for _, val := range about.SocialLinks {
149		var social strings.Builder
150		social.WriteString(`<a target="_blank" href="`)
151		social.WriteString(esc(val.Value))
152		social.WriteString(`">`)
153		social.WriteString(esc(val.Value))
154		social.WriteString("</a><br>")
155		out += template.HTML(social.String()) //nolint:gosec // G203: escaped above
156	}
157	return out
158}
159
160func profileInterests(about devianter.About) template.HTML {
161	var out template.HTML
162	for _, val := range about.Interests {
163		var interest strings.Builder
164		interest.WriteString(esc(val.Label))
165		interest.WriteString(": <b>")
166		interest.WriteString(esc(val.Value))
167		interest.WriteString("</b><br>")
168		out += template.HTML(interest.String()) //nolint:gosec // G203: escaped above
169	}
170	return out
171}
172
173// fillGallery fills the gallery or favourites tab. It returns false when
174// DeviantArt answered with an error, which has already been rendered.
175func (s skunkyart) fillGallery(group *groupUserPage, g devianter.Group) bool {
176	var err error
177	var daError devianter.Error
178	var content devianter.Group
179	folderid, _ := strconv.Atoi(s.Args.Get("folder"))
180	all := s.Args.Get("all") == "true"
181
182	if s.Type == 'f' {
183		content, daError = fetchFavourites(g, s.Page, all, folderid)
184	} else {
185		content, daError, err = fetchGallery(g, s.Page, folderid)
186		try(err)
187	}
188
189	if daError.RAW != nil {
190		s.Error(daError)
191		return false
192	}
193
194	if folderid > 0 || (s.Type == 'f' && all) {
195		group.Gallery.List = template.HTML(s.DeviationList(content.Content.Results, true, DeviationList{ //nolint:gosec // G203: DeviationList escapes its input
196			More: content.Content.HasMore,
197		}))
198		return true
199	}
200	for _, x := range content.Content.Gruser.Page.Modules {
201		if len(x.ModuleData.Folders.Results) != 0 {
202			group.Gallery.Folders = s.folderGrid(x.ModuleData.Folders.Results)
203		}
204		if x.Name == "folder_deviations" {
205			group.Gallery.List = template.HTML(s.DeviationList(x.ModuleData.Folder.Deviations, true, DeviationList{ //nolint:gosec // G203: DeviationList escapes its input
206				Pages: x.ModuleData.Folder.Pages,
207				More:  x.ModuleData.Folder.HasMore,
208			}))
209		}
210	}
211	return true
212}
213
214// galleryFolder is one entry of a gallery's folder list, as devianter decodes it.
215type galleryFolder = struct {
216	Deviations int `json:"totalItemCount"`
217	FolderId   int //nolint:staticcheck // ST1003: must match devianter's field for the types to be identical
218	Size       int
219	Name       string
220	Thumb      devianter.Deviation
221}
222
223// folderGrid renders the non-empty folders of a gallery as thumbnail links.
224func (s skunkyart) folderGrid(results []galleryFolder) template.HTML {
225	var folders strings.Builder
226	folders.WriteString(`<h1 id="folders"><a href="#folders">#</a> ` + esc(T(s.Lang, "gallery.folders")) + `</h1><div class="folders"><br>`)
227	for _, x := range results {
228		if x.FolderId == -1 || x.Size == 0 {
229			continue
230		}
231		folders.WriteString(`<div class="block folder-item">`)
232		if !x.Thumb.NSFW || CFG.Nsfw {
233			folders.WriteString(`<a href="`)
234			folders.WriteString(esc(ConvertDeviantArtURLToSkunkyArt(s.Host, x.Thumb.Url)))
235			folders.WriteString(`"><img loading="lazy" src="`)
236			folders.WriteString(esc(ParseMedia(s.Host, x.Thumb.Media)))
237			folders.WriteString(`" title="`)
238			folders.WriteString(esc(x.Thumb.Title))
239			folders.WriteString(`" alt="`)
240			folders.WriteString(esc(x.Thumb.Title))
241			folders.WriteString(`"></a>`)
242		} else {
243			folders.WriteString(`<h1>[ <span class="nsfw">NSFW</span> ]</h1>`)
244		}
245		folders.WriteString("<br>")
246
247		folders.WriteString(`<a href="group_user?folder=`)
248		folders.WriteString(strconv.Itoa(x.FolderId))
249		folders.WriteString("&q=")
250		folders.WriteString(esc(s.Query))
251		folders.WriteString("&type=")
252		folders.WriteRune(s.Type)
253		folders.WriteString(`">`)
254		folders.WriteString(esc(x.Name))
255		folders.WriteString(`</a>`)
256
257		folders.WriteString("</div>")
258	}
259	folders.WriteString(`</div><h1 id="content"><a href="#content">#</a> ` + esc(T(s.Lang, "gallery.content")) + `</h1>`)
260	return template.HTML(folders.String()) //nolint:gosec // G203: escaped above
261}
262
263// groupSearchUsernames scrapes the group names from DeviantArt's group search page.
264func groupSearchUsernames(body []byte) []string {
265	var usernames []string
266	for z := html.NewTokenizer(strings.NewReader(string(body))); ; {
267		n, token := z.Next(), z.Token()
268		if n == html.ErrorToken {
269			return usernames
270		}
271		if n != html.StartTagToken || token.Data != "a" {
272			continue
273		}
274		for _, x := range token.Attr {
275			if x.Key == "class" && x.Val == "u regular username" {
276				usernames = append(usernames, GetValueOfTag(z))
277			}
278		}
279	}
280}
281
282// groupPlates renders scraped group names as user plates with page navigation.
283func (s skunkyart) groupPlates(usernames []string) template.HTML {
284	var plates strings.Builder
285	plates.WriteString(`<div class="content plates">`)
286	for _, name := range usernames {
287		plates.WriteString(BuildUserPlate(s.Host, name))
288	}
289	plates.WriteString(`</div>`)
290	plates.WriteString(s.NavBase(DeviationList{
291		More: true,
292	}))
293	return template.HTML(plates.String()) //nolint:gosec // G203: BuildUserPlate escapes its input
294}
295
296// Deviation renders a single artwork page, with its description, tags, comments
297// and related work. It responds 403 for NSFW posts on instances that disallow them.
298func (s skunkyart) Deviation(author, postname string) {
299	idSearch := regexp.MustCompile("[0-9]+").FindAllString(postname, -1)
300	if len(idSearch) < 1 {
301		s.ReturnHTTPError(400)
302		return
303	}
304
305	var err devianter.Error
306	post := &s.Templates.Deviation
307
308	id := idSearch[len(idSearch)-1]
309	post.Post, err = fetchDeviation(id, author)
310	if err.RAW != nil {
311		s.Error(err)
312		return
313	}
314
315	if post.Post.Deviation.NSFW && !CFG.Nsfw {
316		s.Writer.Header().Del("Cache-Control")
317		s.Writer.WriteHeader(403)
318		wr(s.Writer, `<html><link rel="stylesheet" href="`+
319			URLBuilder(s.Host, "stylesheet")+
320			`" /><h1>`+esc(T(s.Lang, "error.nsfw"))+`</h1></html>`)
321		return
322	}
323
324	if post.Post.Comments.Total <= 50 {
325		post.Post.Comments.Cursor = ""
326	}
327
328	if post.Post.Deviation.TextContent.Excerpt != "" {
329		post.Description = template.HTML(ParseDescription(s.Host, post.Post.Deviation.TextContent)) //nolint:gosec // G203: ParseDescription escapes its input
330	} else {
331		post.Description = template.HTML(ParseDescription(s.Host, post.Post.Deviation.Extended.DescriptionText)) //nolint:gosec // G203: ParseDescription escapes its input
332	}
333
334	for _, x := range post.Post.Deviation.Extended.RelatedContent {
335		if len(x.Deviations) != 0 {
336			post.Related += template.HTML(s.DeviationList(x.Deviations, false)) //nolint:gosec // G203: DeviationList escapes its input
337		}
338	}
339
340	// hashtags
341	for _, x := range post.Post.Deviation.Extended.Tags {
342		var tag strings.Builder
343		tag.WriteString(` <a href="`)
344		tag.WriteString(esc(URLBuilder(s.Host, "search", "?q=", x.Name, "&type=tag")))
345		tag.WriteString(`">#`)
346		tag.WriteString(esc(x.Name))
347		tag.WriteString("</a>")
348
349		post.Tags += template.HTML(tag.String()) //nolint:gosec // G203: escaped above
350	}
351
352	post.Comments = s.commentsOrLink(id, post.Post.Comments.Cursor, 1, post.Post.Comments.Total)
353	post.StringTime = post.Post.Deviation.PublishedTime.UTC().String()
354	post.Post.IMG = ParseMedia(s.Host, post.Post.Deviation.Media)
355
356	s.ExecuteTemplate("deviantion.htm", "html", &s)
357}
358
359// DD renders the Daily Deviations page, including each themed strip.
360func (s skunkyart) DD() {
361	dd, err := devianter.GetDailyDeviations(s.Page)
362	if err.RAW != nil {
363		s.Error(err)
364		return
365	}
366	var strips strings.Builder
367	for _, x := range dd.Strips {
368		strips.WriteString(`<h3 class="`)
369		strips.WriteString(esc(x.Codename))
370		strips.WriteString(`"> <a href="#`)
371		strips.WriteString(esc(x.Codename))
372		strips.WriteString(`"># </a>`)
373		strips.WriteString(esc(x.Title))
374		strips.WriteString(`</h3>`)
375
376		strips.WriteString(s.DeviationList(x.Deviations, false))
377	}
378	s.Templates.DDStrips = template.HTML(strips.String())                                    //nolint:gosec // G203: escaped above
379	s.Templates.SomeList = template.HTML(s.DeviationList(dd.Deviations, true, DeviationList{ //nolint:gosec // G203: DeviationList escapes its input
380		Pages: 0,
381		More:  dd.HasMore,
382	}))
383	if !s.Atom {
384		s.ExecuteTemplate("daily.htm", "html", &s)
385	}
386}
387
388// Search renders search results for the request's query. Group search is scraped
389// rather than fetched from the API, which DeviantArt does not expose to guests.
390func (s skunkyart) Search() {
391	if s.Query == "" {
392		s.ReturnHTTPError(400)
393		return
394	}
395
396	var err error
397	var daError devianter.Error
398	ss := &s.Templates.Search
399	switch s.Type {
400	case 'a', 't':
401		ss.Content, daError, err = devianter.PerformSearch(s.Query, s.Page, s.Type)
402	case 'g', 'f':
403		ss.Content, daError, err = devianter.PerformSearch(s.Query, s.Page, s.Type, s.Args.Get("usr"))
404	case 'r': // scraper, since DeviantArt withholds the guest API for group search
405		dwnld := Download(groupSearchURL(s.Query, s.Page))
406		if usernames := groupSearchUsernames(dwnld.Body); len(usernames) != 0 {
407			ss.List = s.groupPlates(usernames)
408		}
409	default:
410		s.ReturnHTTPError(400)
411		return
412	}
413	try(err)
414
415	if s.Type != 'r' {
416		if daError.RAW != nil {
417			s.Error(daError)
418			return
419		}
420
421		ss.List = template.HTML(s.DeviationList(ss.Content.Results, false, DeviationList{ //nolint:gosec // G203: DeviationList escapes its input
422			Pages: ss.Content.Pages,
423			More:  ss.Content.HasMore,
424		}))
425	}
426
427	s.ExecuteTemplate("search.htm", "html", &s)
428}
429
430// fetchAvatar is devianter.AEmedia behind a variable so tests can count calls.
431var fetchAvatar = devianter.AEmedia
432
433// Emojitar proxies a user's avatar or emoji image, selected by the request's
434// type argument. With the media cache on, the image is served from it after
435// the first fetch: avatars are on every comment and listing, and DeviantArt
436// answers each fetch with up to three requests.
437func (s skunkyart) Emojitar(name string) {
438	if name == "" || (s.Type != 'a' && s.Type != 'e') {
439		s.ReturnHTTPError(400)
440		return
441	}
442
443	key := sha1.Sum([]byte("emojitar:" + string(s.Type) + ":" + strings.ToLower(name))) //nolint:gosec // G401: cache key, not a security primitive
444	if CFG.Cache.Enabled {
445		if body := cachedBody(key); body != nil {
446			_, _ = s.Writer.Write(body)
447			return
448		}
449	}
450
451	ae, e := fetchAvatar(name, s.Type)
452	if e != nil {
453		s.ReturnHTTPError(404)
454		return
455	}
456	if CFG.Cache.Enabled {
457		storeBody(key, []byte(ae))
458	}
459	wr(s.Writer, ae)
460}