From 88da2f28cc99083340ad93e461d20a349d49b0a7 Mon Sep 17 00:00:00 2001 From: Kanezoh Date: Mon, 31 May 2021 14:46:09 +0900 Subject: [PATCH] select cookies depending on domain --- src/mechanize/http/agent.cr | 22 +++++++++++++++++----- 1 file changed, 17 insertions(+), 5 deletions(-) diff --git a/src/mechanize/http/agent.cr b/src/mechanize/http/agent.cr index fa04905..412a4e6 100644 --- a/src/mechanize/http/agent.cr +++ b/src/mechanize/http/agent.cr @@ -4,17 +4,18 @@ require "http/client" module MechanizeCr module HTTP class Agent - property :request_headers, :context + property :request_headers, :context, :cookies property history : Array(MechanizeCr::Page) def initialize(@context : Mechanize | Nil = nil, history = Array(MechanizeCr::Page).new) @history = history @request_headers = ::HTTP::Headers.new @context = context + @cookies = Hash(String, ::HTTP::Cookies).new end def fetch(uri, method = :get, headers = HTTP::Headers.new, params = Hash(String,String).new) uri = resolve(uri) - set_request_headers(headers) + set_request_headers(uri, headers) uri, params = resolve_parameters(uri, method, params) response = http_request(uri, method, params) body = response.not_nil!.body @@ -36,10 +37,16 @@ module MechanizeCr end end - private def set_request_headers(headers) + private def set_request_headers(uri, headers) headers.each do |k,v| request_headers[k] = v end + if cookies.fetch(uri.host.to_s, nil).nil? + return + else + valid_cookies = cookies[uri.host.to_s] + valid_cookies.not_nil!.add_request_headers(request_headers) + end end private def resolve_parameters(uri, method, params) @@ -66,10 +73,15 @@ module MechanizeCr # end #end header_cookies = response.try &.cookies - if header_cookies.try &.empty? + if (header_cookies.nil?) request_headers else - header_cookies.not_nil!.add_request_headers(request_headers) + if cookies.fetch(uri.host.to_s, ::HTTP::Cookies.new).empty? + cookies[uri.host.to_s] = ::HTTP::Cookies.new + end + header_cookies.each do |cookie| + cookies[uri.host.to_s] << cookie + end end end