FirmwareHelper.pm 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270
  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, $cb) = @_;
  31. Slim::Utils::Timers::killTimers($client, \&initFirmwareDownload);
  32. return unless preferences('server')->get('checkVersion') || $cb;
  33. Slim::Networking::SimpleAsyncHTTP->new(
  34. sub {
  35. my $http = shift;
  36. my $content = eval { from_json( $http->content ) };
  37. if ($content && ref $content) {
  38. my $releaseInfo = getFirmwareTag($content->{version});
  39. if ($releaseInfo && ref $releaseInfo) {
  40. prefetchFirmware($releaseInfo, $cb);
  41. }
  42. else {
  43. $cb->() if $cb;
  44. }
  45. }
  46. },
  47. sub {
  48. my ($http, $error) = @_;
  49. $log->error("Failed to get releases from Github: $error");
  50. $cb->() if $cb;
  51. },
  52. {
  53. timeout => 10
  54. }
  55. )->get(sprintf(ESP32_STATUS_URI, $client->ip));
  56. Slim::Utils::Timers::setTimer($client, Time::HiRes::time() + FIRMWARE_POLL_INTERVAL, \&initFirmwareDownload);
  57. }
  58. sub prefetchFirmware {
  59. my ($releaseInfo, $cb) = @_;
  60. return unless $releaseInfo;
  61. Slim::Networking::SimpleAsyncHTTP->new(
  62. sub {
  63. my $http = shift;
  64. my $content = eval { from_json( $http->content ) };
  65. if (!$content || !ref $content) {
  66. $@ && $log->error("Failed to parse response: $@");
  67. }
  68. my $regex = $releaseInfo->{model} . '\.' . $releaseInfo->{res} . '\.\d+\.' . $releaseInfo->{branch};
  69. my $url;
  70. foreach (@$content) {
  71. if ($_->{tag_name} =~ /$regex/ && $_->{assets} && ref $_->{assets}) {
  72. ($url) = grep /\.bin$/, map {
  73. $_->{browser_download_url}
  74. } @{$_->{assets}};
  75. last if $url;
  76. }
  77. }
  78. my $customFwUrl = sprintf('%s/plugins/SqueezeESP32/firmware/custom.bin', Slim::Utils::Network::serverURL()) if $cb && -f _customFirmwareFile();
  79. if ( ($url && $url =~ /^https?/) || $customFwUrl ) {
  80. downloadFirmwareFile(sub {
  81. main::INFOLOG && $log->is_info && $log->info("Pre-cached firmware file: " . $_[0]);
  82. }, sub {
  83. my ($http, $error, $url, $code) = @_;
  84. $error ||= ($http && $http->error) || 'unknown error';
  85. $url ||= ($http && $http->url) || 'no URL';
  86. $log->error(sprintf("Failed to get firmware image from Github: %s (%s)", $error || $http->error, $url));
  87. }, $url) if $url;
  88. $cb->($releaseInfo, _gh2lmsUrl($url), $customFwUrl) if $cb;
  89. }
  90. },
  91. sub {
  92. my ($http, $error) = @_;
  93. $log->error("Failed to get releases from Github: $error");
  94. },
  95. {
  96. timeout => 10,
  97. cache => 1,
  98. expires => 3600
  99. }
  100. )->get(GITHUB_RELEASES_URI);
  101. }
  102. sub _gh2lmsUrl {
  103. my ($url) = @_;
  104. my $ghPrefix = GITHUB_DOWNLOAD_URI;
  105. my $baseUrl = Slim::Utils::Network::serverURL();
  106. $url =~ s/$ghPrefix/$baseUrl\/plugins\/SqueezeESP32\/firmware\//;
  107. return $url;
  108. }
  109. sub _customFirmwareFile {
  110. return catfile(scalar Slim::Utils::OSDetect::dirsFor('updates'), 'squeezelite-esp32-custom.bin');
  111. }
  112. sub handleFirmwareDownload {
  113. my ($httpClient, $response) = @_;
  114. my $request = $response->request;
  115. my $_errorDownloading = sub {
  116. _errorDownloading($httpClient, $response, @_);
  117. };
  118. my $path;
  119. if (!defined $request || !(($path) = $request->uri =~ $FW_DOWNLOAD_REGEX)) {
  120. return $_errorDownloading->(undef, 'Invalid request', $request->uri, 400);
  121. }
  122. # this is the magic number used on the client to figure out whether the plugin does support download proxying
  123. if ($path eq '-check.bin' && $request->method eq 'HEAD') {
  124. $response->code(204);
  125. $response->header('Access-Control-Allow-Origin' => '*');
  126. $httpClient->send_response($response);
  127. return Slim::Web::HTTP::closeHTTPSocket($httpClient);
  128. }
  129. if ($path =~ $FW_CUSTOM_REGEX) {
  130. my $firmwareFile = _customFirmwareFile();
  131. if (! -f $firmwareFile) {
  132. main::INFOLOG && $log->is_info && $log->info("Failed to find custom firmware build: $firmwareFile");
  133. $response->code(404);
  134. $httpClient->send_response($response);
  135. return Slim::Web::HTTP::closeHTTPSocket($httpClient);
  136. }
  137. main::INFOLOG && $log->is_info && $log->info("Getting custom firmware build");
  138. $response->code(200);
  139. return Slim::Web::HTTP::sendStreamingFile($httpClient, $response, 'application/octet-stream', $firmwareFile, undef, 1);
  140. }
  141. main::INFOLOG && $log->is_info && $log->info("Requesting firmware from: $path");
  142. downloadFirmwareFile(sub {
  143. my $firmwareFile = shift;
  144. $response->code(200);
  145. Slim::Web::HTTP::sendStreamingFile($httpClient, $response, 'application/octet-stream', $firmwareFile, undef, 1);
  146. }, $_errorDownloading, GITHUB_DOWNLOAD_URI . $path);
  147. }
  148. sub downloadFirmwareFile {
  149. my ($cb, $ecb, $url, $name) = @_;
  150. # keep track of the last firmware we requested, to prefetch it in the future
  151. my $releaseInfo = getFirmwareTag($url);
  152. $name ||= basename($url);
  153. if ($name !~ $FW_FILENAME_REGEX) {
  154. return $ecb->(undef, 'Unexpected firmware image name: ' . $name, $url, 400);
  155. }
  156. my $updatesDir = Slim::Utils::OSDetect::dirsFor('updates');
  157. my $firmwareFile = catfile($updatesDir, $name);
  158. my $fileMatchRegex = join('-', '', $releaseInfo->{branch}, $releaseInfo->{model}, $releaseInfo->{res});
  159. Slim::Utils::Misc::deleteFiles($updatesDir, $fileMatchRegex, $firmwareFile);
  160. if (-f $firmwareFile) {
  161. main::INFOLOG && $log->is_info && $log->info("Found cached firmware file");
  162. return $cb->($firmwareFile);
  163. }
  164. Slim::Networking::SimpleAsyncHTTP->new(
  165. sub {
  166. my $http = shift;
  167. if ($http->code != 200 || !-e "$firmwareFile.tmp") {
  168. return $ecb->($http, $http->mess);
  169. }
  170. rename "$firmwareFile.tmp", $firmwareFile or return $ecb->($http, "Unable to rename temporary $firmwareFile file" );
  171. return $cb->($firmwareFile);
  172. },
  173. $ecb,
  174. {
  175. saveAs => "$firmwareFile.tmp",
  176. }
  177. )->get($url);
  178. return;
  179. }
  180. sub getFirmwareTag {
  181. my ($info) = @_;
  182. if (my ($model, $resolution, $version, $branch) = $info =~ $FW_TAG_REGEX) {
  183. my $releaseInfo = {
  184. model => $model,
  185. res => $resolution,
  186. version => $version,
  187. branch => $branch
  188. };
  189. return $releaseInfo;
  190. }
  191. }
  192. sub _errorDownloading {
  193. my ($httpClient, $response, $http, $error, $url, $code) = @_;
  194. $error ||= ($http && $http->error) || 'unknown error';
  195. $url ||= ($http && $http->url) || 'no URL';
  196. $code ||= ($http && $http->code) || 500;
  197. $log->error(sprintf("Failed to get data from Github: %s (%s)", $error || $http->error, $url));
  198. $response->headers->remove_content_headers;
  199. $response->code($code);
  200. $response->content_type('text/plain');
  201. $response->header('Connection' => 'close');
  202. $response->content('');
  203. $httpClient->send_response($response);
  204. Slim::Web::HTTP::closeHTTPSocket($httpClient);
  205. };
  206. 1;