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