forked from youpy/ruby-lastfm
/
lastfm.rb
121 lines (95 loc) · 2.54 KB
/
lastfm.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
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
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
require 'rubygems'
require 'digest/md5'
require 'httparty'
require 'active_support/core_ext/string/inflections'
require 'lastfm/util'
require 'lastfm/response'
require 'lastfm/method_category/base'
require 'lastfm/method_category/album'
require 'lastfm/method_category/artist'
require 'lastfm/method_category/auth'
require 'lastfm/method_category/event'
require 'lastfm/method_category/geo'
require 'lastfm/method_category/library'
require 'lastfm/method_category/tag'
require 'lastfm/method_category/tasteometer'
require 'lastfm/method_category/track'
require 'lastfm/method_category/user'
require 'lastfm/method_category/chart'
class Lastfm
API_ROOT = 'http://ws.audioscrobbler.com/2.0'
include HTTParty
base_uri API_ROOT
attr_accessor :session
class Error < StandardError; end
class ApiError < Error
attr_reader :code
def initialize(message, code = nil)
super(message)
@code = code
end
end
def initialize(api_key, api_secret)
@api_key = api_key
@api_secret = api_secret
end
def album
MethodCategory::Album.new(self)
end
def artist
MethodCategory::Artist.new(self)
end
def auth
MethodCategory::Auth.new(self)
end
def event
MethodCategory::Event.new(self)
end
def geo
MethodCategory::Geo.new(self)
end
def library
MethodCategory::Library.new(self)
end
def tag
MethodCategory::Tag.new(self)
end
def tasteometer
MethodCategory::Tasteometer.new(self)
end
def track
MethodCategory::Track.new(self)
end
def user
MethodCategory::User.new(self)
end
def chart
MethodCategory::Chart.new(self)
end
def request(method, params = {}, http_method = :get, with_signature = false, with_session = false)
params[:method] = method
params[:api_key] = @api_key
params.each do |k, v|
if v.nil?
params.delete(k)
end
end
# http://www.lastfm.jp/group/Last.fm+Web+Services/forum/21604/_/497978
#params[:format] = format
params.update(:sk => @session) if with_session
params.update(:api_sig => Digest::MD5.hexdigest(build_method_signature(params))) if with_signature
response = Response.new(self.class.send(http_method, '/', (http_method == :post ? :body : :query) => params).body)
unless response.success?
raise ApiError.new(response.message, response.error)
end
response
end
private
def build_method_signature(params)
params.to_a.sort_by do |param|
param.first.to_s
end.inject('') do |result, param|
result + param.join('')
end + @api_secret
end
end