Move functions into helpers.cr

This commit is contained in:
Omar Roth 2018-01-27 20:09:27 -06:00
parent cf49306ffb
commit 236fdb85ff
2 changed files with 143 additions and 126 deletions

View File

@ -1,7 +1,57 @@
class Video
module HTTPParamConverter
def self.from_rs(rs)
HTTP::Params.parse(rs.read(String))
end
end
module XMLConverter
def self.from_rs(rs)
XML.parse_html(rs.read(String))
end
end
def initialize(id, info, html, updated, title, views, likes, dislikes, wilson_score)
@id = id
@info = info
@html = html
@updated = updated
@title = title
@views = views
@likes = likes
@dislikes = dislikes
@wilson_score = wilson_score
end
def to_a
return [@id, @info, @html, @updated, @title, @views, @likes, @dislikes, @wilson_score]
end
DB.mapping({
id: String,
info: {
type: HTTP::Params,
default: HTTP::Params.parse(""),
converter: Video::HTTPParamConverter,
},
html: {
type: XML::Node,
default: XML.parse_html(""),
converter: Video::XMLConverter,
},
updated: Time,
title: String,
views: Int64,
likes: Int32,
dislikes: Int32,
wilson_score: Float64,
})
end
# See http://www.evanmiller.org/how-not-to-sort-by-average-rating.html # See http://www.evanmiller.org/how-not-to-sort-by-average-rating.html
def ci_lower_bound(pos, n) def ci_lower_bound(pos, n)
if n == 0 if n == 0
return 0 return 0.0
end end
# z value here represents a confidence level of 0.95 # z value here represents a confidence level of 0.95
@ -18,57 +68,67 @@ def elapsed_text(elapsed)
"#{(millis * 1000).round(2)}µs" "#{(millis * 1000).round(2)}µs"
end end
def get_client def get_client(pool)
while POOL.empty? while pool.empty?
sleep rand(0..10).milliseconds sleep rand(0..10).milliseconds
end end
return POOL.shift return pool.shift
end end
def fetch_video(id) def fetch_video(id, client)
# Grab connection from pool begin
client = get_client
info = client.get("/get_video_info?video_id=#{id}&el=detailpage&ps=default&eurl=&gl=US&hl=en").body info = client.get("/get_video_info?video_id=#{id}&el=detailpage&ps=default&eurl=&gl=US&hl=en").body
info = HTTP::Params.parse(info)
html = client.get("/watch?v=#{id}").body html = client.get("/watch?v=#{id}").body
end
html = XML.parse_html(html) html = XML.parse_html(html)
info = HTTP::Params.parse(info)
if info["reason"]? if info["reason"]?
raise info["reason"] raise info["reason"]
end end
# Return connection to pool title = info["title"]
POOL << client
video = Video.new(id, info, html, Time.now) views = info["view_count"].to_i64
likes = html.xpath_node(%q(//button[@title="I like this"]/span))
likes = likes ? likes.content.delete(",").to_i : 1
dislikes = html.xpath_node(%q(//button[@title="I dislike this"]/span))
dislikes = dislikes ? dislikes.content.delete(",").to_i : 0
wilson_score = ci_lower_bound(likes, likes + dislikes)
video = Video.new(id, info, html, Time.now, title, views, likes, dislikes, wilson_score)
return video return video
end end
def get_video(id, refresh = true) def get_video(id, client, db, refresh = true)
if PG_DB.query_one?("SELECT EXISTS (SELECT true FROM videos WHERE id = $1)", id, as: Bool) if db.query_one?("SELECT EXISTS (SELECT true FROM videos WHERE id = $1)", id, as: Bool)
video = PG_DB.query_one("SELECT * FROM videos WHERE id = $1", id, as: Video) video = db.query_one("SELECT * FROM videos WHERE id = $1", id, as: Video)
# If record was last updated more than 5 hours ago, refresh (expire param in response lasts for 6 hours) # If record was last updated over an hour ago, refresh (expire param in response lasts for 6 hours)
if refresh && Time.now - video.updated > Time::Span.new(0, 5, 0, 0) if refresh && Time.now - video.updated > 1.hours
video = fetch_video(id) video = fetch_video(id, client)
PG_DB.exec("UPDATE videos SET info = $2, html = $3, updated = $4 WHERE id = $1", video.to_a) db.exec("UPDATE videos SET info = $2, html = $3, updated = $4,\
title = $5, views = $6, likes = $7, dislikes = $8, wilson_score = $9 WHERE id = $1", video.to_a)
end end
else else
video = fetch_video(id) video = fetch_video(id, client)
PG_DB.exec("INSERT INTO videos VALUES ($1, $2, $3, $4)", video.to_a) db.exec("INSERT INTO videos VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9)", video.to_a)
end end
return video return video
end end
def search(query) def search(query, client)
client = get_client begin
html = client.get("https://www.youtube.com/results?q=#{query}&sp=EgIQAVAU").body html = client.get("https://www.youtube.com/results?q=#{query}&sp=EgIQAVAU").body
end
html = XML.parse_html(html) html = XML.parse_html(html)
html.xpath_nodes(%q(//ol[@class="item-section"]/li)).each do |item| html.xpath_nodes(%q(//ol[@class="item-section"]/li)).each do |item|
@ -80,6 +140,4 @@ def search(query)
end end
end end
end end
POOL << client
end end

View File

@ -1,8 +1,5 @@
require "http/client"
require "json"
require "kemal" require "kemal"
require "pg" require "pg"
require "time"
require "xml" require "xml"
require "./helpers" require "./helpers"
@ -17,44 +14,51 @@ CONTEXT.add_options(
) )
POOL = Deque.new(30) do POOL = Deque.new(30) do
client = HTTP::Client.new(URL, CONTEXT) client = HTTP::Client.new(URL, CONTEXT)
client.connect_timeout = Time::Span.new(0, 0, 0, 5) client.read_timeout = 5.seconds
client.connect_timeout = 5.seconds
client client
end end
# Refresh connections by crawling YT # Refresh pool by crawling YT
10.times do
spawn do spawn do
# Start video io = STDOUT
ids = Deque.new(10, "_wbqqI0IgY8") ids = Deque(String).new
random = Random.new random = Random.new
client = get_client(POOL)
search(random.base64(3)) do |id| search(random.base64(3), client) do |id|
ids << id ids << id
end end
loop do loop do
if ids.size < 5 if ids.empty?
search(random.base64) do |id| search(random.base64(3), client) do |id|
ids << id ids << id
puts "refreshed ids"
end end
end end
if rand(600) < 1 if rand(300) < 1
client = get_client
client = HTTP::Client.new(URL, CONTEXT) client = HTTP::Client.new(URL, CONTEXT)
client.connect_timeout = Time::Span.new(0, 0, 0, 5) client.read_timeout = 5.seconds
client.connect_timeout = 5.seconds
POOL << client POOL << client
end end
time = Time.now time = Time.now
begin begin
id = ids[rand(ids.size)] id = ids[0]
video = get_video(id, false) video = get_video(id, client, PG_DB, false)
ids.delete(id)
rescue ex rescue ex
puts ex io << id << " : " << ex << "\n"
client = HTTP::Client.new(URL, CONTEXT)
client.read_timeout = 5.seconds
client.connect_timeout = 5.seconds
POOL << client
next next
ensure
ids.delete(id)
end end
rvs = [] of Hash(String, String) rvs = [] of Hash(String, String)
@ -65,17 +69,17 @@ spawn do
end end
rvs.each do |rv| rvs.each do |rv|
if rv.has_key?("id") if rv.has_key?("id") && !PG_DB.query_one?("SELECT EXISTS (SELECT true FROM videos WHERE id = $1)", rv["id"], as: Bool)
if !PG_DB.query_one?("SELECT EXISTS (SELECT true FROM videos WHERE id = $1)", rv["id"], as: Bool) ids.delete(id)
ids << rv["id"] ids << rv["id"]
if ids.size == 50 if ids.size == 150
ids.shift ids.shift
end end
end end
end end
end
puts "#{Time.now} 200 GET www.youtube.com/watch?v=#{video.id} #{elapsed_text(Time.now - time)}" io << Time.now << " 200 GET www.youtube.com/watch?v=" << video.id << " " << elapsed_text(Time.now - time) << "\n"
end
end end
end end
@ -83,46 +87,6 @@ macro templated(filename)
render "src/views/#{{{filename}}}.ecr", "src/views/layout.ecr" render "src/views/#{{{filename}}}.ecr", "src/views/layout.ecr"
end end
class Video
module HTTPParamConverter
def self.from_rs(rs)
HTTP::Params.parse(rs.read(String))
end
end
module XMLConverter
def self.from_rs(rs)
XML.parse_html(rs.read(String))
end
end
def initialize(id, info, html, updated)
@id = id
@info = info
@html = html
@updated = updated
end
def to_a
return [@id, @info, @html, @updated]
end
DB.mapping({
id: String,
info: {
type: HTTP::Params,
default: HTTP::Params.parse(""),
converter: Video::HTTPParamConverter,
},
html: {
type: XML::Node,
default: XML.parse_html(""),
converter: Video::XMLConverter,
},
updated: Time,
})
end
get "/" do |env| get "/" do |env|
templated "index" templated "index"
end end
@ -133,8 +97,9 @@ get "/watch" do |env|
env.params.query.delete_all("listen") env.params.query.delete_all("listen")
client = get_client(POOL)
begin begin
video = get_video(id) video = get_video(id, client, PG_DB)
rescue ex rescue ex
error_message = ex.message error_message = ex.message
next templated "error" next templated "error"
@ -153,6 +118,7 @@ get "/watch" do |env|
adaptive_fmts << HTTP::Params.parse(string) adaptive_fmts << HTTP::Params.parse(string)
end end
end end
rvs = [] of Hash(String, String) rvs = [] of Hash(String, String)
if video.info.has_key?("rvs") if video.info.has_key?("rvs")
video.info["rvs"].split(",").each do |rv| video.info["rvs"].split(",").each do |rv|
@ -162,20 +128,13 @@ get "/watch" do |env|
player_response = JSON.parse(video.info["player_response"]) player_response = JSON.parse(video.info["player_response"])
likes = video.html.xpath_node(%q(//button[@title="I like this"]/span))
likes = likes ? likes.content.delete(",").to_i : 1
dislikes = video.html.xpath_node(%q(//button[@title="I dislike this"]/span))
dislikes = dislikes ? dislikes.content.delete(",").to_i : 1
description = video.html.xpath_node(%q(//p[@id="eow-description"])) description = video.html.xpath_node(%q(//p[@id="eow-description"]))
description = description ? description.to_xml : "Could not load description" description = description ? description.to_xml : "Could not load description"
views = video.info["view_count"].to_i64
rating = video.info["avg_rating"].to_f64 rating = video.info["avg_rating"].to_f64
engagement = ((dislikes.to_f + likes.to_f)/views * 100) engagement = ((video.dislikes.to_f + video.likes.to_f)/video.views * 100)
calculated_rating = (likes.to_f/(likes.to_f + dislikes.to_f) * 4 + 1) calculated_rating = (video.likes.to_f/(video.likes.to_f + video.dislikes.to_f) * 4 + 1)
templated "watch" templated "watch"
end end
@ -184,7 +143,7 @@ get "/search" do |env|
query = env.params.query["q"] query = env.params.query["q"]
page = env.params.query["page"]? && env.params.query["page"].to_i? ? env.params.query["page"].to_i : 1 page = env.params.query["page"]? && env.params.query["page"].to_i? ? env.params.query["page"].to_i : 1
client = get_client client = get_client(POOL)
html = client.get("https://www.youtube.com/results?q=#{URI.escape(query)}&page=#{page}&sp=EgIQAVAU").body html = client.get("https://www.youtube.com/results?q=#{URI.escape(query)}&page=#{page}&sp=EgIQAVAU").body
html = XML.parse_html(html) html = XML.parse_html(html)