1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
package main

import (
	"database/sql"
	"fmt"
	"io"
	"net/http"
	"strings"
	"time"

	"golang.org/x/net/html"
	"golang.org/x/net/html/atom"
)

const listingUrl = "https://rss-parrot.net/web/feeds?page=%d"

// listPause is the wait between two listing pages.
const listPause = time.Second

type entry struct {
	Handle, FeedUrl, SiteUrl, Title, Since, LastPosted string
}

// list reads the listing page by page until one holds no entries, skipping
// pages read completely before.
func list(db *sql.DB, log io.Writer) error {
	client := &http.Client{Timeout: 30 * time.Second}
	for page := 0; ; page++ {
		var n int
		err := db.QueryRow(`SELECT entries FROM listing_page WHERE page=?`, page).Scan(&n)
		if err == nil {
			if n == 0 {
				return nil
			}
			continue
		}
		if err != sql.ErrNoRows {
			return err
		}

		entries, err := getListingPage(client, page)
		if err != nil {
			return fmt.Errorf("page %d: %w", page, err)
		}
		if err = storeListingPage(db, page, entries); err != nil {
			return err
		}
		fmt.Fprintf(log, "page %d: %d entries\n", page, len(entries))
		if len(entries) == 0 {
			return nil
		}
		time.Sleep(listPause)
	}
}

func getListingPage(client *http.Client, page int) ([]entry, error) {
	req, err := http.NewRequest("GET", fmt.Sprintf(listingUrl, page), nil)
	if err != nil {
		return nil, err
	}
	req.Header.Set("User-Agent", userAgent)
	resp, err := client.Do(req)
	if err != nil {
		return nil, err
	}
	defer resp.Body.Close()
	if resp.StatusCode != http.StatusOK {
		return nil, fmt.Errorf("status %d", resp.StatusCode)
	}
	return parseListing(resp.Body)
}

func storeListingPage(db *sql.DB, page int, entries []entry) error {
	tx, err := db.Begin()
	if err != nil {
		return err
	}
	defer tx.Rollback()
	for _, e := range entries {
		// A feed requested while the listing is read moves the others down a
		// place, so one may turn up on two pages; the later one wins.
		if _, err = tx.Exec(`INSERT OR REPLACE INTO listing
			(handle, feed_url, site_url, title, since, last_posted, page) VALUES (?,?,?,?,?,?,?)`,
			e.Handle, e.FeedUrl, e.SiteUrl, e.Title, e.Since, e.LastPosted, page); err != nil {
			return err
		}
	}
	if _, err = tx.Exec(`INSERT INTO listing_page (page, entries) VALUES (?,?)`, page, len(entries)); err != nil {
		return err
	}
	return tx.Commit()
}

// parseListing reads the entries of one listing page. Each is an
//
//	<article class="feed">
//	  <div><h3>FEED URL</h3><span>[<a href="SITE URL">visit</a>]</span></div>
//	  <p class="info">Parroting since DATE as <a href="…">@HANDLE</a></p>
//	  <p class="info">Last posted: DATE</p>
//	  <p class="title">TITLE</p>
//	</article>
func parseListing(r io.Reader) ([]entry, error) {
	var res []entry
	var cur *entry
	var text strings.Builder
	// What the text being collected is: the element it is in.
	var in string
	infos := 0

	z := html.NewTokenizer(r)
	for {
		tt := z.Next()
		switch tt {
		case html.ErrorToken:
			if z.Err() == io.EOF {
				return res, nil
			}
			return nil, z.Err()
		case html.TextToken:
			if in != "" {
				text.Write(z.Text())
			}
		case html.StartTagToken:
			name, hasAttr := z.TagName()
			attrs := map[string]string{}
			for hasAttr {
				var k, v []byte
				k, v, hasAttr = z.TagAttr()
				attrs[string(k)] = string(v)
			}
			a := atom.Lookup(name)
			if a == atom.Article && hasWord(attrs["class"], "feed") {
				res = append(res, entry{})
				cur = &res[len(res)-1]
				infos = 0
				continue
			}
			if cur == nil {
				continue
			}
			switch {
			case a == atom.H3:
				in, text = "h3", strings.Builder{}
			case a == atom.A && in == "" && cur.SiteUrl == "" && cur.Handle == "":
				cur.SiteUrl = attrs["href"]
			case a == atom.P && hasWord(attrs["class"], "info"):
				infos++
				in, text = fmt.Sprintf("info%d", infos), strings.Builder{}
			case a == atom.P && hasWord(attrs["class"], "title"):
				in, text = "title", strings.Builder{}
			}
		case html.EndTagToken:
			name, _ := z.TagName()
			a := atom.Lookup(name)
			if cur == nil {
				continue
			}
			if a == atom.Article {
				cur = nil
				continue
			}
			if (in == "h3" && a == atom.H3) || (in != "" && in != "h3" && a == atom.P) {
				s := strings.Join(strings.Fields(text.String()), " ")
				switch in {
				case "h3":
					cur.FeedUrl = s
				case "info1":
					// "Parroting since January 2, 2024 as @adamj.eu"
					rest := strings.TrimPrefix(s, "Parroting since ")
					if i := strings.LastIndex(rest, " as @"); i >= 0 {
						cur.Since, cur.Handle = rest[:i], rest[i+len(" as @"):]
					}
				case "info2":
					cur.LastPosted = strings.TrimPrefix(s, "Last posted: ")
				case "title":
					cur.Title = s
				}
				in = ""
			}
		}
	}
}

func hasWord(s, word string) bool {
	for _, w := range strings.Fields(s) {
		if strings.EqualFold(w, word) {
			return true
		}
	}
	return false
}