all repos — honk @ 00d1e9979b1bcf03e0146bce91270b89e822d8be

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