Class: Bbs::Downloader

Inherits:
Object
  • Object
show all
Defined in:
lib/bbiff/bbs_reader.rb

Defined Under Namespace

Classes: DownloadFailure, Resource

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(encoding = 'UTF-8') ⇒ Downloader

Returns a new instance of Downloader.



74
75
76
77
# File 'lib/bbiff/bbs_reader.rb', line 74

def initialize(encoding = 'UTF-8')
  @encoding = encoding
  @resource_cache = {}
end

Instance Attribute Details

#encodingObject (readonly)

Returns the value of attribute encoding.



72
73
74
# File 'lib/bbiff/bbs_reader.rb', line 72

def encoding
  @encoding
end

Instance Method Details

#download_binary(uri) ⇒ Object

ASCII-8BIT エンコーディングの文字列を返す。



80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
# File 'lib/bbiff/bbs_reader.rb', line 80

def download_binary(uri)
  resource = @resource_cache[uri]
  if resource
    Net::HTTP.start(uri.host, uri.port) do |http|
      request = Net::HTTP::Get.new(uri)
      request['range'] = "bytes=#{resource.data.bytesize}-"
      response = http.request(request)
      response.body.force_encoding('ASCII-8BIT')
      pp response.code if $DEBUG
      pp response.to_hash if $DEBUG
      case response
      when Net::HTTPPartialContent
        p :partial if $DEBUG
        resource.data += response.body
      when Net::HTTPRequestedRangeNotSatisfiable
        p :not_satisfiable if $DEBUG
        # 多分DATは更新されていない
      when Net::HTTPOK
        p :ok if $DEBUG
        @resource_cache[uri] = Resource.new(response.body)
        return response.body
      else
        raise DownloadFailure.new(response)
      end
      return resource.data
    end
  else
    p :no_resource_yet if $DEBUG
    body = download_binary_nocache(uri)
    @resource_cache[uri] = Resource.new(body)
    return body
  end
end

#download_binary_nocache(uri) ⇒ Object



114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
# File 'lib/bbiff/bbs_reader.rb', line 114

def download_binary_nocache(uri)
  response = nil
  Net::HTTP.start(uri.host, uri.port) do |http|
    request = Net::HTTP::Get.new(uri)
    response = http.request(request)
    response.body.force_encoding('ASCII-8BIT')
    pp response.code if $DEBUG
    pp response.to_hash if $DEBUG
    case response
    when Net::HTTPOK
    else
      raise DownloadFailure.new(response)
    end
  end
  return response.body
end

#download_text(uri) ⇒ Object



131
132
133
134
# File 'lib/bbiff/bbs_reader.rb', line 131

def download_text(uri)
  # dup は重要。
  download_binary(uri).dup.force_encoding(encoding).encode('UTF-8')
end