feature/share-libs
rb 99 lines 2.63 KB
Raw
1 # frozen_string_literal: true
2
3 class SpotifyClient
4 BASE_URI = 'https://api.spotify.com/v1'
5 BASE_URI_ACCOUNT = 'https://accounts.spotify.com/api'
6 LIMIT = 50
7
8 def initialize(authorization)
9 raise 'Authorization is required' if authorization.nil?
10
11 @authorization = authorization
12 @token = authorization.token
13 end
14
15 def user_top_items_request(type, time_range)
16 uri = "#{BASE_URI}/me/top/#{type}"
17 query = { 'time_range' => time_range, 'limit' => LIMIT }
18 header = [
19 ['Accept', 'application/json'],
20 ['Content-Type', 'application/json'],
21 ['Authorization', "Bearer #{@token}"]
22 ]
23 client.get(uri, query, header)
24 end
25
26 def user_recently_played_request
27 uri = "#{BASE_URI}/me/player/recently-played"
28 query = { 'limit' => LIMIT }
29 header = [
30 ['Accept', 'application/json'],
31 ['Content-Type', 'application/json'],
32 ['Authorization', "Bearer #{@token}"]
33 ]
34 client.get(uri, query, header)
35 end
36
37 def album_tracks_request(album_id)
38 uri = "#{BASE_URI}/albums/#{album_id}/tracks"
39 query = { 'limit' => LIMIT }
40 header = [
41 ['Accept', 'application/json'],
42 ['Content-Type', 'application/json'],
43 ['Authorization', "Bearer #{@token}"]
44 ]
45 client.get(uri, query, header)
46 end
47
48 def artist_detail_request(artist_id)
49 uri = "#{BASE_URI}/artists/#{artist_id}"
50 get(uri, {})
51 end
52
53 def get_track(track_id)
54 uri = "#{BASE_URI}/tracks/#{track_id}"
55 get(uri, {})
56 end
57
58 private
59
60 def client
61 HTTPClient.new
62 end
63
64 def get(uri, query)
65 header = [
66 ['Accept', 'application/json'],
67 ['Content-Type', 'application/json'],
68 ['Authorization', "Bearer #{@token}"]
69 ]
70 response = client.get(uri, query, header)
71 return_or_refresh(response, uri, query)
72 end
73
74 def return_or_refresh(response, uri, query)
75 return response if response.status != 401
76
77 refresh_access_token do
78 get(uri, query)
79 end
80 end
81
82 def refresh_access_token
83 header = [
84 ['Accept', 'application/json'],
85 ['Content-Type', 'application/x-www-form-urlencoded'],
86 ['Authorization', "Basic #{Base64.strict_encode64("#{ENV['SPOTIFY_APP_ID']}:#{ENV['SPOTIFY_APP_SECRET']}")}"]
87 ]
88 body = { 'grant_type' => 'refresh_token', 'refresh_token' => @authorization.refresh_token }
89 response = client.post("#{BASE_URI_ACCOUNT}/token", body, header)
90 update_authorization(JSON.parse(response.body))
91 yield
92 end
93
94 def update_authorization(response)
95 @token = response['access_token']
96 @authorization.update(token: @token)
97 @authorization.update(refresh_token: response['refresh_token']) if response['refresh_token'].present?
98 end
99 end