37_Spotify.pm 54 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315
  1. ##############################################################################
  2. # $Id: 37_Spotify.pm 14987 2017-09-02 13:14:37Z neumann $
  3. #
  4. # 37_Spotify.pm
  5. #
  6. # 2017 Oskar Neumann
  7. # oskar.neumann@me.com
  8. #
  9. ##############################################################################
  10. package main;
  11. use strict;
  12. use warnings;
  13. use JSON;
  14. use MIME::Base64;
  15. sub Spotify_Initialize($) {
  16. my ($hash) = @_;
  17. $hash->{DefFn} = 'Spotify_Define';
  18. $hash->{NotifyFn} = 'Spotify_Notify';
  19. $hash->{UndefFn} = 'Spotify_Undefine';
  20. $hash->{SetFn} = 'Spotify_Set';
  21. $hash->{GetFn} = 'Spotify_Get';
  22. #$hash->{AttrFn} = "Spotify_Attr";
  23. $hash->{AttrList} = 'defaultPlaybackDeviceID alwaysStartOnDefaultDevice:0,1 updateInterval updateIntervalWhilePlaying disable:0,1 volumeStep ';
  24. $hash->{AttrList} .= $readingFnAttributes;
  25. $hash->{NOTIFYDEV} = "global";
  26. }
  27. sub Spotify_Define($) {
  28. my ($hash, $def) = @_;
  29. my $name = $hash->{NAME};
  30. my @a = split("[ \t][ \t]*", $def);
  31. my $hintGetVaildPair = "get a valid pair by creating a Spotify app".
  32. " here: https://developer.spotify.com/my-applications/#!/applications/create
  33. (recommendation is to use https://oskar.pw/ as redirect_uri because it displays the temporary access code - ".
  34. "this is safe because the code is useless without your client credentials and expires after a few minutes)";
  35. return 'wrong syntax: define <name> Spotify <client_id> <client_secret> [ <redirect_uri> ]
  36. - '. $hintGetVaildPair
  37. if( @a < 4 );
  38. my $client_id = $a[2];
  39. my $client_secret = $a[3];
  40. return 'invalid client_id / client_secret - '. $hintGetVaildPair
  41. if(length $client_id != 32 || length $client_secret != 32);
  42. $hash->{CLIENT_ID} = $client_id;
  43. $hash->{CLIENT_SECRET} = $client_secret;
  44. $hash->{REDIRECT_URI} = @a > 4 ? $a[4] : 'https://oskar.pw/';
  45. $hash->{helper}{custom_redirect} = @a > 4;
  46. Spotify_loadInternals($hash) if($init_done);
  47. return undef;
  48. }
  49. sub Spotify_Undefine($$) {
  50. my ($hash, $name) = @_;
  51. RemoveInternalTimer($hash);
  52. return undef;
  53. }
  54. sub Spotify_Notify($$) {
  55. my ($own_hash, $dev_hash) = @_;
  56. my $ownName = $own_hash->{NAME}; # own name / hash
  57. return "" if(IsDisabled($ownName)); # Return without any further action if the module is disabled
  58. my $devName = $dev_hash->{NAME}; # Device that created the events
  59. my $events = deviceEvents($dev_hash, 1);
  60. if($devName eq "global" && grep(m/^INITIALIZED|REREADCFG$/, @{$events})) {
  61. Spotify_loadInternals($own_hash);
  62. }
  63. }
  64. sub Spotify_Set($$@) {
  65. my ($hash, $name, $cmd, @args) = @_;
  66. return "\"set $name\" needs at least one argument" unless(defined($cmd));
  67. my $list = '';
  68. if(!defined $hash->{helper}{refresh_token}) {
  69. $list .= ' code';
  70. } else {
  71. $list .= ' playTrackByURI playContextByURI pause:noArg resume:noArg volume:slider,0,1,100 update:noArg';
  72. $list .= ' skipToNext:noArg skipToPrevious:noArg seekToPosition repeat:one,all,off shuffle:on,off transferPlayback volumeFade:slider,0,1,100 playTrackByName playPlaylistByName togglePlayback';
  73. $list .= ' playSavedTracks playRandomTrackFromPlaylistByURI findTrackByName findArtistByName playArtistByName volumeUp volumeDown';
  74. }
  75. if($cmd eq 'code') {
  76. return "please enter the code obtained from the URL after calling \"get $name authorizationURL\""
  77. if( @args < 1 );
  78. return Spotify_getToken($hash, $args[0]);
  79. }
  80. return Spotify_update($hash, 1) if($cmd eq 'update');
  81. return Spotify_pausePlayback($hash) if($cmd eq 'pause');
  82. return Spotify_resumePlayback($hash, @args > 0 ? join(' ', @args) : undef) if($cmd eq 'resume');
  83. return Spotify_setVolume($hash, 1, $args[0], defined $args[1] ? join(' ', @args[1..$#args]) : undef) if ($cmd eq 'volume');
  84. return Spotify_skipToNext($hash) if ($cmd eq 'skipToNext' || $cmd eq 'skip' || $cmd eq 'next');
  85. return Spotify_skipToPrevious($hash) if ($cmd eq 'skipToPrevious' || $cmd eq 'previous' || $cmd eq 'prev');
  86. return Spotify_seekToPosition($hash, $args[0]) if($cmd eq 'seekToPosition');
  87. return Spotify_setRepeat($hash, $args[0]) if($cmd eq 'repeat');
  88. return Spotify_setShuffle($hash, $args[0]) if($cmd eq 'shuffle');
  89. return Spotify_transferPlayback($hash, @args > 0 ? join(' ', @args) : undef) if($cmd eq 'transferPlayback');
  90. return Spotify_playTrackByURI($hash, \@args, undef) if($cmd eq 'playTrackByURI');
  91. return Spotify_playTrackByName($hash, @args > 0 ? join(' ', @args) : undef) if($cmd eq 'playTrackByName');
  92. return Spotify_playPlaylistByName($hash, @args > 0 ? join(' ', @args) : undef) if($cmd eq 'playPlaylistByName');
  93. return Spotify_playContextByURI($hash, $args[0], $args[1], defined $args[2] ? join(' ', @args[2..$#args]) : undef) if($cmd eq 'playContextByURI');
  94. return Spotify_volumeFade($hash, $args[0], $args[1], $args[2], defined $args[3] ? join(' ', @args[3..$#args]) : undef) if($cmd eq 'volumeFade');
  95. return Spotify_volumeFadeStep($hash) if($cmd eq 'volumeFadeStep');
  96. return Spotify_togglePlayback($hash) if($cmd eq 'toggle' || $cmd eq 'togglePlayback');
  97. return Spotify_playSavedTracks($hash, $args[0], defined $args[1] ? join(' ', @args[1..$#args]) : undef) if($cmd eq 'playSavedTracks');
  98. return Spotify_playRandomTrackFromPlaylistByURI($hash, $args[0], $args[1], defined $args[2] ? join(' ', @args[2..$#args]) : undef) if($cmd eq 'playRandomTrackFromPlaylistByURI');
  99. return Spotify_findTrackByName($hash, @args > 0 ? join(' ', @args) : undef) if($cmd eq 'findTrackByName');
  100. return Spotify_findArtistByName($hash, @args > 0 ? join(' ', @args) : undef) if($cmd eq 'findArtistByName');
  101. return Spotify_playArtistByName($hash, @args > 0 ? join(' ', @args) : undef) if($cmd eq 'playArtistByName');
  102. return Spotify_volumeStep($hash, $cmd eq 'volumeDown' ? -1 : 1, $args[0], defined $args[1] ? join(' ', @args[1..$#args]) : undef) if($cmd eq 'volumeUp' || $cmd eq 'volumeDown');
  103. return "Unknown argument $cmd, choose one of $list";
  104. }
  105. sub Spotify_Get($$@) {
  106. my ($hash, $name, $cmd, @args) = @_;
  107. my $list = "";
  108. if(!defined $hash->{helper}{refresh_token}) {
  109. $list .= ' authorizationURL:noArg';
  110. } else {
  111. #$list .= ' me:noArg';
  112. }
  113. if($cmd eq "authorizationURL") {
  114. return $hash->{AUTHORIZATION_URL};
  115. }
  116. return "Unknown argument $cmd, choose one of $list";
  117. }
  118. sub Spotify_loadInternals($) {
  119. my ($hash) = @_;
  120. my $name = $hash->{NAME};
  121. $hash->{helper}{authorization_url} = "https://accounts.spotify.com/authorize/?client_id=$hash->{CLIENT_ID}&response_type=code&scope=playlist-read-private%20playlist-read-collaborative%20streaming%20user-library-read%20user-read-private%20user-read-playback-state&redirect_uri=" . urlEncode($hash->{REDIRECT_URI});
  122. $hash->{helper}{refresh_token} = ReadingsVal($name, '.refresh_token', undef);
  123. $hash->{helper}{access_token} = ReadingsVal($name, '.access_token', undef);
  124. $hash->{helper}{expires} = ReadingsVal($name, '.expires', undef);
  125. RemoveInternalTimer($hash);
  126. if(!defined(ReadingsVal($name, '.refresh_token', undef))) {
  127. $hash->{STATE} = 'authorization pending (see instructions)';
  128. $hash->{AUTHORIZATION_URL} = $hash->{helper}{authorization_url};
  129. $hash->{A1_INSTRUCTIONS} = 'Open AUTHORIZATION_URL in your browser and set the code afterwards. Make sure to specify REDIRECT_URI as a redirect_uri in your API application.';
  130. $hash->{A1_INSTRUCTIONS} .= ' It is safe to rely on https://oskar.pw/ as redirect_uri because your code is worthless without the client secret and only valid for a few minutes.
  131. However, feel free to specify any other redirect_uri in the definition and extract the code after being redirected yourself.' if(!$hash->{helper}{custom_redirect});
  132. } else {
  133. $hash->{STATE} = 'connected';
  134. my $pollInterval = $attr{$name}{pollInterval};
  135. $attr{$name}{webCmd} = 'toggle:next:prev:volumeUp:volumeDown' if(!defined $attr{$name}{webCmd});
  136. Spotify_poll($hash) if(defined $hash->{helper}{refresh_token} && !Spotify_isDisabled($hash));
  137. }
  138. }
  139. sub Spotify_getToken($$) { # exchanging code for token
  140. my ($hash, $code) = @_;
  141. my $name = $hash->{NAME};
  142. Log3 $name, 4, "$name: checking access code";
  143. my ($err,$data) = HttpUtils_BlockingGet({
  144. url => "https://accounts.spotify.com/api/token",
  145. method => "POST",
  146. timeout => 5,
  147. noshutdown => 1,
  148. data => {client_id => $hash->{CLIENT_ID}, client_secret => $hash->{CLIENT_SECRET}, grant_type => 'authorization_code', redirect_uri => $hash->{REDIRECT_URI}, 'code' => $code}
  149. });
  150. my $json = eval { JSON->new->utf8(0)->decode($data) };
  151. if(defined $json->{error}) {
  152. my $msg = 'Failed to get access token: ';
  153. if($json->{error_description} =~ /redirect/) {
  154. $msg = $msg . 'Please add '. $hash->{REDIRECT_URI} . ' as a redirect_uri at https://developer.spotify.com/my-applications/#!/applications/';
  155. } else {
  156. $msg = $msg . $json->{error_description};
  157. }
  158. Log3 $name, 3, "$name: $json->{error} - $msg";
  159. return $msg;
  160. }
  161. return "failed to get access token"
  162. if(!defined $json->{refresh_token});
  163. $hash->{helper}{refresh_token} = $json->{refresh_token};
  164. $hash->{helper}{access_token} = $json->{access_token};
  165. $hash->{helper}{expires} = gettimeofday() + $json->{expires_in};
  166. $hash->{helper}{scope} = $json->{scope};
  167. delete $hash->{AUTHORIZATION_URL};
  168. delete $hash->{A1_INSTRUCTIONS};
  169. $hash->{STATE} = "connected";
  170. Spotify_writeTokens($hash);
  171. RemoveInternalTimer($hash);
  172. Spotify_updateMe($hash, 0);
  173. Spotify_poll($hash);
  174. return undef;
  175. }
  176. sub Spotify_writeTokens($) { # save gathered tokens
  177. my ($hash) = @_;
  178. readingsBeginUpdate($hash);
  179. readingsBulkUpdate($hash, '.refresh_token', $hash->{helper}{refresh_token});
  180. readingsBulkUpdateIfChanged($hash, '.access_token', $hash->{helper}{access_token});
  181. readingsBulkUpdate($hash, '.expires', $hash->{helper}{expires});
  182. readingsEndUpdate($hash, 1);
  183. }
  184. sub Spotify_refreshToken($) { # refresh the access token once it is expired
  185. my ($hash) = @_;
  186. my $name = $hash->{NAME};
  187. return 'Failed to refresh access token: refresh token missing' if(!defined $hash->{helper}{refresh_token});
  188. Log3 $name, 4, "$name: refreshing access code";
  189. my ($err,$data) = HttpUtils_BlockingGet({
  190. url => "https://accounts.spotify.com/api/token",
  191. method => "POST",
  192. timeout => 5,
  193. noshutdown => 1,
  194. data => {client_id => $hash->{CLIENT_ID}, client_secret => $hash->{CLIENT_SECRET}, grant_type => 'refresh_token', refresh_token => $hash->{helper}{refresh_token}}
  195. });
  196. my $json = eval { JSON->new->utf8(0)->decode($data) };
  197. if(defined $json->{error}) {
  198. if($json->{error} eq 'invalid_grant') {
  199. $hash->{helper}{refresh_token} = undef;
  200. $hash->{STATE} = 'invalid refresh token';
  201. $hash->{AUTHORIZATION_URL} = $hash->{helper}{authorization_url};
  202. CommandDeleteReading(undef, "$name .*");
  203. }
  204. my $msg = 'Failed to refresh access token: $json->{error_description}';
  205. Log3 $name, 3, "$name: $json->{error} - $msg";
  206. return $msg;
  207. }
  208. return "failed to refresh access token" if(!defined $json->{access_token});
  209. $hash->{helper}{access_token} = $json->{access_token};
  210. $hash->{helper}{expires} = gettimeofday() + $json->{expires_in};
  211. $hash->{helper}{scope} = $json->{scope} if(defined $json->{scope});
  212. Spotify_writeTokens($hash);
  213. Spotify_updateMe($hash, 0);
  214. Spotify_updateDevices($hash, 0);
  215. }
  216. sub Spotify_apiRequest($$$$$) { # any kind of api request
  217. my ($hash, $path, $args, $method, $blocking) = @_;
  218. my $name = $hash->{NAME};
  219. Spotify_refreshToken($hash) if(gettimeofday() >= $hash->{helper}{expires});
  220. if(!defined $hash->{helper}{refresh_token}) {
  221. Log3 $name, 3, "$name: could not execute API request (not authorized)";
  222. return 'You need to be authorized to perform this action.';
  223. }
  224. if(!defined $blocking || !$blocking) {
  225. HttpUtils_NonblockingGet({
  226. url => "https://api.spotify.com/v1/$path",
  227. method => $method,
  228. hash => $hash,
  229. apiPath => $path,
  230. timeout => 5,
  231. noshutdown => 1,
  232. data => $method eq 'PUT' && defined $args ? encode_json $args : $args,
  233. header => "Authorization: Bearer ". $hash->{helper}{access_token},
  234. callback => \&Spotify_dispatch
  235. });
  236. } else {
  237. my ($err,$data) = HttpUtils_BlockingGet({
  238. url => "https://api.spotify.com/v1/$path",
  239. method => $method,
  240. hash => $hash,
  241. apiPath => $path,
  242. timeout => 5,
  243. noshutdown => 1,
  244. data => $method eq 'PUT' && defined $args ? encode_json $args : $args,
  245. header => "Authorization: Bearer ". $hash->{helper}{access_token}
  246. });
  247. return Spotify_dispatch({hash => $hash, apiPath => $path, method => $method}, $err, $data);
  248. }
  249. }
  250. sub Spotify_updateMe($$) { # update user infos
  251. my ($hash, $blocking) = @_;
  252. Spotify_apiRequest($hash, 'me/', undef, 'GET', $blocking);
  253. return undef;
  254. }
  255. sub Spotify_updateDevices($$) { # update devices
  256. my ($hash, $blocking) = @_;
  257. Spotify_apiRequest($hash, 'me/player/devices', undef, 'GET', $blocking);
  258. return undef;
  259. }
  260. sub Spotify_pausePlayback($) { # pause playback
  261. my ($hash) = @_;
  262. my $name = $hash->{NAME};
  263. $hash->{helper}{is_playing} = 0;
  264. readingsSingleUpdate($hash, 'is_playing', 0, 1);
  265. Spotify_apiRequest($hash, 'me/player/pause', undef, 'PUT', 0);
  266. Log3 $name, 4, "$name: pause";
  267. return undef;
  268. }
  269. sub Spotify_resumePlayback($$) { # resume playback
  270. my ($hash, $device_id) = @_;
  271. my $name = $hash->{NAME};
  272. $device_id = Spotify_getTargetDeviceID($hash, $device_id, 0); # resolve target device id
  273. $hash->{helper}{is_playing} = 1;
  274. readingsSingleUpdate($hash, 'is_playing', 1, 1);
  275. Spotify_apiRequest($hash, 'me/player/play' . (defined $device_id ? "?device_id=$device_id" : ''), undef, 'PUT', 0);
  276. Log3 $name, 4, "$name: resume";
  277. return undef;
  278. }
  279. sub Spotify_updatePlaybackStatus($$) { # update the playback status
  280. my ($hash, $blocking) = @_;
  281. Spotify_apiRequest($hash, 'me/player', undef, 'GET', $blocking);
  282. return undef;
  283. }
  284. sub Spotify_setVolume($$$$) { # set the volume
  285. my ($hash, $blocking, $volume, $device_id) = @_;
  286. my $name = $hash->{NAME};
  287. return 'wrong syntax: set <name> volume <percent> [ <device_id / device_name> ]' if(!defined $volume);
  288. delete $hash->{helper}{fading} if($blocking && defined $hash->{helper}{fading}); # stop volumeFade if currently active (override)
  289. $device_id = Spotify_getTargetDeviceID($hash, $device_id, 0); # resolve target device id
  290. Spotify_apiRequest($hash, "me/player/volume?volume_percent=$volume". (defined $device_id ? "&device_id=$device_id" : ''), undef, 'PUT', $blocking);
  291. Log3 $name, 4, "$name: volume $volume" if(!defined $hash->{helper}{fading});
  292. return undef;
  293. }
  294. sub Spotify_skipToNext($) { # skip to next track
  295. my ($hash) = @_;
  296. my $name = $hash->{NAME};
  297. Spotify_apiRequest($hash, 'me/player/next', undef, 'POST', 0);
  298. Log3 $name, 4, "$name: skipToNext";
  299. return undef;
  300. }
  301. sub Spotify_skipToPrevious($) { # skip to previous track
  302. my ($hash) = @_;
  303. my $name = $hash->{NAME};
  304. Spotify_apiRequest($hash, 'me/player/previous', undef, 'POST', 0);
  305. Log3 $name, 4, "$name: skipToPrevious";
  306. return undef;
  307. }
  308. sub Spotify_seekToPosition($$) { # seek to position in track
  309. my ($hash, $position) = @_;
  310. my $name = $hash->{NAME};
  311. my (undef, $minutes, $seconds) = $position =~ m/(([0-9]+):)?([0-9]+)/;
  312. return 'wrong syntax: set <name> seekToPosition <position_in_s>' if(!defined $minutes && !defined $seconds);
  313. $position = ($minutes * 60 + $seconds) * 1000;
  314. Spotify_apiRequest($hash, "me/player/seek?position_ms=$position", undef, 'PUT', 0);
  315. return undef;
  316. }
  317. sub Spotify_setRepeat($$) { # set the repeat mode
  318. my ($hash, $mode) = @_;
  319. my $name = $hash->{NAME};
  320. return 'wrong syntax: set <name> repeat <one,all,off>' if(!defined $mode || ($mode ne 'one' && $mode ne 'all' && $mode ne 'off'));
  321. $mode = 'track' if($mode eq 'one');
  322. $mode = 'context' if($mode eq 'all');
  323. my $device_id = Spotify_getTargetDeviceID($hash, undef, 0);
  324. Spotify_apiRequest($hash, "me/player/repeat?state=$mode". (defined $device_id ? "&device_id=$device_id" : ""), undef, 'PUT', 0);
  325. Log3 $name, 4, "$name: repeat $mode";
  326. return undef;
  327. }
  328. sub Spotify_setShuffle($$) { # set the shuffle mode
  329. my ($hash, $mode) = @_;
  330. my $name = $hash->{NAME};
  331. return 'wrong syntax: set <name> shuffle <off,on>' if(!defined $mode || ($mode ne 'on' && $mode ne 'off'));
  332. $mode = $mode eq 'on' ? 'true' : 'false';
  333. my $device_id = Spotify_getTargetDeviceID($hash, undef, 0);
  334. Spotify_apiRequest($hash, "me/player/shuffle?state=$mode". (defined $device_id ? "&device_id=$device_id" : ""), undef, 'PUT', 0);
  335. Log3 $name, 4, "$name: shuffle $mode";
  336. return undef;
  337. }
  338. sub Spotify_transferPlayback($$) { # transfer the current playback to another device
  339. my ($hash, $device_id) = @_;
  340. $device_id = Spotify_getTransferTargetDeviceID($hash, $device_id);
  341. return 'device not found' if(!defined $device_id);
  342. my @device_ids = ($device_id);
  343. Spotify_apiRequest($hash, 'me/player', {device_ids => \@device_ids}, 'PUT', 0);
  344. return undef;
  345. }
  346. sub Spotify_playContextByURI($$$$) { # play a context (playlist, album or artist) using its uri
  347. my ($hash, $uri, $position, $device_id) = @_;
  348. my $name = $hash->{NAME};
  349. return 'wrong syntax: set <name> playContextByURI <album_uri / playlist_uri> [ <nr_of_first_track> ] [ <device_id> ]' if(!defined $uri);
  350. $device_id = $position . (defined $device_id ? " ". $device_id : "") if(defined $position && $position !~ /^[0-9]+$/);
  351. $position = 1 if(!defined $position || $position !~ /^[0-9]+$/);
  352. return Spotify_play($hash, undef, $uri, $position, $device_id);
  353. }
  354. sub Spotify_playTrackByURI($$$) { # play a track by its uri
  355. my ($hash, $uris, $device_id) = @_;
  356. my $name = $hash->{NAME};
  357. return 'wrong syntax: set <name> playTrackByURI <track_uri> ... [ <device_id> ]' if(@{$uris} < 1);
  358. Log3 $name, 4, "$name: track". (@{$uris} > 1 ? "s" : "")." ". join(" ", @{$uris}) if(!defined $hash->{helper}{skipTrackLog});
  359. delete $hash->{helper}{skipTrackLog} if(defined $hash->{helper}{skipTrackLog});
  360. return Spotify_play($hash, $uris, undef, undef, $device_id);
  361. }
  362. sub Spotify_playTrackByName($$) { # play a track by its name using search
  363. my ($hash, $trackname) = @_;
  364. return 'wrong syntax: set <name> playTrackByName <track_name> [ <device_id> ]' if(!defined $trackname);
  365. my @parts = split(" ", $trackname);
  366. my $device_id = Spotify_getTargetDeviceID($hash, $parts[-1], 0) if(@parts > 1); # resolve device id (may be last part of the command)
  367. $trackname = substr($trackname, 0, -length($parts[-1])-1) if(@parts > 1 && defined $device_id); # if last part was indeed the device id, remove it from the track name
  368. Spotify_findTrackByName($hash, $trackname);
  369. my $result = $hash->{helper}{searchResult};
  370. return 'could not find track' if(!defined $result);
  371. my @uris = ($result->{uri});
  372. Spotify_playTrackByURI($hash, \@uris, $device_id);
  373. return undef;
  374. }
  375. sub Spotify_findTrackByName($$) { # finds a track by its name and returns the result in the readings
  376. my ($hash, $trackname, $saveTrack) = @_;
  377. return 'wrong syntax: set <name> findTrackByName <track_name> [ <device_id> ]' if(!defined $trackname);
  378. delete $hash->{helper}{searchResult};
  379. Spotify_apiRequest($hash, 'search?limit=1&type=track&q='. urlEncode($trackname), undef, 'GET', 1);
  380. my $result = $hash->{helper}{dispatch}{json}{tracks}{items}[0];
  381. return 'could not find track' if(!defined $result);
  382. $hash->{helper}{searchResult} = $result;
  383. Spotify_saveTrack($hash, $result, 'search_track', 1);
  384. return undef;
  385. }
  386. sub Spotify_findArtistByName($$) { # finds an artist by its name and returns the result in the readings
  387. my ($hash, $artistname, $saveTrack) = @_;
  388. return 'wrong syntax: set <name> findArtistByName <track_name>' if(!defined $artistname);
  389. delete $hash->{helper}{searchResult};
  390. Spotify_apiRequest($hash, 'search?limit=1&type=artist&q='. urlEncode($artistname), undef, 'GET', 1);
  391. my $result = $hash->{helper}{dispatch}{json}{artists}{items}[0];
  392. return 'could not find artist' if(!defined $result);
  393. $hash->{helper}{searchResult} = $result;
  394. Spotify_saveArtist($hash, $result, 'search_artist', 1);
  395. return undef;
  396. }
  397. sub Spotify_playArtistByName($$) { # play an artist by its name using search
  398. my ($hash, $artistname) = @_;
  399. my $name = $hash->{NAME};
  400. return 'wrong syntax: set <name> playArtistByName <artist_name> [ <device_id> ]' if(!defined $artistname);
  401. my @parts = split(" ", $artistname);
  402. my $device_id = Spotify_getTargetDeviceID($hash, $parts[-1], 0) if(@parts > 1); # resolve device id (may be last part of the command)
  403. $artistname = substr($artistname, 0, -length($parts[-1])-1) if(@parts > 1 && defined $device_id); # if last part was indeed the device id, remove it from the track name
  404. Spotify_findArtistByName($hash, $artistname);
  405. my $result = $hash->{helper}{searchResult};
  406. return 'could not find artist' if(!defined $result);
  407. Spotify_playContextByURI($hash, $result->{uri}, undef, $device_id);
  408. Log3 $name, 4, "$name: artist $result->{uri} ($result->{name})";
  409. return undef;
  410. }
  411. sub Spotify_playPlaylistByName($$) { # play a playlist by its name
  412. my ($hash, $playlistname) = @_;
  413. my $name = $hash->{NAME};
  414. return 'wrong syntax: set <name> playPlaylistByName <playlist_name>' if(!defined $playlistname);
  415. my @parts = split(" ", $playlistname);
  416. my $device_id = Spotify_getTargetDeviceID($hash, $parts[-1], 0) if(@parts > 1); # resolve device id (may be last part of the command)
  417. $playlistname = substr($playlistname, 0, -length($parts[-1])-1) if(@parts > 1 && defined $device_id); # if last part was indeed the device id, remove it from the track name
  418. Spotify_apiRequest($hash, 'search?limit=1&type=playlist&q='. urlEncode($playlistname), undef, 'GET', 1);
  419. my $result = $hash->{helper}{dispatch}{json}{playlists}{items}[0];
  420. return 'could not find playlist' if(!defined $result);
  421. Spotify_playContextByURI($hash, $result->{uri}, undef, $device_id);
  422. Log3 $name, 4, "$name: $result->{uri} ($result->{name})";
  423. return undef;
  424. }
  425. sub Spotify_playSavedTracks($$$) { # play users saved tracks
  426. my ($hash, $first, $device_id) = @_;
  427. my $name = $hash->{NAME};
  428. $device_id = $first . (defined $device_id ? " " . $device_id : "") if(defined $first && $first !~ /^[0-9]+$/);
  429. $first = 1 if(!defined $first || $first !~ /^[0-9]+$/);
  430. Spotify_apiRequest($hash, 'me/tracks?limit=50'. ($first > 50 ? '&offset='. int($first/50)-1 : ''), undef, 'GET', 1); # getting saved tracks
  431. my $result = $hash->{helper}{dispatch}{json}{items};
  432. return 'could not get saved tracks' if(!defined $result);
  433. my @uris = map { $_->{track}{uri} } @{$result};
  434. shift @uris for 1..($first%50-1); # removing first elements users wants to skip
  435. Spotify_playTrackByURI($hash, \@uris, $device_id); # play them
  436. Log3 $name, 4, "$name: saved tracks";
  437. return undef;
  438. }
  439. sub Spotify_playRandomTrackFromPlaylistByURI($$$$) { # select a random track from a given playlist and play it (use case: e.g. alarm clocks)
  440. my ($hash, $uri, $limit, $device_id) = @_;
  441. my $name = $hash->{NAME};
  442. return 'wrong syntax: set <name> playRandomTrackFromPlaylistByURI <playlist_uri> [ <limit> ] [ <device_id> ]' if(!defined $uri);
  443. my ($user_id, $playlist_id) = $uri =~ m/user:(.*):playlist:(.*)/;
  444. return 'invalid playlist_uri' if(!defined $user_id || !defined $playlist_id);
  445. $device_id = $limit . (defined $device_id ? " " . $device_id : "") if(defined $limit && $limit !~ /^[0-9]+$/);
  446. $limit = undef if($limit !~ /^[0-9]+$/);
  447. Spotify_apiRequest($hash, "users/$user_id/playlists/$playlist_id/tracks?fields=items(track(name,uri))". (defined $limit ? "&limit=$limit" : ""), undef, 'GET', 1);
  448. my $result = $hash->{helper}{dispatch}{json}{items};
  449. return 'could not find playlist' if(!defined $result);
  450. my @alltracks = map { $_->{track} } @{$result};
  451. my $selectedTrack = $alltracks[rand @alltracks];
  452. my @uris = ($selectedTrack->{uri});
  453. $hash->{helper}{skipTrackLog} = 1;
  454. Spotify_playTrackByURI($hash, \@uris, $device_id);
  455. Log3 $name, 4, "$name: random track $selectedTrack->{uri} ($selectedTrack->{name}) from $uri";
  456. return undef;
  457. }
  458. sub Spotify_play($$$$$) { # any play command (colleciton or track)
  459. my ($hash, $uris, $context_uri, $position, $device_id) = @_;
  460. my $name = $hash->{NAME};
  461. my $data = undef;
  462. if(defined $uris) {
  463. if(@{$uris} > 1 && @{$uris}[-1] !~ /spotify:/) {
  464. $device_id = pop @{$uris};
  465. }
  466. $data = {uris => $uris};
  467. } else {
  468. $data = {context_uri => $context_uri};
  469. $data->{offset} = {position => $position-1} if($position > 1);
  470. }
  471. $device_id = Spotify_getTargetDeviceID($hash, $device_id, 1);
  472. Spotify_apiRequest($hash, 'me/player/play'. (defined $device_id ? '?device_id='. $device_id : ''), $data, 'PUT', 1);
  473. Spotify_updatePlaybackStatus($hash, 1);
  474. return undef;
  475. }
  476. sub Spotify_volumeFade($$$$$) { # fade the volume of a device
  477. my ($hash, $targetVolume, $duration, $step, $device_id) = @_;
  478. return 'wrong syntax: set <name> volumeFade <target_volume> [ <duration_s> <percent_per_step> ] [ <device_id> ]' if(!defined $targetVolume);
  479. Spotify_updateDevices($hash, 1); # make sure devices are up to date (a valid start volume is required)
  480. $device_id = $duration . (defined $device_id ? " " . $device_id : "") if(defined $duration && $duration !~ /^[0-9]+$/);
  481. my $startVolume = $hash->{helper}{device_active}{volume_percent};
  482. return 'could not get start volume of active device' if(!defined $startVolume);
  483. $step = 5 if(!defined $step); # fall back to default step if not specified
  484. $duration = 5 if(!defined $duration || $duration !~ /^[0-9]+$/); # fallback to default value if duration is not specified or valid
  485. my $delta = abs($targetVolume - $startVolume);
  486. my $requiredSteps = int($delta/$step);
  487. return Spotify_setVolume($hash, 0, $targetVolume, $device_id) if($requiredSteps == 0); # no steps required, set volume and exit
  488. #Log3 "spotify", 3, "fading volume start $startVolume target $targetVolume duration $duration step $step steps $requiredSteps";
  489. $hash->{helper}{fading}{step} = $step;
  490. $hash->{helper}{fading}{startVolume} = $startVolume;
  491. $hash->{helper}{fading}{targetVolume} = $targetVolume;
  492. $hash->{helper}{fading}{requiredSteps} = $requiredSteps;
  493. $hash->{helper}{fading}{iteration} = 0;
  494. $hash->{helper}{fading}{duration} = $duration;
  495. $hash->{helper}{fading}{device_id} = $device_id;
  496. Spotify_volumeFadeStep($hash);
  497. return undef;
  498. }
  499. sub Spotify_togglePlayback($) { # toggle playback (pause if active, resume otherwise)
  500. my ($hash) = @_;
  501. my $name = $hash->{NAME};
  502. Log3 $name, 4, "$name: togglePlayback";
  503. if($hash->{helper}{is_playing}) {
  504. Spotify_pausePlayback($hash);
  505. } else {
  506. Spotify_resumePlayback($hash, undef);
  507. }
  508. return undef;
  509. }
  510. sub Spotify_volumeStep($$$$) {
  511. my ($hash, $direction, $step, $device_id) = @_;
  512. my $name = $hash->{NAME};
  513. $device_id = $step . (defined $device_id ? " ". $device_id : "") if(defined $step && $step !~ /^[0-9]+$/);
  514. $step = $attr{$name}{volumeStep} if(!defined $step || $step !~ /^[0-9]+$/);
  515. $step = 5 if(!defined $step);
  516. my $nextVolume = undef;
  517. if(defined $device_id) {
  518. my @devices = @{$hash->{helper}{devices}};
  519. foreach my $device (@devices) {
  520. if(defined $device->{id} && $device->{id} eq $device_id) {
  521. $nextVolume = min(100, max(0, $device->{volume_percent} + $step * $direction));
  522. $device->{volume_percent} = $nextVolume;
  523. }
  524. }
  525. } else {
  526. $nextVolume = min(100, max(0, $hash->{helper}{device_active}{volume_percent} + $step * $direction));
  527. $hash->{helper}{device_active}{volume_percent} = $nextVolume;
  528. }
  529. return "could not find device" if(!defined $nextVolume);
  530. Spotify_setVolume($hash, 0, $nextVolume, $device_id);
  531. return undef;
  532. }
  533. sub Spotify_getTargetDeviceID { # resolve target device settings
  534. my ($hash, $device_id, $newPlayback) = @_;
  535. my $name = $hash->{NAME};
  536. if(defined $device_id) { # use device id given by user
  537. foreach my $device (@{$hash->{helper}{devices}}) {
  538. return $device->{id} if((defined $device->{id} && $device->{id} eq $device_id) || (defined $device->{name} && lc($device->{name}) eq lc($device_id))); # resolve name to / verify device_id
  539. }
  540. # if not verified, continue to look for target device
  541. }
  542. # no specific device given by user for this command
  543. return Spotify_getTargetDeviceID($hash, $attr{$name}{defaultPlaybackDeviceID}, $newPlayback) if(defined $attr{$name}{defaultPlaybackDeviceID} # use default device or active device
  544. && (
  545. (
  546. defined $attr{$name}{alwaysStartOnDefaultDevice}
  547. && (!$hash->{helper}{is_playing} || $newPlayback)
  548. && $attr{$name}{alwaysStartOnDefaultDevice}
  549. )
  550. || !defined $hash->{helper}{device_active}{id}
  551. )
  552. && (!defined $device_id || $attr{$name}{defaultPlaybackDeviceID} ne $device_id)
  553. );
  554. # no default or active device available
  555. return $hash->{helper}{devices}[0]{id} if($newPlayback && !defined $hash->{helper}{device_active}{id}); # use first device available device on new playback
  556. # if no new playback, trust the user anyway (maybe the device list is outdated)
  557. return undef;
  558. }
  559. sub Spotify_getTransferTargetDeviceID($$) { # get target device id for transfer
  560. my ($hash, $targetdevice_id) = @_;
  561. my $device_id = Spotify_getTargetDeviceID($hash, $targetdevice_id, 1); # resolve to user settings
  562. return $device_id if(defined $targetdevice_id || (defined $device_id && $device_id ne $hash->{helper}{device_active}{id})); # only return if device was specified in command or default device is not active
  563. # target device not found, no (inactive) default device available
  564. Spotify_updateDevices($hash, 1); # make sure devices are up to date
  565. # choose any device that is not active
  566. foreach my $device (@{$hash->{helper}{devices}}) {
  567. return $device->{id} if(!$device->{is_active});
  568. }
  569. return undef;
  570. }
  571. sub Spotify_volumeFadeStep { # do a single fading stemp
  572. my ($hash) = @_;
  573. return if(!defined $hash->{helper}{fading});
  574. my $name = $hash->{NAME};
  575. my $iteration = $hash->{helper}{fading}{iteration};
  576. my $requiredSteps = $hash->{helper}{fading}{requiredSteps};
  577. my $startVolume = $hash->{helper}{fading}{startVolume};
  578. my $targetVolume = $hash->{helper}{fading}{targetVolume};
  579. my $step = $hash->{helper}{fading}{step};
  580. my $isLastStep = $iteration+1 >= $requiredSteps;
  581. my $nextVolume = int($isLastStep ? $targetVolume : $startVolume + ($iteration+1)*$step*($targetVolume < $startVolume ? -1 : 1));
  582. my $deltaBetweenSteps = ($hash->{helper}{fading}{duration}/$requiredSteps); # time in s between each step
  583. #Log3 "spotify", 3, "fading volume step start $startVolume target $targetVolume steps $requiredSteps step $step nextVolume $nextVolume iteration $iteration delta $deltaBetweenSteps";
  584. return if($nextVolume < 0 || $nextVolume > 100);
  585. $hash->{helper}{fading}{iteration}++;
  586. Spotify_setVolume($hash, 0, $nextVolume, $hash->{helper}{fading}{device_id});
  587. if(!$isLastStep) {
  588. InternalTimer(gettimeofday()+$deltaBetweenSteps*($iteration+1), 'Spotify_volumeFadeStep', $hash);
  589. }
  590. delete $hash->{helper}{fading} if($isLastStep);
  591. return undef;
  592. }
  593. sub Spotify_dispatch($$$) {
  594. my ($param, $err, $data) = @_;
  595. my $hash = $param->{hash};
  596. my $name = $hash->{NAME};
  597. my ($path) = split('\?', $param->{apiPath}, 2);
  598. my ($pathpt0, $pathpt1, $pathpt2) = split('/', $path, 3);
  599. my $method = $param->{method};
  600. delete $hash->{helper}{dispatch};
  601. if(!defined($param->{hash})){
  602. Log3 "Spotify", 2, 'Spotify: dispatch fail (hash missing)';
  603. return undef;
  604. }
  605. my $json = eval { JSON->new->utf8(0)->decode($data) };
  606. $hash->{helper}{dispatch}{json} = $json;
  607. #Log3 $name, 3, $name . ' : ' . $hash . $data;
  608. if(defined $json->{error}) {
  609. Log3 $name, 3, "$name: request failed: $json->{error}{message}";
  610. return Spotify_refreshToken($hash) if($json->{error}{message} =~ /expired/);
  611. readingsBeginUpdate($hash);
  612. readingsBulkUpdate($hash, 'error_code', $json->{error}{status}, 1);
  613. readingsBulkUpdate($hash, 'error_description', $json->{error}{message}, 1);
  614. readingsEndUpdate($hash, 1);
  615. return "request failed: $json->{error}{message}";
  616. }
  617. Log3 $name, 4, "$name: dispatch successful $path";
  618. if($path eq 'me/') {
  619. return 'could not get user data' if(!defined $json->{id});
  620. $hash->{helper}{user_id} = $json->{id};
  621. $hash->{helper}{subscription} = $json->{product};
  622. $hash->{helper}{uri} = $json->{uri};
  623. readingsBeginUpdate($hash);
  624. readingsBulkUpdateIfChanged($hash, 'user_id', $json->{id}, 1);
  625. readingsBulkUpdateIfChanged($hash, 'user_country', $json->{country}, 1);
  626. readingsBulkUpdateIfChanged($hash, 'user_subscription', $json->{subscription}, 1);
  627. readingsBulkUpdateIfChanged($hash, 'user_display_name', $json->{display_name}, 1);
  628. readingsBulkUpdateIfChanged($hash, 'user_profile_pic_url', $json->{images}[0]{url}, 1) if(defined $json->{images} && $json->{images} > 0);
  629. readingsBulkUpdateIfChanged($hash, 'user_follower_cnt', $json->{followers}{total}, 1);
  630. readingsEndUpdate($hash, 1);
  631. }
  632. if($path eq 'me/player/devices') {
  633. return 'could not update devices' if(!defined $json->{devices});
  634. delete $hash->{helper}{device_active};
  635. # delete any devices that are out of bounds
  636. if(defined $hash->{helper}{devices}) {
  637. my $index = 1;
  638. foreach my $device (@{$hash->{helper}{devices}}) {
  639. if($index > @{$json->{devices}}) {
  640. CommandDeleteReading(undef, "$name device_". $index ."_.*");
  641. }
  642. $index++;
  643. }
  644. } else {
  645. CommandDeleteReading(undef, "$name device_.*");
  646. }
  647. $hash->{helper}{devices} = $json->{devices};
  648. readingsBeginUpdate($hash);
  649. my $index = 1;
  650. foreach my $device (@{$hash->{helper}{devices}}) {
  651. Spotify_saveDevice($hash, $device, "device_". $index, 0);
  652. if($device->{is_active}) {
  653. Spotify_saveDevice($hash, $device, "device_active", 0);
  654. readingsBulkUpdateIfChanged($hash, 'volume', $device->{volume_percent});
  655. $hash->{helper}{device_active} = $device; # found active device
  656. }
  657. $hash->{helper}{device_default} = $device if(defined $attr{$name}{defaultPlaybackDeviceID} && $device->{id} eq $attr{$name}{defaultPlaybackDeviceID}); # found users default device
  658. $index++;
  659. }
  660. readingsBulkUpdateIfChanged($hash, 'devices_cnt', $index-1, 1);
  661. $hash->{helper}{is_active} = defined $hash->{helper}{device_active};
  662. if(!$hash->{helper}{is_active}) {
  663. Spotify_saveDevice($hash, {id => "none", "name" => "none", "volume_percent" => -1, "type" => "none"}, 'device_active', 0);
  664. $hash->{STATE} = "connected";
  665. readingsBulkUpdateIfChanged($hash, 'is_playing', 0, 1);
  666. }
  667. readingsEndUpdate($hash, 1);
  668. }
  669. if($path eq 'me/player') {
  670. if(!defined $json->{is_playing}) {
  671. $hash->{STATE} = 'connected';
  672. $hash->{helper}{is_playing} = 0;
  673. readingsSingleUpdate($hash, 'is_playing', 0, 1);
  674. return undef;
  675. }
  676. $hash->{helper}{is_active} = defined $json->{device} && $json->{device}{is_active};
  677. $hash->{helper}{is_playing} = $json->{is_playing} && $hash->{helper}{is_active};
  678. $hash->{helper}{repeat} = $json->{repeat_state} eq 'track' ? 'one' : ($json->{repeat_state} eq 'context' ? 'all' : 'off');
  679. $hash->{helper}{shuffle} = $json->{shuffle_state};
  680. $hash->{helper}{progress_ms} = $json->{progress_ms};
  681. $hash->{STATE} = $json->{is_playing} ? 'playing' : 'paused';
  682. readingsBeginUpdate($hash);
  683. readingsBulkUpdateIfChanged($hash, 'is_playing', $hash->{helper}{is_playing} ? 1 : 0, 1);
  684. readingsBulkUpdateIfChanged($hash, 'shuffle', $json->{shuffle_state} ? 'on' : 'off', 1);
  685. readingsBulkUpdateIfChanged($hash, 'repeat', $hash->{helper}{repeat}, 1);
  686. readingsBulkUpdateIfChanged($hash, 'progress_ms', $json->{progress_ms}, 1);
  687. readingsBulkUpdateIfChanged($hash, "progress", h2hms_fmt($json->{progress_ms} / 1000 / 60 / 60), 1);
  688. if(defined $json->{item}) {
  689. my $item = $json->{item};
  690. $hash->{helper}{track} = $item;
  691. Spotify_saveTrack($hash, $item, 'track', 0);
  692. } else {
  693. CommandDeleteReading(undef, "$name track_.*");
  694. }
  695. if($hash->{helper}{is_active}) {
  696. my $device = $json->{device};
  697. $hash->{helper}{device_active} = $device;
  698. readingsBulkUpdateIfChanged($hash, 'volume', $device->{volume_percent});
  699. Spotify_saveDevice($hash, $device, "device_active", 0);
  700. } else {
  701. delete $hash->{helper}{device_active};
  702. Spotify_saveDevice($hash, {id => "none", "name" => "none", "volume_percent" => -1, "type" => "none"}, 'device_active', 0);
  703. $hash->{STATE} = 'connected' if(!defined $json->{device});
  704. }
  705. if($hash->{helper}{is_playing}) {
  706. if(!defined $hash->{helper}{updatePlaybackTimer_next} || $hash->{helper}{updatePlaybackTimer_next} <= gettimeofday()) { # start refresh timer if not already started
  707. my $updateIntervalWhilePlaying = $attr{updateIntervalWhilePlaying};
  708. $updateIntervalWhilePlaying = 10 if(!defined $updateIntervalWhilePlaying);
  709. $hash->{helper}{updatePlaybackTimer_next} = gettimeofday()+$updateIntervalWhilePlaying; # refresh playback status every 15 seconds if currently playing
  710. InternalTimer($hash->{helper}{updatePlaybackTimer_next}, 'Spotify_updatePlaybackStatus', $hash);
  711. }
  712. if(defined $json->{item} && (!defined $hash->{helper}{nextSongTimer} || $hash->{helper}{nextSongTimer} <= gettimeofday())) { # refresh on finish of the song
  713. $hash->{helper}{nextSongTimer} = gettimeofday() + int(($json->{item}{duration_ms} - $json->{progress_ms}) / 1000) + 1;
  714. InternalTimer($hash->{helper}{nextSongTimer}, "Spotify_updatePlaybackStatus", $hash);
  715. }
  716. }
  717. readingsEndUpdate($hash, 1);
  718. return undef;
  719. }
  720. if($path eq 'me/player/volume') {
  721. Spotify_updateDevices($hash, 0) if(!defined $hash->{helper}{fading});
  722. return undef; # do not fall through
  723. }
  724. if(defined $pathpt1 && $pathpt1 eq 'player' && $method ne 'GET') { # on every modification on the player, update playback status
  725. Spotify_updatePlaybackStatus($hash, 1);
  726. InternalTimer(gettimeofday()+2, 'Spotify_updatePlaybackStatus', $hash); # make sure the api is already up to date and lists the changes
  727. }
  728. return undef;
  729. }
  730. sub Spotify_poll($) {
  731. my ($hash) = @_;
  732. my $name = $hash->{NAME};
  733. return if(Spotify_isDisabled($hash));
  734. my $pollInterval = $attr{$name}{updateInterval};
  735. InternalTimer(gettimeofday()+(defined $pollInterval ? $pollInterval : 5*60), "Spotify_poll", $hash);
  736. Spotify_update($hash, 0);
  737. }
  738. sub Spotify_update($$) {
  739. my ($hash, $full) = @_;
  740. Spotify_updateMe($hash, 0) if($full);
  741. Spotify_updateDevices($hash, 0);
  742. Spotify_updatePlaybackStatus($hash, 0);
  743. }
  744. sub Spotify_saveTrack($$$$) { # save a track object to the readings
  745. my ($hash, $track, $prefix, $beginUpdate) = @_;
  746. readingsBeginUpdate($hash) if($beginUpdate);
  747. readingsBulkUpdateIfChanged($hash, $prefix."_name", $track->{name}, 1);
  748. readingsBulkUpdateIfChanged($hash, $prefix."_uri", $track->{uri}, 1);
  749. readingsBulkUpdateIfChanged($hash, $prefix."_popularity", $track->{popularity}, 1);
  750. readingsBulkUpdateIfChanged($hash, $prefix."_duration_ms", $track->{duration_ms}, 1);
  751. readingsBulkUpdateIfChanged($hash, $prefix."_artist_name", $track->{artists}[0]{name}, 1);
  752. readingsBulkUpdateIfChanged($hash, $prefix."_artist_uri", $track->{artists}[0]{uri}, 1);
  753. readingsBulkUpdateIfChanged($hash, $prefix."_album_name", $track->{album}{name}, 1);
  754. readingsBulkUpdateIfChanged($hash, $prefix."_album_uri", $track->{album}{uri}, 1);
  755. readingsBulkUpdateIfChanged($hash, $prefix."_duration", h2hms_fmt($track->{duration_ms} / 1000 / 60 / 60), 1);
  756. my @sizes = ("large", "medium", "small");
  757. my $index = 0;
  758. foreach my $image(@{$track->{album}{images}}) {
  759. readingsBulkUpdateIfChanged($hash, $prefix."_album_cover_". $sizes[$index], $image->{url}, 1);
  760. $index++;
  761. last if($index >= 3);
  762. }
  763. readingsEndUpdate($hash, 1) if($beginUpdate);
  764. }
  765. sub Spotify_saveArtist($$$$) { # save an artist object to the readings
  766. my ($hash, $artist, $prefix, $beginUpdate) = @_;
  767. readingsBeginUpdate($hash) if($beginUpdate);
  768. readingsBulkUpdate($hash, $prefix."_name", $artist->{name}, 1);
  769. readingsBulkUpdate($hash, $prefix."_uri", $artist->{uri}, 1);
  770. readingsBulkUpdate($hash, $prefix."_popularity", $artist->{popularity}, 1);
  771. readingsBulkUpdate($hash, $prefix."_follower_cnt", $artist->{followers}{total}, 1);
  772. readingsBulkUpdate($hash, $prefix."_profile_pic_url", $artist->{images}[0]{url}, 1);
  773. readingsEndUpdate($hash, 1) if($beginUpdate);
  774. }
  775. sub Spotify_saveDevice($$$$) {
  776. my ($hash, $device, $prefix, $beginUpdate) = @_;
  777. readingsBeginUpdate($hash) if($beginUpdate);
  778. readingsBulkUpdateIfChanged($hash, $prefix . '_id', $device->{id}, 1);
  779. readingsBulkUpdateIfChanged($hash, $prefix . '_name', $device->{name}, 1);
  780. readingsBulkUpdateIfChanged($hash, $prefix . '_type', $device->{type}, 1);
  781. readingsBulkUpdateIfChanged($hash, $prefix . '_volume', $device->{volume_percent}, 1) if(defined $device->{volume_percent});
  782. readingsEndUpdate($hash, 1) if($beginUpdate);
  783. }
  784. sub Spotify_isDisabled($) {
  785. my ($hash) = @_;
  786. my $name = $hash->{NAME};
  787. return defined $attr{$name}{disable};
  788. }
  789. 1;
  790. =pod
  791. =item device
  792. =item summary control your Spotify (Connect) playback
  793. =item summary_DE Steuerung von Spotify (Connect)
  794. =begin html
  795. <a name="Spotify"></a>
  796. <h3>Spotify</h3>
  797. <ul>
  798. The <i>Spotify</i> module enables you to control your Spotify (Connect) playback.<br>
  799. To be able to control your music, you need to authorize with the Spotify WEB API. To do that, a <a target="_blank" rel="nofollow" href="https://developer.spotify.com/my-applications/#!/applications/create">Spotify API application</a> is required.<br>
  800. While creating the app, enter any <i>redirect_uri</i>. By default the module will use <a href="https://oskar.pw/" target="_blank">https://oskar.pw/</a> as <i>redirect_uri</i> since the site outputs your temporary authentification code.<br>
  801. It is safe to rely on this site because the code is useless without your client secret and only valid for a few minutes (important: you have to press the <b>add</b> and <b>save</b> button while adding the url).<br>
  802. If you want to use it, make sure to add it as <i>redirect_uri</i> to your app - however, you are free to use any other url and extract the code after signing in yourself.<br>
  803. <br>
  804. <a name="Spotify_define"></a>
  805. <p><b>Define</b></p>
  806. <ul>
  807. <code>define &lt;name&gt; Spotify &lt;client_id&gt; &lt;client_secret&gt; [ &lt;redirect_url&gt; ]</code><br>
  808. </ul>
  809. <br>
  810. <ul>
  811. Example: <code>define Spotify Spotify f88e5f5c2911152d914391592e717738 301b6d1a245e4fe01c2f8b4efd250756</code><br>
  812. </ul>
  813. <br>
  814. Once defined, open up your browser and call the URL displayed in <i>AUTHORIZATION_URL</i>, sign in with spotify and extract the code after being redirected.<br>
  815. If you get a <b>redirect_uri mismatch</b> make sure to either add <a href="https://oskar.pw/" target="_blank">https://oskar.pw/</a> as redirect url or that your url <b>matches exactly</b> with the one defined.<br>
  816. As soon as you obtained the code call <code>set &lt;name&gt; code &lt;code&gt;</code> - your state should change to connected and you are ready to go.<br>
  817. <br>
  818. <a name="Spotify_set"></a>
  819. <p><b>set &lt;required&gt; [ &lt;optional&gt; ]</b></p>
  820. Without a target device given, the active device (or default device if <i>alwaysStartOnDefaultDevice</i> is enabled) will be used.<br>
  821. You can also use the name of the target device instead of the id if it does not contain spaces - where it states <i>&lt;device_id / device_name&gt;</i> spaces are allowed.<br>
  822. If no default device is defined and none is active, it will use the first available device.<br>
  823. You can get a spotify uri by pressing the share button in the spotify (desktop) app on a track/playlist/album.<br><br>
  824. <ul>
  825. <li>
  826. <i>findArtistByName</i><br>
  827. finds an artist using its name and returns the result to the readings
  828. </li>
  829. <li>
  830. <i>findTrackByName</i><br>
  831. finds a track using its name and returns the result to the readings
  832. </li>
  833. <li>
  834. <i>pause</i><br>
  835. pause the current playback
  836. </li>
  837. <li>
  838. <i>playArtistByName &lt;artist_name&gt; [ &lt;device_id&gt; ]</i><br>
  839. plays an artist using its name (uses search)
  840. </li>
  841. <li>
  842. <i>playContextByURI &lt;context_uri&gt; [ &lt;nr_of_start_track&gt; ] [ &lt;device_id / device_name&gt; ]</i><br>
  843. plays a context (playlist, album or artist) using a Spotify URI
  844. </li>
  845. <li>
  846. <i>playPlaylistByName &lt;playlist_name&gt; [ &lt;device_id&gt; ]</i><br>
  847. plays any playlist by providing a name (uses search)
  848. </li>
  849. <li>
  850. <i>playRandomTrackFromPlaylistByURI &lt;playlist_uri&gt; [ &lt;limit&gt; ] [ &lt;device_id / device_name&gt; ]</i><br>
  851. plays a random track from a playlist (only considering the first <i>&lt;limit&gt;</i> songs)
  852. </li>
  853. <li>
  854. <i>playSavedTracks [ &lt;nr_of_start_track&gt; ] [ &lt;device_id / device_name&gt; ]</i><br>
  855. plays the saved tracks (beginning with track <i>&lt;nr_of_start_track&gt;</i>)
  856. </li>
  857. <li>
  858. <i>playTrackByName &lt;track_name&gt; [ &lt;device_id&gt; ]</i><br>
  859. finds a song by its name and plays it
  860. </li>
  861. <li>
  862. <i>playTrackByURI &lt;track_uri&gt; [ &lt;device_id / device_name&gt; ]</i><br>
  863. plays a track using a track uri
  864. </li>
  865. <li>
  866. <i>repeat &lt;track,context,off&gt;</i><br>
  867. sets the repeat mode: either <i>one</i>, <i>all</i> (meaning playlist or album) or <i>off</i>
  868. </li>
  869. <li>
  870. <i>resume [ &lt;device_id / device_name&gt; ]</i><br>
  871. resumes playback (on a device)
  872. </li>
  873. <li>
  874. <i>seekToPosition &lt;position&gt;</i><br>
  875. seeks to the position <i>&lt;position&gt;</i> (in seconds, supported formats: 01:20, 80, 00:20, 20)
  876. </li>
  877. <li>
  878. <i>shuffle &lt;off,on&gt;</i><br>
  879. sets the shuffle mode: either <i>on</i> or <i>off</i>
  880. </li>
  881. <li>
  882. <i>skipToNext</i><br>
  883. skips to the next track
  884. </li>
  885. <li>
  886. <i>skipToPrevious</i><br>
  887. skips to the previous track
  888. </li>
  889. <li>
  890. <i>togglePlayback</i><br>
  891. toggles the playback (resumes if paused, pauses if playing)
  892. </li>
  893. <li>
  894. <i>transferPlayback [ &lt;device_id&gt; ]</i><br>
  895. transfers the current playback to the specified device (or the next inactive device if not specified)
  896. </li>
  897. <li>
  898. <i>update</i><br>
  899. updates playback and devices
  900. </li>
  901. <li>
  902. <i>volume &lt;volume&gt; [ &lt;device_id&gt; ]</i><br>
  903. sets the volume
  904. </li>
  905. <li>
  906. <i>volumeDown [ &lt;step&gt; ] [ &lt;device_id / device_name&gt; ]</i><br>
  907. decreases the volume by <i>step</i> (if not set it uses <i>volumeStep</i>)
  908. </li>
  909. <li>
  910. <i>volumeFade &lt;volume&gt; [ &lt;duration&gt; &lt;step&gt; ] [ &lt;device_id&gt; ]</i><br>
  911. fades the volume
  912. </li>
  913. <li>
  914. <i>volumeDown [ &lt;step&gt; ] [ &lt;device_id / device_name&gt; ]</i><br>
  915. increases the volume by <i>step</i> (if not set it uses <i>volumeStep</i>)
  916. </li>
  917. </ul>
  918. <br>
  919. <a name="Spotify_get"></a>
  920. <p><b>Get</b></p>
  921. <ul>
  922. N/A
  923. </ul>
  924. <br>
  925. <a name="Spotify_attr"></a>
  926. <p><b>Attributes</b></p>
  927. <ul>
  928. <li>
  929. <i>alwaysStartOnDefaultDevice</i><br>
  930. always start new playback on the default device<br>
  931. default: 0
  932. </li>
  933. <li>
  934. <i>defaultPlaybackDeviceID</i><br>
  935. the prefered device by its id or device name<br>
  936. </li>
  937. <li>
  938. <i>disable</i><br>
  939. disables the device<br>
  940. default: 0
  941. </li>
  942. <li>
  943. <i>updateInterval</i><br>
  944. the interval to update your playback status while no music is running (in seconds)<br>
  945. default: 300
  946. </li>
  947. <li>
  948. <i>updateIntervalWhilePlaying</i><br>
  949. the interval to update your playback status while music is running (in seconds)<br>
  950. default: 10
  951. </li>
  952. <li>
  953. <i>volumeStep</i><br>
  954. the value by which the volume is in-/decreased by default (in percent)<br>
  955. default: 5
  956. </li>
  957. </ul>
  958. </ul>
  959. =end html
  960. =begin html_DE
  961. <a name="Spotify"></a>
  962. <h3>Spotify</h3>
  963. <ul>
  964. Das <i>Spotify</i> Modul ermöglicht die Steuerung von Spotify (Connect).<br>
  965. Um die Wiedergabe zu steuern, wird die Spotify WEB API verwendet. Dafür wird eine eigene <a target="_blank" rel="nofollow" href="https://developer.spotify.com/my-applications/#!/applications/create">Spotify API application</a> benötigt.<br>
  966. Während der Erstellung muss eine <i>redirect_uri</i> angegeben - standardmäßig wird vom Modul <a href="https://oskar.pw/" target="_blank">https://oskar.pw/</a> verwendet, da diese Seite nach der Anmeldung den Code in leserlicher Form ausgibt.<br>
  967. Die Seite kann bedenkenlos verwendet werden, da der Code ohne <i>client_secret</i> nutzlos und nur wenige Minuten gültig ist.<br>
  968. Wenn du diese verwenden willst, stelle sicher, diese bei der Erstellung anzugeben (wichtig: das Hinzufügen der URL muss mit <b>add</b> und <b>save</b> bestätigt werden), ansonsten kann jede beliebige andere Seite verwendet werden und der Code aus der URL extrahiert werden.<br>
  969. <br>
  970. <a name="Spotify_define"></a>
  971. <p><b>Define</b></p>
  972. <ul>
  973. <code>define &lt;name&gt; Spotify &lt;client_id&gt; &lt;client_secret&gt; [ &lt;redirect_url&gt; ]</code><br>
  974. </ul>
  975. <br>
  976. <ul>
  977. Beispiel: <code>define Spotify Spotify f88e5f5c2911152d914391592e717738 301b6d1a245e4fe01c2f8b4efd250756</code><br>
  978. </ul>
  979. <br>
  980. Sobald das Gerät angelegt wurde, muss die <i>AUTHORIZATION_URL</i> im Browser geöffnet werden und die Anmeldung mit Spotify erfolgen.<br>
  981. Sollte der Fehler <b>redirect_uri mismatch</b> auftauchen, stelle sicher, dass <a href="https://oskar.pw/" target="_blank">https://oskar.pw/</a> als <i>redirect_uri</i> hinzugefügt wurde oder die verwendete URL <b>exakt übereinstimmt</b>.<br>
  982. Sobald der Anmeldecode ermittelt wurde, führe folgenden Befehl aus: <code>set &lt;name&gt; code &lt;code&gt;</code> - der Status sollte nun auf connected wechseln und das Gerät ist einsatzbereit.<br>
  983. <br>
  984. <a name="Spotify_set"></a>
  985. <p><b>set &lt;required&gt; [ &lt;optional&gt; ]</b></p>
  986. Wird kein Zielgerät angegeben, wird das aktive (oder das Standard-Gerät, wenn <i>alwaysStartOnDefaultDevice</i> aktiviert ist) verwendet.<br>
  987. An den Stellen, wo eine <i>&lt;device_id&gt;</i> verlangt wird, kann auch der Gerätename, sofern dieser keine Leerzeichen enthält, verwendet werden. Dort wo es <i>&lt;device_name&gt;</i> heißt, sind auch Leerzeichen im Namen zugelassen.
  988. Wenn kein aktives oder Standard-Gerät vorhanden ist, wird das erste verfügbare Gerät verwendet.<br>
  989. Die Spotify URI kann in der (Desktop) App ermittelt werden, wenn man den teilen Knopf bei einem Track/Playlist/Album drückt.<br><br>
  990. <ul>
  991. <li>
  992. <i>findArtistByName</i><br>
  993. sucht einen Künstler und liefert das Ergebnis in den Readings
  994. </li>
  995. <li>
  996. <i>findTrackByName</i><br>
  997. sucht einen Track und liefert das Ergebnis in den Readings
  998. </li>
  999. <li>
  1000. <i>pause</i><br>
  1001. pausiert die aktuelle Wiedergabe
  1002. </li>
  1003. <li>
  1004. <i>playArtistByName &lt;artist_name&gt; [ &lt;device_id&gt; ]</i><br>
  1005. sucht einen Künstler und spielt dessen Tracks ab
  1006. </li>
  1007. <li>
  1008. <i>playContextByURI &lt;context_uri&gt; [ &lt;nr_of_start_track&gt; ] [ &lt;device_id / device_name&gt; ]</i><br>
  1009. spielt einen Context (Playlist, Album oder Künstler) durch Angabe der URI ab
  1010. </li>
  1011. <li>
  1012. <i>playPlaylistByName &lt;playlist_name&gt; [ &lt;device_id&gt; ]</i><br>
  1013. sucht eine Playlist und spielt diese ab
  1014. </li>
  1015. <li>
  1016. <i>playRandomTrackFromPlaylistByURI &lt;playlist_uri&gt; [ &lt;limit&gt; ] [ &lt;device_id / device_name&gt; ]</i><br>
  1017. spielt einen zufälligen Track aus einer Playlist ab (berücksichtigt nur die ersten <i>&lt;limit&gt;</i> Tracks der Playlist)
  1018. </li>
  1019. <li>
  1020. <i>playSavedTracks [ &lt;nr_of_start_track&gt; ] [ &lt;device_id / device_name&gt; ]</i><br>
  1021. spielt die gespeicherten Tracks ab (beginnend mit Track Nummer <i>&lt;nr_of_start_track&gt;</i>)
  1022. </li>
  1023. <li>
  1024. <i>playTrackByName &lt;track_name&gt; [ &lt;device_id&gt; ]</i><br>
  1025. sucht den Song und spielt ihn ab
  1026. </li>
  1027. <li>
  1028. <i>playTrackByURI &lt;track_uri&gt; [ &lt;device_id / device_name&gt; ]</i><br>
  1029. spielt einen Song durch Angabe der URI ab
  1030. </li>
  1031. <li>
  1032. <i>repeat &lt;track,context,off&gt;</i><br>
  1033. setzt den Wiederholungsmodus: entweder <i>one</i>, <i>all</i> (Playlist, Album, Künstler) oder <i>off</i>
  1034. </li>
  1035. <li>
  1036. <i>resume [ &lt;device_id / device_name&gt; ]</i><br>
  1037. fährt mit der Wiedergabe (auf einem Gerät) fort
  1038. </li>
  1039. <li>
  1040. <i>seekToPosition &lt;position&gt;</i><br>
  1041. spult an die Position <i>&lt;position&gt;</i> (in Sekunden, erlaubte Formate: 01:20, 80, 00:20, 20)
  1042. </li>
  1043. <li>
  1044. <i>shuffle &lt;off,on&gt;</i><br>
  1045. setzt den Shuffle-Modus: entweder <i>on</i> oder <i>off</i>
  1046. </li>
  1047. <li>
  1048. <i>skipToNext</i><br>
  1049. weiter zum nächsten Track
  1050. </li>
  1051. <li>
  1052. <i>skipToPrevious</i><br>
  1053. zurück zum vorherigen Track
  1054. </li>
  1055. <li>
  1056. <i>togglePlayback</i><br>
  1057. toggelt die Wiedergabe (hält an, wenn sie aktiv ist, ansonsten fortsetzen)
  1058. </li>
  1059. <li>
  1060. <i>transferPlayback [ &lt;device_id&gt; ]</i><br>
  1061. überträgt die aktuelle Wiedergabe auf ein anderes Gerät (wenn kein Gerät angegeben wird, wird das nächste inaktive verwendet)
  1062. </li>
  1063. <li>
  1064. <i>update</i><br>
  1065. lädt den aktuellen Zustand neu
  1066. </li>
  1067. <li>
  1068. <i>volume &lt;volume&gt; [ &lt;device_id&gt; ]</i><br>
  1069. setzt die Lautstärke
  1070. </li>
  1071. <li>
  1072. <i>volumeDown [ &lt;step&gt; ] [ &lt;device_id / device_name&gt; ]</i><br>
  1073. verringert die Lautstärke um <i>step</i> (falls nicht gesetzt, um <i>volumeStep</i>)
  1074. </li>
  1075. <li>
  1076. <i>volumeFade &lt;volume&gt; [ &lt;duration&gt; &lt;step&gt; ] [ &lt;device_id&gt; ]</i><br>
  1077. setzt die Lautstärke schrittweise
  1078. </li>
  1079. <li>
  1080. <i>volumeUp [ &lt;step&gt; ] [ &lt;device_id / device_name&gt; ]</i><br>
  1081. erhöht die Lautstärke um <i>step</i> (falls nicht gesetzt, um <i>volumeStep</i>)
  1082. </li>
  1083. </ul>
  1084. <br>
  1085. <a name="Spotify_get"></a>
  1086. <p><b>Get</b></p>
  1087. <ul>
  1088. N/A
  1089. </ul>
  1090. <br>
  1091. <a name="Spotify_attr"></a>
  1092. <p><b>Attributes</b></p>
  1093. <ul>
  1094. <li>
  1095. <i>alwaysStartOnDefaultDevice</i><br>
  1096. startet neue Wiedergabe immer auf dem Standard-Gerät<br>
  1097. default: 0
  1098. </li>
  1099. <li>
  1100. <i>defaultPlaybackDeviceID</i><br>
  1101. das Standard-Gerät durch Angabe der Geräte-ID oder des Geräte-Namens<br>
  1102. </li>
  1103. <li>
  1104. <i>disable</i><br>
  1105. deaktiviert das Gerät<br>
  1106. default: 0
  1107. </li>
  1108. <li>
  1109. <i>updateInterval</i><br>
  1110. Intervall in Sekunden, in dem der Status aktualisiert wird, wenn keine Musik läuft<br>
  1111. default: 300
  1112. </li>
  1113. <li>
  1114. <i>updateIntervalWhilePlaying</i><br>
  1115. Intervall in Sekunden, in dem der Status aktualisiert wird, wenn Musik läuft<br>
  1116. default: 10
  1117. </li>
  1118. <li>
  1119. <i>volumeStep</i><br>
  1120. der Wert, um den die Lautstärke bei volumeUp/volumeDown standardmäßig verändert wird (in Prozent)<br>
  1121. default: 5
  1122. </li>
  1123. </ul>
  1124. </ul>
  1125. =end html_DE
  1126. =cut