FirmwareHelper.pm 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245
  1. package Plugins::SqueezeESP32::FirmwareHelper;
  2. use strict;
  3. use File::Basename qw(basename);
  4. use File::Spec::Functions qw(catfile);
  5. use JSON::XS::VersionOneAndTwo;
  6. use Slim::Utils::Log;
  7. use Slim::Utils::Prefs;
  8. use constant FIRMWARE_POLL_INTERVAL => 3600 * (5 + rand());
  9. use constant GITHUB_RELEASES_URI => "https://api.github.com/repos/sle118/squeezelite-esp32/releases";
  10. use constant GITHUB_ASSET_URI => GITHUB_RELEASES_URI . "/assets/";
  11. use constant GITHUB_DOWNLOAD_URI => "https://github.com/sle118/squeezelite-esp32/releases/download/";
  12. use constant ESP32_STATUS_URI => "http://%s/status.json";
  13. my $FW_DOWNLOAD_REGEX = qr|plugins/SqueezeESP32/firmware/([-a-z0-9-/.]+\.bin)$|i;
  14. my $FW_CUSTOM_REGEX = qr/^((?:squeezelite-esp32-)?custom\.bin)$/;
  15. my $FW_FILENAME_REGEX = qr/^squeezelite-esp32-.*\.bin(\.tmp)?$/;
  16. my $FW_TAG_REGEX = qr/\b(ESP32-A1S|SqueezeAmp|I2S-4MFlash)\.(16|32)\.(\d+)\.([-a-zA-Z0-9]+)\b/;
  17. my $prefs = preferences('plugin.squeezeesp32');
  18. my $log = logger('plugin.squeezeesp32');
  19. my $initialized;
  20. sub init {
  21. my ($client) = @_;
  22. if (!$initialized) {
  23. $initialized = 1;
  24. Slim::Web::Pages->addRawFunction($FW_DOWNLOAD_REGEX, \&handleFirmwareDownload);
  25. }
  26. # start checking for firmware updates
  27. Slim::Utils::Timers::setTimer($client, Time::HiRes::time() + 3.0 + rand(3.0), \&initFirmwareDownload);
  28. }
  29. sub initFirmwareDownload {
  30. my ($client) = @_;
  31. Slim::Utils::Timers::killTimers($client, \&initFirmwareDownload);
  32. Slim::Networking::SimpleAsyncHTTP->new(
  33. sub {
  34. my $http = shift;
  35. my $content = eval { from_json( $http->content ) };
  36. if ($content && ref $content) {
  37. my $releaseInfo = _getFirmwareTag($content->{version});
  38. if ($releaseInfo && ref $releaseInfo) {
  39. prefetchFirmware($releaseInfo);
  40. }
  41. }
  42. },
  43. sub {
  44. my ($http, $error) = @_;
  45. $log->error("Failed to get releases from Github: $error");
  46. },
  47. {
  48. timeout => 10
  49. }
  50. )->get(sprintf(ESP32_STATUS_URI, $client->ip));
  51. Slim::Utils::Timers::setTimer($client, Time::HiRes::time() + FIRMWARE_POLL_INTERVAL, \&initFirmwareDownload);
  52. }
  53. sub prefetchFirmware {
  54. my ($releaseInfo) = @_;
  55. return unless $releaseInfo;
  56. Slim::Networking::SimpleAsyncHTTP->new(
  57. sub {
  58. my $http = shift;
  59. my $content = eval { from_json( $http->content ) };
  60. if (!$content || !ref $content) {
  61. $@ && $log->error("Failed to parse response: $@");
  62. }
  63. my $regex = $releaseInfo->{model} . '\.' . $releaseInfo->{res} . '\.\d+\.' . $releaseInfo->{branch};
  64. my $url;
  65. foreach (@$content) {
  66. if ($_->{tag_name} =~ /$regex/ && $_->{assets} && ref $_->{assets}) {
  67. ($url) = grep /\.bin$/, map {
  68. $_->{browser_download_url}
  69. } @{$_->{assets}};
  70. last if $url;
  71. }
  72. }
  73. downloadFirmwareFile(sub {
  74. main::INFOLOG && $log->is_info && $log->info("Pre-cached firmware file: " . $_[0]);
  75. }, sub {
  76. my ($http, $error, $url, $code) = @_;
  77. $error ||= ($http && $http->error) || 'unknown error';
  78. $url ||= ($http && $http->url) || 'no URL';
  79. $log->error(sprintf("Failed to get firmware image from Github: %s (%s)", $error || $http->error, $url));
  80. }, $url) if $url && $url =~ /^https?/;
  81. },
  82. sub {
  83. my ($http, $error) = @_;
  84. $log->error("Failed to get releases from Github: $error");
  85. },
  86. {
  87. timeout => 10,
  88. cache => 1,
  89. expires => 3600
  90. }
  91. )->get(GITHUB_RELEASES_URI);
  92. }
  93. sub handleFirmwareDownload {
  94. my ($httpClient, $response) = @_;
  95. my $request = $response->request;
  96. my $_errorDownloading = sub {
  97. _errorDownloading($httpClient, $response, @_);
  98. };
  99. my $path;
  100. if (!defined $request || !(($path) = $request->uri =~ $FW_DOWNLOAD_REGEX)) {
  101. return $_errorDownloading->(undef, 'Invalid request', $request->uri, 400);
  102. }
  103. # this is the magic number used on the client to figure out whether the plugin does support download proxying
  104. if ($path eq '-check.bin' && $request->method eq 'HEAD') {
  105. $response->code(204);
  106. $response->header('Access-Control-Allow-Origin' => '*');
  107. $httpClient->send_response($response);
  108. return Slim::Web::HTTP::closeHTTPSocket($httpClient);
  109. }
  110. if ($path =~ $FW_CUSTOM_REGEX) {
  111. my $firmwareFile = catfile(scalar Slim::Utils::OSDetect::dirsFor('updates'), 'squeezelite-esp32-custom.bin');
  112. if (! -f $firmwareFile) {
  113. main::INFOLOG && $log->is_info && $log->info("Failed to find custom firmware build: $firmwareFile");
  114. $response->code(404);
  115. $httpClient->send_response($response);
  116. return Slim::Web::HTTP::closeHTTPSocket($httpClient);
  117. }
  118. main::INFOLOG && $log->is_info && $log->info("Getting custom firmware build");
  119. $response->code(200);
  120. return Slim::Web::HTTP::sendStreamingFile($httpClient, $response, 'application/octet-stream', $firmwareFile, undef, 1);
  121. }
  122. main::INFOLOG && $log->is_info && $log->info("Requesting firmware from: $path");
  123. downloadFirmwareFile(sub {
  124. my $firmwareFile = shift;
  125. $response->code(200);
  126. Slim::Web::HTTP::sendStreamingFile($httpClient, $response, 'application/octet-stream', $firmwareFile, undef, 1);
  127. }, $_errorDownloading, GITHUB_DOWNLOAD_URI . $path);
  128. }
  129. sub downloadFirmwareFile {
  130. my ($cb, $ecb, $url, $name) = @_;
  131. # keep track of the last firmware we requested, to prefetch it in the future
  132. my $releaseInfo = _getFirmwareTag($url);
  133. $name ||= basename($url);
  134. if ($name !~ $FW_FILENAME_REGEX) {
  135. return $ecb->(undef, 'Unexpected firmware image name: ' . $name, $url, 400);
  136. }
  137. my $updatesDir = Slim::Utils::OSDetect::dirsFor('updates');
  138. my $firmwareFile = catfile($updatesDir, $name);
  139. my $fileMatchRegex = join('-', '', $releaseInfo->{branch}, $releaseInfo->{model}, $releaseInfo->{res});
  140. Slim::Utils::Misc::deleteFiles($updatesDir, $fileMatchRegex, $firmwareFile);
  141. if (-f $firmwareFile) {
  142. main::INFOLOG && $log->is_info && $log->info("Found cached firmware file");
  143. return $cb->($firmwareFile);
  144. }
  145. Slim::Networking::SimpleAsyncHTTP->new(
  146. sub {
  147. my $http = shift;
  148. if ($http->code != 200 || !-e "$firmwareFile.tmp") {
  149. return $ecb->($http, $http->mess);
  150. }
  151. rename "$firmwareFile.tmp", $firmwareFile or return $ecb->($http, "Unable to rename temporary $firmwareFile file" );
  152. return $cb->($firmwareFile);
  153. },
  154. $ecb,
  155. {
  156. saveAs => "$firmwareFile.tmp",
  157. }
  158. )->get($url);
  159. return;
  160. }
  161. sub _getFirmwareTag {
  162. my ($info) = @_;
  163. if (my ($model, $resolution, $version, $branch) = $info =~ $FW_TAG_REGEX) {
  164. my $releaseInfo = {
  165. model => $model,
  166. res => $resolution,
  167. version => $version,
  168. branch => $branch
  169. };
  170. return $releaseInfo;
  171. }
  172. }
  173. sub _errorDownloading {
  174. my ($httpClient, $response, $http, $error, $url, $code) = @_;
  175. $error ||= ($http && $http->error) || 'unknown error';
  176. $url ||= ($http && $http->url) || 'no URL';
  177. $code ||= ($http && $http->code) || 500;
  178. $log->error(sprintf("Failed to get data from Github: %s (%s)", $error || $http->error, $url));
  179. $response->headers->remove_content_headers;
  180. $response->code($code);
  181. $response->content_type('text/plain');
  182. $response->header('Connection' => 'close');
  183. $response->content('');
  184. $httpClient->send_response($response);
  185. Slim::Web::HTTP::closeHTTPSocket($httpClient);
  186. };
  187. 1;