Module: RubyTube::Request
- Defined in:
- lib/rubytube/request.rb
Constant Summary collapse
- DEFAULT_RANGE_SIZE =
9437184
Class Method Summary collapse
- .get(url, options = {}) ⇒ Object
- .head(url, options = {}) ⇒ Object
- .post(url, options = {}) ⇒ Object
- .send(method, url, options = {}) ⇒ Object
- .stream(url, timeout: 60, max_retries: 0) ⇒ Object
Class Method Details
.get(url, options = {}) ⇒ Object
7 8 9 |
# File 'lib/rubytube/request.rb', line 7 def get(url, = {}) send(:get, url, ).body end |
.head(url, options = {}) ⇒ Object
15 16 17 |
# File 'lib/rubytube/request.rb', line 15 def head(url, = {}) send(:head, url, ).headers end |
.post(url, options = {}) ⇒ Object
11 12 13 |
# File 'lib/rubytube/request.rb', line 11 def post(url, = {}) send(:post, url, ).body end |
.send(method, url, options = {}) ⇒ Object
58 59 60 61 62 63 64 65 66 67 68 69 70 71 |
# File 'lib/rubytube/request.rb', line 58 def send(method, url, = {}) headers = {"Content-Type": "text/html"} [:headers] && headers.merge!([:headers]) connection = Faraday.new(url: url) do |faraday| faraday.response :follow_redirects faraday.adapter Faraday.default_adapter end connection.send(method) do |req| req.headers = headers [:query] && req.params = [:query] [:data] && req.body = JSON.dump([:data]) end end |
.stream(url, timeout: 60, max_retries: 0) ⇒ Object
19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 |
# File 'lib/rubytube/request.rb', line 19 def stream(url, timeout: 60, max_retries: 0) file_size = DEFAULT_RANGE_SIZE downloaded = 0 while downloaded < file_size stop_pos = [downloaded + DEFAULT_RANGE_SIZE, file_size].min - 1 range_header = "bytes=#{downloaded}-#{stop_pos}" tries = 0 while true begin if tries >= 1 + max_retries raise MaxRetriesExceeded end response = send(:get, "#{url}&range=#{downloaded}-#{stop_pos}") break rescue Faraday::TimeoutError rescue Faraday::ClientError => e raise e end tries += 1 end if file_size == DEFAULT_RANGE_SIZE begin resp = send(:get, "#{url}&range=0-99999999999") content_range = resp.headers["Content-Length"] file_size = content_range.to_i rescue KeyError, IndexError, StandardError => e end end response.body.each_char do |chunk| downloaded += chunk.length yield chunk end end end |