This repository has been archived by the owner on Dec 17, 2023. It is now read-only.
forked from plantimals/rsslay
-
-
Notifications
You must be signed in to change notification settings - Fork 12
/
feed.go
235 lines (199 loc) · 5.43 KB
/
feed.go
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
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
package feed
import (
"crypto/hmac"
"crypto/sha256"
"database/sql"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"github.com/PuerkitoBio/goquery"
strip "github.com/grokify/html-strip-tags-go"
"github.com/mmcdole/gofeed"
"github.com/nbd-wtf/go-nostr"
"github.com/piraces/rsslay/pkg/helpers"
"github.com/rif/cache2go"
"html"
"log"
"net/http"
"strings"
"time"
)
var (
fp = gofeed.NewParser()
feedCache = cache2go.New(512, time.Minute*19)
client = &http.Client{
CheckRedirect: func(req *http.Request, via []*http.Request) error {
if len(via) >= 2 {
return errors.New("stopped after 2 redirects")
}
return nil
},
Timeout: 5 * time.Second,
}
)
type Entity struct {
PublicKey string
PrivateKey string
URL string
}
var types = []string{
"rss+xml",
"atom+xml",
"feed+json",
"text/xml",
"application/xml",
}
func GetFeedURL(url string) string {
resp, err := client.Get(url)
if err != nil || resp.StatusCode >= 300 {
return ""
}
ct := resp.Header.Get("Content-Type")
for _, typ := range types {
if strings.Contains(ct, typ) {
return url
}
}
if strings.Contains(ct, "text/html") {
doc, err := goquery.NewDocumentFromReader(resp.Body)
if err != nil {
return ""
}
for _, typ := range types {
href, _ := doc.Find(fmt.Sprintf("link[type*='%s']", typ)).Attr("href")
if href == "" {
continue
}
if !strings.HasPrefix(href, "http") && !strings.HasPrefix(href, "https") {
href, _ = helpers.UrlJoin(url, href)
}
return href
}
}
return ""
}
func ParseFeed(url string) (*gofeed.Feed, error) {
if feed, ok := feedCache.Get(url); ok {
return feed.(*gofeed.Feed), nil
}
feed, err := fp.ParseURL(url)
if err != nil {
return nil, err
}
// cleanup a little so we don't store too much junk
for i := range feed.Items {
feed.Items[i].Content = ""
}
feedCache.Set(url, feed)
return feed, nil
}
func EntryFeedToSetMetadata(pubkey string, feed *gofeed.Feed, originalUrl string, enableAutoRegistration bool, defaultProfilePictureUrl string) nostr.Event {
// Handle Nitter special cases (http schema)
if strings.Contains(feed.Description, "Twitter feed") {
if strings.HasPrefix(originalUrl, "https://") {
feed.Description = strings.ReplaceAll(feed.Description, "http://", "https://")
feed.Title = strings.ReplaceAll(feed.Title, "http://", "https://")
feed.Image.URL = strings.ReplaceAll(feed.Image.URL, "http://", "https://")
feed.Link = strings.ReplaceAll(feed.Link, "http://", "https://")
}
}
metadata := map[string]string{
"name": feed.Title,
"about": feed.Description + "\n\n" + feed.Link,
}
if enableAutoRegistration {
metadata["nip05"] = fmt.Sprintf("%s@%s", originalUrl, "rsslay.nostr.moe")
}
if feed.Image != nil {
metadata["picture"] = feed.Image.URL
} else if defaultProfilePictureUrl != "" {
metadata["picture"] = defaultProfilePictureUrl
}
content, _ := json.Marshal(metadata)
createdAt := time.Now()
if feed.PublishedParsed != nil {
createdAt = *feed.PublishedParsed
}
evt := nostr.Event{
PubKey: pubkey,
CreatedAt: createdAt,
Kind: nostr.KindSetMetadata,
Tags: nostr.Tags{},
Content: string(content),
}
evt.ID = string(evt.Serialize())
return evt
}
func ItemToTextNote(pubkey string, item *gofeed.Item, feed *gofeed.Feed, defaultCreatedAt time.Time, originalUrl string) nostr.Event {
content := ""
if item.Title != "" {
content = "**" + item.Title + "**\n\n"
}
description := strip.StripTags(item.Description)
// Handle stacker.news comments
if strings.Contains(feed.Link, "stacker.news") {
description += fmt.Sprintf(": %s", item.GUID)
}
if !strings.EqualFold(item.Title, description) {
content += description
}
shouldUpgradeLinkSchema := false
// Handle Nitter special cases (duplicates and http schema)
if strings.Contains(feed.Description, "Twitter feed") {
content = ""
shouldUpgradeLinkSchema = true
if strings.HasPrefix(originalUrl, "https://") {
description = strings.ReplaceAll(description, "http://", "https://")
}
if strings.Contains(item.Title, "RT by @") {
if len(item.DublinCoreExt.Creator) > 0 {
content = "**" + "RT " + item.DublinCoreExt.Creator[0] + ":**\n\n"
}
} else if strings.Contains(item.Title, "R to @") {
fields := strings.Fields(item.Title)
if len(fields) >= 2 {
replyingToHandle := fields[2]
content = "**" + "Response to " + replyingToHandle + "**\n\n"
}
}
content += description
}
content = html.UnescapeString(content)
if len(content) > 250 {
content = content[0:249] + "…"
}
if shouldUpgradeLinkSchema {
item.Link = strings.ReplaceAll(item.Link, "http://", "https://")
}
content += "\n\n" + item.Link
createdAt := defaultCreatedAt
if item.UpdatedParsed != nil {
createdAt = *item.UpdatedParsed
}
if item.PublishedParsed != nil {
createdAt = *item.PublishedParsed
}
evt := nostr.Event{
PubKey: pubkey,
CreatedAt: createdAt,
Kind: nostr.KindTextNote,
Tags: nostr.Tags{},
Content: strings.ToValidUTF8(content, ""),
}
evt.ID = string(evt.Serialize())
return evt
}
func PrivateKeyFromFeed(url string, secret string) string {
m := hmac.New(sha256.New, []byte(secret))
m.Write([]byte(url))
r := m.Sum(nil)
return hex.EncodeToString(r)
}
func DeleteInvalidFeed(url string, db *sql.DB) {
if _, err := db.Exec(`DELETE FROM feeds WHERE url=?`, url); err != nil {
log.Printf("failure to delete invalid feed: " + err.Error())
} else {
log.Printf("deleted invalid feed with url %q", url)
}
}