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.



76
77
78
79
# File 'lib/bbiff/bbs_reader.rb', line 76

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

Instance Attribute Details

#encodingObject (readonly)

Returns the value of attribute encoding.



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

def encoding
  @encoding
end

Instance Method Details

#download_binary(uri) ⇒ Object

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



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
113
114
115
# File 'lib/bbiff/bbs_reader.rb', line 82

def download_binary(uri)
  resource = @resource_cache[uri]
  if resource && resource.data.size > 0

    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')
      p response.code if $DEBUG
      p 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



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

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')
    p response.code if $DEBUG
    p 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



134
135
136
137
# File 'lib/bbiff/bbs_reader.rb', line 134

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