FirmwareHelper.pm 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409
  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. use constant MAX_FW_IMAGE_SIZE => 10 * 1024 * 1024;
  18. my $prefs = preferences('plugin.squeezeesp32');
  19. my $log = logger('plugin.squeezeesp32');
  20. my $initialized;
  21. sub init {
  22. my ($client) = @_;
  23. if (!$initialized) {
  24. $initialized = 1;
  25. Slim::Web::Pages->addRawFunction($FW_DOWNLOAD_REGEX, \&handleFirmwareDownload);
  26. Slim::Web::Pages->addRawFunction('plugins/SqueezeESP32/firmware/upload', \&handleFirmwareUpload);
  27. }
  28. # start checking for firmware updates
  29. Slim::Utils::Timers::setTimer($client, Time::HiRes::time() + 3.0 + rand(3.0), \&initFirmwareDownload);
  30. }
  31. sub initFirmwareDownload {
  32. my ($client, $cb) = @_;
  33. Slim::Utils::Timers::killTimers($client, \&initFirmwareDownload);
  34. return unless preferences('server')->get('checkVersion') || $cb;
  35. Slim::Networking::SimpleAsyncHTTP->new(
  36. sub {
  37. my $http = shift;
  38. my $content = eval { from_json( $http->content ) };
  39. if ($content && ref $content) {
  40. my $releaseInfo = getFirmwareTag($content->{version});
  41. if ($releaseInfo && ref $releaseInfo) {
  42. prefetchFirmware($releaseInfo, $cb);
  43. }
  44. else {
  45. $cb->() if $cb;
  46. }
  47. }
  48. },
  49. sub {
  50. my ($http, $error) = @_;
  51. $log->error("Failed to get releases from Github: $error");
  52. $cb->() if $cb;
  53. },
  54. {
  55. timeout => 10
  56. }
  57. )->get(sprintf(ESP32_STATUS_URI, $client->ip));
  58. Slim::Utils::Timers::setTimer($client, Time::HiRes::time() + FIRMWARE_POLL_INTERVAL, \&initFirmwareDownload);
  59. }
  60. sub prefetchFirmware {
  61. my ($releaseInfo, $cb) = @_;
  62. return unless $releaseInfo;
  63. Slim::Networking::SimpleAsyncHTTP->new(
  64. sub {
  65. my $http = shift;
  66. my $content = eval { from_json( $http->content ) };
  67. if (!$content || !ref $content) {
  68. $@ && $log->error("Failed to parse response: $@");
  69. }
  70. my $regex = $releaseInfo->{model} . '\.' . $releaseInfo->{res} . '\.\d+\.' . $releaseInfo->{branch};
  71. my $url;
  72. foreach (@$content) {
  73. if ($_->{tag_name} =~ /$regex/ && $_->{assets} && ref $_->{assets}) {
  74. ($url) = grep /\.bin$/, map {
  75. $_->{browser_download_url}
  76. } @{$_->{assets}};
  77. last if $url;
  78. }
  79. }
  80. my $customFwUrl = _urlFromPath('custom.bin') if $cb && -f _customFirmwareFile();
  81. if ( ($url && $url =~ /^https?/) || $customFwUrl ) {
  82. downloadFirmwareFile(sub {
  83. main::INFOLOG && $log->is_info && $log->info("Pre-cached firmware file: " . $_[0]);
  84. }, sub {
  85. my ($http, $error, $url, $code) = @_;
  86. $error ||= ($http && $http->error) || 'unknown error';
  87. $url ||= ($http && $http->url) || 'no URL';
  88. $log->error(sprintf("Failed to get firmware image from Github: %s (%s)", $error || $http->error, $url));
  89. }, $url) if $url;
  90. $cb->($releaseInfo, _gh2lmsUrl($url), $customFwUrl) if $cb;
  91. }
  92. },
  93. sub {
  94. my ($http, $error) = @_;
  95. $log->error("Failed to get releases from Github: $error");
  96. },
  97. {
  98. timeout => 10,
  99. cache => 1,
  100. expires => 3600
  101. }
  102. )->get(GITHUB_RELEASES_URI);
  103. }
  104. sub _gh2lmsUrl {
  105. my ($url) = @_;
  106. my $ghPrefix = GITHUB_DOWNLOAD_URI;
  107. my $baseUrl = Slim::Utils::Network::serverURL();
  108. $url =~ s/$ghPrefix/$baseUrl\/plugins\/SqueezeESP32\/firmware\//;
  109. return $url;
  110. }
  111. sub _urlFromPath {
  112. return sprintf('%s/plugins/SqueezeESP32/firmware/%s', Slim::Utils::Network::serverURL(), basename(shift));
  113. }
  114. sub _customFirmwareFile {
  115. return catfile(scalar Slim::Utils::OSDetect::dirsFor('updates'), 'squeezelite-esp32-custom.bin');
  116. }
  117. sub handleFirmwareDownload {
  118. my ($httpClient, $response) = @_;
  119. my $request = $response->request;
  120. my $_errorDownloading = sub {
  121. _errorDownloading($httpClient, $response, @_);
  122. };
  123. my $path;
  124. if (!defined $request || !(($path) = $request->uri =~ $FW_DOWNLOAD_REGEX)) {
  125. return $_errorDownloading->(undef, 'Invalid request', $request->uri, 400);
  126. }
  127. # this is the magic number used on the client to figure out whether the plugin does support download proxying
  128. if ($path eq '-check.bin' && $request->method eq 'HEAD') {
  129. $response->code(204);
  130. $response->header('Access-Control-Allow-Origin' => '*');
  131. $httpClient->send_response($response);
  132. return Slim::Web::HTTP::closeHTTPSocket($httpClient);
  133. }
  134. if ($path =~ $FW_CUSTOM_REGEX) {
  135. my $firmwareFile = _customFirmwareFile();
  136. if (! -f $firmwareFile) {
  137. main::INFOLOG && $log->is_info && $log->info("Failed to find custom firmware build: $firmwareFile");
  138. $response->code(404);
  139. $httpClient->send_response($response);
  140. return Slim::Web::HTTP::closeHTTPSocket($httpClient);
  141. }
  142. main::INFOLOG && $log->is_info && $log->info("Getting custom firmware build");
  143. $response->code(200);
  144. return Slim::Web::HTTP::sendStreamingFile($httpClient, $response, 'application/octet-stream', $firmwareFile, undef, 1);
  145. }
  146. main::INFOLOG && $log->is_info && $log->info("Requesting firmware from: $path");
  147. downloadFirmwareFile(sub {
  148. my $firmwareFile = shift;
  149. $response->code(200);
  150. Slim::Web::HTTP::sendStreamingFile($httpClient, $response, 'application/octet-stream', $firmwareFile, undef, 1);
  151. }, $_errorDownloading, GITHUB_DOWNLOAD_URI . $path);
  152. }
  153. sub downloadFirmwareFile {
  154. my ($cb, $ecb, $url, $name) = @_;
  155. # keep track of the last firmware we requested, to prefetch it in the future
  156. my $releaseInfo = getFirmwareTag($url);
  157. $name ||= basename($url);
  158. if ($name !~ $FW_FILENAME_REGEX) {
  159. return $ecb->(undef, 'Unexpected firmware image name: ' . $name, $url, 400);
  160. }
  161. my $updatesDir = _getTempDir();
  162. my $firmwareFile = catfile($updatesDir, $name);
  163. if (-f $firmwareFile) {
  164. main::INFOLOG && $log->is_info && $log->info("Found uploaded firmware file $name");
  165. return $cb->($firmwareFile);
  166. }
  167. $updatesDir = Slim::Utils::OSDetect::dirsFor('updates');
  168. $firmwareFile = catfile($updatesDir, $name);
  169. if ($releaseInfo) {
  170. my $fileMatchRegex = join('-', '', $releaseInfo->{branch}, $releaseInfo->{model}, $releaseInfo->{res});
  171. Slim::Utils::Misc::deleteFiles($updatesDir, $fileMatchRegex, $firmwareFile);
  172. }
  173. if (-f $firmwareFile) {
  174. main::INFOLOG && $log->is_info && $log->info("Found cached firmware file");
  175. return $cb->($firmwareFile);
  176. }
  177. Slim::Networking::SimpleAsyncHTTP->new(
  178. sub {
  179. my $http = shift;
  180. if ($http->code != 200 || !-e "$firmwareFile.tmp") {
  181. return $ecb->($http, $http->mess);
  182. }
  183. rename "$firmwareFile.tmp", $firmwareFile or return $ecb->($http, "Unable to rename temporary $firmwareFile file" );
  184. return $cb->($firmwareFile);
  185. },
  186. sub {
  187. my ($http, $error) = @_;
  188. $http->code(404) if $error =~ /\b404\b/;
  189. $ecb->(@_);
  190. },
  191. {
  192. saveAs => "$firmwareFile.tmp",
  193. }
  194. )->get($url);
  195. return;
  196. }
  197. sub getFirmwareTag {
  198. my ($info) = @_;
  199. if (my ($model, $resolution, $version, $branch) = $info =~ $FW_TAG_REGEX) {
  200. my $releaseInfo = {
  201. model => $model,
  202. res => $resolution,
  203. version => $version,
  204. branch => $branch
  205. };
  206. return $releaseInfo;
  207. }
  208. }
  209. sub _errorDownloading {
  210. my ($httpClient, $response, $http, $error, $url, $code) = @_;
  211. $error ||= ($http && $http->error) || 'unknown error';
  212. $url ||= ($http && $http->url) || 'no URL';
  213. $code ||= ($http && $http->code) || 500;
  214. $log->error(sprintf("Failed to get data from Github: %s (%s)", $error || $http->error, $url));
  215. $response->headers->remove_content_headers;
  216. $response->code($code);
  217. $response->content_type('text/plain');
  218. $response->header('Connection' => 'close');
  219. $response->content('');
  220. $httpClient->send_response($response);
  221. Slim::Web::HTTP::closeHTTPSocket($httpClient);
  222. };
  223. sub handleFirmwareUpload {
  224. my ($httpClient, $response) = @_;
  225. my $request = $response->request;
  226. my $result = {};
  227. my $t = Time::HiRes::time();
  228. main::INFOLOG && $log->is_info && $log->info("New firmware image to upload. Size: " . formatMB($request->content_length));
  229. if ( $request->method !~ /HEAD|OPTIONS|POST/ ) {
  230. $log->error("Invalid HTTP verb: " . $request->method);
  231. $result = {
  232. error => 'Invalid request.',
  233. code => 400,
  234. };
  235. }
  236. elsif ( $request->content_length > MAX_FW_IMAGE_SIZE ) {
  237. $log->error("Upload data is too large: " . $request->content_length);
  238. $result = {
  239. error => string('PLUGIN_DNDPLAY_FILE_TOO_LARGE', formatMB($request->content_length), formatMB(MAX_FW_IMAGE_SIZE)),
  240. code => 413,
  241. };
  242. }
  243. else {
  244. my $ct = $request->header('Content-Type');
  245. my ($boundary) = $ct =~ /boundary=(.*)/;
  246. my ($uploadedFwFh, $filename, $inUpload, $buf);
  247. # open a pseudo-filehandle to the uploaded data ref for further processing
  248. open TEMP, '<', $request->content_ref;
  249. while (<TEMP>) {
  250. if ( Time::HiRes::time - $t > 0.2 ) {
  251. main::idleStreams();
  252. $t = Time::HiRes::time();
  253. }
  254. # a new part starts - reset some variables
  255. if ( /--\Q$boundary\E/i ) {
  256. $filename = '';
  257. if ($buf) {
  258. $buf =~ s/\r\n$//;
  259. print $uploadedFwFh $buf if $uploadedFwFh;
  260. }
  261. close $uploadedFwFh if $uploadedFwFh;
  262. $inUpload = undef;
  263. }
  264. # write data to file handle
  265. elsif ( $inUpload && $uploadedFwFh ) {
  266. print $uploadedFwFh $buf if defined $buf;
  267. $buf = $_;
  268. }
  269. # we got an uploaded file name
  270. elsif ( /filename="(.+?)"/i ) {
  271. $filename = $1;
  272. main::INFOLOG && $log->is_info && $log->info("New file to upload: $filename")
  273. }
  274. # we got the separator after the upload file name: file data comes next. Open a file handle to write the data to.
  275. elsif ( $filename && /^\s*$/ ) {
  276. $inUpload = 1;
  277. $uploadedFwFh = File::Temp->new(
  278. DIR => _getTempDir(),
  279. SUFFIX => '.bin',
  280. TEMPLATE => 'squeezelite-esp32-upload-XXXXXX',
  281. UNLINK => 0,
  282. ) or $log->warn("Failed to open file: $@");
  283. binmode $uploadedFwFh;
  284. # remove file after a few minutes
  285. Slim::Utils::Timers::setTimer($uploadedFwFh->filename, Time::HiRes::time() + 15 * 60, sub { unlink shift });
  286. }
  287. }
  288. close TEMP;
  289. close $uploadedFwFh if $uploadedFwFh;
  290. main::idleStreams();
  291. if (!$result->{error}) {
  292. $result->{url} = _urlFromPath($uploadedFwFh->filename);
  293. $result->{size} = -s $uploadedFwFh->filename;
  294. }
  295. }
  296. $log->error($result->{error}) if $result->{error};
  297. my $content = to_json($result);
  298. $response->header( 'Content-Length' => length($content) );
  299. $response->code($result->{code} || 200);
  300. $response->header('Connection' => 'close');
  301. $response->content_type('application/json');
  302. Slim::Web::HTTP::addHTTPResponse( $httpClient, $response, \$content );
  303. }
  304. my $tempDir;
  305. sub _getTempDir {
  306. return $tempDir if $tempDir;
  307. eval { $tempDir = Slim::Utils::Misc::getTempDir() }; # LMS 8.2+ only
  308. $tempDir ||= File::Temp::tempdir(CLEANUP => 1, DIR => preferences('server')->get('cachedir'));
  309. return $tempDir;
  310. }
  311. sub formatMB {
  312. return Slim::Utils::Misc::delimitThousands(int($_[0] / 1024 / 1024)) . 'MB';
  313. }
  314. 1;