Class: WhatCD::Client
- Inherits:
-
Object
- Object
- WhatCD::Client
- Defined in:
- lib/whatcd.rb
Instance Attribute Summary collapse
-
#connection ⇒ Object
readonly
Returns the value of attribute connection.
Instance Method Summary collapse
- #authenticate(username, password) ⇒ Object
- #authenticated? ⇒ Boolean
-
#fetch(resource, parameters = {}) ⇒ Object
Public: Fetches a resource.
-
#initialize(username = nil, password = nil) ⇒ Client
constructor
A new instance of Client.
- #set_cookie(cookie) ⇒ Object
Constructor Details
#initialize(username = nil, password = nil) ⇒ Client
23 24 25 26 27 28 29 30 31 32 33 |
# File 'lib/whatcd.rb', line 23 def initialize(username = nil, password = nil) @connection = Faraday.new(:url => "https://what.cd") do |builder| builder.request :url_encoded builder.use :cookie_jar builder.adapter Faraday.default_adapter end unless username.nil? || password.nil? authenticate username, password end end |
Instance Attribute Details
#connection ⇒ Object (readonly)
Returns the value of attribute connection.
21 22 23 |
# File 'lib/whatcd.rb', line 21 def connection @connection end |
Instance Method Details
#authenticate(username, password) ⇒ Object
35 36 37 38 39 40 41 42 43 44 |
# File 'lib/whatcd.rb', line 35 def authenticate(username, password) body = { :username => username, :password => password, :keeplogged => 1 } res = connection.post "/login.php", body unless res["set-cookie"] && res["location"] == "index.php" raise AuthError end @authenticated = true end |
#authenticated? ⇒ Boolean
51 52 53 |
# File 'lib/whatcd.rb', line 51 def authenticated? @authenticated end |
#fetch(resource, parameters = {}) ⇒ Object
Public: Fetches a resource. For all possible resources and parameters see github.com/WhatCD/Gazelle/wiki/JSON-API-Documentation.
resource - A resource name Symbol (ajax.php?action=<this part>). parameters - A Hash.
Returns a Hash. Raises AuthError when not authenticated yet. Raises AuthError when redirected to /login.php. Raises APIError when a HTTP error occurs. Raises APIError when the response body is ‘“failure”`.
66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 |
# File 'lib/whatcd.rb', line 66 def fetch(resource, parameters = {}) unless authenticated? raise AuthError end res = connection.get "ajax.php", parameters.merge(:action => resource) if res.status == "302" && res["location"] == "login.php" raise AuthError elsif !res.success? raise APIError, res.status end parsed_res = JSON.parse res.body if parsed_res["status"] == "failure" raise APIError end parsed_res["response"] end |
#set_cookie(cookie) ⇒ Object
46 47 48 49 |
# File 'lib/whatcd.rb', line 46 def () connection.headers["Cookie"] = @authenticated = true end |