FileBackend.java

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