46 lines
1.3 KiB
Plaintext
46 lines
1.3 KiB
Plaintext
use okhttp, types
|
|
|
|
class Reddit {
|
|
def Reddit(cookie) {
|
|
this.cookie = cookie
|
|
}
|
|
|
|
def fetchSubreddit(subreddit, maxItems = 5) {
|
|
url = "https://www.reddit.com/r/" + subreddit + ".json"
|
|
response = okhttp.request()
|
|
.headers({
|
|
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:109.0) Gecko/20100101 Firefox/116.0",
|
|
"Cookie": this.cookie
|
|
})
|
|
.url(url)
|
|
.get()
|
|
.newCall(okhttp.client)
|
|
.execute()
|
|
.body()
|
|
.string()
|
|
if (!length(response)) return []
|
|
jsonData = jsondecode(response)
|
|
if (typeof(jsonData) != MAP || !arrayKeyExists("data", jsonData)) return []
|
|
data = jsonData.data ?? []
|
|
if (!length(data)) return []
|
|
return stream(data.children)
|
|
.map(def(child) = child.data)
|
|
.limit(min(maxItems, data.dist ?? 0))
|
|
.map(def(post) = {
|
|
"id": post.id,
|
|
"sub": subreddit,
|
|
"url": post.url,
|
|
"time": post.created_utc,
|
|
"title": post.title,
|
|
"permalink": post.permalink,
|
|
"flair_text": arrayKeyExists("link_flair_text", post) ? post.link_flair_text : ""
|
|
})
|
|
.toArray()
|
|
}
|
|
|
|
def fetchSubreddits(subreddits, maxItems = 5) =
|
|
stream(subreddits)
|
|
.flatMap(def(r) = try(def() = this.fetchSubreddit(r, maxItems), def(clazz, cause) = []))
|
|
.toArray()
|
|
}
|