Class: Rapidshare::API

Inherits:
Object
  • Object
show all
Extended by:
Utils
Includes:
Ext::API, Utils
Defined in:
lib/rapidshare-base/api.rb,
lib/rapidshare-ext.rb

Defined Under Namespace

Classes: Error

Constant Summary collapse

ERROR_PREFIX =
'ERROR: '
URL =

Request method uses this string to construct GET requests

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

Constants included from Ext::API

Ext::API::FILE_COLUMNS

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Methods included from Utils

decode_file_status, fileid_and_filename, get, post, text_to_hash

Methods included from Ext::API

#add_folder, #detect_gaps, #erase_all_data!, #file_id, #file_info, #folder_id, #folder_path, #folders_hierarchy, #folders_hierarchy!, #gap?, #move_file, #move_folder, #move_orphans, #orphan?, #remove_file, #remove_folder, #remove_orphans!, #rename_file, #root_folder?, #slice_tree, #upload

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

  • free_user (boolean) - if user identifies himself as free user by setting this to true, skip login

Instead of params hash, you can pass only cookie as a string

PS: free_user option is a beta feature, to be properly implemented



32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
# File 'lib/rapidshare-base/api.rb', line 32

def initialize(params)
  # if there's "just one param", it's a cookie
  params = { :cookie => params } if params.is_a? String

  # skip login for free users
  return nil if params[:free_user]

  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



134
135
136
137
138
139
140
141
142
143
# File 'lib/rapidshare-base/api.rb', line 134

def method_missing(service_name, params = {})
  # remove user-friendly underscores from service names
  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.



6
7
8
# File 'lib/rapidshare-base/api.rb', line 6

def cookie
  @cookie
end

Class Method Details

.parse_response(parser, response) ⇒ Object

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



115
116
117
118
119
120
121
122
123
124
125
126
# File 'lib/rapidshare-base/api.rb', line 115

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
      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.

  • server - option, determines which server will be used to send request

Raises:

  • (Exception)


71
72
73
74
75
76
77
78
79
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
# File 'lib/rapidshare-base/api.rb', line 71

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

  server = params.delete(:server)
  server_url = server ? "https://#{server}/cgi-bin/rsapi.cgi?sub=%s&%s" : URL

  http_method = (params.delete(:method) || :get).to_sym
  raise Exception, "invalid HTTP method #{http_method}" unless self.respond_to? http_method

  case http_method
    when :get
      response = self.send(http_method, server_url % [service_name, params.to_query])
    else
      params[:sub] = service_name
      response = self.send(http_method, server_url.gsub(/\?sub=%s&%s$/,''), params)
  end

  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

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



170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
# File 'lib/rapidshare-base/api.rb', line 170

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 => decode_file_status(data[4].to_i),
      :short_host => data[5],
      :md5 => data[6]
    }
  end
end

#download(file, params = {}, &block) ⇒ Object



191
192
193
194
195
196
197
198
199
# File 'lib/rapidshare-base/api.rb', line 191

def download(file, params= {}, &block)
  if file.match /\Ahttps?:\/\//
    url = file
  else
    url = file_info(file)[:url]
  end

  Rapidshare::Ext::Download.new(url, self, params).perform &block
end

#getaccountdetails(params = {}) ⇒ Object

Returns account details in hash.



147
148
149
# File 'lib/rapidshare-base/api.rb', line 147

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

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

Provides instance interface to class method request.



109
110
111
# File 'lib/rapidshare-base/api.rb', line 109

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