FirmwareHelper.pm 6.7 KB

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