FirmwareHelper.pm 11 KB

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