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