package tv.luma.launcher; import android.content.Context; import android.graphics.*; import android.media.MediaMetadataRetriever; import java.io.*; import java.net.*; import java.nio.charset.StandardCharsets; import java.util.*; import org.json.*; /** Bounded, explicitly requested offline downloads. No background service or scheduled fetches. */ final class SaverMedia { static final String NATURE_URL = "https://www.nps.gov/nps-audiovideo/audiovideo/4dc17e98-b3ae-4bcf-be9e-1179190717f5720p.mp4"; static final class Entry { String file, title, credit, source; Entry(JSONObject j) { file = j.optString("file"); title = j.optString("title"); credit = j.optString("credit"); source = j.optString("source", file); } } interface Progress { void update(String message); } private final Context context; private volatile int generation; private volatile HttpURLConnection connection; SaverMedia(Context c) { context = c.getApplicationContext(); } int newJob() { cancel(); return generation; } void cancel() { generation++; HttpURLConnection c = connection; if (c != null) c.disconnect(); } File videoFile() { return new File(context.getFilesDir(), "saver-nature.mp4"); } long videoBytes() { return videoFile().length(); } List entries(String album) { LinkedHashMap entries = new LinkedHashMap<>(); try (InputStream in = context.getAssets().open("saver/catalog.json")) { JSONArray list = new JSONArray(new String(read(in, 128 * 1024), StandardCharsets.UTF_8)); for (int i = 0; i < list.length(); i++) { JSONObject j = list.getJSONObject(i); if (j.optString("album").equals(album)) { Entry e = new Entry(j); entries.put(e.source, e); } } } catch (Exception ignored) { } File catalog = new File(context.getFilesDir(), "saver-art/catalog.json"); if (album.equals("art") && catalog.exists()) try (InputStream in = new FileInputStream(catalog)) { JSONArray list = new JSONArray(new String(read(in, 128 * 1024), StandardCharsets.UTF_8)); for (int i = 0; i < list.length(); i++) { Entry e = new Entry(list.getJSONObject(i)); if (new File(e.file).isFile()) entries.put(e.source, e); } } catch (Exception ignored) { } return new ArrayList<>(entries.values()); } Bitmap bitmap(Entry entry) { try { BitmapFactory.Options o = new BitmapFactory.Options(); o.inJustDecodeBounds = true; try (InputStream in = open(entry.file)) { BitmapFactory.decodeStream(in, null, o); } o.inJustDecodeBounds = false; o.inSampleSize = 1; o.inPreferredConfig = Bitmap.Config.RGB_565; while (o.outWidth / o.inSampleSize > 1280 || o.outHeight / o.inSampleSize > 1000) o.inSampleSize *= 2; try (InputStream in = open(entry.file)) { return BitmapFactory.decodeStream(in, null, o); } } catch (Exception e) { return null; } } private InputStream open(String path) throws IOException { return path.startsWith("/") ? new FileInputStream(path) : context.getAssets().open(path); } void downloadVideo(String url, int job, Progress progress) throws Exception { if (url.toLowerCase(Locale.ROOT).contains(".m3u8")) throw new IOException( "Live/HLS playlists can stream, but cannot be saved as a single offline video."); File temp = new File(context.getFilesDir(), "saver-video-" + job + ".part"); try { if (context.getFilesDir().getUsableSpace() < 350L * 1024 * 1024) throw new IOException("Not enough free space for a video download."); download(url, temp, 250L * 1024 * 1024, job, progress); MediaMetadataRetriever metadata = new MediaMetadataRetriever(); try { metadata.setDataSource(temp.getAbsolutePath()); if (!"yes".equals(metadata.extractMetadata(MediaMetadataRetriever.METADATA_KEY_HAS_VIDEO))) throw new IOException("The address did not return a playable video file."); } finally { metadata.release(); } check(job); if (!temp.renameTo(videoFile())) throw new IOException("Unable to save the video."); } finally { temp.delete(); } } void downloadArt(int job, Progress progress) throws Exception { File dir = new File(context.getFilesDir(), "saver-art"); if (!dir.exists() && !dir.mkdirs()) throw new IOException("Unable to create gallery."); JSONArray catalog = new JSONArray(); int[] ids = {436535, 45434, 436105, 436532, 437880, 436121}; for (int i = 0; i < ids.length; i++) { check(job); progress.update("Getting museum artwork " + (i + 1) + " of " + ids.length + "…"); try { byte[] bytes = get( "https://collectionapi.metmuseum.org/public/collection/v1/objects/" + ids[i], 1024 * 1024, job); JSONObject object = new JSONObject(new String(bytes, StandardCharsets.UTF_8)); String image = object.optString("primaryImageSmall"); if (!object.optBoolean("isPublicDomain") || image.isEmpty()) continue; File target = new File(dir, ids[i] + ".jpg"), temp = new File(dir, ids[i] + ".part"); try { download(image, temp, 2 * 1024 * 1024, job, message -> {}); check(job); if (!temp.renameTo(target)) continue; } finally { temp.delete(); } JSONObject e = new JSONObject(); e.put("file", target.getAbsolutePath()); e.put("title", object.optString("title")); e.put( "credit", object.optString("artistDisplayName") + " · " + object.optString("objectDate") + " · The Met, CC0"); e.put("source", object.optString("objectURL")); catalog.put(e); } catch (InterruptedIOException e) { throw e; } catch (Exception ignored) { } } check(job); if (catalog.length() == 0) throw new IOException( "Museum images are unavailable. The bundled gallery still works offline."); File temp = new File(dir, "catalog.part"); try (FileOutputStream out = new FileOutputStream(temp)) { out.write(catalog.toString().getBytes(StandardCharsets.UTF_8)); } check(job); if (!temp.renameTo(new File(dir, "catalog.json"))) throw new IOException("Unable to save gallery."); } static void validateUrl(String value) throws Exception { URL url = new URL(value); if (url.getUserInfo() != null) throw new IOException("Use a direct video URL."); if (url.getProtocol().equals("https")) return; if (url.getProtocol().equals("http")) for (InetAddress a : InetAddress.getAllByName(url.getHost())) if (a.isSiteLocalAddress() || a.isLoopbackAddress() || a.isLinkLocalAddress()) return; throw new IOException("Use HTTPS, or HTTP on your local network."); } private void check(int job) throws InterruptedIOException { if (job != generation || Thread.currentThread().isInterrupted()) throw new InterruptedIOException("Canceled"); } private HttpURLConnection connect(String value, int job) throws Exception { for (int redirects = 0; redirects < 5; redirects++) { check(job); validateUrl(value); HttpURLConnection c = (HttpURLConnection) new URL(value).openConnection(); connection = c; c.setConnectTimeout(6000); c.setReadTimeout(12000); c.setInstanceFollowRedirects(false); c.setRequestProperty("User-Agent", "Luma/1.0 AndroidTV"); int status = c.getResponseCode(); if (status >= 300 && status < 400) { String location = c.getHeaderField("Location"); value = new URL(new URL(value), location).toString(); c.disconnect(); continue; } if (status != 200) { c.disconnect(); throw new IOException("Source unavailable (HTTP " + status + ")."); } return c; } throw new IOException("Too many redirects."); } private byte[] get(String value, int limit, int job) throws Exception { HttpURLConnection c = connect(value, job); try (InputStream in = c.getInputStream()) { check(job); return read(in, limit); } finally { c.disconnect(); if (connection == c) connection = null; } } private void download(String value, File file, long limit, int job, Progress progress) throws Exception { HttpURLConnection c = connect(value, job); try { if (c.getContentLengthLong() > limit) throw new IOException("Download exceeds the " + (limit / 1024 / 1024) + " MB limit."); String type = c.getContentType(); if (type != null && (type.contains("text/html") || type.contains("mpegurl"))) throw new IOException("Use a direct MP4 file for offline playback."); try (InputStream in = c.getInputStream(); FileOutputStream out = new FileOutputStream(file)) { byte[] buf = new byte[32768]; long total = 0, lastUpdate = 0; int n; while ((n = in.read(buf)) != -1) { check(job); total += n; if (total > limit) throw new IOException("Download is too large."); out.write(buf, 0, n); long now = System.currentTimeMillis(); if (now - lastUpdate > 750) { progress.update("Downloaded " + (total / 1024 / 1024) + " MB…"); lastUpdate = now; } } } } finally { c.disconnect(); if (connection == c) connection = null; } } private static byte[] read(InputStream in, int limit) throws IOException { ByteArrayOutputStream out = new ByteArrayOutputStream(); byte[] buf = new byte[8192]; int n; while ((n = in.read(buf)) != -1) { if (out.size() + n > limit) throw new IOException("Response too large"); out.write(buf, 0, n); } return out.toByteArray(); } }