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