FileBackend.java

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