FileBackend.java

   1package eu.siacs.conversations.persistance;
   2
   3import android.annotation.TargetApi;
   4import android.content.ContentResolver;
   5import android.content.Context;
   6import android.database.Cursor;
   7import android.graphics.Bitmap;
   8import android.graphics.BitmapFactory;
   9import android.graphics.Canvas;
  10import android.graphics.Color;
  11import android.graphics.Matrix;
  12import android.graphics.Paint;
  13import android.graphics.RectF;
  14import android.graphics.pdf.PdfRenderer;
  15import android.media.MediaMetadataRetriever;
  16import android.media.MediaScannerConnection;
  17import android.net.Uri;
  18import android.os.Build;
  19import android.os.Environment;
  20import android.os.ParcelFileDescriptor;
  21import android.provider.MediaStore;
  22import android.provider.OpenableColumns;
  23import android.system.Os;
  24import android.system.StructStat;
  25import android.util.Base64;
  26import android.util.Base64OutputStream;
  27import android.util.DisplayMetrics;
  28import android.util.Log;
  29import android.util.LruCache;
  30
  31import androidx.annotation.RequiresApi;
  32import androidx.annotation.StringRes;
  33import androidx.core.content.FileProvider;
  34import androidx.exifinterface.media.ExifInterface;
  35
  36import com.google.common.base.Strings;
  37import com.google.common.io.ByteStreams;
  38
  39import java.io.ByteArrayOutputStream;
  40import java.io.Closeable;
  41import java.io.File;
  42import java.io.FileDescriptor;
  43import java.io.FileInputStream;
  44import java.io.FileNotFoundException;
  45import java.io.FileOutputStream;
  46import java.io.IOException;
  47import java.io.InputStream;
  48import java.io.OutputStream;
  49import java.net.ServerSocket;
  50import java.net.Socket;
  51import java.security.DigestOutputStream;
  52import java.security.MessageDigest;
  53import java.security.NoSuchAlgorithmException;
  54import java.text.SimpleDateFormat;
  55import java.util.ArrayList;
  56import java.util.Date;
  57import java.util.List;
  58import java.util.Locale;
  59import java.util.UUID;
  60
  61import eu.siacs.conversations.Config;
  62import eu.siacs.conversations.R;
  63import eu.siacs.conversations.entities.DownloadableFile;
  64import eu.siacs.conversations.entities.Message;
  65import eu.siacs.conversations.services.AttachFileToConversationRunnable;
  66import eu.siacs.conversations.services.XmppConnectionService;
  67import eu.siacs.conversations.ui.adapter.MediaAdapter;
  68import eu.siacs.conversations.ui.util.Attachment;
  69import eu.siacs.conversations.utils.Compatibility;
  70import eu.siacs.conversations.utils.CryptoHelper;
  71import eu.siacs.conversations.utils.FileUtils;
  72import eu.siacs.conversations.utils.FileWriterException;
  73import eu.siacs.conversations.utils.MimeUtils;
  74import eu.siacs.conversations.xmpp.pep.Avatar;
  75
  76public class FileBackend {
  77
  78    private static final Object THUMBNAIL_LOCK = new Object();
  79
  80    private static final SimpleDateFormat IMAGE_DATE_FORMAT =
  81            new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.US);
  82
  83    private static final String FILE_PROVIDER = ".files";
  84    private static final float IGNORE_PADDING = 0.15f;
  85    private final XmppConnectionService mXmppConnectionService;
  86
  87    public FileBackend(XmppConnectionService service) {
  88        this.mXmppConnectionService = service;
  89    }
  90
  91    public static long getFileSize(Context context, Uri uri) {
  92        try {
  93            final Cursor cursor = context.getContentResolver().query(uri, null, null, null, null);
  94            if (cursor != null && cursor.moveToFirst()) {
  95                long size = cursor.getLong(cursor.getColumnIndex(OpenableColumns.SIZE));
  96                cursor.close();
  97                return size;
  98            } else {
  99                return -1;
 100            }
 101        } catch (Exception e) {
 102            return -1;
 103        }
 104    }
 105
 106    public static boolean allFilesUnderSize(
 107            Context context, List<Attachment> attachments, long max) {
 108        final boolean compressVideo =
 109                !AttachFileToConversationRunnable.getVideoCompression(context)
 110                        .equals("uncompressed");
 111        if (max <= 0) {
 112            Log.d(Config.LOGTAG, "server did not report max file size for http upload");
 113            return true; // exception to be compatible with HTTP Upload < v0.2
 114        }
 115        for (Attachment attachment : attachments) {
 116            if (attachment.getType() != Attachment.Type.FILE) {
 117                continue;
 118            }
 119            String mime = attachment.getMime();
 120            if (mime != null && mime.startsWith("video/") && compressVideo) {
 121                try {
 122                    Dimensions dimensions =
 123                            FileBackend.getVideoDimensions(context, attachment.getUri());
 124                    if (dimensions.getMin() > 720) {
 125                        Log.d(
 126                                Config.LOGTAG,
 127                                "do not consider video file with min width larger than 720 for size check");
 128                        continue;
 129                    }
 130                } catch (NotAVideoFile notAVideoFile) {
 131                    // ignore and fall through
 132                }
 133            }
 134            if (FileBackend.getFileSize(context, attachment.getUri()) > max) {
 135                Log.d(
 136                        Config.LOGTAG,
 137                        "not all files are under "
 138                                + max
 139                                + " bytes. suggesting falling back to jingle");
 140                return false;
 141            }
 142        }
 143        return true;
 144    }
 145
 146    public static File getBackupDirectory(final Context context) {
 147        final File conversationsDownloadDirectory =
 148                new File(
 149                        Environment.getExternalStoragePublicDirectory(
 150                                Environment.DIRECTORY_DOWNLOADS),
 151                        context.getString(R.string.app_name));
 152        return new File(conversationsDownloadDirectory, "Backup");
 153    }
 154
 155    public static File getLegacyBackupDirectory(final String app) {
 156        final File appDirectory = new File(Environment.getExternalStorageDirectory(), app);
 157        return new File(appDirectory, "Backup");
 158    }
 159
 160    private static Bitmap rotate(final Bitmap bitmap, final int degree) {
 161        if (degree == 0) {
 162            return bitmap;
 163        }
 164        final int w = bitmap.getWidth();
 165        final int h = bitmap.getHeight();
 166        final Matrix matrix = new Matrix();
 167        matrix.postRotate(degree);
 168        final Bitmap result = Bitmap.createBitmap(bitmap, 0, 0, w, h, matrix, true);
 169        if (!bitmap.isRecycled()) {
 170            bitmap.recycle();
 171        }
 172        return result;
 173    }
 174
 175    public static boolean isPathBlacklisted(String path) {
 176        final String androidDataPath =
 177                Environment.getExternalStorageDirectory().getAbsolutePath() + "/Android/data/";
 178        return path.startsWith(androidDataPath);
 179    }
 180
 181    private static Paint createAntiAliasingPaint() {
 182        Paint paint = new Paint();
 183        paint.setAntiAlias(true);
 184        paint.setFilterBitmap(true);
 185        paint.setDither(true);
 186        return paint;
 187    }
 188
 189    public static Uri getUriForUri(Context context, Uri uri) {
 190        if ("file".equals(uri.getScheme())) {
 191            return getUriForFile(context, new File(uri.getPath()));
 192        } else {
 193            return uri;
 194        }
 195    }
 196
 197    public static Uri getUriForFile(Context context, File file) {
 198        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N || Config.ONLY_INTERNAL_STORAGE) {
 199            try {
 200                return FileProvider.getUriForFile(context, getAuthority(context), file);
 201            } catch (IllegalArgumentException e) {
 202                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
 203                    throw new SecurityException(e);
 204                } else {
 205                    return Uri.fromFile(file);
 206                }
 207            }
 208        } else {
 209            return Uri.fromFile(file);
 210        }
 211    }
 212
 213    public static String getAuthority(Context context) {
 214        return context.getPackageName() + FILE_PROVIDER;
 215    }
 216
 217    private static boolean hasAlpha(final Bitmap bitmap) {
 218        final int w = bitmap.getWidth();
 219        final int h = bitmap.getHeight();
 220        final int yStep = Math.max(1, w / 100);
 221        final int xStep = Math.max(1, h / 100);
 222        for (int x = 0; x < w; x += xStep) {
 223            for (int y = 0; y < h; y += yStep) {
 224                if (Color.alpha(bitmap.getPixel(x, y)) < 255) {
 225                    return true;
 226                }
 227            }
 228        }
 229        return false;
 230    }
 231
 232    private static int calcSampleSize(File image, int size) {
 233        BitmapFactory.Options options = new BitmapFactory.Options();
 234        options.inJustDecodeBounds = true;
 235        BitmapFactory.decodeFile(image.getAbsolutePath(), options);
 236        return calcSampleSize(options, size);
 237    }
 238
 239    private static int calcSampleSize(BitmapFactory.Options options, int size) {
 240        int height = options.outHeight;
 241        int width = options.outWidth;
 242        int inSampleSize = 1;
 243
 244        if (height > size || width > size) {
 245            int halfHeight = height / 2;
 246            int halfWidth = width / 2;
 247
 248            while ((halfHeight / inSampleSize) > size && (halfWidth / inSampleSize) > size) {
 249                inSampleSize *= 2;
 250            }
 251        }
 252        return inSampleSize;
 253    }
 254
 255    private static Dimensions getVideoDimensions(Context context, Uri uri) throws NotAVideoFile {
 256        MediaMetadataRetriever mediaMetadataRetriever = new MediaMetadataRetriever();
 257        try {
 258            mediaMetadataRetriever.setDataSource(context, uri);
 259        } catch (RuntimeException e) {
 260            throw new NotAVideoFile(e);
 261        }
 262        return getVideoDimensions(mediaMetadataRetriever);
 263    }
 264
 265    private static Dimensions getVideoDimensionsOfFrame(
 266            MediaMetadataRetriever mediaMetadataRetriever) {
 267        Bitmap bitmap = null;
 268        try {
 269            bitmap = mediaMetadataRetriever.getFrameAtTime();
 270            return new Dimensions(bitmap.getHeight(), bitmap.getWidth());
 271        } catch (Exception e) {
 272            return null;
 273        } finally {
 274            if (bitmap != null) {
 275                bitmap.recycle();
 276            }
 277        }
 278    }
 279
 280    private static Dimensions getVideoDimensions(MediaMetadataRetriever metadataRetriever)
 281            throws NotAVideoFile {
 282        String hasVideo =
 283                metadataRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_HAS_VIDEO);
 284        if (hasVideo == null) {
 285            throw new NotAVideoFile();
 286        }
 287        Dimensions dimensions = getVideoDimensionsOfFrame(metadataRetriever);
 288        if (dimensions != null) {
 289            return dimensions;
 290        }
 291        final int rotation = extractRotationFromMediaRetriever(metadataRetriever);
 292        boolean rotated = rotation == 90 || rotation == 270;
 293        int height;
 294        try {
 295            String h =
 296                    metadataRetriever.extractMetadata(
 297                            MediaMetadataRetriever.METADATA_KEY_VIDEO_HEIGHT);
 298            height = Integer.parseInt(h);
 299        } catch (Exception e) {
 300            height = -1;
 301        }
 302        int width;
 303        try {
 304            String w =
 305                    metadataRetriever.extractMetadata(
 306                            MediaMetadataRetriever.METADATA_KEY_VIDEO_WIDTH);
 307            width = Integer.parseInt(w);
 308        } catch (Exception e) {
 309            width = -1;
 310        }
 311        metadataRetriever.release();
 312        Log.d(Config.LOGTAG, "extracted video dims " + width + "x" + height);
 313        return rotated ? new Dimensions(width, height) : new Dimensions(height, width);
 314    }
 315
 316    private static int extractRotationFromMediaRetriever(MediaMetadataRetriever metadataRetriever) {
 317        String r =
 318                metadataRetriever.extractMetadata(
 319                        MediaMetadataRetriever.METADATA_KEY_VIDEO_ROTATION);
 320        try {
 321            return Integer.parseInt(r);
 322        } catch (Exception e) {
 323            return 0;
 324        }
 325    }
 326
 327    public static void close(final Closeable stream) {
 328        if (stream != null) {
 329            try {
 330                stream.close();
 331            } catch (Exception e) {
 332                Log.d(Config.LOGTAG, "unable to close stream", e);
 333            }
 334        }
 335    }
 336
 337    public static void close(final Socket socket) {
 338        if (socket != null) {
 339            try {
 340                socket.close();
 341            } catch (IOException e) {
 342                Log.d(Config.LOGTAG, "unable to close socket", e);
 343            }
 344        }
 345    }
 346
 347    public static void close(final ServerSocket socket) {
 348        if (socket != null) {
 349            try {
 350                socket.close();
 351            } catch (IOException e) {
 352                Log.d(Config.LOGTAG, "unable to close server socket", e);
 353            }
 354        }
 355    }
 356
 357    public static boolean weOwnFile(Context context, Uri uri) {
 358        if (uri == null || !ContentResolver.SCHEME_FILE.equals(uri.getScheme())) {
 359            return false;
 360        } else if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
 361            return fileIsInFilesDir(context, uri);
 362        } else {
 363            return weOwnFileLollipop(uri);
 364        }
 365    }
 366
 367    /**
 368     * This is more than hacky but probably way better than doing nothing Further 'optimizations'
 369     * might contain to get the parents of CacheDir and NoBackupDir and check against those as well
 370     */
 371    private static boolean fileIsInFilesDir(Context context, Uri uri) {
 372        try {
 373            final String haystack = context.getFilesDir().getParentFile().getCanonicalPath();
 374            final String needle = new File(uri.getPath()).getCanonicalPath();
 375            return needle.startsWith(haystack);
 376        } catch (IOException e) {
 377            return false;
 378        }
 379    }
 380
 381    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
 382    private static boolean weOwnFileLollipop(Uri uri) {
 383        try {
 384            File file = new File(uri.getPath());
 385            FileDescriptor fd =
 386                    ParcelFileDescriptor.open(file, ParcelFileDescriptor.MODE_READ_ONLY)
 387                            .getFileDescriptor();
 388            StructStat st = Os.fstat(fd);
 389            return st.st_uid == android.os.Process.myUid();
 390        } catch (FileNotFoundException e) {
 391            return false;
 392        } catch (Exception e) {
 393            return true;
 394        }
 395    }
 396
 397    public static Uri getMediaUri(Context context, File file) {
 398        final String filePath = file.getAbsolutePath();
 399        final Cursor cursor;
 400        try {
 401            cursor =
 402                    context.getContentResolver()
 403                            .query(
 404                                    MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
 405                                    new String[] {MediaStore.Images.Media._ID},
 406                                    MediaStore.Images.Media.DATA + "=? ",
 407                                    new String[] {filePath},
 408                                    null);
 409        } catch (SecurityException e) {
 410            return null;
 411        }
 412        if (cursor != null && cursor.moveToFirst()) {
 413            final int id = cursor.getInt(cursor.getColumnIndex(MediaStore.MediaColumns._ID));
 414            cursor.close();
 415            return Uri.withAppendedPath(
 416                    MediaStore.Images.Media.EXTERNAL_CONTENT_URI, String.valueOf(id));
 417        } else {
 418            return null;
 419        }
 420    }
 421
 422    public static void updateFileParams(Message message, String url, long size) {
 423        final StringBuilder body = new StringBuilder();
 424        body.append(url).append('|').append(size);
 425        message.setBody(body.toString());
 426    }
 427
 428    public Bitmap getPreviewForUri(Attachment attachment, int size, boolean cacheOnly) {
 429        final String key = "attachment_" + attachment.getUuid().toString() + "_" + size;
 430        final LruCache<String, Bitmap> cache = mXmppConnectionService.getBitmapCache();
 431        Bitmap bitmap = cache.get(key);
 432        if (bitmap != null || cacheOnly) {
 433            return bitmap;
 434        }
 435        final String mime = attachment.getMime();
 436        if ("application/pdf".equals(mime) && Compatibility.runsTwentyOne()) {
 437            bitmap = cropCenterSquarePdf(attachment.getUri(), size);
 438            drawOverlay(
 439                    bitmap,
 440                    paintOverlayBlackPdf(bitmap)
 441                            ? R.drawable.open_pdf_black
 442                            : R.drawable.open_pdf_white,
 443                    0.75f);
 444        } else if (mime != null && mime.startsWith("video/")) {
 445            bitmap = cropCenterSquareVideo(attachment.getUri(), size);
 446            drawOverlay(
 447                    bitmap,
 448                    paintOverlayBlack(bitmap)
 449                            ? R.drawable.play_video_black
 450                            : R.drawable.play_video_white,
 451                    0.75f);
 452        } else {
 453            bitmap = cropCenterSquare(attachment.getUri(), size);
 454            if (bitmap != null && "image/gif".equals(mime)) {
 455                Bitmap withGifOverlay = bitmap.copy(Bitmap.Config.ARGB_8888, true);
 456                drawOverlay(
 457                        withGifOverlay,
 458                        paintOverlayBlack(withGifOverlay)
 459                                ? R.drawable.play_gif_black
 460                                : R.drawable.play_gif_white,
 461                        1.0f);
 462                bitmap.recycle();
 463                bitmap = withGifOverlay;
 464            }
 465        }
 466        if (bitmap != null) {
 467            cache.put(key, bitmap);
 468        }
 469        return bitmap;
 470    }
 471
 472    public void updateMediaScanner(File file) {
 473        updateMediaScanner(file, null);
 474    }
 475
 476    public void updateMediaScanner(File file, final Runnable callback) {
 477        MediaScannerConnection.scanFile(
 478                mXmppConnectionService,
 479                new String[] {file.getAbsolutePath()},
 480                null,
 481                new MediaScannerConnection.MediaScannerConnectionClient() {
 482                    @Override
 483                    public void onMediaScannerConnected() {}
 484
 485                    @Override
 486                    public void onScanCompleted(String path, Uri uri) {
 487                        if (callback != null && file.getAbsolutePath().equals(path)) {
 488                            callback.run();
 489                        } else {
 490                            Log.d(Config.LOGTAG, "media scanner scanned wrong file");
 491                            if (callback != null) {
 492                                callback.run();
 493                            }
 494                        }
 495                    }
 496                });
 497    }
 498
 499    public boolean deleteFile(Message message) {
 500        File file = getFile(message);
 501        if (file.delete()) {
 502            updateMediaScanner(file);
 503            return true;
 504        } else {
 505            return false;
 506        }
 507    }
 508
 509    public DownloadableFile getFile(Message message) {
 510        return getFile(message, true);
 511    }
 512
 513    public DownloadableFile getFileForPath(String path) {
 514        return getFileForPath(
 515                path,
 516                MimeUtils.guessMimeTypeFromExtension(MimeUtils.extractRelevantExtension(path)));
 517    }
 518
 519    private DownloadableFile getFileForPath(final String path, final String mime) {
 520        if (path.startsWith("/")) {
 521            return new DownloadableFile(path);
 522        } else {
 523            return getLegacyFileForFilename(path, mime);
 524        }
 525    }
 526
 527    public DownloadableFile getLegacyFileForFilename(final String filename, final String mime) {
 528        if (Strings.isNullOrEmpty(mime)) {
 529            return new DownloadableFile(getLegacyStorageLocation("Files"), filename);
 530        } else if (mime.startsWith("image/")) {
 531            return new DownloadableFile(getLegacyStorageLocation("Images"), filename);
 532        } else if (mime.startsWith("video/")) {
 533            return new DownloadableFile(getLegacyStorageLocation("Videos"), filename);
 534        } else {
 535            return new DownloadableFile(getLegacyStorageLocation("Files"), filename);
 536        }
 537    }
 538
 539    public boolean isInternalFile(final File file) {
 540        final File internalFile = getFileForPath(file.getName());
 541        return file.getAbsolutePath().equals(internalFile.getAbsolutePath());
 542    }
 543
 544    public DownloadableFile getFile(Message message, boolean decrypted) {
 545        final boolean encrypted =
 546                !decrypted
 547                        && (message.getEncryption() == Message.ENCRYPTION_PGP
 548                                || message.getEncryption() == Message.ENCRYPTION_DECRYPTED);
 549        String path = message.getRelativeFilePath();
 550        if (path == null) {
 551            path = message.getUuid();
 552        }
 553        final DownloadableFile file = getFileForPath(path, message.getMimeType());
 554        if (encrypted) {
 555            return new DownloadableFile(getLegacyStorageLocation("Files"), file.getName() + ".pgp");
 556        } else {
 557            return file;
 558        }
 559    }
 560
 561    public List<Attachment> convertToAttachments(List<DatabaseBackend.FilePath> relativeFilePaths) {
 562        final List<Attachment> attachments = new ArrayList<>();
 563        for (final DatabaseBackend.FilePath relativeFilePath : relativeFilePaths) {
 564            final String mime =
 565                    MimeUtils.guessMimeTypeFromExtension(
 566                            MimeUtils.extractRelevantExtension(relativeFilePath.path));
 567            final File file = getFileForPath(relativeFilePath.path, mime);
 568            attachments.add(Attachment.of(relativeFilePath.uuid, file, mime));
 569        }
 570        return attachments;
 571    }
 572
 573    private File getLegacyStorageLocation(final String type) {
 574        if (Config.ONLY_INTERNAL_STORAGE) {
 575            return new File(mXmppConnectionService.getFilesDir(), type);
 576        } else {
 577            final File appDirectory =
 578                    new File(
 579                            Environment.getExternalStorageDirectory(),
 580                            mXmppConnectionService.getString(R.string.app_name));
 581            final File appMediaDirectory = new File(appDirectory, "Media");
 582            final String locationName =
 583                    String.format(
 584                            "%s %s", mXmppConnectionService.getString(R.string.app_name), type);
 585            return new File(appMediaDirectory, locationName);
 586        }
 587    }
 588
 589    private Bitmap resize(final Bitmap originalBitmap, int size) throws IOException {
 590        int w = originalBitmap.getWidth();
 591        int h = originalBitmap.getHeight();
 592        if (w <= 0 || h <= 0) {
 593            throw new IOException("Decoded bitmap reported bounds smaller 0");
 594        } else if (Math.max(w, h) > size) {
 595            int scalledW;
 596            int scalledH;
 597            if (w <= h) {
 598                scalledW = Math.max((int) (w / ((double) h / size)), 1);
 599                scalledH = size;
 600            } else {
 601                scalledW = size;
 602                scalledH = Math.max((int) (h / ((double) w / size)), 1);
 603            }
 604            final Bitmap result =
 605                    Bitmap.createScaledBitmap(originalBitmap, scalledW, scalledH, true);
 606            if (!originalBitmap.isRecycled()) {
 607                originalBitmap.recycle();
 608            }
 609            return result;
 610        } else {
 611            return originalBitmap;
 612        }
 613    }
 614
 615    public boolean useImageAsIs(final Uri uri) {
 616        final String path = getOriginalPath(uri);
 617        if (path == null || isPathBlacklisted(path)) {
 618            return false;
 619        }
 620        final File file = new File(path);
 621        long size = file.length();
 622        if (size == 0
 623                || size
 624                        >= mXmppConnectionService
 625                                .getResources()
 626                                .getInteger(R.integer.auto_accept_filesize)) {
 627            return false;
 628        }
 629        BitmapFactory.Options options = new BitmapFactory.Options();
 630        options.inJustDecodeBounds = true;
 631        try {
 632            final InputStream inputStream =
 633                    mXmppConnectionService.getContentResolver().openInputStream(uri);
 634            BitmapFactory.decodeStream(inputStream, null, options);
 635            close(inputStream);
 636            if (options.outMimeType == null || options.outHeight <= 0 || options.outWidth <= 0) {
 637                return false;
 638            }
 639            return (options.outWidth <= Config.IMAGE_SIZE
 640                    && options.outHeight <= Config.IMAGE_SIZE
 641                    && options.outMimeType.contains(Config.IMAGE_FORMAT.name().toLowerCase()));
 642        } catch (FileNotFoundException e) {
 643            Log.d(Config.LOGTAG, "unable to get image dimensions", e);
 644            return false;
 645        }
 646    }
 647
 648    public String getOriginalPath(Uri uri) {
 649        return FileUtils.getPath(mXmppConnectionService, uri);
 650    }
 651
 652    private void copyFileToPrivateStorage(File file, Uri uri) throws FileCopyException {
 653        Log.d(
 654                Config.LOGTAG,
 655                "copy file (" + uri.toString() + ") to private storage " + file.getAbsolutePath());
 656        file.getParentFile().mkdirs();
 657        try {
 658            file.createNewFile();
 659        } catch (IOException e) {
 660            throw new FileCopyException(R.string.error_unable_to_create_temporary_file);
 661        }
 662        try (final OutputStream os = new FileOutputStream(file);
 663                final InputStream is =
 664                        mXmppConnectionService.getContentResolver().openInputStream(uri)) {
 665            if (is == null) {
 666                throw new FileCopyException(R.string.error_file_not_found);
 667            }
 668            try {
 669                ByteStreams.copy(is, os);
 670            } catch (IOException e) {
 671                throw new FileWriterException();
 672            }
 673            try {
 674                os.flush();
 675            } catch (IOException e) {
 676                throw new FileWriterException();
 677            }
 678        } catch (final FileNotFoundException e) {
 679            cleanup(file);
 680            throw new FileCopyException(R.string.error_file_not_found);
 681        } catch (final FileWriterException e) {
 682            cleanup(file);
 683            throw new FileCopyException(R.string.error_unable_to_create_temporary_file);
 684        } catch (final SecurityException e) {
 685            cleanup(file);
 686            throw new FileCopyException(R.string.error_security_exception);
 687        } catch (final IOException e) {
 688            cleanup(file);
 689            throw new FileCopyException(R.string.error_io_exception);
 690        }
 691    }
 692
 693    public void copyFileToPrivateStorage(Message message, Uri uri, String type)
 694            throws FileCopyException {
 695        String mime = MimeUtils.guessMimeTypeFromUriAndMime(mXmppConnectionService, uri, type);
 696        Log.d(Config.LOGTAG, "copy " + uri.toString() + " to private storage (mime=" + mime + ")");
 697        String extension = MimeUtils.guessExtensionFromMimeType(mime);
 698        if (extension == null) {
 699            Log.d(Config.LOGTAG, "extension from mime type was null");
 700            extension = getExtensionFromUri(uri);
 701        }
 702        if ("ogg".equals(extension) && type != null && type.startsWith("audio/")) {
 703            extension = "oga";
 704        }
 705        setupRelativeFilePath(message, String.format("%s.%s", message.getUuid(), extension));
 706        copyFileToPrivateStorage(mXmppConnectionService.getFileBackend().getFile(message), uri);
 707    }
 708
 709    private String getExtensionFromUri(final Uri uri) {
 710        final String[] projection = {MediaStore.MediaColumns.DATA};
 711        String filename = null;
 712        try (final Cursor cursor =
 713                mXmppConnectionService
 714                        .getContentResolver()
 715                        .query(uri, projection, null, null, null)) {
 716            if (cursor != null && cursor.moveToFirst()) {
 717                filename = cursor.getString(0);
 718            }
 719        } catch (final SecurityException | IllegalArgumentException e) {
 720            filename = null;
 721        }
 722        if (filename == null) {
 723            final List<String> segments = uri.getPathSegments();
 724            if (segments.size() > 0) {
 725                filename = segments.get(segments.size() - 1);
 726            }
 727        }
 728        final int pos = filename == null ? -1 : filename.lastIndexOf('.');
 729        return pos > 0 ? filename.substring(pos + 1) : null;
 730    }
 731
 732    private void copyImageToPrivateStorage(File file, Uri image, int sampleSize)
 733            throws FileCopyException, ImageCompressionException {
 734        final File parent = file.getParentFile();
 735        if (parent != null && parent.mkdirs()) {
 736            Log.d(Config.LOGTAG, "created parent directory");
 737        }
 738        InputStream is = null;
 739        OutputStream os = null;
 740        try {
 741            if (!file.exists() && !file.createNewFile()) {
 742                throw new FileCopyException(R.string.error_unable_to_create_temporary_file);
 743            }
 744            is = mXmppConnectionService.getContentResolver().openInputStream(image);
 745            if (is == null) {
 746                throw new FileCopyException(R.string.error_not_an_image_file);
 747            }
 748            final Bitmap originalBitmap;
 749            final BitmapFactory.Options options = new BitmapFactory.Options();
 750            final int inSampleSize = (int) Math.pow(2, sampleSize);
 751            Log.d(Config.LOGTAG, "reading bitmap with sample size " + inSampleSize);
 752            options.inSampleSize = inSampleSize;
 753            originalBitmap = BitmapFactory.decodeStream(is, null, options);
 754            is.close();
 755            if (originalBitmap == null) {
 756                throw new ImageCompressionException("Source file was not an image");
 757            }
 758            if (!"image/jpeg".equals(options.outMimeType) && hasAlpha(originalBitmap)) {
 759                originalBitmap.recycle();
 760                throw new ImageCompressionException("Source file had alpha channel");
 761            }
 762            Bitmap scaledBitmap = resize(originalBitmap, Config.IMAGE_SIZE);
 763            final int rotation = getRotation(image);
 764            scaledBitmap = rotate(scaledBitmap, rotation);
 765            boolean targetSizeReached = false;
 766            int quality = Config.IMAGE_QUALITY;
 767            final int imageMaxSize =
 768                    mXmppConnectionService
 769                            .getResources()
 770                            .getInteger(R.integer.auto_accept_filesize);
 771            while (!targetSizeReached) {
 772                os = new FileOutputStream(file);
 773                Log.d(Config.LOGTAG, "compressing image with quality " + quality);
 774                boolean success = scaledBitmap.compress(Config.IMAGE_FORMAT, quality, os);
 775                if (!success) {
 776                    throw new FileCopyException(R.string.error_compressing_image);
 777                }
 778                os.flush();
 779                final long fileSize = file.length();
 780                Log.d(Config.LOGTAG, "achieved file size of " + fileSize);
 781                targetSizeReached = fileSize <= imageMaxSize || quality <= 50;
 782                quality -= 5;
 783            }
 784            scaledBitmap.recycle();
 785        } catch (final FileNotFoundException e) {
 786            cleanup(file);
 787            throw new FileCopyException(R.string.error_file_not_found);
 788        } catch (final IOException e) {
 789            cleanup(file);
 790            throw new FileCopyException(R.string.error_io_exception);
 791        } catch (SecurityException e) {
 792            cleanup(file);
 793            throw new FileCopyException(R.string.error_security_exception_during_image_copy);
 794        } catch (final OutOfMemoryError e) {
 795            ++sampleSize;
 796            if (sampleSize <= 3) {
 797                copyImageToPrivateStorage(file, image, sampleSize);
 798            } else {
 799                throw new FileCopyException(R.string.error_out_of_memory);
 800            }
 801        } finally {
 802            close(os);
 803            close(is);
 804        }
 805    }
 806
 807    private static void cleanup(final File file) {
 808        try {
 809            file.delete();
 810        } catch (Exception e) {
 811
 812        }
 813    }
 814
 815    public void copyImageToPrivateStorage(File file, Uri image)
 816            throws FileCopyException, ImageCompressionException {
 817        Log.d(
 818                Config.LOGTAG,
 819                "copy image ("
 820                        + image.toString()
 821                        + ") to private storage "
 822                        + file.getAbsolutePath());
 823        copyImageToPrivateStorage(file, image, 0);
 824    }
 825
 826    public void copyImageToPrivateStorage(Message message, Uri image)
 827            throws FileCopyException, ImageCompressionException {
 828        final String filename;
 829        switch (Config.IMAGE_FORMAT) {
 830            case JPEG:
 831                filename = String.format("%s.%s", message.getUuid(), "jpg");
 832                break;
 833            case PNG:
 834                filename = String.format("%s.%s", message.getUuid(), "png");
 835                break;
 836            case WEBP:
 837                filename = String.format("%s.%s", message.getUuid(), "webp");
 838                break;
 839            default:
 840                throw new IllegalStateException("Unknown image format");
 841        }
 842        setupRelativeFilePath(message, filename);
 843        copyImageToPrivateStorage(getFile(message), image);
 844        updateFileParams(message);
 845    }
 846
 847    public void setupRelativeFilePath(final Message message, final String filename) {
 848        final String extension = MimeUtils.extractRelevantExtension(filename);
 849        final String mime = MimeUtils.guessMimeTypeFromExtension(extension);
 850        setupRelativeFilePath(message, filename, mime);
 851    }
 852
 853    public File getStorageLocation(final String filename, final String mime) {
 854        final File parentDirectory;
 855        if (Strings.isNullOrEmpty(mime)) {
 856            parentDirectory =
 857                    Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
 858        } else if (mime.startsWith("image/")) {
 859            parentDirectory =
 860                    Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
 861        } else if (mime.startsWith("video/")) {
 862            parentDirectory =
 863                    Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MOVIES);
 864        } else if (MediaAdapter.DOCUMENT_MIMES.contains(mime)) {
 865            parentDirectory =
 866                    Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS);
 867        } else {
 868            parentDirectory =
 869                    Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
 870        }
 871        final File appDirectory =
 872                new File(parentDirectory, mXmppConnectionService.getString(R.string.app_name));
 873        return new File(appDirectory, filename);
 874    }
 875
 876    public void setupRelativeFilePath(
 877            final Message message, final String filename, final String mime) {
 878        final File file = getStorageLocation(filename, mime);
 879        message.setRelativeFilePath(file.getAbsolutePath());
 880    }
 881
 882    public boolean unusualBounds(final Uri image) {
 883        try {
 884            final BitmapFactory.Options options = new BitmapFactory.Options();
 885            options.inJustDecodeBounds = true;
 886            final InputStream inputStream =
 887                    mXmppConnectionService.getContentResolver().openInputStream(image);
 888            BitmapFactory.decodeStream(inputStream, null, options);
 889            close(inputStream);
 890            float ratio = (float) options.outHeight / options.outWidth;
 891            return ratio > (21.0f / 9.0f) || ratio < (9.0f / 21.0f);
 892        } catch (final Exception e) {
 893            Log.w(Config.LOGTAG, "unable to detect image bounds", e);
 894            return false;
 895        }
 896    }
 897
 898    private int getRotation(final File file) {
 899        try (final InputStream inputStream = new FileInputStream(file)) {
 900            return getRotation(inputStream);
 901        } catch (Exception e) {
 902            return 0;
 903        }
 904    }
 905
 906    private int getRotation(final Uri image) {
 907        try (final InputStream is =
 908                mXmppConnectionService.getContentResolver().openInputStream(image)) {
 909            return is == null ? 0 : getRotation(is);
 910        } catch (final Exception e) {
 911            return 0;
 912        }
 913    }
 914
 915    private static int getRotation(final InputStream inputStream) throws IOException {
 916        final ExifInterface exif = new ExifInterface(inputStream);
 917        final int orientation =
 918                exif.getAttributeInt(
 919                        ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_UNDEFINED);
 920        switch (orientation) {
 921            case ExifInterface.ORIENTATION_ROTATE_180:
 922                return 180;
 923            case ExifInterface.ORIENTATION_ROTATE_90:
 924                return 90;
 925            case ExifInterface.ORIENTATION_ROTATE_270:
 926                return 270;
 927            default:
 928                return 0;
 929        }
 930    }
 931
 932    public Bitmap getThumbnail(Message message, int size, boolean cacheOnly) throws IOException {
 933        final String uuid = message.getUuid();
 934        final LruCache<String, Bitmap> cache = mXmppConnectionService.getBitmapCache();
 935        Bitmap thumbnail = cache.get(uuid);
 936        if ((thumbnail == null) && (!cacheOnly)) {
 937            synchronized (THUMBNAIL_LOCK) {
 938                thumbnail = cache.get(uuid);
 939                if (thumbnail != null) {
 940                    return thumbnail;
 941                }
 942                DownloadableFile file = getFile(message);
 943                final String mime = file.getMimeType();
 944                if ("application/pdf".equals(mime) && Compatibility.runsTwentyOne()) {
 945                    thumbnail = getPdfDocumentPreview(file, size);
 946                } else if (mime.startsWith("video/")) {
 947                    thumbnail = getVideoPreview(file, size);
 948                } else {
 949                    final Bitmap fullSize = getFullSizeImagePreview(file, size);
 950                    if (fullSize == null) {
 951                        throw new FileNotFoundException();
 952                    }
 953                    thumbnail = resize(fullSize, size);
 954                    thumbnail = rotate(thumbnail, getRotation(file));
 955                    if (mime.equals("image/gif")) {
 956                        Bitmap withGifOverlay = thumbnail.copy(Bitmap.Config.ARGB_8888, true);
 957                        drawOverlay(
 958                                withGifOverlay,
 959                                paintOverlayBlack(withGifOverlay)
 960                                        ? R.drawable.play_gif_black
 961                                        : R.drawable.play_gif_white,
 962                                1.0f);
 963                        thumbnail.recycle();
 964                        thumbnail = withGifOverlay;
 965                    }
 966                }
 967                cache.put(uuid, thumbnail);
 968            }
 969        }
 970        return thumbnail;
 971    }
 972
 973    private Bitmap getFullSizeImagePreview(File file, int size) {
 974        BitmapFactory.Options options = new BitmapFactory.Options();
 975        options.inSampleSize = calcSampleSize(file, size);
 976        try {
 977            return BitmapFactory.decodeFile(file.getAbsolutePath(), options);
 978        } catch (OutOfMemoryError e) {
 979            options.inSampleSize *= 2;
 980            return BitmapFactory.decodeFile(file.getAbsolutePath(), options);
 981        }
 982    }
 983
 984    private void drawOverlay(Bitmap bitmap, int resource, float factor) {
 985        Bitmap overlay =
 986                BitmapFactory.decodeResource(mXmppConnectionService.getResources(), resource);
 987        Canvas canvas = new Canvas(bitmap);
 988        float targetSize = Math.min(canvas.getWidth(), canvas.getHeight()) * factor;
 989        Log.d(
 990                Config.LOGTAG,
 991                "target size overlay: "
 992                        + targetSize
 993                        + " overlay bitmap size was "
 994                        + overlay.getHeight());
 995        float left = (canvas.getWidth() - targetSize) / 2.0f;
 996        float top = (canvas.getHeight() - targetSize) / 2.0f;
 997        RectF dst = new RectF(left, top, left + targetSize - 1, top + targetSize - 1);
 998        canvas.drawBitmap(overlay, null, dst, createAntiAliasingPaint());
 999    }
1000
1001    /** https://stackoverflow.com/a/3943023/210897 */
1002    private boolean paintOverlayBlack(final Bitmap bitmap) {
1003        final int h = bitmap.getHeight();
1004        final int w = bitmap.getWidth();
1005        int record = 0;
1006        for (int y = Math.round(h * IGNORE_PADDING); y < h - Math.round(h * IGNORE_PADDING); ++y) {
1007            for (int x = Math.round(w * IGNORE_PADDING);
1008                    x < w - Math.round(w * IGNORE_PADDING);
1009                    ++x) {
1010                int pixel = bitmap.getPixel(x, y);
1011                if ((Color.red(pixel) * 0.299
1012                                + Color.green(pixel) * 0.587
1013                                + Color.blue(pixel) * 0.114)
1014                        > 186) {
1015                    --record;
1016                } else {
1017                    ++record;
1018                }
1019            }
1020        }
1021        return record < 0;
1022    }
1023
1024    private boolean paintOverlayBlackPdf(final Bitmap bitmap) {
1025        final int h = bitmap.getHeight();
1026        final int w = bitmap.getWidth();
1027        int white = 0;
1028        for (int y = 0; y < h; ++y) {
1029            for (int x = 0; x < w; ++x) {
1030                int pixel = bitmap.getPixel(x, y);
1031                if ((Color.red(pixel) * 0.299
1032                                + Color.green(pixel) * 0.587
1033                                + Color.blue(pixel) * 0.114)
1034                        > 186) {
1035                    white++;
1036                }
1037            }
1038        }
1039        return white > (h * w * 0.4f);
1040    }
1041
1042    private Bitmap cropCenterSquareVideo(Uri uri, int size) {
1043        MediaMetadataRetriever metadataRetriever = new MediaMetadataRetriever();
1044        Bitmap frame;
1045        try {
1046            metadataRetriever.setDataSource(mXmppConnectionService, uri);
1047            frame = metadataRetriever.getFrameAtTime(0);
1048            metadataRetriever.release();
1049            return cropCenterSquare(frame, size);
1050        } catch (Exception e) {
1051            frame = Bitmap.createBitmap(size, size, Bitmap.Config.ARGB_8888);
1052            frame.eraseColor(0xff000000);
1053            return frame;
1054        }
1055    }
1056
1057    private Bitmap getVideoPreview(final File file, final int size) {
1058        final MediaMetadataRetriever metadataRetriever = new MediaMetadataRetriever();
1059        Bitmap frame;
1060        try {
1061            metadataRetriever.setDataSource(file.getAbsolutePath());
1062            frame = metadataRetriever.getFrameAtTime(0);
1063            metadataRetriever.release();
1064            frame = resize(frame, size);
1065        } catch (IOException | RuntimeException e) {
1066            frame = Bitmap.createBitmap(size, size, Bitmap.Config.ARGB_8888);
1067            frame.eraseColor(0xff000000);
1068        }
1069        drawOverlay(
1070                frame,
1071                paintOverlayBlack(frame)
1072                        ? R.drawable.play_video_black
1073                        : R.drawable.play_video_white,
1074                0.75f);
1075        return frame;
1076    }
1077
1078    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
1079    private Bitmap getPdfDocumentPreview(final File file, final int size) {
1080        try {
1081            final ParcelFileDescriptor fileDescriptor =
1082                    ParcelFileDescriptor.open(file, ParcelFileDescriptor.MODE_READ_ONLY);
1083            final Bitmap rendered = renderPdfDocument(fileDescriptor, size, true);
1084            drawOverlay(
1085                    rendered,
1086                    paintOverlayBlackPdf(rendered)
1087                            ? R.drawable.open_pdf_black
1088                            : R.drawable.open_pdf_white,
1089                    0.75f);
1090            return rendered;
1091        } catch (final IOException | SecurityException e) {
1092            Log.d(Config.LOGTAG, "unable to render PDF document preview", e);
1093            final Bitmap placeholder = Bitmap.createBitmap(size, size, Bitmap.Config.ARGB_8888);
1094            placeholder.eraseColor(0xff000000);
1095            return placeholder;
1096        }
1097    }
1098
1099    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
1100    private Bitmap cropCenterSquarePdf(final Uri uri, final int size) {
1101        try {
1102            ParcelFileDescriptor fileDescriptor =
1103                    mXmppConnectionService.getContentResolver().openFileDescriptor(uri, "r");
1104            final Bitmap bitmap = renderPdfDocument(fileDescriptor, size, false);
1105            return cropCenterSquare(bitmap, size);
1106        } catch (Exception e) {
1107            final Bitmap placeholder = Bitmap.createBitmap(size, size, Bitmap.Config.ARGB_8888);
1108            placeholder.eraseColor(0xff000000);
1109            return placeholder;
1110        }
1111    }
1112
1113    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
1114    private Bitmap renderPdfDocument(
1115            ParcelFileDescriptor fileDescriptor, int targetSize, boolean fit) throws IOException {
1116        final PdfRenderer pdfRenderer = new PdfRenderer(fileDescriptor);
1117        final PdfRenderer.Page page = pdfRenderer.openPage(0);
1118        final Dimensions dimensions =
1119                scalePdfDimensions(
1120                        new Dimensions(page.getHeight(), page.getWidth()), targetSize, fit);
1121        final Bitmap rendered =
1122                Bitmap.createBitmap(dimensions.width, dimensions.height, Bitmap.Config.ARGB_8888);
1123        rendered.eraseColor(0xffffffff);
1124        page.render(rendered, null, null, PdfRenderer.Page.RENDER_MODE_FOR_DISPLAY);
1125        page.close();
1126        pdfRenderer.close();
1127        fileDescriptor.close();
1128        return rendered;
1129    }
1130
1131    public Uri getTakePhotoUri() {
1132        final String filename =
1133                String.format("IMG_%s.%s", IMAGE_DATE_FORMAT.format(new Date()), "jpg");
1134        final File directory;
1135        if (Config.ONLY_INTERNAL_STORAGE) {
1136            directory = new File(mXmppConnectionService.getCacheDir(), "Camera");
1137        } else {
1138            directory =
1139                    new File(
1140                            Environment.getExternalStoragePublicDirectory(
1141                                    Environment.DIRECTORY_DCIM),
1142                            "Camera");
1143        }
1144        final File file = new File(directory, filename);
1145        file.getParentFile().mkdirs();
1146        return getUriForFile(mXmppConnectionService, file);
1147    }
1148
1149    public Avatar getPepAvatar(Uri image, int size, Bitmap.CompressFormat format) {
1150
1151        final Avatar uncompressAvatar = getUncompressedAvatar(image);
1152        if (uncompressAvatar != null
1153                && uncompressAvatar.image.length() <= Config.AVATAR_CHAR_LIMIT) {
1154            return uncompressAvatar;
1155        }
1156        if (uncompressAvatar != null) {
1157            Log.d(
1158                    Config.LOGTAG,
1159                    "uncompressed avatar exceeded char limit by "
1160                            + (uncompressAvatar.image.length() - Config.AVATAR_CHAR_LIMIT));
1161        }
1162
1163        Bitmap bm = cropCenterSquare(image, size);
1164        if (bm == null) {
1165            return null;
1166        }
1167        if (hasAlpha(bm)) {
1168            Log.d(Config.LOGTAG, "alpha in avatar detected; uploading as PNG");
1169            bm.recycle();
1170            bm = cropCenterSquare(image, 96);
1171            return getPepAvatar(bm, Bitmap.CompressFormat.PNG, 100);
1172        }
1173        return getPepAvatar(bm, format, 100);
1174    }
1175
1176    private Avatar getUncompressedAvatar(Uri uri) {
1177        Bitmap bitmap = null;
1178        try {
1179            bitmap =
1180                    BitmapFactory.decodeStream(
1181                            mXmppConnectionService.getContentResolver().openInputStream(uri));
1182            return getPepAvatar(bitmap, Bitmap.CompressFormat.PNG, 100);
1183        } catch (Exception e) {
1184            return null;
1185        } finally {
1186            if (bitmap != null) {
1187                bitmap.recycle();
1188            }
1189        }
1190    }
1191
1192    private Avatar getPepAvatar(Bitmap bitmap, Bitmap.CompressFormat format, int quality) {
1193        try {
1194            ByteArrayOutputStream mByteArrayOutputStream = new ByteArrayOutputStream();
1195            Base64OutputStream mBase64OutputStream =
1196                    new Base64OutputStream(mByteArrayOutputStream, Base64.DEFAULT);
1197            MessageDigest digest = MessageDigest.getInstance("SHA-1");
1198            DigestOutputStream mDigestOutputStream =
1199                    new DigestOutputStream(mBase64OutputStream, digest);
1200            if (!bitmap.compress(format, quality, mDigestOutputStream)) {
1201                return null;
1202            }
1203            mDigestOutputStream.flush();
1204            mDigestOutputStream.close();
1205            long chars = mByteArrayOutputStream.size();
1206            if (format != Bitmap.CompressFormat.PNG
1207                    && quality >= 50
1208                    && chars >= Config.AVATAR_CHAR_LIMIT) {
1209                int q = quality - 2;
1210                Log.d(
1211                        Config.LOGTAG,
1212                        "avatar char length was " + chars + " reducing quality to " + q);
1213                return getPepAvatar(bitmap, format, q);
1214            }
1215            Log.d(Config.LOGTAG, "settled on char length " + chars + " with quality=" + quality);
1216            final Avatar avatar = new Avatar();
1217            avatar.sha1sum = CryptoHelper.bytesToHex(digest.digest());
1218            avatar.image = new String(mByteArrayOutputStream.toByteArray());
1219            if (format.equals(Bitmap.CompressFormat.WEBP)) {
1220                avatar.type = "image/webp";
1221            } else if (format.equals(Bitmap.CompressFormat.JPEG)) {
1222                avatar.type = "image/jpeg";
1223            } else if (format.equals(Bitmap.CompressFormat.PNG)) {
1224                avatar.type = "image/png";
1225            }
1226            avatar.width = bitmap.getWidth();
1227            avatar.height = bitmap.getHeight();
1228            return avatar;
1229        } catch (OutOfMemoryError e) {
1230            Log.d(Config.LOGTAG, "unable to convert avatar to base64 due to low memory");
1231            return null;
1232        } catch (Exception e) {
1233            return null;
1234        }
1235    }
1236
1237    public Avatar getStoredPepAvatar(String hash) {
1238        if (hash == null) {
1239            return null;
1240        }
1241        Avatar avatar = new Avatar();
1242        final File file = getAvatarFile(hash);
1243        FileInputStream is = null;
1244        try {
1245            avatar.size = file.length();
1246            BitmapFactory.Options options = new BitmapFactory.Options();
1247            options.inJustDecodeBounds = true;
1248            BitmapFactory.decodeFile(file.getAbsolutePath(), options);
1249            is = new FileInputStream(file);
1250            ByteArrayOutputStream mByteArrayOutputStream = new ByteArrayOutputStream();
1251            Base64OutputStream mBase64OutputStream =
1252                    new Base64OutputStream(mByteArrayOutputStream, Base64.DEFAULT);
1253            MessageDigest digest = MessageDigest.getInstance("SHA-1");
1254            DigestOutputStream os = new DigestOutputStream(mBase64OutputStream, digest);
1255            byte[] buffer = new byte[4096];
1256            int length;
1257            while ((length = is.read(buffer)) > 0) {
1258                os.write(buffer, 0, length);
1259            }
1260            os.flush();
1261            os.close();
1262            avatar.sha1sum = CryptoHelper.bytesToHex(digest.digest());
1263            avatar.image = new String(mByteArrayOutputStream.toByteArray());
1264            avatar.height = options.outHeight;
1265            avatar.width = options.outWidth;
1266            avatar.type = options.outMimeType;
1267            return avatar;
1268        } catch (NoSuchAlgorithmException | IOException e) {
1269            return null;
1270        } finally {
1271            close(is);
1272        }
1273    }
1274
1275    public boolean isAvatarCached(Avatar avatar) {
1276        final File file = getAvatarFile(avatar.getFilename());
1277        return file.exists();
1278    }
1279
1280    public boolean save(final Avatar avatar) {
1281        File file;
1282        if (isAvatarCached(avatar)) {
1283            file = getAvatarFile(avatar.getFilename());
1284            avatar.size = file.length();
1285        } else {
1286            file =
1287                    new File(
1288                            mXmppConnectionService.getCacheDir().getAbsolutePath()
1289                                    + "/"
1290                                    + UUID.randomUUID().toString());
1291            if (file.getParentFile().mkdirs()) {
1292                Log.d(Config.LOGTAG, "created cache directory");
1293            }
1294            OutputStream os = null;
1295            try {
1296                if (!file.createNewFile()) {
1297                    Log.d(
1298                            Config.LOGTAG,
1299                            "unable to create temporary file " + file.getAbsolutePath());
1300                }
1301                os = new FileOutputStream(file);
1302                MessageDigest digest = MessageDigest.getInstance("SHA-1");
1303                digest.reset();
1304                DigestOutputStream mDigestOutputStream = new DigestOutputStream(os, digest);
1305                final byte[] bytes = avatar.getImageAsBytes();
1306                mDigestOutputStream.write(bytes);
1307                mDigestOutputStream.flush();
1308                mDigestOutputStream.close();
1309                String sha1sum = CryptoHelper.bytesToHex(digest.digest());
1310                if (sha1sum.equals(avatar.sha1sum)) {
1311                    final File outputFile = getAvatarFile(avatar.getFilename());
1312                    if (outputFile.getParentFile().mkdirs()) {
1313                        Log.d(Config.LOGTAG, "created avatar directory");
1314                    }
1315                    final File avatarFile = getAvatarFile(avatar.getFilename());
1316                    if (!file.renameTo(avatarFile)) {
1317                        Log.d(
1318                                Config.LOGTAG,
1319                                "unable to rename " + file.getAbsolutePath() + " to " + outputFile);
1320                        return false;
1321                    }
1322                } else {
1323                    Log.d(Config.LOGTAG, "sha1sum mismatch for " + avatar.owner);
1324                    if (!file.delete()) {
1325                        Log.d(Config.LOGTAG, "unable to delete temporary file");
1326                    }
1327                    return false;
1328                }
1329                avatar.size = bytes.length;
1330            } catch (IllegalArgumentException | IOException | NoSuchAlgorithmException e) {
1331                return false;
1332            } finally {
1333                close(os);
1334            }
1335        }
1336        return true;
1337    }
1338
1339    public void deleteHistoricAvatarPath() {
1340        delete(getHistoricAvatarPath());
1341    }
1342
1343    private void delete(final File file) {
1344        if (file.isDirectory()) {
1345            final File[] files = file.listFiles();
1346            if (files != null) {
1347                for (final File f : files) {
1348                    delete(f);
1349                }
1350            }
1351        }
1352        if (file.delete()) {
1353            Log.d(Config.LOGTAG, "deleted " + file.getAbsolutePath());
1354        }
1355    }
1356
1357    private File getHistoricAvatarPath() {
1358        return new File(mXmppConnectionService.getFilesDir(), "/avatars/");
1359    }
1360
1361    private File getAvatarFile(String avatar) {
1362        return new File(mXmppConnectionService.getCacheDir(), "/avatars/" + avatar);
1363    }
1364
1365    public Uri getAvatarUri(String avatar) {
1366        return Uri.fromFile(getAvatarFile(avatar));
1367    }
1368
1369    public Bitmap cropCenterSquare(Uri image, int size) {
1370        if (image == null) {
1371            return null;
1372        }
1373        InputStream is = null;
1374        try {
1375            BitmapFactory.Options options = new BitmapFactory.Options();
1376            options.inSampleSize = calcSampleSize(image, size);
1377            is = mXmppConnectionService.getContentResolver().openInputStream(image);
1378            if (is == null) {
1379                return null;
1380            }
1381            Bitmap input = BitmapFactory.decodeStream(is, null, options);
1382            if (input == null) {
1383                return null;
1384            } else {
1385                input = rotate(input, getRotation(image));
1386                return cropCenterSquare(input, size);
1387            }
1388        } catch (FileNotFoundException | SecurityException e) {
1389            Log.d(Config.LOGTAG, "unable to open file " + image.toString(), e);
1390            return null;
1391        } finally {
1392            close(is);
1393        }
1394    }
1395
1396    public Bitmap cropCenter(Uri image, int newHeight, int newWidth) {
1397        if (image == null) {
1398            return null;
1399        }
1400        InputStream is = null;
1401        try {
1402            BitmapFactory.Options options = new BitmapFactory.Options();
1403            options.inSampleSize = calcSampleSize(image, Math.max(newHeight, newWidth));
1404            is = mXmppConnectionService.getContentResolver().openInputStream(image);
1405            if (is == null) {
1406                return null;
1407            }
1408            Bitmap source = BitmapFactory.decodeStream(is, null, options);
1409            if (source == null) {
1410                return null;
1411            }
1412            int sourceWidth = source.getWidth();
1413            int sourceHeight = source.getHeight();
1414            float xScale = (float) newWidth / sourceWidth;
1415            float yScale = (float) newHeight / sourceHeight;
1416            float scale = Math.max(xScale, yScale);
1417            float scaledWidth = scale * sourceWidth;
1418            float scaledHeight = scale * sourceHeight;
1419            float left = (newWidth - scaledWidth) / 2;
1420            float top = (newHeight - scaledHeight) / 2;
1421
1422            RectF targetRect = new RectF(left, top, left + scaledWidth, top + scaledHeight);
1423            Bitmap dest = Bitmap.createBitmap(newWidth, newHeight, Bitmap.Config.ARGB_8888);
1424            Canvas canvas = new Canvas(dest);
1425            canvas.drawBitmap(source, null, targetRect, createAntiAliasingPaint());
1426            if (source.isRecycled()) {
1427                source.recycle();
1428            }
1429            return dest;
1430        } catch (SecurityException e) {
1431            return null; // android 6.0 with revoked permissions for example
1432        } catch (FileNotFoundException e) {
1433            return null;
1434        } finally {
1435            close(is);
1436        }
1437    }
1438
1439    public Bitmap cropCenterSquare(Bitmap input, int size) {
1440        int w = input.getWidth();
1441        int h = input.getHeight();
1442
1443        float scale = Math.max((float) size / h, (float) size / w);
1444
1445        float outWidth = scale * w;
1446        float outHeight = scale * h;
1447        float left = (size - outWidth) / 2;
1448        float top = (size - outHeight) / 2;
1449        RectF target = new RectF(left, top, left + outWidth, top + outHeight);
1450
1451        Bitmap output = Bitmap.createBitmap(size, size, Bitmap.Config.ARGB_8888);
1452        Canvas canvas = new Canvas(output);
1453        canvas.drawBitmap(input, null, target, createAntiAliasingPaint());
1454        if (!input.isRecycled()) {
1455            input.recycle();
1456        }
1457        return output;
1458    }
1459
1460    private int calcSampleSize(Uri image, int size)
1461            throws FileNotFoundException, SecurityException {
1462        final BitmapFactory.Options options = new BitmapFactory.Options();
1463        options.inJustDecodeBounds = true;
1464        final InputStream inputStream =
1465                mXmppConnectionService.getContentResolver().openInputStream(image);
1466        BitmapFactory.decodeStream(inputStream, null, options);
1467        close(inputStream);
1468        return calcSampleSize(options, size);
1469    }
1470
1471    public void updateFileParams(Message message) {
1472        updateFileParams(message, null);
1473    }
1474
1475    public void updateFileParams(Message message, String url) {
1476        DownloadableFile file = getFile(message);
1477        final String mime = file.getMimeType();
1478        final boolean privateMessage = message.isPrivateMessage();
1479        final boolean image =
1480                message.getType() == Message.TYPE_IMAGE
1481                        || (mime != null && mime.startsWith("image/"));
1482        final boolean video = mime != null && mime.startsWith("video/");
1483        final boolean audio = mime != null && mime.startsWith("audio/");
1484        final boolean pdf = "application/pdf".equals(mime);
1485        final StringBuilder body = new StringBuilder();
1486        if (url != null) {
1487            body.append(url);
1488        }
1489        body.append('|').append(file.getSize());
1490        if (image || video || (pdf && Compatibility.runsTwentyOne())) {
1491            try {
1492                final Dimensions dimensions;
1493                if (video) {
1494                    dimensions = getVideoDimensions(file);
1495                } else if (pdf && Compatibility.runsTwentyOne()) {
1496                    dimensions = getPdfDocumentDimensions(file);
1497                } else {
1498                    dimensions = getImageDimensions(file);
1499                }
1500                if (dimensions.valid()) {
1501                    body.append('|').append(dimensions.width).append('|').append(dimensions.height);
1502                }
1503            } catch (NotAVideoFile notAVideoFile) {
1504                Log.d(
1505                        Config.LOGTAG,
1506                        "file with mime type " + file.getMimeType() + " was not a video file");
1507                // fall threw
1508            }
1509        } else if (audio) {
1510            body.append("|0|0|").append(getMediaRuntime(file));
1511        }
1512        message.setBody(body.toString());
1513        message.setDeleted(false);
1514        message.setType(
1515                privateMessage
1516                        ? Message.TYPE_PRIVATE_FILE
1517                        : (image ? Message.TYPE_IMAGE : Message.TYPE_FILE));
1518    }
1519
1520    private int getMediaRuntime(File file) {
1521        try {
1522            MediaMetadataRetriever mediaMetadataRetriever = new MediaMetadataRetriever();
1523            mediaMetadataRetriever.setDataSource(file.toString());
1524            return Integer.parseInt(
1525                    mediaMetadataRetriever.extractMetadata(
1526                            MediaMetadataRetriever.METADATA_KEY_DURATION));
1527        } catch (RuntimeException e) {
1528            return 0;
1529        }
1530    }
1531
1532    private Dimensions getImageDimensions(File file) {
1533        BitmapFactory.Options options = new BitmapFactory.Options();
1534        options.inJustDecodeBounds = true;
1535        BitmapFactory.decodeFile(file.getAbsolutePath(), options);
1536        int rotation = getRotation(file);
1537        boolean rotated = rotation == 90 || rotation == 270;
1538        int imageHeight = rotated ? options.outWidth : options.outHeight;
1539        int imageWidth = rotated ? options.outHeight : options.outWidth;
1540        return new Dimensions(imageHeight, imageWidth);
1541    }
1542
1543    private Dimensions getVideoDimensions(File file) throws NotAVideoFile {
1544        MediaMetadataRetriever metadataRetriever = new MediaMetadataRetriever();
1545        try {
1546            metadataRetriever.setDataSource(file.getAbsolutePath());
1547        } catch (RuntimeException e) {
1548            throw new NotAVideoFile(e);
1549        }
1550        return getVideoDimensions(metadataRetriever);
1551    }
1552
1553    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
1554    private Dimensions getPdfDocumentDimensions(final File file) {
1555        final ParcelFileDescriptor fileDescriptor;
1556        try {
1557            fileDescriptor = ParcelFileDescriptor.open(file, ParcelFileDescriptor.MODE_READ_ONLY);
1558            if (fileDescriptor == null) {
1559                return new Dimensions(0, 0);
1560            }
1561        } catch (FileNotFoundException e) {
1562            return new Dimensions(0, 0);
1563        }
1564        try {
1565            final PdfRenderer pdfRenderer = new PdfRenderer(fileDescriptor);
1566            final PdfRenderer.Page page = pdfRenderer.openPage(0);
1567            final int height = page.getHeight();
1568            final int width = page.getWidth();
1569            page.close();
1570            pdfRenderer.close();
1571            return scalePdfDimensions(new Dimensions(height, width));
1572        } catch (IOException | SecurityException e) {
1573            Log.d(Config.LOGTAG, "unable to get dimensions for pdf document", e);
1574            return new Dimensions(0, 0);
1575        }
1576    }
1577
1578    private Dimensions scalePdfDimensions(Dimensions in) {
1579        final DisplayMetrics displayMetrics =
1580                mXmppConnectionService.getResources().getDisplayMetrics();
1581        final int target = (int) (displayMetrics.density * 288);
1582        return scalePdfDimensions(in, target, true);
1583    }
1584
1585    private static Dimensions scalePdfDimensions(
1586            final Dimensions in, final int target, final boolean fit) {
1587        final int w, h;
1588        if (fit == (in.width <= in.height)) {
1589            w = Math.max((int) (in.width / ((double) in.height / target)), 1);
1590            h = target;
1591        } else {
1592            w = target;
1593            h = Math.max((int) (in.height / ((double) in.width / target)), 1);
1594        }
1595        return new Dimensions(h, w);
1596    }
1597
1598    public Bitmap getAvatar(String avatar, int size) {
1599        if (avatar == null) {
1600            return null;
1601        }
1602        Bitmap bm = cropCenter(getAvatarUri(avatar), size, size);
1603        return bm;
1604    }
1605
1606    private static class Dimensions {
1607        public final int width;
1608        public final int height;
1609
1610        Dimensions(int height, int width) {
1611            this.width = width;
1612            this.height = height;
1613        }
1614
1615        public int getMin() {
1616            return Math.min(width, height);
1617        }
1618
1619        public boolean valid() {
1620            return width > 0 && height > 0;
1621        }
1622    }
1623
1624    private static class NotAVideoFile extends Exception {
1625        public NotAVideoFile(Throwable t) {
1626            super(t);
1627        }
1628
1629        public NotAVideoFile() {
1630            super();
1631        }
1632    }
1633
1634    public static class ImageCompressionException extends Exception {
1635
1636        ImageCompressionException(String message) {
1637            super(message);
1638        }
1639    }
1640
1641    public static class FileCopyException extends Exception {
1642        private final int resId;
1643
1644        private FileCopyException(@StringRes int resId) {
1645            this.resId = resId;
1646        }
1647
1648        public @StringRes int getResId() {
1649            return resId;
1650        }
1651    }
1652}