FirmwareHelper.pm 11 KB

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