package me.teafry.voipmessages; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.net.Uri; import android.util.LruCache; import org.json.JSONObject; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.nio.file.Files; import java.security.MessageDigest; import java.util.List; /** * Attachments, cached in files/media named by content hash -- the same layout * as the desktop's /media, which the installer copies over, so the * MediaRef.file names in the copied history resolve as-is. */ final class Media { private Media() {} /** voip.ms takes ~1.2 MB per file and carriers are stricter. */ static final int BUDGET = 900 * 1024; static File dir(Context c) { File d = new File(c.getFilesDir(), "media"); d.mkdirs(); return d; } static String ext(String mime) { if (mime == null) return "bin"; switch (mime) { case "image/jpeg": return "jpg"; case "image/png": return "png"; case "image/gif": return "gif"; case "image/webp": return "webp"; case "video/mp4": return "mp4"; case "audio/mpeg": return "mp3"; case "audio/mp4": return "m4a"; default: { int slash = mime.indexOf('/'); return slash > 0 ? mime.substring(slash + 1).replaceAll("[^a-z0-9]", "") : "bin"; } } } static String save(Context c, byte[] data, String mime) throws IOException { String name; try { byte[] h = MessageDigest.getInstance("SHA-1").digest(data); StringBuilder sb = new StringBuilder(); for (byte b : h) sb.append(String.format("%02x", b)); name = sb + "." + ext(mime); } catch (Exception e) { throw new IOException(e); } File f = new File(dir(c), name); if (!f.exists()) try (FileOutputStream out = new FileOutputStream(f)) { out.write(data); } return name; } /** The local file for attachment `index` of message `id`, downloading it first if needed. */ static File resolve(Context c, long id, int index) { // Already here: no need to wait behind someone else's download. File have = local(c, id, index); if (have != null) return have; synchronized (Media.class) { return download(c, id, index); } } private static File local(Context c, long id, int index) { Store.Msg m = Store.get(c).getMessage(id); List refs = m == null ? null : m.media(); if (refs == null || index >= refs.size()) return null; String file = refs.get(index).optString("file", ""); if (file.isEmpty()) return null; File f = new File(dir(c), new File(file).getName()); return f.exists() ? f : null; } private static File download(Context c, long id, int index) { Store store = Store.get(c); Store.Msg m = store.getMessage(id); if (m == null) return null; List refs = m.media(); if (index >= refs.size()) return null; JSONObject ref = refs.get(index); String file = ref.optString("file", ""); if (!file.isEmpty()) { File f = new File(dir(c), new File(file).getName()); if (f.exists()) return f; } String url = ref.optString("url", ""); if (url.isEmpty()) return null; try { byte[] data; String mime; if (url.startsWith("mmspart:")) { // A SIM MMS: in Android's message store (Sim.readMms). try (InputStream in = c.getContentResolver().openInputStream(Uri.parse("content://mms/part/" + url.substring(8)))) { if (in == null) return null; data = Http.readAll(in); } mime = ref.optString("mime", "application/octet-stream"); } else if (url.startsWith("gv:")) { Object[] r = new GVoice(Config.get(c)).download(url.substring(3)); data = (byte[]) r[0]; mime = (String) r[1]; } else { Http.Response r = Http.request("GET", url, null, null, 60_000); if (r.status >= 400) return null; data = r.body; mime = r.header("Content-Type"); } if (mime != null) mime = mime.split(";")[0].trim(); if ("text/html".equals(mime)) return null; // expired voip.ms media answers with a page if (mime == null || mime.equals("application/octet-stream")) mime = ref.optString("mime", "application/octet-stream"); String name = save(c, data, mime); BitmapFactory.Options o = new BitmapFactory.Options(); o.inJustDecodeBounds = true; BitmapFactory.decodeByteArray(data, 0, data.length, o); store.setMediaFile(id, index, name, mime, o.outWidth, o.outHeight); return new File(dir(c), name); } catch (Exception e) { return null; } } private static final LruCache cache = new LruCache(24 * 1024 * 1024) { @Override protected int sizeOf(String key, Bitmap value) { return value.getByteCount(); } }; /** An attachment's bitmap if it's already decoded, without touching the disk. */ static Bitmap cached(JSONObject ref, int maxEdge) { String file = ref.optString("file", ""); return file.isEmpty() ? null : cache.get(new File(file).getName() + "@" + maxEdge); } /** A bitmap no bigger than maxEdge on its long side. */ static Bitmap bitmap(File f, int maxEdge) { String key = f.getName() + "@" + maxEdge; Bitmap b = cache.get(key); if (b != null) return b; BitmapFactory.Options o = new BitmapFactory.Options(); o.inJustDecodeBounds = true; BitmapFactory.decodeFile(f.getPath(), o); int sample = 1; while (Math.max(o.outWidth, o.outHeight) / (sample * 2) >= maxEdge) sample *= 2; o = new BitmapFactory.Options(); o.inSampleSize = sample; b = BitmapFactory.decodeFile(f.getPath(), o); if (b != null) cache.put(key, b); return b; } /** * A picked photo, ready to send: under BUDGET, JPEG unless it was already a * small JPEG/PNG/GIF. Returns [bytes, mime]. */ static Object[] prepare(Context c, Uri uri) throws IOException { String mime = c.getContentResolver().getType(uri); byte[] original; try (InputStream in = c.getContentResolver().openInputStream(uri)) { if (in == null) throw new IOException("Couldn't open that photo."); original = Http.readAll(in); } boolean passthrough = "image/jpeg".equals(mime) || "image/png".equals(mime) || "image/gif".equals(mime); if (passthrough && original.length <= BUDGET) return new Object[] {original, mime}; Bitmap full = BitmapFactory.decodeByteArray(original, 0, original.length); if (full == null) throw new IOException("That file isn't a photo the Rabbit can read."); int[] edges = {2048, 1600, 1280, 1024, 800, 640}; int[] qualities = {85, 72, 60}; for (int edge : edges) { float scale = Math.min(1f, edge / (float) Math.max(full.getWidth(), full.getHeight())); Bitmap b = scale < 1f ? Bitmap.createScaledBitmap(full, Math.round(full.getWidth() * scale), Math.round(full.getHeight() * scale), true) : full; for (int q : qualities) { ByteArrayOutputStream out = new ByteArrayOutputStream(); b.compress(Bitmap.CompressFormat.JPEG, q, out); if (out.size() <= BUDGET) return new Object[] {out.toByteArray(), "image/jpeg"}; } } throw new IOException("That photo is too big to send, even shrunk."); } static byte[] read(File f) throws IOException { return Files.readAllBytes(f.toPath()); } }