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