Class: Rapidshare::API

Inherits:
Object
  • Object
show all
Defined in:
lib/rapidshare/api.rb

Overview

Provides interface to RapidShare API.

HTTPS requests are used by default, as recommended by RapidShare API documentation. If you want to use HTTP, you have to write complete URI in the API request, for example:

Rapidshare::API.get('https://api.rapidshare.com/cgi-bin/rsapi.cgi?sub=...')

Defined Under Namespace

Classes: Error

Constant Summary

ERROR_PREFIX =
"ERROR: "
URL =

Request method uses this string to construct GET requests

'https://api.rapidshare.com/cgi-bin/rsapi.cgi?sub=%s&%s'

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(params) ⇒ API

Connects to Rapidshare API (which basically means: uses login and password to retrieve cookie for future service calls)

Params:

  • login - premium account login

  • password - premium account password

  • cookie - cookie can be provided instead of login and password



36
37
38
39
40
41
42
43
44
45
# File 'lib/rapidshare/api.rb', line 36

def initialize(params)
  if params[:cookie]
    @cookie = params[:cookie]
    # throws LoginFailed exception if cookie is invalid
    ()
  else
    response = (params.merge(:withcookie => 1))
    @cookie = response[:cookie]
  end
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(service_name, params = {}) ⇒ Object

Attempts to do Rapidshare service call. If it doesn't recognize the method name, this gem assumes that user wants to make a Rapidshare service call.

This method also handles aliases for service calls: get_account_details -> getaccountdetails



124
125
126
127
128
129
130
131
132
133
# File 'lib/rapidshare/api.rb', line 124

def method_missing(service_name, params = {})
  # remove user-friendly underscores from service namess
  service_name = service_name.to_s.gsub('_', '')
  
  if respond_to?(service_name)
    send(service_name, params)
  else
    request(service_name, params)
  end
end

Instance Attribute Details

Returns the value of attribute cookie



15
16
17
# File 'lib/rapidshare/api.rb', line 15

def cookie
  @cookie
end

Class Method Details

.debug(debug) ⇒ Object



47
48
49
# File 'lib/rapidshare/api.rb', line 47

def self.debug(debug)
  debug_output debug ? $stderr : false
end

.decode_file_status(status_code) ⇒ Object

Convert file status code (returned by checkfiles method) to :ok or :error symbol.



206
207
208
209
210
211
212
213
214
215
216
217
# File 'lib/rapidshare/api.rb', line 206

def self.decode_file_status(status_code)
  # TODO in checkfiles, return both file_status as is and decoded file status
  # or just boolean value if file is OK and can be downloaded
  
  case status_code
    when 0 then :error # File not found
    when 1 then :ok # File OK
    when 3 then :error # Server down
    when 4 then :error # File marked as illegal
    else :error # uknown status, this shouldn't happen
  end
end

.get(url) ⇒ Object

Provides interface for GET requests



197
198
199
200
201
202
# File 'lib/rapidshare/api.rb', line 197

def self.get(url)
  url = URI.parse(url)
  http = Net::HTTP.new(url.host, url.port)
  http.use_ssl = (url.scheme == 'https')
  http.get URI::escape(url.request_uri)
end

.parse_response(parser, response) ⇒ Object

Parses response from request method (parser options are listed there)



104
105
106
107
108
109
110
111
112
113
114
115
116
# File 'lib/rapidshare/api.rb', line 104

def self.parse_response(parser, response)    
  case parser.to_sym
    when :none
      response
    when :csv
      # PS: we could use gem for csv parsing, but that's an overkill in this
      # case, IMHO
      response.to_s.strip.split(/\s*\n\s*/).map { |line| line.split(',') }
    when :hash
      self.text_to_hash(response)
  end

end

.request(service_name, params = {}) ⇒ Object

Calls specific RapidShare API service and returns result.

Throws exception if error is received from RapidShare API.

Params:

  • service_name - name of the RapidShare service, for example checkfiles

  • params - hash of service parameters and options (listed below)

  • parser - option, determines how the response body will be parsed:

    • none - default value, returns response body as it is

    • csv - comma-separated values, for example: getrapidtranslogs. Returns array or arrays, one array per each line.

    • hash - lines with key and value separated by ???=???, for example: getaccountdetails. Returns hash.



72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
# File 'lib/rapidshare/api.rb', line 72

def self.request(service_name, params = {})
  params.symbolize_keys!
  
  parser = (params.delete(:parser) || :none).to_sym
  unless [:none, :csv, :hash].include?(parser)
    raise Rapidshare::API::Error.new("Invalid parser for request method: #{parser}")
  end
  
  response = self.get(URL % [service_name, params.to_query]).body
  
  if response.start_with?(ERROR_PREFIX)
    case error = response.sub(ERROR_PREFIX, "").split('.').first
      when "Login failed"
        raise Rapidshare::API::Error::LoginFailed
      when "Invalid routine called"
        raise Rapidshare::API::Error::InvalidRoutineCalled.new(service_name)
      else
        raise Rapidshare::API::Error.new(error)
      end
  end
  
  self.parse_response(parser, response)
end

.text_to_hash(response) ⇒ Object

Converts rapidshare response (which is just a text in specific format) to hash.

Example:

"key1=value1\nkey1=value2" -> { :key1 => 'value1', :key2 => 'value2' }


233
234
235
# File 'lib/rapidshare/api.rb', line 233

def self.text_to_hash(response)
  Hash[ response.strip.split(/\s*\n\s*/).map { |param| param.split('=') } ].symbolize_keys
end

Instance Method Details

#checkfiles(*urls) ⇒ Object

Retrieves information about RapidShare files.

Input: array of files

Examples: checkfiles(file1), checkfiles(file1,file2) or +checkfiles()+

Output: array of hashes, which contain information about files

  • :file_id (string) - part of url

    Example: -> 829628035

  • :file_name (string) - part of url

    Example: -> HornyRhinos.jpg

  • :file_size (integer) - in bytes. returns 0 if files does not exists

  • :file_status - decoded file status: :ok or :error

  • :short_host - used to construct download url

  • :server_id - used to construct download url

  • :md5



160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
# File 'lib/rapidshare/api.rb', line 160

def checkfiles(*urls)
  raise Rapidshare::API::Error if urls.empty?
  
  files, filenames = urls.flatten.map { |url| fileid_and_filename(url) }.transpose
  
  response = request(:checkfiles, :files => files.join(","), :filenames => filenames.join(","))
  
  response.strip.split(/\s*\n\s*/).map do |r|
    data = r.split(",")
    {
      :file_id => data[0],
      :file_name => data[1],
      :file_size => data[2],
      :server_id => data[3],
      :file_status => self.class.decode_file_status(data[4].to_i),
      :short_host => data[5],
      :md5 => data[6]
    }
  end
end

#download(file, options = {}) ⇒ Object

Downloads file.

Options:

  • filename (optional) - specifies filename under which the file will be saved. Default: filename parsed from Rapidshare link.

  • downloads_dir (optional) - specifies directory into which downloaded files will be saved. Default: current directory.



189
190
191
# File 'lib/rapidshare/api.rb', line 189

def download(file, options= {})
  Rapidshare::Download.new(file, self, options).perform
end

#fileid_and_filename(url) ⇒ Object

Extracts file id and file name from Rapidshare url. Returns both in array.

Example:

https://rapidshare.com/files/829628035/HornyRhinos.jpg -> [ '829628035', 'HornyRhinos.jpg' ]


224
225
226
# File 'lib/rapidshare/api.rb', line 224

def fileid_and_filename(url)
  url.split('/').slice(-2,2) || ['', '']
end

#getaccountdetails(params = {}) ⇒ Object

Returns account details in hash.



137
138
139
# File 'lib/rapidshare/api.rb', line 137

def getaccountdetails(params = {})
  request :getaccountdetails, params.merge( :parser => :hash)
end

#request(service_name, params = {}) ⇒ Object

Provides instance interface to class method request.



98
99
100
# File 'lib/rapidshare/api.rb', line 98

def request(service_name, params = {})
  self.class.request(service_name, params.merge(:cookie => @cookie))
end