forked from KrauseFx/auxcord.org
-
Notifications
You must be signed in to change notification settings - Fork 0
/
sonos.rb
427 lines (374 loc) · 13.4 KB
/
sonos.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
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
# frozen_string_literal: true
require 'excon'
require 'json'
require_relative './db'
module SonosPartyMode
class Sonos
# Basic attributes
attr_accessor :user_id
attr_accessor :group_to_use, :currently_playing_guest_wished_song, :favorites_cached
attr_reader :party_session_active
# Queueing system
attr_accessor :current_item_id # it's being set by the `/callback` triggers
# Session specific settings
attr_accessor :target_volume
# Caches
attr_accessor :groups_cached
# Optionally pass in `authorization_code` if this is the first time
# the account is being used, this will store the token in the database
def initialize(user_id:, authorization_code: nil)
@user_id = user_id
new_auth!(authorization_code: authorization_code) if authorization_code
return if database_row.nil? # this is the case if a user didn't finish onboarding
@target_volume = database_row[:volume] # default volume is defined as part of `db.rb`
@group_to_use = database_row[:group]
groups_cached = groups
return if groups_cached.nil? # no household
unless groups_cached.collect { |a| a['id'] }.include?(@group_to_use)
# The group ID doesn't exist any more, fallback to the default one (most speakers)
@group_to_use = groups_cached.sort_by { |a| a['playerIds'].count }.reverse.first.fetch('id')
# Also store the resulting group in the database
Db.sonos_tokens.where(user_id: user_id).update(group: @group_to_use) # important to use full query
end
@party_session_active = database_row[:party_active] || false
@currently_playing_guest_wished_song = false
subscribe_to_playback
subscribe_to_playback_metadata
end
def subscribe_to_playback
client_control_request("/groups/#{group_to_use}/playback/subscription", method: :post)
end
def subscribe_to_playback_metadata
client_control_request("/groups/#{group_to_use}/playbackMetadata/subscription", method: :post)
end
def did_receive_new_playback_metadata(info)
# See example output at the very bottom of this file
@_playback_metadata = info
end
def playback_metadata
# this is cached from the Sonos subscription
if @_playback_metadata && @_playback_metadata['currentItem'] && @_playback_metadata['currentItem']['track'] && @_playback_metadata['currentItem']['track']['id']
return @_playback_metadata
end
# fallback, in case we didn't get a Sonos message yet. I confirmed it's the exact same data
return client_control_request("groups/#{group_to_use}/playbackMetadata")
end
def ensure_playlist_in_favorites(spotify_playlist_id, force_refresh: true)
favs = favorites_cached unless force_refresh
favs ||= client_control_request("/households/#{primary_household}/favorites")
return favs.fetch('items').find do |fav|
fav['service']['name'] == 'Spotify' &&
fav['resource']['type'] == 'PLAYLIST' &&
fav['resource']['id']['objectId'].include?(spotify_playlist_id)
end
rescue => ex
puts "fav playlist error"
puts ex.message
return nil
end
def ensure_current_sonos_settings!
return unless party_session_active
ensure_volume!(target_volume)
ensure_music_playing!
unmute_speakers!
end
# Called every ~15s
def refresh_caches
self.groups_cached = groups
self.favorites_cached = client_control_request("/households/#{primary_household}/favorites")
end
def playback_status
status = client_control_request("/groups/#{group_to_use}/playback")
return status.fetch('playbackState')
end
def playback_is_playing?
%w[PLAYBACK_STATE_PLAYING PLAYBACK_STATE_BUFFERING].include?(playback_status)
end
def ensure_music_playing!
return if playback_is_playing?
play_music!
end
def play_music!
puts 'Resuming playback for Sonos system'
client_control_request("groups/#{group_to_use}/playback/play", method: :post)
end
def pause_playback!
return unless playback_is_playing?
puts 'Pausing playback for Sonos system'
client_control_request("groups/#{group_to_use}/playback/pause", method: :post)
end
def skip_song!
puts 'Skipping song'
client_control_request("/groups/#{group_to_use}/playback/skipToNextTrack", method: :post)
end
def get_volume
# {"volume"=>40, "muted"=>false, "fixed"=>false}
client_control_request("groups/#{group_to_use}/groupVolume")
end
def ensure_volume!(goal_volume, check_first: true)
if check_first # when volume is manually changed in admin panel, we want to skip that
get_volume_cached = get_volume
# If the speakers are unmuted, and the volume is correct, nothing to do here
return if get_volume_cached.fetch('volume') == goal_volume && get_volume_cached.fetch('muted') == false
end
# The request below will set the volume
client_control_request(
"groups/#{group_to_use}/groupVolume",
method: :post,
body: { volume: goal_volume }
)
unmute_speakers!
end
def unmute_speakers!
# This is a separate request. It seems like there is no good Sonos API endpoint
# to check if any of the speakers in a given group is muted, so it's best to just
# send this API request from time to time in the background
client_control_request(
"groups/#{group_to_use}/groupVolume/mute",
method: :post,
body: { muted: false }
)
end
# ----------------
# Under the hood
# ----------------
def primary_household
return @_primary_household if @_primary_household
# I don't have an account with multiple households, but for now let's just access the household
# with the highest number of speakers associated
household_speakers = households.collect do |household|
household_groups = client_control_request("/households/#{household['id']}/groups").fetch('groups', nil)
[
household["id"],
household_groups.collect { |a| a["playerIds"] }.flatten.count
]
end.to_h
@_primary_household = household_speakers.max_by { |k, v| v }.first
rescue => ex
puts ex
puts ex.backtrace.join("\n")
@_primary_household ||= households.first
end
def households
client_control_request('households').fetch('households')
end
def groups
return nil if primary_household.nil?
client_control_request("/households/#{primary_household}/groups").fetch('groups', nil)
end
def access_token
database_row.fetch(:access_token)
end
def database_row
Db.sonos_tokens.where(user_id: user_id).first
end
def client_login
Excon.new('https://api.sonos.com/login/v3/oauth/access')
end
def client_control
Excon.new('https://api.ws.sonos.com/control/api/v1/')
end
def default_headers
{
'Authorization' => "Bearer #{access_token}",
'Content-Type' => 'application/json'
}
end
def refresh_token
puts 'Refreshing API token...'
refresh_token = database_row.fetch(:refresh_token)
response = client_login.post(
headers: {
'Content-Type' => 'application/x-www-form-urlencoded',
'Accept-Charset' => 'UTF-8',
'Authorization' => "Basic #{Base64.strict_encode64("#{ENV.fetch('SONOS_KEY')}:#{ENV.fetch('SONOS_SECRET')}")}"
},
body: URI.encode_www_form({
grant_type: 'refresh_token',
refresh_token: refresh_token
})
)
parsed_body = JSON.parse(response.body)
access_token = parsed_body.fetch('access_token')
Db.sonos_tokens.where(user_id: user_id).update(access_token: access_token) # important to use full query
end
def client_control_request(path, method: :get, body: nil)
response = client_control.request(
method: method,
path: File.join(client_control.data[:path], path),
headers: default_headers,
body: Hash(body).to_json
)
parsed_body = JSON.parse(response.body)
# Check if Sonos API token has expired
# "=> {"fault"=>{"faultstring"=>"Access Token expired", "detail"=>{"errorcode"=>"keymanagement.service.access_token_expired"}}}"
if parsed_body['fault'].to_s.length.positive?
if ['keymanagement.service.invalid_access_token',
'keymanagement.service.access_token_expired'].include?(parsed_body['fault']['detail']['errorcode'])
refresh_token
return client_control_request(path, method: method, body: body)
else
raise parsed_body['fault']['faultstring']
end
end
return parsed_body
end
# Override party_session_active setter
def party_session_active=(value)
@party_session_active = value
Db.sonos_tokens.where(user_id: user_id).update(party_active: value) # important to use full query
end
def new_auth!(authorization_code:)
# Very important: the redirect_uri has to match exactly
response = client_login.post(
headers: {
'Content-Type' => 'application/x-www-form-urlencoded',
'Accept-Charset' => 'UTF-8',
'Authorization' => "Basic #{Base64.strict_encode64("#{ENV.fetch('SONOS_KEY')}:#{ENV.fetch('SONOS_SECRET')}")}"
},
body: URI.encode_www_form({
grant_type: 'authorization_code',
code: authorization_code,
redirect_uri: "#{ENV.fetch('CUSTOM_HOST_URL')}/sonos/authorized.html"
})
)
response = JSON.parse(response.body)
puts "sonos api response: #{response}"
raise response['error'] if response['error'].to_s.length.positive?
access_token = response.fetch('access_token')
refresh_token = response.fetch('refresh_token')
# Store the access token in the database
Db.sonos_tokens.insert(
user_id: user_id,
access_token: access_token,
refresh_token: refresh_token,
expires_in: response.fetch('expires_in')
)
Db.sonos_tokens.where(user_id: user_id).update(household: primary_household)
end
end
end
# {
# "container": {
# "name": "Work",
# "type": "track",
# "id": {
# "serviceId": "12",
# "objectId": "spotify:track:3KliPMvk1EvFZu9cvkj8p1",
# "accountId": "sn_1"
# },
# "service": {
# "name": "Spotify",
# "id": "12",
# "images": [
# ]
# },
# "imageUrl": "https://i.scdn.co/image/ab67616d0000b2733c9f7b8faf039c7607d12255",
# "images": [
# {
# "url": "https://i.scdn.co/image/ab67616d0000b2733c9f7b8faf039c7607d12255",
# "height": 0,
# "width": 0
# }
# ],
# "tags": [
# "TAG_EXPLICIT"
# ],
# "explicit": true
# },
# "currentItem": {
# "track": {
# "type": "track",
# "name": "Work",
# "imageUrl": "http://192.168.0.168:1400/getaa?s=1&u=x-sonos-spotify%3aspotify%253atrack%253a3KliPMvk1EvFZu9cvkj8p1%3fsid%3d12%26flags%3d8232%26sn%3d1",
# "images": [
# {
# "url": "http://192.168.0.168:1400/getaa?s=1&u=x-sonos-spotify%3aspotify%253atrack%253a3KliPMvk1EvFZu9cvkj8p1%3fsid%3d12%26flags%3d8232%26sn%3d1",
# "height": 0,
# "width": 0
# }
# ],
# "album": {
# "name": "Britney Jean (Deluxe Version)",
# "explicit": false
# },
# "artist": {
# "name": "Britney Spears",
# "explicit": false
# },
# "id": {
# "serviceId": "12",
# "objectId": "spotify:track:3KliPMvk1EvFZu9cvkj8p1",
# "accountId": "sn_1"
# },
# "service": {
# "name": "Spotify",
# "id": "12",
# "images": [
# ]
# },
# "durationMillis": 247000,
# "tags": [
# "TAG_EXPLICIT"
# ],
# "explicit": true,
# "advertisement": false,
# "quality": {
# "bitDepth": 0,
# "sampleRate": 0,
# "lossless": false,
# "immersive": false
# }
# },
# "deleted": false,
# "policies": {
# ...
# }
# },
# "nextItem": {
# "track": {
# "type": "track",
# "name": "Inner Tale",
# "imageUrl": "http://192.168.0.168:1400/getaa?s=1&u=x-sonos-spotify%3aspotify%253atrack%253a4aAPW97U3nrnELAknGdV2L%3fsid%3d12%26flags%3d8232%26sn%3d1",
# "images": [
# {
# "url": "http://192.168.0.168:1400/getaa?s=1&u=x-sonos-spotify%3aspotify%253atrack%253a4aAPW97U3nrnELAknGdV2L%3fsid%3d12%26flags%3d8232%26sn%3d1",
# "height": 0,
# "width": 0
# }
# ],
# "album": {
# "name": "Orchestra",
# "explicit": false
# },
# "artist": {
# "name": "Worakls",
# "explicit": false
# },
# "id": {
# "serviceId": "12",
# "objectId": "spotify:track:4aAPW97U3nrnELAknGdV2L",
# "accountId": "sn_1"
# },
# "service": {
# "name": "Spotify",
# "id": "12",
# "images": [
# ]
# },
# "durationMillis": 259000,
# "explicit": false,
# "advertisement": false,
# "quality": {
# "bitDepth": 0,
# "sampleRate": 0,
# "lossless": false,
# "immersive": false
# }
# },
# "deleted": false,
# "policies": {
# ...
# }
# }
# }