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