FileBackend.java

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