all repos — honk @ 9a91ab546ebda986c501c8553deca8a70ff60496

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	"github.com/sassoftware/relic/lib/dlog"
 28	"golang.org/x/net/html"
 29	"humungus.tedunangst.com/r/webs/htfilter"
 30	"humungus.tedunangst.com/r/webs/templates"
 31)
 32
 33var tweetsel = cascadia.MustCompile("div[data-testid=tweetText]")
 34var linksel = cascadia.MustCompile("a time")
 35var replyingto = cascadia.MustCompile(".ReplyingToContextBelowAuthor")
 36var imgsel = cascadia.MustCompile("div[data-testid=tweetPhoto] img")
 37var authorregex = regexp.MustCompile("twitter.com/([^/]+)")
 38
 39var re_hoots = regexp.MustCompile(`hoot: ?https://\S+`)
 40var re_removepics = regexp.MustCompile(`pic\.twitter\.com/[[:alnum:]]+`)
 41
 42func hootextractor(r io.Reader, url string, seen map[string]bool) string {
 43	root, err := html.Parse(r)
 44	if err != nil {
 45		elog.Printf("error parsing hoot: %s", err)
 46		return url
 47	}
 48
 49	url = strings.Replace(url, "mobile.twitter.com", "twitter.com", -1)
 50	wantmatch := authorregex.FindStringSubmatch(url)
 51	var wanted string
 52	if len(wantmatch) == 2 {
 53		wanted = wantmatch[1]
 54	}
 55
 56	var htf htfilter.Filter
 57	htf.Imager = func(node *html.Node) string {
 58		alt := htfilter.GetAttr(node, "alt")
 59		src := htfilter.GetAttr(node, "src")
 60		if htfilter.HasClass(node, "Emoji") || strings.HasSuffix(src, ".svg") {
 61			return alt
 62		}
 63		return string(templates.Sprintf(" <img src='%s' alt='%s'>", src, alt))
 64	}
 65
 66	var buf strings.Builder
 67	fmt.Fprintf(&buf, "%s\n", url)
 68
 69	divs := tweetsel.MatchAll(root)
 70	for i, div := range divs {
 71		twp := div.Parent.Parent.Parent.Parent.Parent
 72		link := url
 73		alink := linksel.MatchFirst(twp)
 74		if alink == nil {
 75			if i != 0 {
 76				dlog.Printf("missing link")
 77				continue
 78			}
 79		} else {
 80			alink = alink.Parent
 81			link = "https://twitter.com" + htfilter.GetAttr(alink, "href")
 82		}
 83		authormatch := authorregex.FindStringSubmatch(link)
 84		if len(authormatch) < 2 {
 85			dlog.Printf("no author?: %s", link)
 86			continue
 87		}
 88		author := authormatch[1]
 89		if wanted == "" {
 90			wanted = author
 91		}
 92		if author != wanted {
 93			continue
 94		}
 95		for _, img := range imgsel.MatchAll(twp) {
 96			img.Parent.RemoveChild(img)
 97			div.AppendChild(img)
 98		}
 99		text := htf.NodeText(div)
100		text = strings.Replace(text, "\n", " ", -1)
101		fmt.Fprintf(&buf, "> @%s: %s\n", author, text)
102	}
103	return buf.String()
104}
105
106func hooterize(noise string) string {
107	seen := make(map[string]bool)
108
109	hootfetcher := func(hoot string) string {
110		url := hoot[5:]
111		if url[0] == ' ' {
112			url = url[1:]
113		}
114		url = strings.Replace(url, "mobile.twitter.com", "twitter.com", -1)
115		dlog.Printf("hooterizing %s", url)
116		req, err := http.NewRequest("GET", url, nil)
117		if err != nil {
118			ilog.Printf("error: %s", err)
119			return hoot
120		}
121		req.Header.Set("User-Agent", "Bot")
122		req.Header.Set("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8")
123		req.Header.Set("Accept-Language", "en-US,en;q=0.9")
124		resp, err := http.DefaultClient.Do(req)
125		if err != nil {
126			ilog.Printf("error: %s", err)
127			return hoot
128		}
129		defer resp.Body.Close()
130		if resp.StatusCode != 200 {
131			ilog.Printf("error getting %s: %d", url, resp.StatusCode)
132			return hoot
133		}
134		ld, _ := os.Create("lasthoot.html")
135		r := io.TeeReader(resp.Body, ld)
136		return hootextractor(r, url, seen)
137	}
138
139	return re_hoots.ReplaceAllStringFunc(noise, hootfetcher)
140}