From 236fdb85ff3695c57e041709f860ed9d69525322 Mon Sep 17 00:00:00 2001 From: Omar Roth Date: Sat, 27 Jan 2018 20:09:27 -0600 Subject: [PATCH] Move functions into helpers.cr --- src/helpers.cr | 114 +++++++++++++++++++++++++--------- src/invidious.cr | 155 +++++++++++++++++------------------------------ 2 files changed, 143 insertions(+), 126 deletions(-) diff --git a/src/helpers.cr b/src/helpers.cr index 1a6037a5..a9866cee 100644 --- a/src/helpers.cr +++ b/src/helpers.cr @@ -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 def ci_lower_bound(pos, n) if n == 0 - return 0 + return 0.0 end # z value here represents a confidence level of 0.95 @@ -18,57 +68,67 @@ def elapsed_text(elapsed) "#{(millis * 1000).round(2)}µs" end -def get_client - while POOL.empty? +def get_client(pool) + while pool.empty? sleep rand(0..10).milliseconds end - return POOL.shift + return pool.shift end -def fetch_video(id) - # Grab connection from pool - client = get_client +def fetch_video(id, client) + begin + info = client.get("/get_video_info?video_id=#{id}&el=detailpage&ps=default&eurl=&gl=US&hl=en").body + html = client.get("/watch?v=#{id}").body + end - 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 = XML.parse_html(html) + info = HTTP::Params.parse(info) if info["reason"]? raise info["reason"] end - # Return connection to pool - POOL << client + title = info["title"] - 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 end -def get_video(id, refresh = true) - if PG_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) +def get_video(id, client, db, refresh = true) + if db.query_one?("SELECT EXISTS (SELECT true FROM videos WHERE id = $1)", id, as: Bool) + 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 refresh && Time.now - video.updated > Time::Span.new(0, 5, 0, 0) - video = fetch_video(id) - PG_DB.exec("UPDATE videos SET info = $2, html = $3, updated = $4 WHERE id = $1", video.to_a) + # If record was last updated over an hour ago, refresh (expire param in response lasts for 6 hours) + if refresh && Time.now - video.updated > 1.hours + video = fetch_video(id, client) + 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 else - video = fetch_video(id) - PG_DB.exec("INSERT INTO videos VALUES ($1, $2, $3, $4)", video.to_a) + video = fetch_video(id, client) + db.exec("INSERT INTO videos VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9)", video.to_a) end return video end -def search(query) - client = get_client +def search(query, client) + begin + html = client.get("https://www.youtube.com/results?q=#{query}&sp=EgIQAVAU").body + end - html = client.get("https://www.youtube.com/results?q=#{query}&sp=EgIQAVAU").body html = XML.parse_html(html) html.xpath_nodes(%q(//ol[@class="item-section"]/li)).each do |item| @@ -80,6 +140,4 @@ def search(query) end end end - - POOL << client end diff --git a/src/invidious.cr b/src/invidious.cr index 9c143dc5..c09ee7e0 100644 --- a/src/invidious.cr +++ b/src/invidious.cr @@ -1,8 +1,5 @@ -require "http/client" -require "json" require "kemal" require "pg" -require "time" require "xml" require "./helpers" @@ -17,65 +14,72 @@ CONTEXT.add_options( ) POOL = Deque.new(30) do 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 end -# Refresh connections by crawling YT -spawn do - # Start video - ids = Deque.new(10, "_wbqqI0IgY8") - random = Random.new +# Refresh pool by crawling YT +10.times do + spawn do + io = STDOUT + ids = Deque(String).new + random = Random.new + client = get_client(POOL) - search(random.base64(3)) do |id| - ids << id - end + search(random.base64(3), client) do |id| + ids << id + end - loop do - if ids.size < 5 - search(random.base64) do |id| - ids << id - puts "refreshed ids" + loop do + if ids.empty? + search(random.base64(3), client) do |id| + ids << id + end end - end - if rand(600) < 1 - client = get_client - client = HTTP::Client.new(URL, CONTEXT) - client.connect_timeout = Time::Span.new(0, 0, 0, 5) - POOL << client - end - - time = Time.now - - begin - id = ids[rand(ids.size)] - video = get_video(id, false) - ids.delete(id) - rescue ex - puts ex - next - end - - rvs = [] of Hash(String, String) - if video.info.has_key?("rvs") - video.info["rvs"].split(",").each do |rv| - rvs << HTTP::Params.parse(rv).to_h + if rand(300) < 1 + client = HTTP::Client.new(URL, CONTEXT) + client.read_timeout = 5.seconds + client.connect_timeout = 5.seconds + POOL << client end - end - rvs.each do |rv| - if rv.has_key?("id") - if !PG_DB.query_one?("SELECT EXISTS (SELECT true FROM videos WHERE id = $1)", rv["id"], as: Bool) + time = Time.now + + begin + id = ids[0] + video = get_video(id, client, PG_DB, false) + rescue ex + io << id << " : " << ex << "\n" + client = HTTP::Client.new(URL, CONTEXT) + client.read_timeout = 5.seconds + client.connect_timeout = 5.seconds + POOL << client + next + ensure + ids.delete(id) + end + + rvs = [] of Hash(String, String) + if video.info.has_key?("rvs") + video.info["rvs"].split(",").each do |rv| + rvs << HTTP::Params.parse(rv).to_h + end + end + + rvs.each do |rv| + if rv.has_key?("id") && !PG_DB.query_one?("SELECT EXISTS (SELECT true FROM videos WHERE id = $1)", rv["id"], as: Bool) + ids.delete(id) ids << rv["id"] - if ids.size == 50 + if ids.size == 150 ids.shift 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 @@ -83,46 +87,6 @@ macro templated(filename) render "src/views/#{{{filename}}}.ecr", "src/views/layout.ecr" 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| templated "index" end @@ -133,8 +97,9 @@ get "/watch" do |env| env.params.query.delete_all("listen") + client = get_client(POOL) begin - video = get_video(id) + video = get_video(id, client, PG_DB) rescue ex error_message = ex.message next templated "error" @@ -153,6 +118,7 @@ get "/watch" do |env| adaptive_fmts << HTTP::Params.parse(string) end end + rvs = [] of Hash(String, String) if video.info.has_key?("rvs") video.info["rvs"].split(",").each do |rv| @@ -162,20 +128,13 @@ get "/watch" do |env| 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 = description ? description.to_xml : "Could not load description" - views = video.info["view_count"].to_i64 rating = video.info["avg_rating"].to_f64 - engagement = ((dislikes.to_f + likes.to_f)/views * 100) - calculated_rating = (likes.to_f/(likes.to_f + dislikes.to_f) * 4 + 1) + engagement = ((video.dislikes.to_f + video.likes.to_f)/video.views * 100) + calculated_rating = (video.likes.to_f/(video.likes.to_f + video.dislikes.to_f) * 4 + 1) templated "watch" end @@ -184,7 +143,7 @@ get "/search" do |env| query = env.params.query["q"] 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 = XML.parse_html(html)