FileBackend.java

   1package eu.siacs.conversations.persistance;
   2
   3import android.annotation.TargetApi;
   4import android.content.ContentResolver;
   5import android.content.Context;
   6import android.content.Intent;
   7import android.database.Cursor;
   8import android.graphics.Bitmap;
   9import android.graphics.BitmapFactory;
  10import android.graphics.Canvas;
  11import android.graphics.Color;
  12import android.graphics.Matrix;
  13import android.graphics.Paint;
  14import android.graphics.RectF;
  15import android.media.MediaMetadataRetriever;
  16import android.net.Uri;
  17import android.os.Build;
  18import android.os.Environment;
  19import android.os.ParcelFileDescriptor;
  20import android.provider.MediaStore;
  21import android.provider.OpenableColumns;
  22import android.support.v4.content.FileProvider;
  23import android.system.Os;
  24import android.system.StructStat;
  25import android.util.Base64;
  26import android.util.Base64OutputStream;
  27import android.util.Log;
  28import android.util.LruCache;
  29
  30import java.io.ByteArrayOutputStream;
  31import java.io.Closeable;
  32import java.io.File;
  33import java.io.FileDescriptor;
  34import java.io.FileInputStream;
  35import java.io.FileNotFoundException;
  36import java.io.FileOutputStream;
  37import java.io.IOException;
  38import java.io.InputStream;
  39import java.io.OutputStream;
  40import java.net.Socket;
  41import java.net.URL;
  42import java.security.DigestOutputStream;
  43import java.security.MessageDigest;
  44import java.security.NoSuchAlgorithmException;
  45import java.text.SimpleDateFormat;
  46import java.util.Date;
  47import java.util.List;
  48import java.util.Locale;
  49import java.util.UUID;
  50
  51import eu.siacs.conversations.Config;
  52import eu.siacs.conversations.R;
  53import eu.siacs.conversations.entities.DownloadableFile;
  54import eu.siacs.conversations.entities.Message;
  55import eu.siacs.conversations.services.XmppConnectionService;
  56import eu.siacs.conversations.ui.RecordingActivity;
  57import eu.siacs.conversations.utils.CryptoHelper;
  58import eu.siacs.conversations.utils.ExifHelper;
  59import eu.siacs.conversations.utils.FileUtils;
  60import eu.siacs.conversations.utils.FileWriterException;
  61import eu.siacs.conversations.utils.MimeUtils;
  62import eu.siacs.conversations.xmpp.pep.Avatar;
  63
  64public class FileBackend {
  65
  66    private static final Object THUMBNAIL_LOCK = new Object();
  67
  68    private static final SimpleDateFormat IMAGE_DATE_FORMAT = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.US);
  69
  70    private static final String FILE_PROVIDER = ".files";
  71
  72    private XmppConnectionService mXmppConnectionService;
  73
  74    private static final float IGNORE_PADDING = 0.15f;
  75
  76    public FileBackend(XmppConnectionService service) {
  77        this.mXmppConnectionService = service;
  78    }
  79
  80    private static boolean isInDirectoryThatShouldNotBeScanned(Context context, File file) {
  81        return isInDirectoryThatShouldNotBeScanned(context, file.getAbsolutePath());
  82    }
  83
  84    public static boolean isInDirectoryThatShouldNotBeScanned(Context context, String path) {
  85        for (String type : new String[]{RecordingActivity.STORAGE_DIRECTORY_TYPE_NAME, "Files"}) {
  86            if (path.startsWith(getConversationsDirectory(context, type))) {
  87                return true;
  88            }
  89        }
  90        return false;
  91    }
  92
  93    public static long getFileSize(Context context, Uri uri) {
  94        try {
  95            final Cursor cursor = context.getContentResolver().query(uri, null, null, null, null);
  96            if (cursor != null && cursor.moveToFirst()) {
  97                long size = cursor.getLong(cursor.getColumnIndex(OpenableColumns.SIZE));
  98                cursor.close();
  99                return size;
 100            } else {
 101                return -1;
 102            }
 103        } catch (Exception e) {
 104            return -1;
 105        }
 106    }
 107
 108    public static boolean allFilesUnderSize(Context context, List<Uri> uris, long max) {
 109        if (max <= 0) {
 110            Log.d(Config.LOGTAG, "server did not report max file size for http upload");
 111            return true; //exception to be compatible with HTTP Upload < v0.2
 112        }
 113        for (Uri uri : uris) {
 114            String mime = context.getContentResolver().getType(uri);
 115            if (mime != null && mime.startsWith("video/")) {
 116                try {
 117                    Dimensions dimensions = FileBackend.getVideoDimensions(context, uri);
 118                    if (dimensions.getMin() > 720) {
 119                        Log.d(Config.LOGTAG, "do not consider video file with min width larger than 720 for size check");
 120                        continue;
 121                    }
 122                } catch (NotAVideoFile notAVideoFile) {
 123                    //ignore and fall through
 124                }
 125            }
 126            if (FileBackend.getFileSize(context, uri) > max) {
 127                Log.d(Config.LOGTAG, "not all files are under " + max + " bytes. suggesting falling back to jingle");
 128                return false;
 129            }
 130        }
 131        return true;
 132    }
 133
 134    public static String getConversationsDirectory(Context context, final String type) {
 135        if (Config.ONLY_INTERNAL_STORAGE) {
 136            return context.getFilesDir().getAbsolutePath() + "/" + type + "/";
 137        } else {
 138            return getAppMediaDirectory(context) + context.getString(R.string.app_name) + " " + type + "/";
 139        }
 140    }
 141
 142    public static String getAppMediaDirectory(Context context) {
 143        return Environment.getExternalStorageDirectory().getAbsolutePath() + "/" + context.getString(R.string.app_name) + "/Media/";
 144    }
 145
 146    public static String getConversationsLogsDirectory() {
 147        return Environment.getExternalStorageDirectory().getAbsolutePath() + "/Conversations/";
 148    }
 149
 150    private static Bitmap rotate(Bitmap bitmap, int degree) {
 151        if (degree == 0) {
 152            return bitmap;
 153        }
 154        int w = bitmap.getWidth();
 155        int h = bitmap.getHeight();
 156        Matrix mtx = new Matrix();
 157        mtx.postRotate(degree);
 158        Bitmap result = Bitmap.createBitmap(bitmap, 0, 0, w, h, mtx, true);
 159        if (bitmap != null && !bitmap.isRecycled()) {
 160            bitmap.recycle();
 161        }
 162        return result;
 163    }
 164
 165    public static boolean isPathBlacklisted(String path) {
 166        final String androidDataPath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/Android/data/";
 167        return path.startsWith(androidDataPath);
 168    }
 169
 170    private static Paint createAntiAliasingPaint() {
 171        Paint paint = new Paint();
 172        paint.setAntiAlias(true);
 173        paint.setFilterBitmap(true);
 174        paint.setDither(true);
 175        return paint;
 176    }
 177
 178    private static String getTakePhotoPath() {
 179        return Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM) + "/Camera/";
 180    }
 181
 182    public static Uri getUriForFile(Context context, File file) {
 183        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N || Config.ONLY_INTERNAL_STORAGE) {
 184            try {
 185                return FileProvider.getUriForFile(context, getAuthority(context), file);
 186            } catch (IllegalArgumentException e) {
 187                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
 188                    throw new SecurityException(e);
 189                } else {
 190                    return Uri.fromFile(file);
 191                }
 192            }
 193        } else {
 194            return Uri.fromFile(file);
 195        }
 196    }
 197
 198    public static String getAuthority(Context context) {
 199        return context.getPackageName() + FILE_PROVIDER;
 200    }
 201
 202    private static boolean hasAlpha(final Bitmap bitmap) {
 203        for (int x = 0; x < bitmap.getWidth(); ++x) {
 204            for (int y = 0; y < bitmap.getWidth(); ++y) {
 205                if (Color.alpha(bitmap.getPixel(x, y)) < 255) {
 206                    return true;
 207                }
 208            }
 209        }
 210        return false;
 211    }
 212
 213    private static int calcSampleSize(File image, int size) {
 214        BitmapFactory.Options options = new BitmapFactory.Options();
 215        options.inJustDecodeBounds = true;
 216        BitmapFactory.decodeFile(image.getAbsolutePath(), options);
 217        return calcSampleSize(options, size);
 218    }
 219
 220    private static int calcSampleSize(BitmapFactory.Options options, int size) {
 221        int height = options.outHeight;
 222        int width = options.outWidth;
 223        int inSampleSize = 1;
 224
 225        if (height > size || width > size) {
 226            int halfHeight = height / 2;
 227            int halfWidth = width / 2;
 228
 229            while ((halfHeight / inSampleSize) > size
 230                    && (halfWidth / inSampleSize) > size) {
 231                inSampleSize *= 2;
 232            }
 233        }
 234        return inSampleSize;
 235    }
 236
 237    private static Dimensions getVideoDimensions(Context context, Uri uri) throws NotAVideoFile {
 238        MediaMetadataRetriever mediaMetadataRetriever = new MediaMetadataRetriever();
 239        try {
 240            mediaMetadataRetriever.setDataSource(context, uri);
 241        } catch (RuntimeException e) {
 242            throw new NotAVideoFile(e);
 243        }
 244        return getVideoDimensions(mediaMetadataRetriever);
 245    }
 246
 247    private static Dimensions getVideoDimensionsOfFrame(MediaMetadataRetriever mediaMetadataRetriever) {
 248        Bitmap bitmap = null;
 249        try {
 250            bitmap = mediaMetadataRetriever.getFrameAtTime();
 251            return new Dimensions(bitmap.getHeight(), bitmap.getWidth());
 252        } catch (Exception e) {
 253            return null;
 254        } finally {
 255            if (bitmap != null) {
 256                bitmap.recycle();
 257                ;
 258            }
 259        }
 260    }
 261
 262    private static Dimensions getVideoDimensions(MediaMetadataRetriever metadataRetriever) throws NotAVideoFile {
 263        String hasVideo = metadataRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_HAS_VIDEO);
 264        if (hasVideo == null) {
 265            throw new NotAVideoFile();
 266        }
 267        Dimensions dimensions = getVideoDimensionsOfFrame(metadataRetriever);
 268        if (dimensions != null) {
 269            return dimensions;
 270        }
 271        int rotation = extractRotationFromMediaRetriever(metadataRetriever);
 272        boolean rotated = rotation == 90 || rotation == 270;
 273        int height;
 274        try {
 275            String h = metadataRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_HEIGHT);
 276            height = Integer.parseInt(h);
 277        } catch (Exception e) {
 278            height = -1;
 279        }
 280        int width;
 281        try {
 282            String w = metadataRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_WIDTH);
 283            width = Integer.parseInt(w);
 284        } catch (Exception e) {
 285            width = -1;
 286        }
 287        metadataRetriever.release();
 288        Log.d(Config.LOGTAG, "extracted video dims " + width + "x" + height);
 289        return rotated ? new Dimensions(width, height) : new Dimensions(height, width);
 290    }
 291
 292    private static int extractRotationFromMediaRetriever(MediaMetadataRetriever metadataRetriever) {
 293        String r = metadataRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_ROTATION);
 294        try {
 295            return Integer.parseInt(r);
 296        } catch (Exception e) {
 297            return 0;
 298        }
 299    }
 300
 301    public static void close(Closeable stream) {
 302        if (stream != null) {
 303            try {
 304                stream.close();
 305            } catch (IOException e) {
 306            }
 307        }
 308    }
 309
 310    public static void close(Socket socket) {
 311        if (socket != null) {
 312            try {
 313                socket.close();
 314            } catch (IOException e) {
 315            }
 316        }
 317    }
 318
 319    public static boolean weOwnFile(Context context, Uri uri) {
 320        if (uri == null || !ContentResolver.SCHEME_FILE.equals(uri.getScheme())) {
 321            return false;
 322        } else if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
 323            return fileIsInFilesDir(context, uri);
 324        } else {
 325            return weOwnFileLollipop(uri);
 326        }
 327    }
 328
 329    /**
 330     * This is more than hacky but probably way better than doing nothing
 331     * Further 'optimizations' might contain to get the parents of CacheDir and NoBackupDir
 332     * and check against those as well
 333     */
 334    private static boolean fileIsInFilesDir(Context context, Uri uri) {
 335        try {
 336            final String haystack = context.getFilesDir().getParentFile().getCanonicalPath();
 337            final String needle = new File(uri.getPath()).getCanonicalPath();
 338            return needle.startsWith(haystack);
 339        } catch (IOException e) {
 340            return false;
 341        }
 342    }
 343
 344    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
 345    private static boolean weOwnFileLollipop(Uri uri) {
 346        try {
 347            File file = new File(uri.getPath());
 348            FileDescriptor fd = ParcelFileDescriptor.open(file, ParcelFileDescriptor.MODE_READ_ONLY).getFileDescriptor();
 349            StructStat st = Os.fstat(fd);
 350            return st.st_uid == android.os.Process.myUid();
 351        } catch (FileNotFoundException e) {
 352            return false;
 353        } catch (Exception e) {
 354            return true;
 355        }
 356    }
 357
 358    private void createNoMedia(File diretory) {
 359        final File noMedia = new File(diretory, ".nomedia");
 360        if (!noMedia.exists()) {
 361            try {
 362                if (!noMedia.createNewFile()) {
 363                    Log.d(Config.LOGTAG, "created nomedia file " + noMedia.getAbsolutePath());
 364                }
 365            } catch (Exception e) {
 366                Log.d(Config.LOGTAG, "could not create nomedia file");
 367            }
 368        }
 369    }
 370
 371    public void updateMediaScanner(File file) {
 372        if (!isInDirectoryThatShouldNotBeScanned(mXmppConnectionService, file)) {
 373            Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
 374            intent.setData(Uri.fromFile(file));
 375            mXmppConnectionService.sendBroadcast(intent);
 376        } else if (file.getAbsolutePath().startsWith(getAppMediaDirectory(mXmppConnectionService))) {
 377            createNoMedia(file.getParentFile());
 378        }
 379    }
 380
 381    public boolean deleteFile(Message message) {
 382        File file = getFile(message);
 383        if (file.delete()) {
 384            updateMediaScanner(file);
 385            return true;
 386        } else {
 387            return false;
 388        }
 389    }
 390
 391    public DownloadableFile getFile(Message message) {
 392        return getFile(message, true);
 393    }
 394
 395    public DownloadableFile getFileForPath(String path, String mime) {
 396        final DownloadableFile file;
 397        if (path.startsWith("/")) {
 398            file = new DownloadableFile(path);
 399        } else {
 400            if (mime != null && mime.startsWith("image/")) {
 401                file = new DownloadableFile(getConversationsDirectory("Images") + path);
 402            } else if (mime != null && mime.startsWith("video/")) {
 403                file = new DownloadableFile(getConversationsDirectory("Videos") + path);
 404            } else {
 405                file = new DownloadableFile(getConversationsDirectory("Files") + path);
 406            }
 407        }
 408        return file;
 409    }
 410
 411    public DownloadableFile getFile(Message message, boolean decrypted) {
 412        final boolean encrypted = !decrypted
 413                && (message.getEncryption() == Message.ENCRYPTION_PGP
 414                || message.getEncryption() == Message.ENCRYPTION_DECRYPTED);
 415        String path = message.getRelativeFilePath();
 416        if (path == null) {
 417            path = message.getUuid();
 418        }
 419        final DownloadableFile file = getFileForPath(path, message.getMimeType());
 420        if (encrypted) {
 421            return new DownloadableFile(getConversationsDirectory("Files") + file.getName() + ".pgp");
 422        } else {
 423            return file;
 424        }
 425    }
 426
 427    public String getConversationsDirectory(final String type) {
 428        return getConversationsDirectory(mXmppConnectionService, type);
 429    }
 430
 431    private Bitmap resize(final Bitmap originalBitmap, int size) throws IOException {
 432        int w = originalBitmap.getWidth();
 433        int h = originalBitmap.getHeight();
 434        if (w <= 0 || h <= 0) {
 435            throw new IOException("Decoded bitmap reported bounds smaller 0");
 436        } else if (Math.max(w, h) > size) {
 437            int scalledW;
 438            int scalledH;
 439            if (w <= h) {
 440                scalledW = Math.max((int) (w / ((double) h / size)), 1);
 441                scalledH = size;
 442            } else {
 443                scalledW = size;
 444                scalledH = Math.max((int) (h / ((double) w / size)), 1);
 445            }
 446            final Bitmap result = Bitmap.createScaledBitmap(originalBitmap, scalledW, scalledH, true);
 447            if (!originalBitmap.isRecycled()) {
 448                originalBitmap.recycle();
 449            }
 450            return result;
 451        } else {
 452            return originalBitmap;
 453        }
 454    }
 455
 456    public boolean useImageAsIs(Uri uri) {
 457        String path = getOriginalPath(uri);
 458        if (path == null || isPathBlacklisted(path)) {
 459            return false;
 460        }
 461        File file = new File(path);
 462        long size = file.length();
 463        if (size == 0 || size >= mXmppConnectionService.getResources().getInteger(R.integer.auto_accept_filesize)) {
 464            return false;
 465        }
 466        BitmapFactory.Options options = new BitmapFactory.Options();
 467        options.inJustDecodeBounds = true;
 468        try {
 469            BitmapFactory.decodeStream(mXmppConnectionService.getContentResolver().openInputStream(uri), null, options);
 470            if (options.outMimeType == null || options.outHeight <= 0 || options.outWidth <= 0) {
 471                return false;
 472            }
 473            return (options.outWidth <= Config.IMAGE_SIZE && options.outHeight <= Config.IMAGE_SIZE && options.outMimeType.contains(Config.IMAGE_FORMAT.name().toLowerCase()));
 474        } catch (FileNotFoundException e) {
 475            return false;
 476        }
 477    }
 478
 479    public String getOriginalPath(Uri uri) {
 480        return FileUtils.getPath(mXmppConnectionService, uri);
 481    }
 482
 483    private void copyFileToPrivateStorage(File file, Uri uri) throws FileCopyException {
 484        Log.d(Config.LOGTAG, "copy file (" + uri.toString() + ") to private storage " + file.getAbsolutePath());
 485        file.getParentFile().mkdirs();
 486        OutputStream os = null;
 487        InputStream is = null;
 488        try {
 489            file.createNewFile();
 490            os = new FileOutputStream(file);
 491            is = mXmppConnectionService.getContentResolver().openInputStream(uri);
 492            byte[] buffer = new byte[1024];
 493            int length;
 494            while ((length = is.read(buffer)) > 0) {
 495                try {
 496                    os.write(buffer, 0, length);
 497                } catch (IOException e) {
 498                    throw new FileWriterException();
 499                }
 500            }
 501            try {
 502                os.flush();
 503            } catch (IOException e) {
 504                throw new FileWriterException();
 505            }
 506        } catch (FileNotFoundException e) {
 507            throw new FileCopyException(R.string.error_file_not_found);
 508        } catch (FileWriterException e) {
 509            throw new FileCopyException(R.string.error_unable_to_create_temporary_file);
 510        } catch (IOException e) {
 511            e.printStackTrace();
 512            throw new FileCopyException(R.string.error_io_exception);
 513        } finally {
 514            close(os);
 515            close(is);
 516        }
 517    }
 518
 519    public void copyFileToPrivateStorage(Message message, Uri uri, String type) throws FileCopyException {
 520        String mime = type != null ? type : MimeUtils.guessMimeTypeFromUri(mXmppConnectionService, uri);
 521        Log.d(Config.LOGTAG, "copy " + uri.toString() + " to private storage (mime=" + mime + ")");
 522        String extension = MimeUtils.guessExtensionFromMimeType(mime);
 523        if (extension == null) {
 524            Log.d(Config.LOGTAG, "extension from mime type was null");
 525            extension = getExtensionFromUri(uri);
 526        }
 527        if ("ogg".equals(extension) && type != null && type.startsWith("audio/")) {
 528            extension = "oga";
 529        }
 530        message.setRelativeFilePath(message.getUuid() + "." + extension);
 531        copyFileToPrivateStorage(mXmppConnectionService.getFileBackend().getFile(message), uri);
 532    }
 533
 534    private String getExtensionFromUri(Uri uri) {
 535        String[] projection = {MediaStore.MediaColumns.DATA};
 536        String filename = null;
 537        Cursor cursor = mXmppConnectionService.getContentResolver().query(uri, projection, null, null, null);
 538        if (cursor != null) {
 539            try {
 540                if (cursor.moveToFirst()) {
 541                    filename = cursor.getString(0);
 542                }
 543            } catch (Exception e) {
 544                filename = null;
 545            } finally {
 546                cursor.close();
 547            }
 548        }
 549        if (filename == null) {
 550            final List<String> segments = uri.getPathSegments();
 551            if (segments.size() > 0) {
 552                filename = segments.get(segments.size() - 1);
 553            }
 554        }
 555        int pos = filename == null ? -1 : filename.lastIndexOf('.');
 556        return pos > 0 ? filename.substring(pos + 1) : null;
 557    }
 558
 559    private void copyImageToPrivateStorage(File file, Uri image, int sampleSize) throws FileCopyException {
 560        file.getParentFile().mkdirs();
 561        InputStream is = null;
 562        OutputStream os = null;
 563        try {
 564            if (!file.exists() && !file.createNewFile()) {
 565                throw new FileCopyException(R.string.error_unable_to_create_temporary_file);
 566            }
 567            is = mXmppConnectionService.getContentResolver().openInputStream(image);
 568            if (is == null) {
 569                throw new FileCopyException(R.string.error_not_an_image_file);
 570            }
 571            Bitmap originalBitmap;
 572            BitmapFactory.Options options = new BitmapFactory.Options();
 573            int inSampleSize = (int) Math.pow(2, sampleSize);
 574            Log.d(Config.LOGTAG, "reading bitmap with sample size " + inSampleSize);
 575            options.inSampleSize = inSampleSize;
 576            originalBitmap = BitmapFactory.decodeStream(is, null, options);
 577            is.close();
 578            if (originalBitmap == null) {
 579                throw new FileCopyException(R.string.error_not_an_image_file);
 580            }
 581            Bitmap scaledBitmap = resize(originalBitmap, Config.IMAGE_SIZE);
 582            int rotation = getRotation(image);
 583            scaledBitmap = rotate(scaledBitmap, rotation);
 584            boolean targetSizeReached = false;
 585            int quality = Config.IMAGE_QUALITY;
 586            final int imageMaxSize = mXmppConnectionService.getResources().getInteger(R.integer.auto_accept_filesize);
 587            while (!targetSizeReached) {
 588                os = new FileOutputStream(file);
 589                boolean success = scaledBitmap.compress(Config.IMAGE_FORMAT, quality, os);
 590                if (!success) {
 591                    throw new FileCopyException(R.string.error_compressing_image);
 592                }
 593                os.flush();
 594                targetSizeReached = file.length() <= imageMaxSize || quality <= 50;
 595                quality -= 5;
 596            }
 597            scaledBitmap.recycle();
 598        } catch (FileNotFoundException e) {
 599            throw new FileCopyException(R.string.error_file_not_found);
 600        } catch (IOException e) {
 601            e.printStackTrace();
 602            throw new FileCopyException(R.string.error_io_exception);
 603        } catch (SecurityException e) {
 604            throw new FileCopyException(R.string.error_security_exception_during_image_copy);
 605        } catch (OutOfMemoryError e) {
 606            ++sampleSize;
 607            if (sampleSize <= 3) {
 608                copyImageToPrivateStorage(file, image, sampleSize);
 609            } else {
 610                throw new FileCopyException(R.string.error_out_of_memory);
 611            }
 612        } finally {
 613            close(os);
 614            close(is);
 615        }
 616    }
 617
 618    public void copyImageToPrivateStorage(File file, Uri image) throws FileCopyException {
 619        Log.d(Config.LOGTAG, "copy image (" + image.toString() + ") to private storage " + file.getAbsolutePath());
 620        copyImageToPrivateStorage(file, image, 0);
 621    }
 622
 623    public void copyImageToPrivateStorage(Message message, Uri image) throws FileCopyException {
 624        switch (Config.IMAGE_FORMAT) {
 625            case JPEG:
 626                message.setRelativeFilePath(message.getUuid() + ".jpg");
 627                break;
 628            case PNG:
 629                message.setRelativeFilePath(message.getUuid() + ".png");
 630                break;
 631            case WEBP:
 632                message.setRelativeFilePath(message.getUuid() + ".webp");
 633                break;
 634        }
 635        copyImageToPrivateStorage(getFile(message), image);
 636        updateFileParams(message);
 637    }
 638
 639    private int getRotation(File file) {
 640        return getRotation(Uri.parse("file://" + file.getAbsolutePath()));
 641    }
 642
 643    private int getRotation(Uri image) {
 644        InputStream is = null;
 645        try {
 646            is = mXmppConnectionService.getContentResolver().openInputStream(image);
 647            return ExifHelper.getOrientation(is);
 648        } catch (FileNotFoundException e) {
 649            return 0;
 650        } finally {
 651            close(is);
 652        }
 653    }
 654
 655    public Bitmap getThumbnail(Message message, int size, boolean cacheOnly) throws IOException {
 656        final String uuid = message.getUuid();
 657        final LruCache<String, Bitmap> cache = mXmppConnectionService.getBitmapCache();
 658        Bitmap thumbnail = cache.get(uuid);
 659        if ((thumbnail == null) && (!cacheOnly)) {
 660            synchronized (THUMBNAIL_LOCK) {
 661                thumbnail = cache.get(uuid);
 662                if (thumbnail != null) {
 663                    return thumbnail;
 664                }
 665                DownloadableFile file = getFile(message);
 666                final String mime = file.getMimeType();
 667                if (mime.startsWith("video/")) {
 668                    thumbnail = getVideoPreview(file, size);
 669                } else {
 670                    Bitmap fullsize = getFullsizeImagePreview(file, size);
 671                    if (fullsize == null) {
 672                        throw new FileNotFoundException();
 673                    }
 674                    thumbnail = resize(fullsize, size);
 675                    thumbnail = rotate(thumbnail, getRotation(file));
 676                    if (mime.equals("image/gif")) {
 677                        Bitmap withGifOverlay = thumbnail.copy(Bitmap.Config.ARGB_8888, true);
 678                        drawOverlay(withGifOverlay, paintOverlayBlack(withGifOverlay) ? R.drawable.play_gif_black : R.drawable.play_gif_white, 1.0f);
 679                        thumbnail.recycle();
 680                        thumbnail = withGifOverlay;
 681                    }
 682                }
 683                this.mXmppConnectionService.getBitmapCache().put(uuid, thumbnail);
 684            }
 685        }
 686        return thumbnail;
 687    }
 688
 689    private Bitmap getFullsizeImagePreview(File file, int size) {
 690        BitmapFactory.Options options = new BitmapFactory.Options();
 691        options.inSampleSize = calcSampleSize(file, size);
 692        try {
 693            return BitmapFactory.decodeFile(file.getAbsolutePath(), options);
 694        } catch (OutOfMemoryError e) {
 695            options.inSampleSize *= 2;
 696            return BitmapFactory.decodeFile(file.getAbsolutePath(), options);
 697        }
 698    }
 699
 700    private void drawOverlay(Bitmap bitmap, int resource, float factor) {
 701        Bitmap overlay = BitmapFactory.decodeResource(mXmppConnectionService.getResources(), resource);
 702        Canvas canvas = new Canvas(bitmap);
 703        float targetSize = Math.min(canvas.getWidth(), canvas.getHeight()) * factor;
 704        Log.d(Config.LOGTAG, "target size overlay: " + targetSize + " overlay bitmap size was " + overlay.getHeight());
 705        float left = (canvas.getWidth() - targetSize) / 2.0f;
 706        float top = (canvas.getHeight() - targetSize) / 2.0f;
 707        RectF dst = new RectF(left, top, left + targetSize - 1, top + targetSize - 1);
 708        canvas.drawBitmap(overlay, null, dst, createAntiAliasingPaint());
 709    }
 710
 711    /**
 712     * https://stackoverflow.com/a/3943023/210897
 713     */
 714    private boolean paintOverlayBlack(final Bitmap bitmap) {
 715        final int h = bitmap.getHeight();
 716        final int w = bitmap.getWidth();
 717        int record = 0;
 718        for (int y = Math.round(h * IGNORE_PADDING); y < h - Math.round(h * IGNORE_PADDING); ++y) {
 719            for (int x = Math.round(w * IGNORE_PADDING); x < w - Math.round(w * IGNORE_PADDING); ++x) {
 720                int pixel = bitmap.getPixel(x, y);
 721                if ((Color.red(pixel) * 0.299 + Color.green(pixel) * 0.587 + Color.blue(pixel) * 0.114) > 186) {
 722                    --record;
 723                } else {
 724                    ++record;
 725                }
 726            }
 727        }
 728        return record < 0;
 729    }
 730
 731    private Bitmap getVideoPreview(File file, int size) {
 732        MediaMetadataRetriever metadataRetriever = new MediaMetadataRetriever();
 733        Bitmap frame;
 734        try {
 735            metadataRetriever.setDataSource(file.getAbsolutePath());
 736            frame = metadataRetriever.getFrameAtTime(0);
 737            metadataRetriever.release();
 738            frame = resize(frame, size);
 739        } catch (IOException | RuntimeException e) {
 740            frame = Bitmap.createBitmap(size, size, Bitmap.Config.ARGB_8888);
 741            frame.eraseColor(0xff000000);
 742        }
 743        drawOverlay(frame, paintOverlayBlack(frame) ? R.drawable.play_video_black : R.drawable.play_video_white, 0.75f);
 744        return frame;
 745    }
 746
 747    public Uri getTakePhotoUri() {
 748        File file;
 749        if (Config.ONLY_INTERNAL_STORAGE) {
 750            file = new File(mXmppConnectionService.getCacheDir().getAbsolutePath(), "Camera/IMG_" + this.IMAGE_DATE_FORMAT.format(new Date()) + ".jpg");
 751        } else {
 752            file = new File(getTakePhotoPath() + "IMG_" + this.IMAGE_DATE_FORMAT.format(new Date()) + ".jpg");
 753        }
 754        file.getParentFile().mkdirs();
 755        return getUriForFile(mXmppConnectionService, file);
 756    }
 757
 758    public Avatar getPepAvatar(Uri image, int size, Bitmap.CompressFormat format) {
 759
 760        final Avatar uncompressAvatar = getUncompressedAvatar(image);
 761        if (uncompressAvatar != null && uncompressAvatar.image.length() <= Config.AVATAR_CHAR_LIMIT) {
 762            return uncompressAvatar;
 763        }
 764        if (uncompressAvatar != null) {
 765            Log.d(Config.LOGTAG, "uncompressed avatar exceeded char limit by " + (uncompressAvatar.image.length() - Config.AVATAR_CHAR_LIMIT));
 766        }
 767
 768        Bitmap bm = cropCenterSquare(image, size);
 769        if (bm == null) {
 770            return null;
 771        }
 772        if (hasAlpha(bm)) {
 773            Log.d(Config.LOGTAG, "alpha in avatar detected; uploading as PNG");
 774            bm.recycle();
 775            bm = cropCenterSquare(image, 96);
 776            return getPepAvatar(bm, Bitmap.CompressFormat.PNG, 100);
 777        }
 778        return getPepAvatar(bm, format, 100);
 779    }
 780
 781    private Avatar getUncompressedAvatar(Uri uri) {
 782        Bitmap bitmap = null;
 783        try {
 784            bitmap = BitmapFactory.decodeStream(mXmppConnectionService.getContentResolver().openInputStream(uri));
 785            return getPepAvatar(bitmap, Bitmap.CompressFormat.PNG, 100);
 786        } catch (Exception e) {
 787            return null;
 788        } finally {
 789            if (bitmap != null) {
 790                bitmap.recycle();
 791            }
 792        }
 793    }
 794
 795    private Avatar getPepAvatar(Bitmap bitmap, Bitmap.CompressFormat format, int quality) {
 796        try {
 797            ByteArrayOutputStream mByteArrayOutputStream = new ByteArrayOutputStream();
 798            Base64OutputStream mBase64OutputStream = new Base64OutputStream(mByteArrayOutputStream, Base64.DEFAULT);
 799            MessageDigest digest = MessageDigest.getInstance("SHA-1");
 800            DigestOutputStream mDigestOutputStream = new DigestOutputStream(mBase64OutputStream, digest);
 801            if (!bitmap.compress(format, quality, mDigestOutputStream)) {
 802                return null;
 803            }
 804            mDigestOutputStream.flush();
 805            mDigestOutputStream.close();
 806            long chars = mByteArrayOutputStream.size();
 807            if (format != Bitmap.CompressFormat.PNG && quality >= 50 && chars >= Config.AVATAR_CHAR_LIMIT) {
 808                int q = quality - 2;
 809                Log.d(Config.LOGTAG, "avatar char length was " + chars + " reducing quality to " + q);
 810                return getPepAvatar(bitmap, format, q);
 811            }
 812            Log.d(Config.LOGTAG, "settled on char length " + chars + " with quality=" + quality);
 813            final Avatar avatar = new Avatar();
 814            avatar.sha1sum = CryptoHelper.bytesToHex(digest.digest());
 815            avatar.image = new String(mByteArrayOutputStream.toByteArray());
 816            if (format.equals(Bitmap.CompressFormat.WEBP)) {
 817                avatar.type = "image/webp";
 818            } else if (format.equals(Bitmap.CompressFormat.JPEG)) {
 819                avatar.type = "image/jpeg";
 820            } else if (format.equals(Bitmap.CompressFormat.PNG)) {
 821                avatar.type = "image/png";
 822            }
 823            avatar.width = bitmap.getWidth();
 824            avatar.height = bitmap.getHeight();
 825            return avatar;
 826        } catch (OutOfMemoryError e) {
 827            Log.d(Config.LOGTAG,"unable to convert avatar to base64 due to low memory");
 828            return null;
 829        } catch (Exception e) {
 830            return null;
 831        }
 832    }
 833
 834    public Avatar getStoredPepAvatar(String hash) {
 835        if (hash == null) {
 836            return null;
 837        }
 838        Avatar avatar = new Avatar();
 839        File file = new File(getAvatarPath(hash));
 840        FileInputStream is = null;
 841        try {
 842            avatar.size = file.length();
 843            BitmapFactory.Options options = new BitmapFactory.Options();
 844            options.inJustDecodeBounds = true;
 845            BitmapFactory.decodeFile(file.getAbsolutePath(), options);
 846            is = new FileInputStream(file);
 847            ByteArrayOutputStream mByteArrayOutputStream = new ByteArrayOutputStream();
 848            Base64OutputStream mBase64OutputStream = new Base64OutputStream(mByteArrayOutputStream, Base64.DEFAULT);
 849            MessageDigest digest = MessageDigest.getInstance("SHA-1");
 850            DigestOutputStream os = new DigestOutputStream(mBase64OutputStream, digest);
 851            byte[] buffer = new byte[4096];
 852            int length;
 853            while ((length = is.read(buffer)) > 0) {
 854                os.write(buffer, 0, length);
 855            }
 856            os.flush();
 857            os.close();
 858            avatar.sha1sum = CryptoHelper.bytesToHex(digest.digest());
 859            avatar.image = new String(mByteArrayOutputStream.toByteArray());
 860            avatar.height = options.outHeight;
 861            avatar.width = options.outWidth;
 862            avatar.type = options.outMimeType;
 863            return avatar;
 864        } catch (NoSuchAlgorithmException | IOException e) {
 865            return null;
 866        } finally {
 867            close(is);
 868        }
 869    }
 870
 871    public boolean isAvatarCached(Avatar avatar) {
 872        File file = new File(getAvatarPath(avatar.getFilename()));
 873        return file.exists();
 874    }
 875
 876    public boolean save(final Avatar avatar) {
 877        File file;
 878        if (isAvatarCached(avatar)) {
 879            file = new File(getAvatarPath(avatar.getFilename()));
 880            avatar.size = file.length();
 881        } else {
 882            file = new File(mXmppConnectionService.getCacheDir().getAbsolutePath() + "/" + UUID.randomUUID().toString());
 883            if (file.getParentFile().mkdirs()) {
 884                Log.d(Config.LOGTAG, "created cache directory");
 885            }
 886            OutputStream os = null;
 887            try {
 888                if (!file.createNewFile()) {
 889                    Log.d(Config.LOGTAG, "unable to create temporary file " + file.getAbsolutePath());
 890                }
 891                os = new FileOutputStream(file);
 892                MessageDigest digest = MessageDigest.getInstance("SHA-1");
 893                digest.reset();
 894                DigestOutputStream mDigestOutputStream = new DigestOutputStream(os, digest);
 895                final byte[] bytes = avatar.getImageAsBytes();
 896                mDigestOutputStream.write(bytes);
 897                mDigestOutputStream.flush();
 898                mDigestOutputStream.close();
 899                String sha1sum = CryptoHelper.bytesToHex(digest.digest());
 900                if (sha1sum.equals(avatar.sha1sum)) {
 901                    File outputFile = new File(getAvatarPath(avatar.getFilename()));
 902                    if (outputFile.getParentFile().mkdirs()) {
 903                        Log.d(Config.LOGTAG, "created avatar directory");
 904                    }
 905                    String filename = getAvatarPath(avatar.getFilename());
 906                    if (!file.renameTo(new File(filename))) {
 907                        Log.d(Config.LOGTAG, "unable to rename " + file.getAbsolutePath() + " to " + outputFile);
 908                        return false;
 909                    }
 910                } else {
 911                    Log.d(Config.LOGTAG, "sha1sum mismatch for " + avatar.owner);
 912                    if (!file.delete()) {
 913                        Log.d(Config.LOGTAG, "unable to delete temporary file");
 914                    }
 915                    return false;
 916                }
 917                avatar.size = bytes.length;
 918            } catch (IllegalArgumentException | IOException | NoSuchAlgorithmException e) {
 919                return false;
 920            } finally {
 921                close(os);
 922            }
 923        }
 924        return true;
 925    }
 926
 927    private String getAvatarPath(String avatar) {
 928        return mXmppConnectionService.getFilesDir().getAbsolutePath() + "/avatars/" + avatar;
 929    }
 930
 931    public Uri getAvatarUri(String avatar) {
 932        return Uri.parse("file:" + getAvatarPath(avatar));
 933    }
 934
 935    public Bitmap cropCenterSquare(Uri image, int size) {
 936        if (image == null) {
 937            return null;
 938        }
 939        InputStream is = null;
 940        try {
 941            BitmapFactory.Options options = new BitmapFactory.Options();
 942            options.inSampleSize = calcSampleSize(image, size);
 943            is = mXmppConnectionService.getContentResolver().openInputStream(image);
 944            if (is == null) {
 945                return null;
 946            }
 947            Bitmap input = BitmapFactory.decodeStream(is, null, options);
 948            if (input == null) {
 949                return null;
 950            } else {
 951                input = rotate(input, getRotation(image));
 952                return cropCenterSquare(input, size);
 953            }
 954        } catch (FileNotFoundException | SecurityException e) {
 955            return null;
 956        } finally {
 957            close(is);
 958        }
 959    }
 960
 961    public Bitmap cropCenter(Uri image, int newHeight, int newWidth) {
 962        if (image == null) {
 963            return null;
 964        }
 965        InputStream is = null;
 966        try {
 967            BitmapFactory.Options options = new BitmapFactory.Options();
 968            options.inSampleSize = calcSampleSize(image, Math.max(newHeight, newWidth));
 969            is = mXmppConnectionService.getContentResolver().openInputStream(image);
 970            if (is == null) {
 971                return null;
 972            }
 973            Bitmap source = BitmapFactory.decodeStream(is, null, options);
 974            if (source == null) {
 975                return null;
 976            }
 977            int sourceWidth = source.getWidth();
 978            int sourceHeight = source.getHeight();
 979            float xScale = (float) newWidth / sourceWidth;
 980            float yScale = (float) newHeight / sourceHeight;
 981            float scale = Math.max(xScale, yScale);
 982            float scaledWidth = scale * sourceWidth;
 983            float scaledHeight = scale * sourceHeight;
 984            float left = (newWidth - scaledWidth) / 2;
 985            float top = (newHeight - scaledHeight) / 2;
 986
 987            RectF targetRect = new RectF(left, top, left + scaledWidth, top + scaledHeight);
 988            Bitmap dest = Bitmap.createBitmap(newWidth, newHeight, Bitmap.Config.ARGB_8888);
 989            Canvas canvas = new Canvas(dest);
 990            canvas.drawBitmap(source, null, targetRect, createAntiAliasingPaint());
 991            if (source.isRecycled()) {
 992                source.recycle();
 993            }
 994            return dest;
 995        } catch (SecurityException e) {
 996            return null; //android 6.0 with revoked permissions for example
 997        } catch (FileNotFoundException e) {
 998            return null;
 999        } finally {
1000            close(is);
1001        }
1002    }
1003
1004    public Bitmap cropCenterSquare(Bitmap input, int size) {
1005        int w = input.getWidth();
1006        int h = input.getHeight();
1007
1008        float scale = Math.max((float) size / h, (float) size / w);
1009
1010        float outWidth = scale * w;
1011        float outHeight = scale * h;
1012        float left = (size - outWidth) / 2;
1013        float top = (size - outHeight) / 2;
1014        RectF target = new RectF(left, top, left + outWidth, top + outHeight);
1015
1016        Bitmap output = Bitmap.createBitmap(size, size, Bitmap.Config.ARGB_8888);
1017        Canvas canvas = new Canvas(output);
1018        canvas.drawBitmap(input, null, target, createAntiAliasingPaint());
1019        if (!input.isRecycled()) {
1020            input.recycle();
1021        }
1022        return output;
1023    }
1024
1025    private int calcSampleSize(Uri image, int size) throws FileNotFoundException, SecurityException {
1026        BitmapFactory.Options options = new BitmapFactory.Options();
1027        options.inJustDecodeBounds = true;
1028        BitmapFactory.decodeStream(mXmppConnectionService.getContentResolver().openInputStream(image), null, options);
1029        return calcSampleSize(options, size);
1030    }
1031
1032    public void updateFileParams(Message message) {
1033        updateFileParams(message, null);
1034    }
1035
1036    public void updateFileParams(Message message, URL url) {
1037        DownloadableFile file = getFile(message);
1038        final String mime = file.getMimeType();
1039        boolean image = message.getType() == Message.TYPE_IMAGE || (mime != null && mime.startsWith("image/"));
1040        boolean video = mime != null && mime.startsWith("video/");
1041        boolean audio = mime != null && mime.startsWith("audio/");
1042        final StringBuilder body = new StringBuilder();
1043        if (url != null) {
1044            body.append(url.toString());
1045        }
1046        body.append('|').append(file.getSize());
1047        if (image || video) {
1048            try {
1049                Dimensions dimensions = image ? getImageDimensions(file) : getVideoDimensions(file);
1050                if (dimensions.valid()) {
1051                    body.append('|').append(dimensions.width).append('|').append(dimensions.height);
1052                }
1053            } catch (NotAVideoFile notAVideoFile) {
1054                Log.d(Config.LOGTAG, "file with mime type " + file.getMimeType() + " was not a video file");
1055                //fall threw
1056            }
1057        } else if (audio) {
1058            body.append("|0|0|").append(getMediaRuntime(file));
1059        }
1060        message.setBody(body.toString());
1061    }
1062
1063    public int getMediaRuntime(Uri uri) {
1064        try {
1065            MediaMetadataRetriever mediaMetadataRetriever = new MediaMetadataRetriever();
1066            mediaMetadataRetriever.setDataSource(mXmppConnectionService, uri);
1067            return Integer.parseInt(mediaMetadataRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION));
1068        } catch (RuntimeException e) {
1069            return 0;
1070        }
1071    }
1072
1073    private int getMediaRuntime(File file) {
1074        try {
1075            MediaMetadataRetriever mediaMetadataRetriever = new MediaMetadataRetriever();
1076            mediaMetadataRetriever.setDataSource(file.toString());
1077            return Integer.parseInt(mediaMetadataRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION));
1078        } catch (RuntimeException e) {
1079            return 0;
1080        }
1081    }
1082
1083    private Dimensions getImageDimensions(File file) {
1084        BitmapFactory.Options options = new BitmapFactory.Options();
1085        options.inJustDecodeBounds = true;
1086        BitmapFactory.decodeFile(file.getAbsolutePath(), options);
1087        int rotation = getRotation(file);
1088        boolean rotated = rotation == 90 || rotation == 270;
1089        int imageHeight = rotated ? options.outWidth : options.outHeight;
1090        int imageWidth = rotated ? options.outHeight : options.outWidth;
1091        return new Dimensions(imageHeight, imageWidth);
1092    }
1093
1094    private Dimensions getVideoDimensions(File file) throws NotAVideoFile {
1095        MediaMetadataRetriever metadataRetriever = new MediaMetadataRetriever();
1096        try {
1097            metadataRetriever.setDataSource(file.getAbsolutePath());
1098        } catch (RuntimeException e) {
1099            throw new NotAVideoFile(e);
1100        }
1101        return getVideoDimensions(metadataRetriever);
1102    }
1103
1104    public Bitmap getAvatar(String avatar, int size) {
1105        if (avatar == null) {
1106            return null;
1107        }
1108        Bitmap bm = cropCenter(getAvatarUri(avatar), size, size);
1109        if (bm == null) {
1110            return null;
1111        }
1112        return bm;
1113    }
1114
1115    public boolean isFileAvailable(Message message) {
1116        return getFile(message).exists();
1117    }
1118
1119    private static class Dimensions {
1120        public final int width;
1121        public final int height;
1122
1123        Dimensions(int height, int width) {
1124            this.width = width;
1125            this.height = height;
1126        }
1127
1128        public int getMin() {
1129            return Math.min(width, height);
1130        }
1131
1132        public boolean valid() {
1133            return width > 0 && height > 0;
1134        }
1135    }
1136
1137    private static class NotAVideoFile extends Exception {
1138        public NotAVideoFile(Throwable t) {
1139            super(t);
1140        }
1141
1142        public NotAVideoFile() {
1143            super();
1144        }
1145    }
1146
1147    public class FileCopyException extends Exception {
1148        private static final long serialVersionUID = -1010013599132881427L;
1149        private int resId;
1150
1151        public FileCopyException(int resId) {
1152            this.resId = resId;
1153        }
1154
1155        public int getResId() {
1156            return resId;
1157        }
1158    }
1159}