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