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 = context.getContentResolver().query(
 417                MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
 418                new String[] { MediaStore.Images.Media._ID },
 419                MediaStore.Images.Media.DATA + "=? ",
 420                new String[] { filePath }, null);
 421        if (cursor != null && cursor.moveToFirst()) {
 422            final int id = cursor.getInt(cursor.getColumnIndex(MediaStore.MediaColumns._ID));
 423            cursor.close();
 424            return Uri.withAppendedPath(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, String.valueOf(id));
 425        } else {
 426            return null;
 427        }
 428    }
 429
 430    public void updateMediaScanner(File file) {
 431        updateMediaScanner(file, null);
 432    }
 433
 434    public void updateMediaScanner(File file, final Runnable callback) {
 435        if (!isInDirectoryThatShouldNotBeScanned(mXmppConnectionService, file)) {
 436            MediaScannerConnection.scanFile(mXmppConnectionService, new String[]{file.getAbsolutePath()}, null, new MediaScannerConnection.MediaScannerConnectionClient() {
 437                @Override
 438                public void onMediaScannerConnected() {
 439
 440                }
 441
 442                @Override
 443                public void onScanCompleted(String path, Uri uri) {
 444                    if (callback != null && file.getAbsolutePath().equals(path)) {
 445                        callback.run();
 446                    } else {
 447                        Log.d(Config.LOGTAG,"media scanner scanned wrong file");
 448                        if (callback != null) {
 449                            callback.run();
 450                        }
 451                    }
 452                }
 453            });
 454            return;
 455            /*Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
 456            intent.setData(Uri.fromFile(file));
 457            mXmppConnectionService.sendBroadcast(intent);*/
 458        } else if (file.getAbsolutePath().startsWith(getAppMediaDirectory(mXmppConnectionService))) {
 459            createNoMedia(file.getParentFile());
 460        }
 461        if (callback != null) {
 462            callback.run();
 463        }
 464    }
 465
 466    public boolean deleteFile(Message message) {
 467        File file = getFile(message);
 468        if (file.delete()) {
 469            updateMediaScanner(file);
 470            return true;
 471        } else {
 472            return false;
 473        }
 474    }
 475
 476    public DownloadableFile getFile(Message message) {
 477        return getFile(message, true);
 478    }
 479
 480    public DownloadableFile getFileForPath(String path) {
 481        return getFileForPath(path,MimeUtils.guessMimeTypeFromExtension(MimeUtils.extractRelevantExtension(path)));
 482    }
 483
 484    public DownloadableFile getFileForPath(String path, String mime) {
 485        final DownloadableFile file;
 486        if (path.startsWith("/")) {
 487            file = new DownloadableFile(path);
 488        } else {
 489            if (mime != null && mime.startsWith("image/")) {
 490                file = new DownloadableFile(getConversationsDirectory("Images") + path);
 491            } else if (mime != null && mime.startsWith("video/")) {
 492                file = new DownloadableFile(getConversationsDirectory("Videos") + path);
 493            } else {
 494                file = new DownloadableFile(getConversationsDirectory("Files") + path);
 495            }
 496        }
 497        return file;
 498    }
 499
 500    public boolean isInternalFile(final File file) {
 501        final File internalFile = getFileForPath(file.getName());
 502        return file.getAbsolutePath().equals(internalFile.getAbsolutePath());
 503    }
 504
 505    public DownloadableFile getFile(Message message, boolean decrypted) {
 506        final boolean encrypted = !decrypted
 507                && (message.getEncryption() == Message.ENCRYPTION_PGP
 508                || message.getEncryption() == Message.ENCRYPTION_DECRYPTED);
 509        String path = message.getRelativeFilePath();
 510        if (path == null) {
 511            path = message.getUuid();
 512        }
 513        final DownloadableFile file = getFileForPath(path, message.getMimeType());
 514        if (encrypted) {
 515            return new DownloadableFile(getConversationsDirectory("Files") + file.getName() + ".pgp");
 516        } else {
 517            return file;
 518        }
 519    }
 520
 521    public List<Attachment> convertToAttachments(List<DatabaseBackend.FilePath> relativeFilePaths) {
 522        List<Attachment> attachments = new ArrayList<>();
 523        for(DatabaseBackend.FilePath relativeFilePath : relativeFilePaths) {
 524            final String mime = MimeUtils.guessMimeTypeFromExtension(MimeUtils.extractRelevantExtension(relativeFilePath.path));
 525            final File file = getFileForPath(relativeFilePath.path, mime);
 526            attachments.add(Attachment.of(relativeFilePath.uuid, file, mime));
 527        }
 528        return attachments;
 529    }
 530
 531    private String getConversationsDirectory(final String type) {
 532        return getConversationsDirectory(mXmppConnectionService, type);
 533    }
 534
 535    private Bitmap resize(final Bitmap originalBitmap, int size) throws IOException {
 536        int w = originalBitmap.getWidth();
 537        int h = originalBitmap.getHeight();
 538        if (w <= 0 || h <= 0) {
 539            throw new IOException("Decoded bitmap reported bounds smaller 0");
 540        } else if (Math.max(w, h) > size) {
 541            int scalledW;
 542            int scalledH;
 543            if (w <= h) {
 544                scalledW = Math.max((int) (w / ((double) h / size)), 1);
 545                scalledH = size;
 546            } else {
 547                scalledW = size;
 548                scalledH = Math.max((int) (h / ((double) w / size)), 1);
 549            }
 550            final Bitmap result = Bitmap.createScaledBitmap(originalBitmap, scalledW, scalledH, true);
 551            if (!originalBitmap.isRecycled()) {
 552                originalBitmap.recycle();
 553            }
 554            return result;
 555        } else {
 556            return originalBitmap;
 557        }
 558    }
 559
 560    public boolean useImageAsIs(Uri uri) {
 561        String path = getOriginalPath(uri);
 562        if (path == null || isPathBlacklisted(path)) {
 563            return false;
 564        }
 565        File file = new File(path);
 566        long size = file.length();
 567        if (size == 0 || size >= mXmppConnectionService.getResources().getInteger(R.integer.auto_accept_filesize)) {
 568            return false;
 569        }
 570        BitmapFactory.Options options = new BitmapFactory.Options();
 571        options.inJustDecodeBounds = true;
 572        try {
 573            BitmapFactory.decodeStream(mXmppConnectionService.getContentResolver().openInputStream(uri), null, options);
 574            if (options.outMimeType == null || options.outHeight <= 0 || options.outWidth <= 0) {
 575                return false;
 576            }
 577            return (options.outWidth <= Config.IMAGE_SIZE && options.outHeight <= Config.IMAGE_SIZE && options.outMimeType.contains(Config.IMAGE_FORMAT.name().toLowerCase()));
 578        } catch (FileNotFoundException e) {
 579            return false;
 580        }
 581    }
 582
 583    public String getOriginalPath(Uri uri) {
 584        return FileUtils.getPath(mXmppConnectionService, uri);
 585    }
 586
 587    private void copyFileToPrivateStorage(File file, Uri uri) throws FileCopyException {
 588        Log.d(Config.LOGTAG, "copy file (" + uri.toString() + ") to private storage " + file.getAbsolutePath());
 589        file.getParentFile().mkdirs();
 590        OutputStream os = null;
 591        InputStream is = null;
 592        try {
 593            file.createNewFile();
 594            os = new FileOutputStream(file);
 595            is = mXmppConnectionService.getContentResolver().openInputStream(uri);
 596            byte[] buffer = new byte[1024];
 597            int length;
 598            while ((length = is.read(buffer)) > 0) {
 599                try {
 600                    os.write(buffer, 0, length);
 601                } catch (IOException e) {
 602                    throw new FileWriterException();
 603                }
 604            }
 605            try {
 606                os.flush();
 607            } catch (IOException e) {
 608                throw new FileWriterException();
 609            }
 610        } catch (FileNotFoundException e) {
 611            throw new FileCopyException(R.string.error_file_not_found);
 612        } catch (FileWriterException e) {
 613            throw new FileCopyException(R.string.error_unable_to_create_temporary_file);
 614        } catch (IOException e) {
 615            e.printStackTrace();
 616            throw new FileCopyException(R.string.error_io_exception);
 617        } finally {
 618            close(os);
 619            close(is);
 620        }
 621    }
 622
 623    public void copyFileToPrivateStorage(Message message, Uri uri, String type) throws FileCopyException {
 624        String mime = MimeUtils.guessMimeTypeFromUriAndMime(mXmppConnectionService, uri, type);
 625        Log.d(Config.LOGTAG, "copy " + uri.toString() + " to private storage (mime=" + mime + ")");
 626        String extension = MimeUtils.guessExtensionFromMimeType(mime);
 627        if (extension == null) {
 628            Log.d(Config.LOGTAG, "extension from mime type was null");
 629            extension = getExtensionFromUri(uri);
 630        }
 631        if ("ogg".equals(extension) && type != null && type.startsWith("audio/")) {
 632            extension = "oga";
 633        }
 634        message.setRelativeFilePath(message.getUuid() + "." + extension);
 635        copyFileToPrivateStorage(mXmppConnectionService.getFileBackend().getFile(message), uri);
 636    }
 637
 638    private String getExtensionFromUri(Uri uri) {
 639        String[] projection = {MediaStore.MediaColumns.DATA};
 640        String filename = null;
 641        Cursor cursor;
 642        try {
 643            cursor = mXmppConnectionService.getContentResolver().query(uri, projection, null, null, null);
 644        } catch (IllegalArgumentException e) {
 645            cursor = null;
 646        }
 647        if (cursor != null) {
 648            try {
 649                if (cursor.moveToFirst()) {
 650                    filename = cursor.getString(0);
 651                }
 652            } catch (Exception e) {
 653                filename = null;
 654            } finally {
 655                cursor.close();
 656            }
 657        }
 658        if (filename == null) {
 659            final List<String> segments = uri.getPathSegments();
 660            if (segments.size() > 0) {
 661                filename = segments.get(segments.size() - 1);
 662            }
 663        }
 664        int pos = filename == null ? -1 : filename.lastIndexOf('.');
 665        return pos > 0 ? filename.substring(pos + 1) : null;
 666    }
 667
 668    private void copyImageToPrivateStorage(File file, Uri image, int sampleSize) throws FileCopyException {
 669        file.getParentFile().mkdirs();
 670        InputStream is = null;
 671        OutputStream os = null;
 672        try {
 673            if (!file.exists() && !file.createNewFile()) {
 674                throw new FileCopyException(R.string.error_unable_to_create_temporary_file);
 675            }
 676            is = mXmppConnectionService.getContentResolver().openInputStream(image);
 677            if (is == null) {
 678                throw new FileCopyException(R.string.error_not_an_image_file);
 679            }
 680            Bitmap originalBitmap;
 681            BitmapFactory.Options options = new BitmapFactory.Options();
 682            int inSampleSize = (int) Math.pow(2, sampleSize);
 683            Log.d(Config.LOGTAG, "reading bitmap with sample size " + inSampleSize);
 684            options.inSampleSize = inSampleSize;
 685            originalBitmap = BitmapFactory.decodeStream(is, null, options);
 686            is.close();
 687            if (originalBitmap == null) {
 688                throw new FileCopyException(R.string.error_not_an_image_file);
 689            }
 690            Bitmap scaledBitmap = resize(originalBitmap, Config.IMAGE_SIZE);
 691            int rotation = getRotation(image);
 692            scaledBitmap = rotate(scaledBitmap, rotation);
 693            boolean targetSizeReached = false;
 694            int quality = Config.IMAGE_QUALITY;
 695            final int imageMaxSize = mXmppConnectionService.getResources().getInteger(R.integer.auto_accept_filesize);
 696            while (!targetSizeReached) {
 697                os = new FileOutputStream(file);
 698                boolean success = scaledBitmap.compress(Config.IMAGE_FORMAT, quality, os);
 699                if (!success) {
 700                    throw new FileCopyException(R.string.error_compressing_image);
 701                }
 702                os.flush();
 703                targetSizeReached = file.length() <= imageMaxSize || quality <= 50;
 704                quality -= 5;
 705            }
 706            scaledBitmap.recycle();
 707        } catch (FileNotFoundException e) {
 708            throw new FileCopyException(R.string.error_file_not_found);
 709        } catch (IOException e) {
 710            e.printStackTrace();
 711            throw new FileCopyException(R.string.error_io_exception);
 712        } catch (SecurityException e) {
 713            throw new FileCopyException(R.string.error_security_exception_during_image_copy);
 714        } catch (OutOfMemoryError e) {
 715            ++sampleSize;
 716            if (sampleSize <= 3) {
 717                copyImageToPrivateStorage(file, image, sampleSize);
 718            } else {
 719                throw new FileCopyException(R.string.error_out_of_memory);
 720            }
 721        } finally {
 722            close(os);
 723            close(is);
 724        }
 725    }
 726
 727    public void copyImageToPrivateStorage(File file, Uri image) throws FileCopyException {
 728        Log.d(Config.LOGTAG, "copy image (" + image.toString() + ") to private storage " + file.getAbsolutePath());
 729        copyImageToPrivateStorage(file, image, 0);
 730    }
 731
 732    public void copyImageToPrivateStorage(Message message, Uri image) throws FileCopyException {
 733        switch (Config.IMAGE_FORMAT) {
 734            case JPEG:
 735                message.setRelativeFilePath(message.getUuid() + ".jpg");
 736                break;
 737            case PNG:
 738                message.setRelativeFilePath(message.getUuid() + ".png");
 739                break;
 740            case WEBP:
 741                message.setRelativeFilePath(message.getUuid() + ".webp");
 742                break;
 743        }
 744        copyImageToPrivateStorage(getFile(message), image);
 745        updateFileParams(message);
 746    }
 747
 748    public boolean unusualBounds(Uri image) {
 749        try {
 750            BitmapFactory.Options options = new BitmapFactory.Options();
 751            options.inJustDecodeBounds = true;
 752            BitmapFactory.decodeStream(mXmppConnectionService.getContentResolver().openInputStream(image), null, options);
 753            float ratio = (float) options.outHeight / options.outWidth;
 754            return ratio > (21.0f / 9.0f) || ratio < (9.0f / 21.0f);
 755        } catch (Exception e) {
 756            return false;
 757        }
 758    }
 759
 760    private int getRotation(File file) {
 761        return getRotation(Uri.parse("file://" + file.getAbsolutePath()));
 762    }
 763
 764    private int getRotation(Uri image) {
 765        InputStream is = null;
 766        try {
 767            is = mXmppConnectionService.getContentResolver().openInputStream(image);
 768            return ExifHelper.getOrientation(is);
 769        } catch (FileNotFoundException e) {
 770            return 0;
 771        } finally {
 772            close(is);
 773        }
 774    }
 775
 776    public Bitmap getThumbnail(Message message, int size, boolean cacheOnly) throws IOException {
 777        final String uuid = message.getUuid();
 778        final LruCache<String, Bitmap> cache = mXmppConnectionService.getBitmapCache();
 779        Bitmap thumbnail = cache.get(uuid);
 780        if ((thumbnail == null) && (!cacheOnly)) {
 781            synchronized (THUMBNAIL_LOCK) {
 782                thumbnail = cache.get(uuid);
 783                if (thumbnail != null) {
 784                    return thumbnail;
 785                }
 786                DownloadableFile file = getFile(message);
 787                final String mime = file.getMimeType();
 788                if (mime.startsWith("video/")) {
 789                    thumbnail = getVideoPreview(file, size);
 790                } else {
 791                    Bitmap fullsize = getFullsizeImagePreview(file, size);
 792                    if (fullsize == null) {
 793                        throw new FileNotFoundException();
 794                    }
 795                    thumbnail = resize(fullsize, size);
 796                    thumbnail = rotate(thumbnail, getRotation(file));
 797                    if (mime.equals("image/gif")) {
 798                        Bitmap withGifOverlay = thumbnail.copy(Bitmap.Config.ARGB_8888, true);
 799                        drawOverlay(withGifOverlay, paintOverlayBlack(withGifOverlay) ? R.drawable.play_gif_black : R.drawable.play_gif_white, 1.0f);
 800                        thumbnail.recycle();
 801                        thumbnail = withGifOverlay;
 802                    }
 803                }
 804                cache.put(uuid, thumbnail);
 805            }
 806        }
 807        return thumbnail;
 808    }
 809
 810    private Bitmap getFullsizeImagePreview(File file, int size) {
 811        BitmapFactory.Options options = new BitmapFactory.Options();
 812        options.inSampleSize = calcSampleSize(file, size);
 813        try {
 814            return BitmapFactory.decodeFile(file.getAbsolutePath(), options);
 815        } catch (OutOfMemoryError e) {
 816            options.inSampleSize *= 2;
 817            return BitmapFactory.decodeFile(file.getAbsolutePath(), options);
 818        }
 819    }
 820
 821    private void drawOverlay(Bitmap bitmap, int resource, float factor) {
 822        Bitmap overlay = BitmapFactory.decodeResource(mXmppConnectionService.getResources(), resource);
 823        Canvas canvas = new Canvas(bitmap);
 824        float targetSize = Math.min(canvas.getWidth(), canvas.getHeight()) * factor;
 825        Log.d(Config.LOGTAG, "target size overlay: " + targetSize + " overlay bitmap size was " + overlay.getHeight());
 826        float left = (canvas.getWidth() - targetSize) / 2.0f;
 827        float top = (canvas.getHeight() - targetSize) / 2.0f;
 828        RectF dst = new RectF(left, top, left + targetSize - 1, top + targetSize - 1);
 829        canvas.drawBitmap(overlay, null, dst, createAntiAliasingPaint());
 830    }
 831
 832    /**
 833     * https://stackoverflow.com/a/3943023/210897
 834     */
 835    private boolean paintOverlayBlack(final Bitmap bitmap) {
 836        final int h = bitmap.getHeight();
 837        final int w = bitmap.getWidth();
 838        int record = 0;
 839        for (int y = Math.round(h * IGNORE_PADDING); y < h - Math.round(h * IGNORE_PADDING); ++y) {
 840            for (int x = Math.round(w * IGNORE_PADDING); x < w - Math.round(w * IGNORE_PADDING); ++x) {
 841                int pixel = bitmap.getPixel(x, y);
 842                if ((Color.red(pixel) * 0.299 + Color.green(pixel) * 0.587 + Color.blue(pixel) * 0.114) > 186) {
 843                    --record;
 844                } else {
 845                    ++record;
 846                }
 847            }
 848        }
 849        return record < 0;
 850    }
 851
 852    private Bitmap cropCenterSquareVideo(Uri uri, int size) {
 853        MediaMetadataRetriever metadataRetriever = new MediaMetadataRetriever();
 854        Bitmap frame;
 855        try {
 856            metadataRetriever.setDataSource(mXmppConnectionService, uri);
 857            frame = metadataRetriever.getFrameAtTime(0);
 858            metadataRetriever.release();
 859            return cropCenterSquare(frame, size);
 860        } catch (Exception e) {
 861            frame = Bitmap.createBitmap(size, size, Bitmap.Config.ARGB_8888);
 862            frame.eraseColor(0xff000000);
 863            return frame;
 864        }
 865    }
 866
 867    private Bitmap getVideoPreview(File file, int size) {
 868        MediaMetadataRetriever metadataRetriever = new MediaMetadataRetriever();
 869        Bitmap frame;
 870        try {
 871            metadataRetriever.setDataSource(file.getAbsolutePath());
 872            frame = metadataRetriever.getFrameAtTime(0);
 873            metadataRetriever.release();
 874            frame = resize(frame, size);
 875        } catch (IOException | RuntimeException e) {
 876            frame = Bitmap.createBitmap(size, size, Bitmap.Config.ARGB_8888);
 877            frame.eraseColor(0xff000000);
 878        }
 879        drawOverlay(frame, paintOverlayBlack(frame) ? R.drawable.play_video_black : R.drawable.play_video_white, 0.75f);
 880        return frame;
 881    }
 882
 883    public Uri getTakePhotoUri() {
 884        File file;
 885        if (Config.ONLY_INTERNAL_STORAGE) {
 886            file = new File(mXmppConnectionService.getCacheDir().getAbsolutePath(), "Camera/IMG_" + this.IMAGE_DATE_FORMAT.format(new Date()) + ".jpg");
 887        } else {
 888            file = new File(getTakePhotoPath() + "IMG_" + this.IMAGE_DATE_FORMAT.format(new Date()) + ".jpg");
 889        }
 890        file.getParentFile().mkdirs();
 891        return getUriForFile(mXmppConnectionService, file);
 892    }
 893
 894    public Avatar getPepAvatar(Uri image, int size, Bitmap.CompressFormat format) {
 895
 896        final Avatar uncompressAvatar = getUncompressedAvatar(image);
 897        if (uncompressAvatar != null && uncompressAvatar.image.length() <= Config.AVATAR_CHAR_LIMIT) {
 898            return uncompressAvatar;
 899        }
 900        if (uncompressAvatar != null) {
 901            Log.d(Config.LOGTAG, "uncompressed avatar exceeded char limit by " + (uncompressAvatar.image.length() - Config.AVATAR_CHAR_LIMIT));
 902        }
 903
 904        Bitmap bm = cropCenterSquare(image, size);
 905        if (bm == null) {
 906            return null;
 907        }
 908        if (hasAlpha(bm)) {
 909            Log.d(Config.LOGTAG, "alpha in avatar detected; uploading as PNG");
 910            bm.recycle();
 911            bm = cropCenterSquare(image, 96);
 912            return getPepAvatar(bm, Bitmap.CompressFormat.PNG, 100);
 913        }
 914        return getPepAvatar(bm, format, 100);
 915    }
 916
 917    private Avatar getUncompressedAvatar(Uri uri) {
 918        Bitmap bitmap = null;
 919        try {
 920            bitmap = BitmapFactory.decodeStream(mXmppConnectionService.getContentResolver().openInputStream(uri));
 921            return getPepAvatar(bitmap, Bitmap.CompressFormat.PNG, 100);
 922        } catch (Exception e) {
 923            return null;
 924        } finally {
 925            if (bitmap != null) {
 926                bitmap.recycle();
 927            }
 928        }
 929    }
 930
 931    private Avatar getPepAvatar(Bitmap bitmap, Bitmap.CompressFormat format, int quality) {
 932        try {
 933            ByteArrayOutputStream mByteArrayOutputStream = new ByteArrayOutputStream();
 934            Base64OutputStream mBase64OutputStream = new Base64OutputStream(mByteArrayOutputStream, Base64.DEFAULT);
 935            MessageDigest digest = MessageDigest.getInstance("SHA-1");
 936            DigestOutputStream mDigestOutputStream = new DigestOutputStream(mBase64OutputStream, digest);
 937            if (!bitmap.compress(format, quality, mDigestOutputStream)) {
 938                return null;
 939            }
 940            mDigestOutputStream.flush();
 941            mDigestOutputStream.close();
 942            long chars = mByteArrayOutputStream.size();
 943            if (format != Bitmap.CompressFormat.PNG && quality >= 50 && chars >= Config.AVATAR_CHAR_LIMIT) {
 944                int q = quality - 2;
 945                Log.d(Config.LOGTAG, "avatar char length was " + chars + " reducing quality to " + q);
 946                return getPepAvatar(bitmap, format, q);
 947            }
 948            Log.d(Config.LOGTAG, "settled on char length " + chars + " with quality=" + quality);
 949            final Avatar avatar = new Avatar();
 950            avatar.sha1sum = CryptoHelper.bytesToHex(digest.digest());
 951            avatar.image = new String(mByteArrayOutputStream.toByteArray());
 952            if (format.equals(Bitmap.CompressFormat.WEBP)) {
 953                avatar.type = "image/webp";
 954            } else if (format.equals(Bitmap.CompressFormat.JPEG)) {
 955                avatar.type = "image/jpeg";
 956            } else if (format.equals(Bitmap.CompressFormat.PNG)) {
 957                avatar.type = "image/png";
 958            }
 959            avatar.width = bitmap.getWidth();
 960            avatar.height = bitmap.getHeight();
 961            return avatar;
 962        } catch (OutOfMemoryError e) {
 963            Log.d(Config.LOGTAG,"unable to convert avatar to base64 due to low memory");
 964            return null;
 965        } catch (Exception e) {
 966            return null;
 967        }
 968    }
 969
 970    public Avatar getStoredPepAvatar(String hash) {
 971        if (hash == null) {
 972            return null;
 973        }
 974        Avatar avatar = new Avatar();
 975        File file = new File(getAvatarPath(hash));
 976        FileInputStream is = null;
 977        try {
 978            avatar.size = file.length();
 979            BitmapFactory.Options options = new BitmapFactory.Options();
 980            options.inJustDecodeBounds = true;
 981            BitmapFactory.decodeFile(file.getAbsolutePath(), options);
 982            is = new FileInputStream(file);
 983            ByteArrayOutputStream mByteArrayOutputStream = new ByteArrayOutputStream();
 984            Base64OutputStream mBase64OutputStream = new Base64OutputStream(mByteArrayOutputStream, Base64.DEFAULT);
 985            MessageDigest digest = MessageDigest.getInstance("SHA-1");
 986            DigestOutputStream os = new DigestOutputStream(mBase64OutputStream, digest);
 987            byte[] buffer = new byte[4096];
 988            int length;
 989            while ((length = is.read(buffer)) > 0) {
 990                os.write(buffer, 0, length);
 991            }
 992            os.flush();
 993            os.close();
 994            avatar.sha1sum = CryptoHelper.bytesToHex(digest.digest());
 995            avatar.image = new String(mByteArrayOutputStream.toByteArray());
 996            avatar.height = options.outHeight;
 997            avatar.width = options.outWidth;
 998            avatar.type = options.outMimeType;
 999            return avatar;
1000        } catch (NoSuchAlgorithmException | IOException e) {
1001            return null;
1002        } finally {
1003            close(is);
1004        }
1005    }
1006
1007    public boolean isAvatarCached(Avatar avatar) {
1008        File file = new File(getAvatarPath(avatar.getFilename()));
1009        return file.exists();
1010    }
1011
1012    public boolean save(final Avatar avatar) {
1013        File file;
1014        if (isAvatarCached(avatar)) {
1015            file = new File(getAvatarPath(avatar.getFilename()));
1016            avatar.size = file.length();
1017        } else {
1018            file = new File(mXmppConnectionService.getCacheDir().getAbsolutePath() + "/" + UUID.randomUUID().toString());
1019            if (file.getParentFile().mkdirs()) {
1020                Log.d(Config.LOGTAG, "created cache directory");
1021            }
1022            OutputStream os = null;
1023            try {
1024                if (!file.createNewFile()) {
1025                    Log.d(Config.LOGTAG, "unable to create temporary file " + file.getAbsolutePath());
1026                }
1027                os = new FileOutputStream(file);
1028                MessageDigest digest = MessageDigest.getInstance("SHA-1");
1029                digest.reset();
1030                DigestOutputStream mDigestOutputStream = new DigestOutputStream(os, digest);
1031                final byte[] bytes = avatar.getImageAsBytes();
1032                mDigestOutputStream.write(bytes);
1033                mDigestOutputStream.flush();
1034                mDigestOutputStream.close();
1035                String sha1sum = CryptoHelper.bytesToHex(digest.digest());
1036                if (sha1sum.equals(avatar.sha1sum)) {
1037                    File outputFile = new File(getAvatarPath(avatar.getFilename()));
1038                    if (outputFile.getParentFile().mkdirs()) {
1039                        Log.d(Config.LOGTAG, "created avatar directory");
1040                    }
1041                    String filename = getAvatarPath(avatar.getFilename());
1042                    if (!file.renameTo(new File(filename))) {
1043                        Log.d(Config.LOGTAG, "unable to rename " + file.getAbsolutePath() + " to " + outputFile);
1044                        return false;
1045                    }
1046                } else {
1047                    Log.d(Config.LOGTAG, "sha1sum mismatch for " + avatar.owner);
1048                    if (!file.delete()) {
1049                        Log.d(Config.LOGTAG, "unable to delete temporary file");
1050                    }
1051                    return false;
1052                }
1053                avatar.size = bytes.length;
1054            } catch (IllegalArgumentException | IOException | NoSuchAlgorithmException e) {
1055                return false;
1056            } finally {
1057                close(os);
1058            }
1059        }
1060        return true;
1061    }
1062
1063    private String getAvatarPath(String avatar) {
1064        return mXmppConnectionService.getFilesDir().getAbsolutePath() + "/avatars/" + avatar;
1065    }
1066
1067    public Uri getAvatarUri(String avatar) {
1068        return Uri.parse("file:" + getAvatarPath(avatar));
1069    }
1070
1071    public Bitmap cropCenterSquare(Uri image, int size) {
1072        if (image == null) {
1073            return null;
1074        }
1075        InputStream is = null;
1076        try {
1077            BitmapFactory.Options options = new BitmapFactory.Options();
1078            options.inSampleSize = calcSampleSize(image, size);
1079            is = mXmppConnectionService.getContentResolver().openInputStream(image);
1080            if (is == null) {
1081                return null;
1082            }
1083            Bitmap input = BitmapFactory.decodeStream(is, null, options);
1084            if (input == null) {
1085                return null;
1086            } else {
1087                input = rotate(input, getRotation(image));
1088                return cropCenterSquare(input, size);
1089            }
1090        } catch (FileNotFoundException | SecurityException e) {
1091            Log.d(Config.LOGTAG,"unable to open file "+image.toString(), e);
1092            return null;
1093        } finally {
1094            close(is);
1095        }
1096    }
1097
1098    public Bitmap cropCenter(Uri image, int newHeight, int newWidth) {
1099        if (image == null) {
1100            return null;
1101        }
1102        InputStream is = null;
1103        try {
1104            BitmapFactory.Options options = new BitmapFactory.Options();
1105            options.inSampleSize = calcSampleSize(image, Math.max(newHeight, newWidth));
1106            is = mXmppConnectionService.getContentResolver().openInputStream(image);
1107            if (is == null) {
1108                return null;
1109            }
1110            Bitmap source = BitmapFactory.decodeStream(is, null, options);
1111            if (source == null) {
1112                return null;
1113            }
1114            int sourceWidth = source.getWidth();
1115            int sourceHeight = source.getHeight();
1116            float xScale = (float) newWidth / sourceWidth;
1117            float yScale = (float) newHeight / sourceHeight;
1118            float scale = Math.max(xScale, yScale);
1119            float scaledWidth = scale * sourceWidth;
1120            float scaledHeight = scale * sourceHeight;
1121            float left = (newWidth - scaledWidth) / 2;
1122            float top = (newHeight - scaledHeight) / 2;
1123
1124            RectF targetRect = new RectF(left, top, left + scaledWidth, top + scaledHeight);
1125            Bitmap dest = Bitmap.createBitmap(newWidth, newHeight, Bitmap.Config.ARGB_8888);
1126            Canvas canvas = new Canvas(dest);
1127            canvas.drawBitmap(source, null, targetRect, createAntiAliasingPaint());
1128            if (source.isRecycled()) {
1129                source.recycle();
1130            }
1131            return dest;
1132        } catch (SecurityException e) {
1133            return null; //android 6.0 with revoked permissions for example
1134        } catch (FileNotFoundException e) {
1135            return null;
1136        } finally {
1137            close(is);
1138        }
1139    }
1140
1141    public Bitmap cropCenterSquare(Bitmap input, int size) {
1142        int w = input.getWidth();
1143        int h = input.getHeight();
1144
1145        float scale = Math.max((float) size / h, (float) size / w);
1146
1147        float outWidth = scale * w;
1148        float outHeight = scale * h;
1149        float left = (size - outWidth) / 2;
1150        float top = (size - outHeight) / 2;
1151        RectF target = new RectF(left, top, left + outWidth, top + outHeight);
1152
1153        Bitmap output = Bitmap.createBitmap(size, size, Bitmap.Config.ARGB_8888);
1154        Canvas canvas = new Canvas(output);
1155        canvas.drawBitmap(input, null, target, createAntiAliasingPaint());
1156        if (!input.isRecycled()) {
1157            input.recycle();
1158        }
1159        return output;
1160    }
1161
1162    private int calcSampleSize(Uri image, int size) throws FileNotFoundException, SecurityException {
1163        BitmapFactory.Options options = new BitmapFactory.Options();
1164        options.inJustDecodeBounds = true;
1165        BitmapFactory.decodeStream(mXmppConnectionService.getContentResolver().openInputStream(image), null, options);
1166        return calcSampleSize(options, size);
1167    }
1168
1169    public void updateFileParams(Message message) {
1170        updateFileParams(message, null);
1171    }
1172
1173    public void updateFileParams(Message message, URL url) {
1174        DownloadableFile file = getFile(message);
1175        final String mime = file.getMimeType();
1176        final boolean image = message.getType() == Message.TYPE_IMAGE || (mime != null && mime.startsWith("image/"));
1177        final boolean video = mime != null && mime.startsWith("video/");
1178        final boolean audio = mime != null && mime.startsWith("audio/");
1179        final StringBuilder body = new StringBuilder();
1180        if (url != null) {
1181            body.append(url.toString());
1182        }
1183        body.append('|').append(file.getSize());
1184        if (image || video) {
1185            try {
1186                Dimensions dimensions = image ? getImageDimensions(file) : getVideoDimensions(file);
1187                if (dimensions.valid()) {
1188                    body.append('|').append(dimensions.width).append('|').append(dimensions.height);
1189                }
1190            } catch (NotAVideoFile notAVideoFile) {
1191                Log.d(Config.LOGTAG, "file with mime type " + file.getMimeType() + " was not a video file");
1192                //fall threw
1193            }
1194        } else if (audio) {
1195            body.append("|0|0|").append(getMediaRuntime(file));
1196        }
1197        message.setBody(body.toString());
1198        message.setDeleted(false);
1199        message.setType(image ? Message.TYPE_IMAGE : Message.TYPE_FILE);
1200    }
1201
1202
1203    private int getMediaRuntime(File file) {
1204        try {
1205            MediaMetadataRetriever mediaMetadataRetriever = new MediaMetadataRetriever();
1206            mediaMetadataRetriever.setDataSource(file.toString());
1207            return Integer.parseInt(mediaMetadataRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION));
1208        } catch (RuntimeException e) {
1209            return 0;
1210        }
1211    }
1212
1213    private Dimensions getImageDimensions(File file) {
1214        BitmapFactory.Options options = new BitmapFactory.Options();
1215        options.inJustDecodeBounds = true;
1216        BitmapFactory.decodeFile(file.getAbsolutePath(), options);
1217        int rotation = getRotation(file);
1218        boolean rotated = rotation == 90 || rotation == 270;
1219        int imageHeight = rotated ? options.outWidth : options.outHeight;
1220        int imageWidth = rotated ? options.outHeight : options.outWidth;
1221        return new Dimensions(imageHeight, imageWidth);
1222    }
1223
1224    private Dimensions getVideoDimensions(File file) throws NotAVideoFile {
1225        MediaMetadataRetriever metadataRetriever = new MediaMetadataRetriever();
1226        try {
1227            metadataRetriever.setDataSource(file.getAbsolutePath());
1228        } catch (RuntimeException e) {
1229            throw new NotAVideoFile(e);
1230        }
1231        return getVideoDimensions(metadataRetriever);
1232    }
1233
1234    public Bitmap getAvatar(String avatar, int size) {
1235        if (avatar == null) {
1236            return null;
1237        }
1238        Bitmap bm = cropCenter(getAvatarUri(avatar), size, size);
1239        if (bm == null) {
1240            return null;
1241        }
1242        return bm;
1243    }
1244
1245    public boolean isFileAvailable(Message message) {
1246        return getFile(message).exists();
1247    }
1248
1249    private static class Dimensions {
1250        public final int width;
1251        public final int height;
1252
1253        Dimensions(int height, int width) {
1254            this.width = width;
1255            this.height = height;
1256        }
1257
1258        public int getMin() {
1259            return Math.min(width, height);
1260        }
1261
1262        public boolean valid() {
1263            return width > 0 && height > 0;
1264        }
1265    }
1266
1267    private static class NotAVideoFile extends Exception {
1268        public NotAVideoFile(Throwable t) {
1269            super(t);
1270        }
1271
1272        public NotAVideoFile() {
1273            super();
1274        }
1275    }
1276
1277    public class FileCopyException extends Exception {
1278        private static final long serialVersionUID = -1010013599132881427L;
1279        private int resId;
1280
1281        public FileCopyException(int resId) {
1282            this.resId = resId;
1283        }
1284
1285        public int getResId() {
1286            return resId;
1287        }
1288    }
1289}