Plugin.pm 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247
  1. package Plugins::SqueezeESP32::Plugin;
  2. use strict;
  3. use base qw(Slim::Plugin::Base);
  4. use File::Basename qw(basename);
  5. use File::Spec::Functions qw(catfile);
  6. use JSON::XS::VersionOneAndTwo;
  7. use Slim::Utils::Prefs;
  8. use Slim::Utils::Log;
  9. use Slim::Web::ImageProxy;
  10. my $prefs = preferences('plugin.squeezeesp32');
  11. my $log = Slim::Utils::Log->addLogCategory({
  12. 'category' => 'plugin.squeezeesp32',
  13. 'defaultLevel' => 'INFO',
  14. 'description' => 'PLUGIN_SQUEEZEESP32',
  15. });
  16. use constant GITHUB_ASSET_URI => "https://api.github.com/repos/sle118/squeezelite-esp32/releases/assets/";
  17. use constant GITHUB_DOWNLOAD_URI => "https://github.com/sle118/squeezelite-esp32/releases/download/";
  18. my $FW_DOWNLOAD_ID_REGEX = qr|plugins/SqueezeESP32/firmware/(-?\d+)|;
  19. my $FW_DOWNLOAD_REGEX = qr|plugins/SqueezeESP32/firmware/([-a-z0-9-/.]+\.bin)$|i;
  20. my $FW_FILENAME_REGEX = qr/^squeezelite-esp32-.*\.bin(\.tmp)?$/;
  21. # migrate 'eq' pref, as that's a reserved word and could cause problems in the future
  22. $prefs->migrateClient(1, sub {
  23. my ($cprefs, $client) = @_;
  24. $cprefs->set('equalizer', $cprefs->get('eq'));
  25. $cprefs->remove('eq');
  26. 1;
  27. });
  28. $prefs->migrateClient(2, sub {
  29. my ($cprefs, $client) = @_;
  30. $cprefs->set('artwork', undef) if $cprefs->get('artwork') && ref $cprefs->get('artwork') ne 'HASH';
  31. 1;
  32. });
  33. $prefs->setChange(sub {
  34. $_[2]->send_equalizer;
  35. }, 'equalizer');
  36. sub initPlugin {
  37. my $class = shift;
  38. if ( main::WEBUI ) {
  39. require Plugins::SqueezeESP32::PlayerSettings;
  40. Plugins::SqueezeESP32::PlayerSettings->new;
  41. # require Plugins::SqueezeESP32::Settings;
  42. # Plugins::SqueezeESP32::Settings->new;
  43. }
  44. $class->SUPER::initPlugin(@_);
  45. # no name can be a subset of others due to a bug in addPlayerClass
  46. Slim::Networking::Slimproto::addPlayerClass($class, 100, 'squeezeesp32-basic', { client => 'Plugins::SqueezeESP32::Player', display => 'Plugins::SqueezeESP32::Graphics' });
  47. Slim::Networking::Slimproto::addPlayerClass($class, 101, 'squeezeesp32-graphic', { client => 'Plugins::SqueezeESP32::Player', display => 'Slim::Display::NoDisplay' });
  48. main::INFOLOG && $log->is_info && $log->info("Added class 100 and 101 for SqueezeESP32");
  49. # register a command to set the EQ - without saving the values! Send params as single comma separated list of values
  50. Slim::Control::Request::addDispatch(['squeezeesp32', 'seteq', '_eq'], [1, 0, 0, \&setEQ]);
  51. # Note for some forgetful know-it-all: we need to wrap the callback to make it unique. Otherwise subscriptions would overwrite each other.
  52. Slim::Control::Request::subscribe( sub { onNotification(@_) }, [ ['newmetadata'] ] );
  53. Slim::Control::Request::subscribe( sub { onNotification(@_) }, [ ['playlist'], ['open', 'newsong'] ]);
  54. Slim::Control::Request::subscribe( \&onStopClear, [ ['playlist'], ['stop', 'clear'] ]);
  55. Slim::Web::Pages->addRawFunction($FW_DOWNLOAD_ID_REGEX, \&handleFirmwareDownload);
  56. Slim::Web::Pages->addRawFunction($FW_DOWNLOAD_REGEX, \&handleFirmwareDownloadDirect);
  57. }
  58. sub onStopClear {
  59. my $request = shift;
  60. my $client = $request->client || return;
  61. if ($client->isa('Plugins::SqueezeESP32::Player')) {
  62. $client->clear_artwork(0, $request->getRequestString());
  63. }
  64. }
  65. sub onNotification {
  66. my $request = shift;
  67. my $client = $request->client || return;
  68. foreach my $player ($client->syncGroupActiveMembers) {
  69. next unless $player->isa('Plugins::SqueezeESP32::Player');
  70. $player->update_artwork;
  71. }
  72. }
  73. sub setEQ {
  74. my $request = shift;
  75. # check this is the correct command.
  76. if ($request->isNotCommand([['squeezeesp32'],['seteq']])) {
  77. $request->setStatusBadDispatch();
  78. return;
  79. }
  80. # get our parameters
  81. my $client = $request->client();
  82. my @eqParams = split(/,/, $request->getParam('_eq') || '');
  83. for (my $x = 0; $x < 10; $x++) {
  84. $eqParams[$x] ||= 0;
  85. }
  86. $client->send_equalizer(\@eqParams);
  87. }
  88. sub handleFirmwareDownload {
  89. my ($httpClient, $response) = @_;
  90. my $request = $response->request;
  91. my $_errorDownloading = sub {
  92. _errorDownloading($httpClient, $response, @_);
  93. };
  94. my $id;
  95. if (!defined $request || !(($id) = $request->uri =~ $FW_DOWNLOAD_ID_REGEX)) {
  96. return $_errorDownloading->(undef, 'Invalid request', $request->uri, 400);
  97. }
  98. # this is the magic number used on the client to figure out whether the plugin does support download proxying
  99. if ($id == -99) {
  100. $response->code(204);
  101. $response->header('Access-Control-Allow-Origin' => '*');
  102. $httpClient->send_response($response);
  103. return Slim::Web::HTTP::closeHTTPSocket($httpClient);
  104. }
  105. Slim::Networking::SimpleAsyncHTTP->new(
  106. sub {
  107. my $http = shift;
  108. my $content = eval { from_json( $http->content ) };
  109. if (!$content || !ref $content) {
  110. $@ && $log->error("Failed to parse response: $@");
  111. return $_errorDownloading->($http);
  112. }
  113. elsif (!$content->{browser_download_url} || !$content->{name}) {
  114. return $_errorDownloading->($http, 'No download URL found');
  115. }
  116. downloadAndStreamFirmware($httpClient, $response, $content->{browser_download_url}, $content->{name});
  117. },
  118. $_errorDownloading,
  119. {
  120. timeout => 10,
  121. cache => 1,
  122. expires => 86400
  123. }
  124. )->get(GITHUB_ASSET_URI . $id);
  125. return;
  126. }
  127. sub handleFirmwareDownloadDirect {
  128. my ($httpClient, $response) = @_;
  129. my $request = $response->request;
  130. my $_errorDownloading = sub {
  131. _errorDownloading($httpClient, $response, @_);
  132. };
  133. my $path;
  134. if (!defined $request || !(($path) = $request->uri =~ $FW_DOWNLOAD_REGEX)) {
  135. return $_errorDownloading->(undef, 'Invalid request', $request->uri, 400);
  136. }
  137. main::INFOLOG && $log->is_info && $log->info("Requesting firmware from: $path");
  138. downloadAndStreamFirmware($httpClient, $response, GITHUB_DOWNLOAD_URI . $path);
  139. }
  140. sub downloadAndStreamFirmware {
  141. my ($httpClient, $response, $url, $name) = @_;
  142. my $_errorDownloading = sub {
  143. _errorDownloading($httpClient, $response, @_);
  144. };
  145. $name ||= basename($url);
  146. if ($name !~ $FW_FILENAME_REGEX) {
  147. return $_errorDownloading->(undef, 'Unexpected firmware image name: ' . $name, $url, 400);
  148. }
  149. my $updatesDir = Slim::Utils::OSDetect::dirsFor('updates');
  150. my $firmwareFile = catfile($updatesDir, $name);
  151. Slim::Utils::Misc::deleteFiles($updatesDir, $FW_FILENAME_REGEX, $firmwareFile);
  152. if (-f $firmwareFile) {
  153. main::INFOLOG && $log->is_info && $log->info("Found cached firmware version");
  154. $response->code(200);
  155. return Slim::Web::HTTP::sendStreamingFile($httpClient, $response, 'application/octet-stream', $firmwareFile, undef, 1);
  156. }
  157. Slim::Networking::SimpleAsyncHTTP->new(
  158. sub {
  159. my $http = shift;
  160. if ($http->code != 200 || !-e "$firmwareFile.tmp") {
  161. return $_errorDownloading->($http, $http->mess);
  162. }
  163. rename "$firmwareFile.tmp", $firmwareFile or return $_errorDownloading->($http, "Unable to rename temporary $firmwareFile file" );
  164. $response->code(200);
  165. Slim::Web::HTTP::sendStreamingFile($httpClient, $response, 'application/octet-stream', $firmwareFile, undef, 1);
  166. },
  167. $_errorDownloading,
  168. {
  169. saveAs => "$firmwareFile.tmp",
  170. }
  171. )->get($url);
  172. return;
  173. }
  174. sub _errorDownloading {
  175. my ($httpClient, $response, $http, $error, $url, $code) = @_;
  176. $error ||= ($http && $http->error) || 'unknown error';
  177. $url ||= ($http && $http->url) || 'no URL';
  178. $code ||= ($http && $http->code) || 500;
  179. $log->error(sprintf("Failed to get data from Github: %s (%s)", $error || $http->error, $url));
  180. $response->headers->remove_content_headers;
  181. $response->code($code);
  182. $response->content_type('text/plain');
  183. $response->header('Connection' => 'close');
  184. $response->content('');
  185. $httpClient->send_response($response);
  186. Slim::Web::HTTP::closeHTTPSocket($httpClient);
  187. };
  188. 1;