Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add basic connection cache #130

Open
wants to merge 2 commits into
base: dev
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 9 additions & 3 deletions src/mangadex/downloader.cr
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ require "compress/zip"
module MangaDex
class PageJob
property success = false
property url : String
property url : URI
property filename : String
property writer : Compress::Zip::Writer
property tries_remaning : Int32
Expand All @@ -17,6 +17,7 @@ module MangaDex
@wait_seconds : Int32 = Config.current.mangadex["download_wait_seconds"]
.to_i32
@retries : Int32 = Config.current.mangadex["download_retries"].to_i32
@client_cache = {} of String => HTTP::Client

use_default

Expand Down Expand Up @@ -77,7 +78,7 @@ module MangaDex
fn, url = tuple
ext = File.extname fn
fn = "#{i.to_s.rjust len, '0'}#{ext}"
page_job = PageJob.new url, fn, writer, @retries
page_job = PageJob.new URI.parse(url), fn, writer, @retries
Logger.debug "Downloading #{url}"
loop do
sleep @wait_seconds.seconds
Expand Down Expand Up @@ -149,8 +150,9 @@ module MangaDex
headers = HTTP::Headers{
"User-agent" => "Mangadex.cr",
}

begin
HTTP::Client.get job.url, headers do |res|
cached_client(job.url).get job.url.full_path, headers do |res|
unless res.success?
raise "Failed to download page #{job.url}. " \
"[#{res.status_code}] #{res.status_message}"
Expand All @@ -163,5 +165,9 @@ module MangaDex
job.success = false
end
end

private def cached_client(url : URI)
@client_cache[url.host.not_nil!]? || (@client_cache[url.host.not_nil!] = HTTP::Client.new(url))
end
end
end