all repos — honk @ 165909bfeb513a9054801e375970eb2187e505ec

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		alt := htfilter.GetAttr(node, "alt")
 57		if htfilter.HasClass(node, "Emoji") && alt != "" {
 58			return alt
 59		}
 60		return fmt.Sprintf(" <img src='%s'>", htfilter.GetAttr(node, "src"))
 61	}
 62
 63	var buf strings.Builder
 64	fmt.Fprintf(&buf, "%s\n", url)
 65
 66	divs := tweetsel.MatchAll(root)
 67	for i, div := range divs {
 68		twp := div.Parent.Parent.Parent
 69		link := url
 70		alink := linksel.MatchFirst(twp)
 71		if alink == nil {
 72			if i != 0 {
 73				dlog.Printf("missing link")
 74				continue
 75			}
 76		} else {
 77			link = "https://twitter.com" + htfilter.GetAttr(alink, "href")
 78		}
 79		replto := replyingto.MatchFirst(twp)
 80		if replto != nil {
 81			continue
 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		text = re_removepics.ReplaceAllString(text, "")
102
103		if seen[text] {
104			continue
105		}
106
107		fmt.Fprintf(&buf, "> @%s: %s\n", author, text)
108		seen[text] = true
109	}
110	return buf.String()
111}
112
113func hooterize(noise string) string {
114	seen := make(map[string]bool)
115
116	hootfetcher := func(hoot string) string {
117		url := hoot[5:]
118		if url[0] == ' ' {
119			url = url[1:]
120		}
121		url = strings.Replace(url, "mobile.twitter.com", "twitter.com", -1)
122		dlog.Printf("hooterizing %s", url)
123		req, err := http.NewRequest("GET", url, nil)
124		if err != nil {
125			ilog.Printf("error: %s", err)
126			return hoot
127		}
128		req.Header.Set("User-Agent", "Bot")
129		req.Header.Set("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8")
130		req.Header.Set("Accept-Language", "en-US,en;q=0.9")
131		resp, err := http.DefaultClient.Do(req)
132		if err != nil {
133			ilog.Printf("error: %s", err)
134			return hoot
135		}
136		defer resp.Body.Close()
137		if resp.StatusCode != 200 {
138			ilog.Printf("error getting %s: %d", url, resp.StatusCode)
139			return hoot
140		}
141		ld, _ := os.Create("lasthoot.html")
142		r := io.TeeReader(resp.Body, ld)
143		return hootextractor(r, url, seen)
144	}
145
146	return re_hoots.ReplaceAllStringFunc(noise, hootfetcher)
147}