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