all repos — honk @ fc6607ef85f04b58a51df07d6c88c92824a2eceb

my fork of honk

hoot.go (view raw)

  1//
  2// Copyright (c) 2019 Ted Unangst <tedu@tedunangst.com>
  3//
  4// Permission to use, copy, modify, and distribute this software for any
  5// purpose with or without fee is hereby granted, provided that the above
  6// copyright notice and this permission notice appear in all copies.
  7//
  8// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
  9// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 10// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
 11// ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 12// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
 13// ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
 14// OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 15
 16package main
 17
 18import (
 19	"fmt"
 20	"io"
 21	"net/http"
 22	"os"
 23	"regexp"
 24	"strings"
 25
 26	"github.com/andybalholm/cascadia"
 27	"golang.org/x/net/html"
 28	"humungus.tedunangst.com/r/webs/htfilter"
 29	"humungus.tedunangst.com/r/webs/templates"
 30)
 31
 32var tweetsel = cascadia.MustCompile("div[data-testid=tweetText]")
 33var linksel = cascadia.MustCompile("a time")
 34var replyingto = cascadia.MustCompile(".ReplyingToContextBelowAuthor")
 35var imgsel = cascadia.MustCompile("div[data-testid=tweetPhoto] img")
 36var authorregex = regexp.MustCompile("twitter.com/([^/]+)")
 37
 38var re_hoots = regexp.MustCompile(`hoot: ?https://\S+`)
 39var re_removepics = regexp.MustCompile(`pic\.twitter\.com/[[:alnum:]]+`)
 40
 41func hootextractor(r io.Reader, url string, seen map[string]bool) string {
 42	root, err := html.Parse(r)
 43	if err != nil {
 44		elog.Printf("error parsing hoot: %s", err)
 45		return url
 46	}
 47
 48	url = strings.Replace(url, "mobile.twitter.com", "twitter.com", -1)
 49	wantmatch := authorregex.FindStringSubmatch(url)
 50	var wanted string
 51	if len(wantmatch) == 2 {
 52		wanted = wantmatch[1]
 53	}
 54
 55	var htf htfilter.Filter
 56	htf.Imager = func(node *html.Node) string {
 57		alt := htfilter.GetAttr(node, "alt")
 58		src := htfilter.GetAttr(node, "src")
 59		if htfilter.HasClass(node, "Emoji") || strings.HasSuffix(src, ".svg") {
 60			return alt
 61		}
 62		return string(templates.Sprintf(" <img src='%s' alt='%s'>", src, alt))
 63	}
 64
 65	var buf strings.Builder
 66	fmt.Fprintf(&buf, "%s\n", url)
 67
 68	divs := tweetsel.MatchAll(root)
 69	for i, div := range divs {
 70		twp := div.Parent.Parent.Parent.Parent.Parent
 71		link := url
 72		alink := linksel.MatchFirst(twp)
 73		if alink == nil {
 74			if i != 0 {
 75				dlog.Printf("missing link")
 76				continue
 77			}
 78		} else {
 79			alink = alink.Parent
 80			link = "https://twitter.com" + htfilter.GetAttr(alink, "href")
 81		}
 82		authormatch := authorregex.FindStringSubmatch(link)
 83		if len(authormatch) < 2 {
 84			dlog.Printf("no author?: %s", link)
 85			continue
 86		}
 87		author := authormatch[1]
 88		if wanted == "" {
 89			wanted = author
 90		}
 91		if author != wanted {
 92			continue
 93		}
 94		for _, img := range imgsel.MatchAll(twp) {
 95			img.Parent.RemoveChild(img)
 96			div.AppendChild(img)
 97		}
 98		text := htf.NodeText(div)
 99		text = strings.Replace(text, "\n", " ", -1)
100		fmt.Fprintf(&buf, "> @%s: %s\n", author, text)
101	}
102	return buf.String()
103}
104
105func hooterize(noise string) string {
106	seen := make(map[string]bool)
107
108	hootfetcher := func(hoot string) string {
109		url := hoot[5:]
110		if url[0] == ' ' {
111			url = url[1:]
112		}
113		url = strings.Replace(url, "mobile.twitter.com", "twitter.com", -1)
114		dlog.Printf("hooterizing %s", url)
115		req, err := http.NewRequest("GET", url, nil)
116		if err != nil {
117			ilog.Printf("error: %s", err)
118			return hoot
119		}
120		req.Header.Set("User-Agent", "Bot")
121		req.Header.Set("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8")
122		req.Header.Set("Accept-Language", "en-US,en;q=0.9")
123		resp, err := http.DefaultClient.Do(req)
124		if err != nil {
125			ilog.Printf("error: %s", err)
126			return hoot
127		}
128		defer resp.Body.Close()
129		if resp.StatusCode != 200 {
130			ilog.Printf("error getting %s: %d", url, resp.StatusCode)
131			return hoot
132		}
133		ld, _ := os.Create("lasthoot.html")
134		r := io.TeeReader(resp.Body, ld)
135		return hootextractor(r, url, seen)
136	}
137
138	return re_hoots.ReplaceAllStringFunc(noise, hootfetcher)
139}