all repos — honk @ 4124f790bbcde57cc9b17f2899b14f1e2446563d

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