lib/comic_walker/v1/client.rb in comic_walker-0.2.2 vs lib/comic_walker/v1/client.rb in comic_walker-0.3.0
- old
+ new
@@ -1,40 +1,34 @@
require 'addressable/uri'
require 'http-cookie'
require 'json'
-require 'net/http'
+require 'net/http/persistent'
+require 'retryable'
+require 'uri'
module ComicWalker
module V1
class Client
BASE_URI = Addressable::URI.parse("https://cnts.comic-walker.com")
def initialize(jar, uuid)
- @https = Net::HTTP.new(BASE_URI.host, 443)
- @https.use_ssl = true
- @https.verify_mode = OpenSSL::SSL::VERIFY_PEER
+ @https = Net::HTTP::Persistent.new('comic_walker')
@jar = jar
@uuid = uuid
end
- def start(&block)
- @https.start do
- block.call
- end
- end
-
AID = 'KDCWI_JP'
AVER = '1.2.0'
class UnknownDeviceError < StandardError
end
class NoValidSessionError < StandardError
end
def create_session
- retried = 0
- begin
+ on_exception = lambda { |exception| create_user }
+ retryable(tries: 2, on: UnknownDeviceError, sleep: 0, exception_cb: on_exception) do
res = post('/user_sessions/create', {
DID: @uuid,
PIN: @uuid,
AID: AID,
AVER: AVER,
@@ -45,18 +39,10 @@
when 'ValidSessionExistsError'
nil
else
JSON.parse(res.body)
end
- rescue UnknownDeviceError => e
- if retried == 0
- retried += 1
- create_user
- retry
- else
- raise e
- end
end
end
def create_user
post('/users/create', {
@@ -66,11 +52,10 @@
AVER: AVER,
})
end
def contents(params = {})
- retried = 0
params = {
AID: AID,
AVER: AVER,
W: '320',
H: '480',
@@ -78,26 +63,19 @@
include_hidden: 1,
include_meta: 1,
languages: 'ja',
}.merge(params)
- begin
+ on_exception = lambda { |exception| create_session }
+ retryable(tries: 2, on: NoValidSessionError, sleep: 0, exception_cb: on_exception) do
res = get('/v1/contents', params)
case res.body
when 'NoValidSessionError'
raise NoValidSessionError.new
else
JSON.parse(res.body)
end
- rescue NoValidSessionError => e
- if retried == 0
- retried += 1
- create_session
- retry
- else
- raise e
- end
end
end
private
@@ -115,10 +93,10 @@
request_with_cookie(uri, req)
end
def request_with_cookie(uri, req)
req['cookie'] = HTTP::Cookie.cookie_value(@jar.cookies(uri.to_s))
- @https.request(req).tap do |res|
+ @https.request(URI.parse(uri.to_s), req).tap do |res|
@jar.parse(res['set-cookie'], uri.to_s)
end
end
end
end