FileBackend.java

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