Refactor some reddit polling code

This commit is contained in:
Danila Fedorin 2019-04-14 14:39:38 -07:00
parent 92cdd200ba
commit 3f1039e5dc
1 changed files with 49 additions and 17 deletions

View File

@ -1,27 +1,59 @@
require "http/client" require "http/client"
require "json" require "json"
def get_reddit_json(subreddit) class RedditWrapper(T)
request_url = "https://www.reddit.com/r/#{subreddit}/hot.json?limit=30" JSON.mapping(
kind: String,
data: T)
end
class RedditChild
JSON.mapping(
url: String,
name: String,
title: String)
end
class RedditResponse
JSON.mapping(
modhash: String,
dist: Int32,
children: Array(RedditWrapper(RedditChild)))
def self.from_subreddits(subreddits : Array(String))
request_url = "https://www.reddit.com/r/#{subreddits.join "+" }/hot.json?limit=30"
response = HTTP::Client.get(request_url, headers: HTTP::Headers { response = HTTP::Client.get(request_url, headers: HTTP::Headers {
"User-agent" => "Joann-Pupper-Bot" "User-agent" => "Joann-Pupper-Bot"
}) })
response.body?.try { |body| JSON.parse(body) }
return nil unless body = response.body?
begin
RedditWrapper(RedditResponse).from_json body
rescue
nil
end
end end
def filter_reddit_json(json, completed) def self.from_subreddit(subreddit)
json["data"]["children"] from_subreddits [subreddit]
.as_a end
.map(&.["data"])
.select do |it| def posts_matching(&block)
url = it["url"].as_s children
name = it["name"].as_s .map(&.data)
!completed.includes?(name) && (url.ends_with?(".png") || url.ends_with?(".jpg")) .select { |it| yield it }
end
end
def filter_reddit_json(json, completed, extensions = ["png", "json"])
json.data.posts_matching do |post|
extensions.any? { |it| post.url.ends_with? it } && !completed.includes? post.url
end end
end end
def get_reddit_post(subreddit, completed) def get_reddit_post(subreddit, completed)
json = get_reddit_json(subreddit) json = RedditResponse.from_subreddit subreddit
post = json.try { |json| filter_reddit_json(json, completed).first? } post = json.try { |json| filter_reddit_json(json, completed).first? }
post.try { |post| completed.push(post["name"].as_s); { post["url"].as_s, post["title"].as_s } } post.try { |post| completed.push(post.name); { post.url, post.title } }
end end