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.system.Os;
24import android.system.StructStat;
25import android.util.Base64;
26import android.util.Base64OutputStream;
27import android.util.DisplayMetrics;
28import android.util.Log;
29import android.util.LruCache;
30
31import androidx.annotation.RequiresApi;
32import androidx.annotation.StringRes;
33import androidx.core.content.FileProvider;
34import androidx.exifinterface.media.ExifInterface;
35
36import com.google.common.base.Strings;
37import com.google.common.io.ByteStreams;
38
39import java.io.ByteArrayOutputStream;
40import java.io.Closeable;
41import java.io.File;
42import java.io.FileDescriptor;
43import java.io.FileInputStream;
44import java.io.FileNotFoundException;
45import java.io.FileOutputStream;
46import java.io.IOException;
47import java.io.InputStream;
48import java.io.OutputStream;
49import java.net.ServerSocket;
50import java.net.Socket;
51import java.security.DigestOutputStream;
52import java.security.MessageDigest;
53import java.security.NoSuchAlgorithmException;
54import java.text.SimpleDateFormat;
55import java.util.ArrayList;
56import java.util.Date;
57import java.util.List;
58import java.util.Locale;
59import java.util.UUID;
60
61import eu.siacs.conversations.Config;
62import eu.siacs.conversations.R;
63import eu.siacs.conversations.entities.DownloadableFile;
64import eu.siacs.conversations.entities.Message;
65import eu.siacs.conversations.services.AttachFileToConversationRunnable;
66import eu.siacs.conversations.services.XmppConnectionService;
67import eu.siacs.conversations.ui.adapter.MediaAdapter;
68import eu.siacs.conversations.ui.util.Attachment;
69import eu.siacs.conversations.utils.Compatibility;
70import eu.siacs.conversations.utils.CryptoHelper;
71import eu.siacs.conversations.utils.FileUtils;
72import eu.siacs.conversations.utils.FileWriterException;
73import eu.siacs.conversations.utils.MimeUtils;
74import eu.siacs.conversations.xmpp.pep.Avatar;
75
76public class FileBackend {
77
78 private static final Object THUMBNAIL_LOCK = new Object();
79
80 private static final SimpleDateFormat IMAGE_DATE_FORMAT =
81 new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.US);
82
83 private static final String FILE_PROVIDER = ".files";
84 private static final float IGNORE_PADDING = 0.15f;
85 private final XmppConnectionService mXmppConnectionService;
86
87 public FileBackend(XmppConnectionService service) {
88 this.mXmppConnectionService = service;
89 }
90
91 public static long getFileSize(Context context, Uri uri) {
92 try {
93 final Cursor cursor = context.getContentResolver().query(uri, null, null, null, null);
94 if (cursor != null && cursor.moveToFirst()) {
95 long size = cursor.getLong(cursor.getColumnIndex(OpenableColumns.SIZE));
96 cursor.close();
97 return size;
98 } else {
99 return -1;
100 }
101 } catch (Exception e) {
102 return -1;
103 }
104 }
105
106 public static boolean allFilesUnderSize(
107 Context context, List<Attachment> attachments, long max) {
108 final boolean compressVideo =
109 !AttachFileToConversationRunnable.getVideoCompression(context)
110 .equals("uncompressed");
111 if (max <= 0) {
112 Log.d(Config.LOGTAG, "server did not report max file size for http upload");
113 return true; // exception to be compatible with HTTP Upload < v0.2
114 }
115 for (Attachment attachment : attachments) {
116 if (attachment.getType() != Attachment.Type.FILE) {
117 continue;
118 }
119 String mime = attachment.getMime();
120 if (mime != null && mime.startsWith("video/") && compressVideo) {
121 try {
122 Dimensions dimensions =
123 FileBackend.getVideoDimensions(context, attachment.getUri());
124 if (dimensions.getMin() > 720) {
125 Log.d(
126 Config.LOGTAG,
127 "do not consider video file with min width larger than 720 for size check");
128 continue;
129 }
130 } catch (NotAVideoFile notAVideoFile) {
131 // ignore and fall through
132 }
133 }
134 if (FileBackend.getFileSize(context, attachment.getUri()) > max) {
135 Log.d(
136 Config.LOGTAG,
137 "not all files are under "
138 + max
139 + " bytes. suggesting falling back to jingle");
140 return false;
141 }
142 }
143 return true;
144 }
145
146 public static File getBackupDirectory(final Context context) {
147 final File conversationsDownloadDirectory =
148 new File(
149 Environment.getExternalStoragePublicDirectory(
150 Environment.DIRECTORY_DOWNLOADS),
151 context.getString(R.string.app_name));
152 return new File(conversationsDownloadDirectory, "Backup");
153 }
154
155 public static File getLegacyBackupDirectory(final String app) {
156 final File appDirectory = new File(Environment.getExternalStorageDirectory(), app);
157 return new File(appDirectory, "Backup");
158 }
159
160 private static Bitmap rotate(final Bitmap bitmap, final int degree) {
161 if (degree == 0) {
162 return bitmap;
163 }
164 final int w = bitmap.getWidth();
165 final int h = bitmap.getHeight();
166 final Matrix matrix = new Matrix();
167 matrix.postRotate(degree);
168 final Bitmap result = Bitmap.createBitmap(bitmap, 0, 0, w, h, matrix, true);
169 if (!bitmap.isRecycled()) {
170 bitmap.recycle();
171 }
172 return result;
173 }
174
175 public static boolean isPathBlacklisted(String path) {
176 final String androidDataPath =
177 Environment.getExternalStorageDirectory().getAbsolutePath() + "/Android/data/";
178 return path.startsWith(androidDataPath);
179 }
180
181 private static Paint createAntiAliasingPaint() {
182 Paint paint = new Paint();
183 paint.setAntiAlias(true);
184 paint.setFilterBitmap(true);
185 paint.setDither(true);
186 return paint;
187 }
188
189 public static Uri getUriForUri(Context context, Uri uri) {
190 if ("file".equals(uri.getScheme())) {
191 return getUriForFile(context, new File(uri.getPath()));
192 } else {
193 return uri;
194 }
195 }
196
197 public static Uri getUriForFile(Context context, File file) {
198 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N || Config.ONLY_INTERNAL_STORAGE) {
199 try {
200 return FileProvider.getUriForFile(context, getAuthority(context), file);
201 } catch (IllegalArgumentException e) {
202 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
203 throw new SecurityException(e);
204 } else {
205 return Uri.fromFile(file);
206 }
207 }
208 } else {
209 return Uri.fromFile(file);
210 }
211 }
212
213 public static String getAuthority(Context context) {
214 return context.getPackageName() + FILE_PROVIDER;
215 }
216
217 private static boolean hasAlpha(final Bitmap bitmap) {
218 final int w = bitmap.getWidth();
219 final int h = bitmap.getHeight();
220 final int yStep = Math.max(1, w / 100);
221 final int xStep = Math.max(1, h / 100);
222 for (int x = 0; x < w; x += xStep) {
223 for (int y = 0; y < h; y += yStep) {
224 if (Color.alpha(bitmap.getPixel(x, y)) < 255) {
225 return true;
226 }
227 }
228 }
229 return false;
230 }
231
232 private static int calcSampleSize(File image, int size) {
233 BitmapFactory.Options options = new BitmapFactory.Options();
234 options.inJustDecodeBounds = true;
235 BitmapFactory.decodeFile(image.getAbsolutePath(), options);
236 return calcSampleSize(options, size);
237 }
238
239 private static int calcSampleSize(BitmapFactory.Options options, int size) {
240 int height = options.outHeight;
241 int width = options.outWidth;
242 int inSampleSize = 1;
243
244 if (height > size || width > size) {
245 int halfHeight = height / 2;
246 int halfWidth = width / 2;
247
248 while ((halfHeight / inSampleSize) > size && (halfWidth / inSampleSize) > size) {
249 inSampleSize *= 2;
250 }
251 }
252 return inSampleSize;
253 }
254
255 private static Dimensions getVideoDimensions(Context context, Uri uri) throws NotAVideoFile {
256 MediaMetadataRetriever mediaMetadataRetriever = new MediaMetadataRetriever();
257 try {
258 mediaMetadataRetriever.setDataSource(context, uri);
259 } catch (RuntimeException e) {
260 throw new NotAVideoFile(e);
261 }
262 return getVideoDimensions(mediaMetadataRetriever);
263 }
264
265 private static Dimensions getVideoDimensionsOfFrame(
266 MediaMetadataRetriever mediaMetadataRetriever) {
267 Bitmap bitmap = null;
268 try {
269 bitmap = mediaMetadataRetriever.getFrameAtTime();
270 return new Dimensions(bitmap.getHeight(), bitmap.getWidth());
271 } catch (Exception e) {
272 return null;
273 } finally {
274 if (bitmap != null) {
275 bitmap.recycle();
276 }
277 }
278 }
279
280 private static Dimensions getVideoDimensions(MediaMetadataRetriever metadataRetriever)
281 throws NotAVideoFile {
282 String hasVideo =
283 metadataRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_HAS_VIDEO);
284 if (hasVideo == null) {
285 throw new NotAVideoFile();
286 }
287 Dimensions dimensions = getVideoDimensionsOfFrame(metadataRetriever);
288 if (dimensions != null) {
289 return dimensions;
290 }
291 final int rotation = extractRotationFromMediaRetriever(metadataRetriever);
292 boolean rotated = rotation == 90 || rotation == 270;
293 int height;
294 try {
295 String h =
296 metadataRetriever.extractMetadata(
297 MediaMetadataRetriever.METADATA_KEY_VIDEO_HEIGHT);
298 height = Integer.parseInt(h);
299 } catch (Exception e) {
300 height = -1;
301 }
302 int width;
303 try {
304 String w =
305 metadataRetriever.extractMetadata(
306 MediaMetadataRetriever.METADATA_KEY_VIDEO_WIDTH);
307 width = Integer.parseInt(w);
308 } catch (Exception e) {
309 width = -1;
310 }
311 metadataRetriever.release();
312 Log.d(Config.LOGTAG, "extracted video dims " + width + "x" + height);
313 return rotated ? new Dimensions(width, height) : new Dimensions(height, width);
314 }
315
316 private static int extractRotationFromMediaRetriever(MediaMetadataRetriever metadataRetriever) {
317 String r =
318 metadataRetriever.extractMetadata(
319 MediaMetadataRetriever.METADATA_KEY_VIDEO_ROTATION);
320 try {
321 return Integer.parseInt(r);
322 } catch (Exception e) {
323 return 0;
324 }
325 }
326
327 public static void close(final Closeable stream) {
328 if (stream != null) {
329 try {
330 stream.close();
331 } catch (Exception e) {
332 Log.d(Config.LOGTAG, "unable to close stream", e);
333 }
334 }
335 }
336
337 public static void close(final Socket socket) {
338 if (socket != null) {
339 try {
340 socket.close();
341 } catch (IOException e) {
342 Log.d(Config.LOGTAG, "unable to close socket", e);
343 }
344 }
345 }
346
347 public static void close(final ServerSocket socket) {
348 if (socket != null) {
349 try {
350 socket.close();
351 } catch (IOException e) {
352 Log.d(Config.LOGTAG, "unable to close server socket", e);
353 }
354 }
355 }
356
357 public static boolean weOwnFile(final Uri uri) {
358 if (uri == null || !ContentResolver.SCHEME_FILE.equals(uri.getScheme())) {
359 return false;
360 } else {
361 return weOwnFileLollipop(uri);
362 }
363 }
364
365 private static boolean weOwnFileLollipop(final Uri uri) {
366 try {
367 File file = new File(uri.getPath());
368 FileDescriptor fd =
369 ParcelFileDescriptor.open(file, ParcelFileDescriptor.MODE_READ_ONLY)
370 .getFileDescriptor();
371 StructStat st = Os.fstat(fd);
372 return st.st_uid == android.os.Process.myUid();
373 } catch (FileNotFoundException e) {
374 return false;
375 } catch (Exception e) {
376 return true;
377 }
378 }
379
380 public static Uri getMediaUri(Context context, File file) {
381 final String filePath = file.getAbsolutePath();
382 final Cursor cursor;
383 try {
384 cursor =
385 context.getContentResolver()
386 .query(
387 MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
388 new String[] {MediaStore.Images.Media._ID},
389 MediaStore.Images.Media.DATA + "=? ",
390 new String[] {filePath},
391 null);
392 } catch (SecurityException e) {
393 return null;
394 }
395 if (cursor != null && cursor.moveToFirst()) {
396 final int id = cursor.getInt(cursor.getColumnIndex(MediaStore.MediaColumns._ID));
397 cursor.close();
398 return Uri.withAppendedPath(
399 MediaStore.Images.Media.EXTERNAL_CONTENT_URI, String.valueOf(id));
400 } else {
401 return null;
402 }
403 }
404
405 public static void updateFileParams(Message message, String url, long size) {
406 final StringBuilder body = new StringBuilder();
407 body.append(url).append('|').append(size);
408 message.setBody(body.toString());
409 }
410
411 public Bitmap getPreviewForUri(Attachment attachment, int size, boolean cacheOnly) {
412 final String key = "attachment_" + attachment.getUuid().toString() + "_" + size;
413 final LruCache<String, Bitmap> cache = mXmppConnectionService.getBitmapCache();
414 Bitmap bitmap = cache.get(key);
415 if (bitmap != null || cacheOnly) {
416 return bitmap;
417 }
418 final String mime = attachment.getMime();
419 if ("application/pdf".equals(mime) && Compatibility.runsTwentyOne()) {
420 bitmap = cropCenterSquarePdf(attachment.getUri(), size);
421 drawOverlay(
422 bitmap,
423 paintOverlayBlackPdf(bitmap)
424 ? R.drawable.open_pdf_black
425 : R.drawable.open_pdf_white,
426 0.75f);
427 } else if (mime != null && mime.startsWith("video/")) {
428 bitmap = cropCenterSquareVideo(attachment.getUri(), size);
429 drawOverlay(
430 bitmap,
431 paintOverlayBlack(bitmap)
432 ? R.drawable.play_video_black
433 : R.drawable.play_video_white,
434 0.75f);
435 } else {
436 bitmap = cropCenterSquare(attachment.getUri(), size);
437 if (bitmap != null && "image/gif".equals(mime)) {
438 Bitmap withGifOverlay = bitmap.copy(Bitmap.Config.ARGB_8888, true);
439 drawOverlay(
440 withGifOverlay,
441 paintOverlayBlack(withGifOverlay)
442 ? R.drawable.play_gif_black
443 : R.drawable.play_gif_white,
444 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 public void updateMediaScanner(File file) {
456 updateMediaScanner(file, null);
457 }
458
459 public void updateMediaScanner(File file, final Runnable callback) {
460 MediaScannerConnection.scanFile(
461 mXmppConnectionService,
462 new String[] {file.getAbsolutePath()},
463 null,
464 new MediaScannerConnection.MediaScannerConnectionClient() {
465 @Override
466 public void onMediaScannerConnected() {}
467
468 @Override
469 public void onScanCompleted(String path, Uri uri) {
470 if (callback != null && file.getAbsolutePath().equals(path)) {
471 callback.run();
472 } else {
473 Log.d(Config.LOGTAG, "media scanner scanned wrong file");
474 if (callback != null) {
475 callback.run();
476 }
477 }
478 }
479 });
480 }
481
482 public boolean deleteFile(Message message) {
483 File file = getFile(message);
484 if (file.delete()) {
485 updateMediaScanner(file);
486 return true;
487 } else {
488 return false;
489 }
490 }
491
492 public DownloadableFile getFile(Message message) {
493 return getFile(message, true);
494 }
495
496 public DownloadableFile getFileForPath(String path) {
497 return getFileForPath(
498 path,
499 MimeUtils.guessMimeTypeFromExtension(MimeUtils.extractRelevantExtension(path)));
500 }
501
502 private DownloadableFile getFileForPath(final String path, final String mime) {
503 if (path.startsWith("/")) {
504 return new DownloadableFile(path);
505 } else {
506 return getLegacyFileForFilename(path, mime);
507 }
508 }
509
510 public DownloadableFile getLegacyFileForFilename(final String filename, final String mime) {
511 if (Strings.isNullOrEmpty(mime)) {
512 return new DownloadableFile(getLegacyStorageLocation("Files"), filename);
513 } else if (mime.startsWith("image/")) {
514 return new DownloadableFile(getLegacyStorageLocation("Images"), filename);
515 } else if (mime.startsWith("video/")) {
516 return new DownloadableFile(getLegacyStorageLocation("Videos"), filename);
517 } else {
518 return new DownloadableFile(getLegacyStorageLocation("Files"), filename);
519 }
520 }
521
522 public boolean isInternalFile(final File file) {
523 final File internalFile = getFileForPath(file.getName());
524 return file.getAbsolutePath().equals(internalFile.getAbsolutePath());
525 }
526
527 public DownloadableFile getFile(Message message, boolean decrypted) {
528 final boolean encrypted =
529 !decrypted
530 && (message.getEncryption() == Message.ENCRYPTION_PGP
531 || message.getEncryption() == Message.ENCRYPTION_DECRYPTED);
532 String path = message.getRelativeFilePath();
533 if (path == null) {
534 path = message.getUuid();
535 }
536 final DownloadableFile file = getFileForPath(path, message.getMimeType());
537 if (encrypted) {
538 return new DownloadableFile(getLegacyStorageLocation("Files"), file.getName() + ".pgp");
539 } else {
540 return file;
541 }
542 }
543
544 public List<Attachment> convertToAttachments(List<DatabaseBackend.FilePath> relativeFilePaths) {
545 final List<Attachment> attachments = new ArrayList<>();
546 for (final DatabaseBackend.FilePath relativeFilePath : relativeFilePaths) {
547 final String mime =
548 MimeUtils.guessMimeTypeFromExtension(
549 MimeUtils.extractRelevantExtension(relativeFilePath.path));
550 final File file = getFileForPath(relativeFilePath.path, mime);
551 attachments.add(Attachment.of(relativeFilePath.uuid, file, mime));
552 }
553 return attachments;
554 }
555
556 private File getLegacyStorageLocation(final String type) {
557 if (Config.ONLY_INTERNAL_STORAGE) {
558 return new File(mXmppConnectionService.getFilesDir(), type);
559 } else {
560 final File appDirectory =
561 new File(
562 Environment.getExternalStorageDirectory(),
563 mXmppConnectionService.getString(R.string.app_name));
564 final File appMediaDirectory = new File(appDirectory, "Media");
565 final String locationName =
566 String.format(
567 "%s %s", mXmppConnectionService.getString(R.string.app_name), type);
568 return new File(appMediaDirectory, locationName);
569 }
570 }
571
572 private Bitmap resize(final Bitmap originalBitmap, int size) throws IOException {
573 int w = originalBitmap.getWidth();
574 int h = originalBitmap.getHeight();
575 if (w <= 0 || h <= 0) {
576 throw new IOException("Decoded bitmap reported bounds smaller 0");
577 } else if (Math.max(w, h) > size) {
578 int scalledW;
579 int scalledH;
580 if (w <= h) {
581 scalledW = Math.max((int) (w / ((double) h / size)), 1);
582 scalledH = size;
583 } else {
584 scalledW = size;
585 scalledH = Math.max((int) (h / ((double) w / size)), 1);
586 }
587 final Bitmap result =
588 Bitmap.createScaledBitmap(originalBitmap, scalledW, scalledH, true);
589 if (!originalBitmap.isRecycled()) {
590 originalBitmap.recycle();
591 }
592 return result;
593 } else {
594 return originalBitmap;
595 }
596 }
597
598 public boolean useImageAsIs(final Uri uri) {
599 final String path = getOriginalPath(uri);
600 if (path == null || isPathBlacklisted(path)) {
601 return false;
602 }
603 final File file = new File(path);
604 long size = file.length();
605 if (size == 0
606 || size
607 >= mXmppConnectionService
608 .getResources()
609 .getInteger(R.integer.auto_accept_filesize)) {
610 return false;
611 }
612 BitmapFactory.Options options = new BitmapFactory.Options();
613 options.inJustDecodeBounds = true;
614 try {
615 final InputStream inputStream =
616 mXmppConnectionService.getContentResolver().openInputStream(uri);
617 BitmapFactory.decodeStream(inputStream, null, options);
618 close(inputStream);
619 if (options.outMimeType == null || options.outHeight <= 0 || options.outWidth <= 0) {
620 return false;
621 }
622 return (options.outWidth <= Config.IMAGE_SIZE
623 && options.outHeight <= Config.IMAGE_SIZE
624 && options.outMimeType.contains(Config.IMAGE_FORMAT.name().toLowerCase()));
625 } catch (FileNotFoundException e) {
626 Log.d(Config.LOGTAG, "unable to get image dimensions", e);
627 return false;
628 }
629 }
630
631 public String getOriginalPath(Uri uri) {
632 return FileUtils.getPath(mXmppConnectionService, uri);
633 }
634
635 private void copyFileToPrivateStorage(File file, Uri uri) throws FileCopyException {
636 Log.d(
637 Config.LOGTAG,
638 "copy file (" + uri.toString() + ") to private storage " + file.getAbsolutePath());
639 file.getParentFile().mkdirs();
640 try {
641 file.createNewFile();
642 } catch (IOException e) {
643 throw new FileCopyException(R.string.error_unable_to_create_temporary_file);
644 }
645 try (final OutputStream os = new FileOutputStream(file);
646 final InputStream is =
647 mXmppConnectionService.getContentResolver().openInputStream(uri)) {
648 if (is == null) {
649 throw new FileCopyException(R.string.error_file_not_found);
650 }
651 try {
652 ByteStreams.copy(is, os);
653 } catch (IOException e) {
654 throw new FileWriterException();
655 }
656 try {
657 os.flush();
658 } catch (IOException e) {
659 throw new FileWriterException();
660 }
661 } catch (final FileNotFoundException e) {
662 cleanup(file);
663 throw new FileCopyException(R.string.error_file_not_found);
664 } catch (final FileWriterException e) {
665 cleanup(file);
666 throw new FileCopyException(R.string.error_unable_to_create_temporary_file);
667 } catch (final SecurityException e) {
668 cleanup(file);
669 throw new FileCopyException(R.string.error_security_exception);
670 } catch (final IOException e) {
671 cleanup(file);
672 throw new FileCopyException(R.string.error_io_exception);
673 }
674 }
675
676 public void copyFileToPrivateStorage(Message message, Uri uri, String type)
677 throws FileCopyException {
678 String mime = MimeUtils.guessMimeTypeFromUriAndMime(mXmppConnectionService, uri, type);
679 Log.d(Config.LOGTAG, "copy " + uri.toString() + " to private storage (mime=" + mime + ")");
680 String extension = MimeUtils.guessExtensionFromMimeType(mime);
681 if (extension == null) {
682 Log.d(Config.LOGTAG, "extension from mime type was null");
683 extension = getExtensionFromUri(uri);
684 }
685 if ("ogg".equals(extension) && type != null && type.startsWith("audio/")) {
686 extension = "oga";
687 }
688 setupRelativeFilePath(message, String.format("%s.%s", message.getUuid(), extension));
689 copyFileToPrivateStorage(mXmppConnectionService.getFileBackend().getFile(message), uri);
690 }
691
692 private String getExtensionFromUri(final Uri uri) {
693 final String[] projection = {MediaStore.MediaColumns.DATA};
694 String filename = null;
695 try (final Cursor cursor =
696 mXmppConnectionService
697 .getContentResolver()
698 .query(uri, projection, null, null, null)) {
699 if (cursor != null && cursor.moveToFirst()) {
700 filename = cursor.getString(0);
701 }
702 } catch (final SecurityException | IllegalArgumentException e) {
703 filename = null;
704 }
705 if (filename == null) {
706 final List<String> segments = uri.getPathSegments();
707 if (segments.size() > 0) {
708 filename = segments.get(segments.size() - 1);
709 }
710 }
711 final int pos = filename == null ? -1 : filename.lastIndexOf('.');
712 return pos > 0 ? filename.substring(pos + 1) : null;
713 }
714
715 private void copyImageToPrivateStorage(File file, Uri image, int sampleSize)
716 throws FileCopyException, ImageCompressionException {
717 final File parent = file.getParentFile();
718 if (parent != null && parent.mkdirs()) {
719 Log.d(Config.LOGTAG, "created parent directory");
720 }
721 InputStream is = null;
722 OutputStream os = null;
723 try {
724 if (!file.exists() && !file.createNewFile()) {
725 throw new FileCopyException(R.string.error_unable_to_create_temporary_file);
726 }
727 is = mXmppConnectionService.getContentResolver().openInputStream(image);
728 if (is == null) {
729 throw new FileCopyException(R.string.error_not_an_image_file);
730 }
731 final Bitmap originalBitmap;
732 final BitmapFactory.Options options = new BitmapFactory.Options();
733 final int inSampleSize = (int) Math.pow(2, sampleSize);
734 Log.d(Config.LOGTAG, "reading bitmap with sample size " + inSampleSize);
735 options.inSampleSize = inSampleSize;
736 originalBitmap = BitmapFactory.decodeStream(is, null, options);
737 is.close();
738 if (originalBitmap == null) {
739 throw new ImageCompressionException("Source file was not an image");
740 }
741 if (!"image/jpeg".equals(options.outMimeType) && hasAlpha(originalBitmap)) {
742 originalBitmap.recycle();
743 throw new ImageCompressionException("Source file had alpha channel");
744 }
745 Bitmap scaledBitmap = resize(originalBitmap, Config.IMAGE_SIZE);
746 final int rotation = getRotation(image);
747 scaledBitmap = rotate(scaledBitmap, rotation);
748 boolean targetSizeReached = false;
749 int quality = Config.IMAGE_QUALITY;
750 final int imageMaxSize =
751 mXmppConnectionService
752 .getResources()
753 .getInteger(R.integer.auto_accept_filesize);
754 while (!targetSizeReached) {
755 os = new FileOutputStream(file);
756 Log.d(Config.LOGTAG, "compressing image with quality " + quality);
757 boolean success = scaledBitmap.compress(Config.IMAGE_FORMAT, quality, os);
758 if (!success) {
759 throw new FileCopyException(R.string.error_compressing_image);
760 }
761 os.flush();
762 final long fileSize = file.length();
763 Log.d(Config.LOGTAG, "achieved file size of " + fileSize);
764 targetSizeReached = fileSize <= imageMaxSize || quality <= 50;
765 quality -= 5;
766 }
767 scaledBitmap.recycle();
768 } catch (final FileNotFoundException e) {
769 cleanup(file);
770 throw new FileCopyException(R.string.error_file_not_found);
771 } catch (final IOException e) {
772 cleanup(file);
773 throw new FileCopyException(R.string.error_io_exception);
774 } catch (SecurityException e) {
775 cleanup(file);
776 throw new FileCopyException(R.string.error_security_exception_during_image_copy);
777 } catch (final OutOfMemoryError e) {
778 ++sampleSize;
779 if (sampleSize <= 3) {
780 copyImageToPrivateStorage(file, image, sampleSize);
781 } else {
782 throw new FileCopyException(R.string.error_out_of_memory);
783 }
784 } finally {
785 close(os);
786 close(is);
787 }
788 }
789
790 private static void cleanup(final File file) {
791 try {
792 file.delete();
793 } catch (Exception e) {
794
795 }
796 }
797
798 public void copyImageToPrivateStorage(File file, Uri image)
799 throws FileCopyException, ImageCompressionException {
800 Log.d(
801 Config.LOGTAG,
802 "copy image ("
803 + image.toString()
804 + ") to private storage "
805 + file.getAbsolutePath());
806 copyImageToPrivateStorage(file, image, 0);
807 }
808
809 public void copyImageToPrivateStorage(Message message, Uri image)
810 throws FileCopyException, ImageCompressionException {
811 final String filename;
812 switch (Config.IMAGE_FORMAT) {
813 case JPEG:
814 filename = String.format("%s.%s", message.getUuid(), "jpg");
815 break;
816 case PNG:
817 filename = String.format("%s.%s", message.getUuid(), "png");
818 break;
819 case WEBP:
820 filename = String.format("%s.%s", message.getUuid(), "webp");
821 break;
822 default:
823 throw new IllegalStateException("Unknown image format");
824 }
825 setupRelativeFilePath(message, filename);
826 copyImageToPrivateStorage(getFile(message), image);
827 updateFileParams(message);
828 }
829
830 public void setupRelativeFilePath(final Message message, final String filename) {
831 final String extension = MimeUtils.extractRelevantExtension(filename);
832 final String mime = MimeUtils.guessMimeTypeFromExtension(extension);
833 setupRelativeFilePath(message, filename, mime);
834 }
835
836 public File getStorageLocation(final String filename, final String mime) {
837 final File parentDirectory;
838 if (Strings.isNullOrEmpty(mime)) {
839 parentDirectory =
840 Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
841 } else if (mime.startsWith("image/")) {
842 parentDirectory =
843 Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
844 } else if (mime.startsWith("video/")) {
845 parentDirectory =
846 Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MOVIES);
847 } else if (MediaAdapter.DOCUMENT_MIMES.contains(mime)) {
848 parentDirectory =
849 Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS);
850 } else {
851 parentDirectory =
852 Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
853 }
854 final File appDirectory =
855 new File(parentDirectory, mXmppConnectionService.getString(R.string.app_name));
856 return new File(appDirectory, filename);
857 }
858
859 public void setupRelativeFilePath(
860 final Message message, final String filename, final String mime) {
861 final File file = getStorageLocation(filename, mime);
862 message.setRelativeFilePath(file.getAbsolutePath());
863 }
864
865 public boolean unusualBounds(final Uri image) {
866 try {
867 final BitmapFactory.Options options = new BitmapFactory.Options();
868 options.inJustDecodeBounds = true;
869 final InputStream inputStream =
870 mXmppConnectionService.getContentResolver().openInputStream(image);
871 BitmapFactory.decodeStream(inputStream, null, options);
872 close(inputStream);
873 float ratio = (float) options.outHeight / options.outWidth;
874 return ratio > (21.0f / 9.0f) || ratio < (9.0f / 21.0f);
875 } catch (final Exception e) {
876 Log.w(Config.LOGTAG, "unable to detect image bounds", e);
877 return false;
878 }
879 }
880
881 private int getRotation(final File file) {
882 try (final InputStream inputStream = new FileInputStream(file)) {
883 return getRotation(inputStream);
884 } catch (Exception e) {
885 return 0;
886 }
887 }
888
889 private int getRotation(final Uri image) {
890 try (final InputStream is =
891 mXmppConnectionService.getContentResolver().openInputStream(image)) {
892 return is == null ? 0 : getRotation(is);
893 } catch (final Exception e) {
894 return 0;
895 }
896 }
897
898 private static int getRotation(final InputStream inputStream) throws IOException {
899 final ExifInterface exif = new ExifInterface(inputStream);
900 final int orientation =
901 exif.getAttributeInt(
902 ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_UNDEFINED);
903 switch (orientation) {
904 case ExifInterface.ORIENTATION_ROTATE_180:
905 return 180;
906 case ExifInterface.ORIENTATION_ROTATE_90:
907 return 90;
908 case ExifInterface.ORIENTATION_ROTATE_270:
909 return 270;
910 default:
911 return 0;
912 }
913 }
914
915 public Bitmap getThumbnail(Message message, int size, boolean cacheOnly) throws IOException {
916 final String uuid = message.getUuid();
917 final LruCache<String, Bitmap> cache = mXmppConnectionService.getBitmapCache();
918 Bitmap thumbnail = cache.get(uuid);
919 if ((thumbnail == null) && (!cacheOnly)) {
920 synchronized (THUMBNAIL_LOCK) {
921 thumbnail = cache.get(uuid);
922 if (thumbnail != null) {
923 return thumbnail;
924 }
925 DownloadableFile file = getFile(message);
926 final String mime = file.getMimeType();
927 if ("application/pdf".equals(mime) && Compatibility.runsTwentyOne()) {
928 thumbnail = getPdfDocumentPreview(file, size);
929 } else if (mime.startsWith("video/")) {
930 thumbnail = getVideoPreview(file, size);
931 } else {
932 final Bitmap fullSize = getFullSizeImagePreview(file, size);
933 if (fullSize == null) {
934 throw new FileNotFoundException();
935 }
936 thumbnail = resize(fullSize, size);
937 thumbnail = rotate(thumbnail, getRotation(file));
938 if (mime.equals("image/gif")) {
939 Bitmap withGifOverlay = thumbnail.copy(Bitmap.Config.ARGB_8888, true);
940 drawOverlay(
941 withGifOverlay,
942 paintOverlayBlack(withGifOverlay)
943 ? R.drawable.play_gif_black
944 : R.drawable.play_gif_white,
945 1.0f);
946 thumbnail.recycle();
947 thumbnail = withGifOverlay;
948 }
949 }
950 cache.put(uuid, thumbnail);
951 }
952 }
953 return thumbnail;
954 }
955
956 private Bitmap getFullSizeImagePreview(File file, int size) {
957 BitmapFactory.Options options = new BitmapFactory.Options();
958 options.inSampleSize = calcSampleSize(file, size);
959 try {
960 return BitmapFactory.decodeFile(file.getAbsolutePath(), options);
961 } catch (OutOfMemoryError e) {
962 options.inSampleSize *= 2;
963 return BitmapFactory.decodeFile(file.getAbsolutePath(), options);
964 }
965 }
966
967 private void drawOverlay(Bitmap bitmap, int resource, float factor) {
968 Bitmap overlay =
969 BitmapFactory.decodeResource(mXmppConnectionService.getResources(), resource);
970 Canvas canvas = new Canvas(bitmap);
971 float targetSize = Math.min(canvas.getWidth(), canvas.getHeight()) * factor;
972 Log.d(
973 Config.LOGTAG,
974 "target size overlay: "
975 + targetSize
976 + " overlay bitmap size was "
977 + overlay.getHeight());
978 float left = (canvas.getWidth() - targetSize) / 2.0f;
979 float top = (canvas.getHeight() - targetSize) / 2.0f;
980 RectF dst = new RectF(left, top, left + targetSize - 1, top + targetSize - 1);
981 canvas.drawBitmap(overlay, null, dst, createAntiAliasingPaint());
982 }
983
984 /** https://stackoverflow.com/a/3943023/210897 */
985 private boolean paintOverlayBlack(final Bitmap bitmap) {
986 final int h = bitmap.getHeight();
987 final int w = bitmap.getWidth();
988 int record = 0;
989 for (int y = Math.round(h * IGNORE_PADDING); y < h - Math.round(h * IGNORE_PADDING); ++y) {
990 for (int x = Math.round(w * IGNORE_PADDING);
991 x < w - Math.round(w * IGNORE_PADDING);
992 ++x) {
993 int pixel = bitmap.getPixel(x, y);
994 if ((Color.red(pixel) * 0.299
995 + Color.green(pixel) * 0.587
996 + Color.blue(pixel) * 0.114)
997 > 186) {
998 --record;
999 } else {
1000 ++record;
1001 }
1002 }
1003 }
1004 return record < 0;
1005 }
1006
1007 private boolean paintOverlayBlackPdf(final Bitmap bitmap) {
1008 final int h = bitmap.getHeight();
1009 final int w = bitmap.getWidth();
1010 int white = 0;
1011 for (int y = 0; y < h; ++y) {
1012 for (int x = 0; x < w; ++x) {
1013 int pixel = bitmap.getPixel(x, y);
1014 if ((Color.red(pixel) * 0.299
1015 + Color.green(pixel) * 0.587
1016 + Color.blue(pixel) * 0.114)
1017 > 186) {
1018 white++;
1019 }
1020 }
1021 }
1022 return white > (h * w * 0.4f);
1023 }
1024
1025 private Bitmap cropCenterSquareVideo(Uri uri, int size) {
1026 MediaMetadataRetriever metadataRetriever = new MediaMetadataRetriever();
1027 Bitmap frame;
1028 try {
1029 metadataRetriever.setDataSource(mXmppConnectionService, uri);
1030 frame = metadataRetriever.getFrameAtTime(0);
1031 metadataRetriever.release();
1032 return cropCenterSquare(frame, size);
1033 } catch (Exception e) {
1034 frame = Bitmap.createBitmap(size, size, Bitmap.Config.ARGB_8888);
1035 frame.eraseColor(0xff000000);
1036 return frame;
1037 }
1038 }
1039
1040 private Bitmap getVideoPreview(final File file, final int size) {
1041 final MediaMetadataRetriever metadataRetriever = new MediaMetadataRetriever();
1042 Bitmap frame;
1043 try {
1044 metadataRetriever.setDataSource(file.getAbsolutePath());
1045 frame = metadataRetriever.getFrameAtTime(0);
1046 metadataRetriever.release();
1047 frame = resize(frame, size);
1048 } catch (IOException | RuntimeException e) {
1049 frame = Bitmap.createBitmap(size, size, Bitmap.Config.ARGB_8888);
1050 frame.eraseColor(0xff000000);
1051 }
1052 drawOverlay(
1053 frame,
1054 paintOverlayBlack(frame)
1055 ? R.drawable.play_video_black
1056 : R.drawable.play_video_white,
1057 0.75f);
1058 return frame;
1059 }
1060
1061 @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
1062 private Bitmap getPdfDocumentPreview(final File file, final int size) {
1063 try {
1064 final ParcelFileDescriptor fileDescriptor =
1065 ParcelFileDescriptor.open(file, ParcelFileDescriptor.MODE_READ_ONLY);
1066 final Bitmap rendered = renderPdfDocument(fileDescriptor, size, true);
1067 drawOverlay(
1068 rendered,
1069 paintOverlayBlackPdf(rendered)
1070 ? R.drawable.open_pdf_black
1071 : R.drawable.open_pdf_white,
1072 0.75f);
1073 return rendered;
1074 } catch (final IOException | SecurityException e) {
1075 Log.d(Config.LOGTAG, "unable to render PDF document preview", e);
1076 final Bitmap placeholder = Bitmap.createBitmap(size, size, Bitmap.Config.ARGB_8888);
1077 placeholder.eraseColor(0xff000000);
1078 return placeholder;
1079 }
1080 }
1081
1082 @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
1083 private Bitmap cropCenterSquarePdf(final Uri uri, final int size) {
1084 try {
1085 ParcelFileDescriptor fileDescriptor =
1086 mXmppConnectionService.getContentResolver().openFileDescriptor(uri, "r");
1087 final Bitmap bitmap = renderPdfDocument(fileDescriptor, size, false);
1088 return cropCenterSquare(bitmap, size);
1089 } catch (Exception e) {
1090 final Bitmap placeholder = Bitmap.createBitmap(size, size, Bitmap.Config.ARGB_8888);
1091 placeholder.eraseColor(0xff000000);
1092 return placeholder;
1093 }
1094 }
1095
1096 @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
1097 private Bitmap renderPdfDocument(
1098 ParcelFileDescriptor fileDescriptor, int targetSize, boolean fit) throws IOException {
1099 final PdfRenderer pdfRenderer = new PdfRenderer(fileDescriptor);
1100 final PdfRenderer.Page page = pdfRenderer.openPage(0);
1101 final Dimensions dimensions =
1102 scalePdfDimensions(
1103 new Dimensions(page.getHeight(), page.getWidth()), targetSize, fit);
1104 final Bitmap rendered =
1105 Bitmap.createBitmap(dimensions.width, dimensions.height, Bitmap.Config.ARGB_8888);
1106 rendered.eraseColor(0xffffffff);
1107 page.render(rendered, null, null, PdfRenderer.Page.RENDER_MODE_FOR_DISPLAY);
1108 page.close();
1109 pdfRenderer.close();
1110 fileDescriptor.close();
1111 return rendered;
1112 }
1113
1114 public Uri getTakePhotoUri() {
1115 final String filename =
1116 String.format("IMG_%s.%s", IMAGE_DATE_FORMAT.format(new Date()), "jpg");
1117 final File directory;
1118 if (Config.ONLY_INTERNAL_STORAGE) {
1119 directory = new File(mXmppConnectionService.getCacheDir(), "Camera");
1120 } else {
1121 directory =
1122 new File(
1123 Environment.getExternalStoragePublicDirectory(
1124 Environment.DIRECTORY_DCIM),
1125 "Camera");
1126 }
1127 final File file = new File(directory, filename);
1128 file.getParentFile().mkdirs();
1129 return getUriForFile(mXmppConnectionService, file);
1130 }
1131
1132 public Avatar getPepAvatar(Uri image, int size, Bitmap.CompressFormat format) {
1133
1134 final Avatar uncompressAvatar = getUncompressedAvatar(image);
1135 if (uncompressAvatar != null
1136 && uncompressAvatar.image.length() <= Config.AVATAR_CHAR_LIMIT) {
1137 return uncompressAvatar;
1138 }
1139 if (uncompressAvatar != null) {
1140 Log.d(
1141 Config.LOGTAG,
1142 "uncompressed avatar exceeded char limit by "
1143 + (uncompressAvatar.image.length() - Config.AVATAR_CHAR_LIMIT));
1144 }
1145
1146 Bitmap bm = cropCenterSquare(image, size);
1147 if (bm == null) {
1148 return null;
1149 }
1150 if (hasAlpha(bm)) {
1151 Log.d(Config.LOGTAG, "alpha in avatar detected; uploading as PNG");
1152 bm.recycle();
1153 bm = cropCenterSquare(image, 96);
1154 return getPepAvatar(bm, Bitmap.CompressFormat.PNG, 100);
1155 }
1156 return getPepAvatar(bm, format, 100);
1157 }
1158
1159 private Avatar getUncompressedAvatar(Uri uri) {
1160 Bitmap bitmap = null;
1161 try {
1162 bitmap =
1163 BitmapFactory.decodeStream(
1164 mXmppConnectionService.getContentResolver().openInputStream(uri));
1165 return getPepAvatar(bitmap, Bitmap.CompressFormat.PNG, 100);
1166 } catch (Exception e) {
1167 return null;
1168 } finally {
1169 if (bitmap != null) {
1170 bitmap.recycle();
1171 }
1172 }
1173 }
1174
1175 private Avatar getPepAvatar(Bitmap bitmap, Bitmap.CompressFormat format, int quality) {
1176 try {
1177 ByteArrayOutputStream mByteArrayOutputStream = new ByteArrayOutputStream();
1178 Base64OutputStream mBase64OutputStream =
1179 new Base64OutputStream(mByteArrayOutputStream, Base64.DEFAULT);
1180 MessageDigest digest = MessageDigest.getInstance("SHA-1");
1181 DigestOutputStream mDigestOutputStream =
1182 new DigestOutputStream(mBase64OutputStream, digest);
1183 if (!bitmap.compress(format, quality, mDigestOutputStream)) {
1184 return null;
1185 }
1186 mDigestOutputStream.flush();
1187 mDigestOutputStream.close();
1188 long chars = mByteArrayOutputStream.size();
1189 if (format != Bitmap.CompressFormat.PNG
1190 && quality >= 50
1191 && chars >= Config.AVATAR_CHAR_LIMIT) {
1192 int q = quality - 2;
1193 Log.d(
1194 Config.LOGTAG,
1195 "avatar char length was " + chars + " reducing quality to " + q);
1196 return getPepAvatar(bitmap, format, q);
1197 }
1198 Log.d(Config.LOGTAG, "settled on char length " + chars + " with quality=" + quality);
1199 final Avatar avatar = new Avatar();
1200 avatar.sha1sum = CryptoHelper.bytesToHex(digest.digest());
1201 avatar.image = new String(mByteArrayOutputStream.toByteArray());
1202 if (format.equals(Bitmap.CompressFormat.WEBP)) {
1203 avatar.type = "image/webp";
1204 } else if (format.equals(Bitmap.CompressFormat.JPEG)) {
1205 avatar.type = "image/jpeg";
1206 } else if (format.equals(Bitmap.CompressFormat.PNG)) {
1207 avatar.type = "image/png";
1208 }
1209 avatar.width = bitmap.getWidth();
1210 avatar.height = bitmap.getHeight();
1211 return avatar;
1212 } catch (OutOfMemoryError e) {
1213 Log.d(Config.LOGTAG, "unable to convert avatar to base64 due to low memory");
1214 return null;
1215 } catch (Exception e) {
1216 return null;
1217 }
1218 }
1219
1220 public Avatar getStoredPepAvatar(String hash) {
1221 if (hash == null) {
1222 return null;
1223 }
1224 Avatar avatar = new Avatar();
1225 final File file = getAvatarFile(hash);
1226 FileInputStream is = null;
1227 try {
1228 avatar.size = file.length();
1229 BitmapFactory.Options options = new BitmapFactory.Options();
1230 options.inJustDecodeBounds = true;
1231 BitmapFactory.decodeFile(file.getAbsolutePath(), options);
1232 is = new FileInputStream(file);
1233 ByteArrayOutputStream mByteArrayOutputStream = new ByteArrayOutputStream();
1234 Base64OutputStream mBase64OutputStream =
1235 new Base64OutputStream(mByteArrayOutputStream, Base64.DEFAULT);
1236 MessageDigest digest = MessageDigest.getInstance("SHA-1");
1237 DigestOutputStream os = new DigestOutputStream(mBase64OutputStream, digest);
1238 byte[] buffer = new byte[4096];
1239 int length;
1240 while ((length = is.read(buffer)) > 0) {
1241 os.write(buffer, 0, length);
1242 }
1243 os.flush();
1244 os.close();
1245 avatar.sha1sum = CryptoHelper.bytesToHex(digest.digest());
1246 avatar.image = new String(mByteArrayOutputStream.toByteArray());
1247 avatar.height = options.outHeight;
1248 avatar.width = options.outWidth;
1249 avatar.type = options.outMimeType;
1250 return avatar;
1251 } catch (NoSuchAlgorithmException | IOException e) {
1252 return null;
1253 } finally {
1254 close(is);
1255 }
1256 }
1257
1258 public boolean isAvatarCached(Avatar avatar) {
1259 final File file = getAvatarFile(avatar.getFilename());
1260 return file.exists();
1261 }
1262
1263 public boolean save(final Avatar avatar) {
1264 File file;
1265 if (isAvatarCached(avatar)) {
1266 file = getAvatarFile(avatar.getFilename());
1267 avatar.size = file.length();
1268 } else {
1269 file =
1270 new File(
1271 mXmppConnectionService.getCacheDir().getAbsolutePath()
1272 + "/"
1273 + UUID.randomUUID().toString());
1274 if (file.getParentFile().mkdirs()) {
1275 Log.d(Config.LOGTAG, "created cache directory");
1276 }
1277 OutputStream os = null;
1278 try {
1279 if (!file.createNewFile()) {
1280 Log.d(
1281 Config.LOGTAG,
1282 "unable to create temporary file " + file.getAbsolutePath());
1283 }
1284 os = new FileOutputStream(file);
1285 MessageDigest digest = MessageDigest.getInstance("SHA-1");
1286 digest.reset();
1287 DigestOutputStream mDigestOutputStream = new DigestOutputStream(os, digest);
1288 final byte[] bytes = avatar.getImageAsBytes();
1289 mDigestOutputStream.write(bytes);
1290 mDigestOutputStream.flush();
1291 mDigestOutputStream.close();
1292 String sha1sum = CryptoHelper.bytesToHex(digest.digest());
1293 if (sha1sum.equals(avatar.sha1sum)) {
1294 final File outputFile = getAvatarFile(avatar.getFilename());
1295 if (outputFile.getParentFile().mkdirs()) {
1296 Log.d(Config.LOGTAG, "created avatar directory");
1297 }
1298 final File avatarFile = getAvatarFile(avatar.getFilename());
1299 if (!file.renameTo(avatarFile)) {
1300 Log.d(
1301 Config.LOGTAG,
1302 "unable to rename " + file.getAbsolutePath() + " to " + outputFile);
1303 return false;
1304 }
1305 } else {
1306 Log.d(Config.LOGTAG, "sha1sum mismatch for " + avatar.owner);
1307 if (!file.delete()) {
1308 Log.d(Config.LOGTAG, "unable to delete temporary file");
1309 }
1310 return false;
1311 }
1312 avatar.size = bytes.length;
1313 } catch (IllegalArgumentException | IOException | NoSuchAlgorithmException e) {
1314 return false;
1315 } finally {
1316 close(os);
1317 }
1318 }
1319 return true;
1320 }
1321
1322 public void deleteHistoricAvatarPath() {
1323 delete(getHistoricAvatarPath());
1324 }
1325
1326 private void delete(final File file) {
1327 if (file.isDirectory()) {
1328 final File[] files = file.listFiles();
1329 if (files != null) {
1330 for (final File f : files) {
1331 delete(f);
1332 }
1333 }
1334 }
1335 if (file.delete()) {
1336 Log.d(Config.LOGTAG, "deleted " + file.getAbsolutePath());
1337 }
1338 }
1339
1340 private File getHistoricAvatarPath() {
1341 return new File(mXmppConnectionService.getFilesDir(), "/avatars/");
1342 }
1343
1344 private File getAvatarFile(String avatar) {
1345 return new File(mXmppConnectionService.getCacheDir(), "/avatars/" + avatar);
1346 }
1347
1348 public Uri getAvatarUri(String avatar) {
1349 return Uri.fromFile(getAvatarFile(avatar));
1350 }
1351
1352 public Bitmap cropCenterSquare(Uri image, int size) {
1353 if (image == null) {
1354 return null;
1355 }
1356 InputStream is = null;
1357 try {
1358 BitmapFactory.Options options = new BitmapFactory.Options();
1359 options.inSampleSize = calcSampleSize(image, size);
1360 is = mXmppConnectionService.getContentResolver().openInputStream(image);
1361 if (is == null) {
1362 return null;
1363 }
1364 Bitmap input = BitmapFactory.decodeStream(is, null, options);
1365 if (input == null) {
1366 return null;
1367 } else {
1368 input = rotate(input, getRotation(image));
1369 return cropCenterSquare(input, size);
1370 }
1371 } catch (FileNotFoundException | SecurityException e) {
1372 Log.d(Config.LOGTAG, "unable to open file " + image.toString(), e);
1373 return null;
1374 } finally {
1375 close(is);
1376 }
1377 }
1378
1379 public Bitmap cropCenter(Uri image, int newHeight, int newWidth) {
1380 if (image == null) {
1381 return null;
1382 }
1383 InputStream is = null;
1384 try {
1385 BitmapFactory.Options options = new BitmapFactory.Options();
1386 options.inSampleSize = calcSampleSize(image, Math.max(newHeight, newWidth));
1387 is = mXmppConnectionService.getContentResolver().openInputStream(image);
1388 if (is == null) {
1389 return null;
1390 }
1391 Bitmap source = BitmapFactory.decodeStream(is, null, options);
1392 if (source == null) {
1393 return null;
1394 }
1395 int sourceWidth = source.getWidth();
1396 int sourceHeight = source.getHeight();
1397 float xScale = (float) newWidth / sourceWidth;
1398 float yScale = (float) newHeight / sourceHeight;
1399 float scale = Math.max(xScale, yScale);
1400 float scaledWidth = scale * sourceWidth;
1401 float scaledHeight = scale * sourceHeight;
1402 float left = (newWidth - scaledWidth) / 2;
1403 float top = (newHeight - scaledHeight) / 2;
1404
1405 RectF targetRect = new RectF(left, top, left + scaledWidth, top + scaledHeight);
1406 Bitmap dest = Bitmap.createBitmap(newWidth, newHeight, Bitmap.Config.ARGB_8888);
1407 Canvas canvas = new Canvas(dest);
1408 canvas.drawBitmap(source, null, targetRect, createAntiAliasingPaint());
1409 if (source.isRecycled()) {
1410 source.recycle();
1411 }
1412 return dest;
1413 } catch (SecurityException e) {
1414 return null; // android 6.0 with revoked permissions for example
1415 } catch (FileNotFoundException e) {
1416 return null;
1417 } finally {
1418 close(is);
1419 }
1420 }
1421
1422 public Bitmap cropCenterSquare(Bitmap input, int size) {
1423 int w = input.getWidth();
1424 int h = input.getHeight();
1425
1426 float scale = Math.max((float) size / h, (float) size / w);
1427
1428 float outWidth = scale * w;
1429 float outHeight = scale * h;
1430 float left = (size - outWidth) / 2;
1431 float top = (size - outHeight) / 2;
1432 RectF target = new RectF(left, top, left + outWidth, top + outHeight);
1433
1434 Bitmap output = Bitmap.createBitmap(size, size, Bitmap.Config.ARGB_8888);
1435 Canvas canvas = new Canvas(output);
1436 canvas.drawBitmap(input, null, target, createAntiAliasingPaint());
1437 if (!input.isRecycled()) {
1438 input.recycle();
1439 }
1440 return output;
1441 }
1442
1443 private int calcSampleSize(Uri image, int size)
1444 throws FileNotFoundException, SecurityException {
1445 final BitmapFactory.Options options = new BitmapFactory.Options();
1446 options.inJustDecodeBounds = true;
1447 final InputStream inputStream =
1448 mXmppConnectionService.getContentResolver().openInputStream(image);
1449 BitmapFactory.decodeStream(inputStream, null, options);
1450 close(inputStream);
1451 return calcSampleSize(options, size);
1452 }
1453
1454 public void updateFileParams(Message message) {
1455 updateFileParams(message, null);
1456 }
1457
1458 public void updateFileParams(Message message, String url) {
1459 DownloadableFile file = getFile(message);
1460 final String mime = file.getMimeType();
1461 final boolean privateMessage = message.isPrivateMessage();
1462 final boolean image =
1463 message.getType() == Message.TYPE_IMAGE
1464 || (mime != null && mime.startsWith("image/"));
1465 final boolean video = mime != null && mime.startsWith("video/");
1466 final boolean audio = mime != null && mime.startsWith("audio/");
1467 final boolean pdf = "application/pdf".equals(mime);
1468 final StringBuilder body = new StringBuilder();
1469 if (url != null) {
1470 body.append(url);
1471 }
1472 body.append('|').append(file.getSize());
1473 if (image || video || (pdf && Compatibility.runsTwentyOne())) {
1474 try {
1475 final Dimensions dimensions;
1476 if (video) {
1477 dimensions = getVideoDimensions(file);
1478 } else if (pdf && Compatibility.runsTwentyOne()) {
1479 dimensions = getPdfDocumentDimensions(file);
1480 } else {
1481 dimensions = getImageDimensions(file);
1482 }
1483 if (dimensions.valid()) {
1484 body.append('|').append(dimensions.width).append('|').append(dimensions.height);
1485 }
1486 } catch (NotAVideoFile notAVideoFile) {
1487 Log.d(
1488 Config.LOGTAG,
1489 "file with mime type " + file.getMimeType() + " was not a video file");
1490 // fall threw
1491 }
1492 } else if (audio) {
1493 body.append("|0|0|").append(getMediaRuntime(file));
1494 }
1495 message.setBody(body.toString());
1496 message.setDeleted(false);
1497 message.setType(
1498 privateMessage
1499 ? Message.TYPE_PRIVATE_FILE
1500 : (image ? Message.TYPE_IMAGE : Message.TYPE_FILE));
1501 }
1502
1503 private int getMediaRuntime(File file) {
1504 try {
1505 MediaMetadataRetriever mediaMetadataRetriever = new MediaMetadataRetriever();
1506 mediaMetadataRetriever.setDataSource(file.toString());
1507 return Integer.parseInt(
1508 mediaMetadataRetriever.extractMetadata(
1509 MediaMetadataRetriever.METADATA_KEY_DURATION));
1510 } catch (RuntimeException e) {
1511 return 0;
1512 }
1513 }
1514
1515 private Dimensions getImageDimensions(File file) {
1516 BitmapFactory.Options options = new BitmapFactory.Options();
1517 options.inJustDecodeBounds = true;
1518 BitmapFactory.decodeFile(file.getAbsolutePath(), options);
1519 int rotation = getRotation(file);
1520 boolean rotated = rotation == 90 || rotation == 270;
1521 int imageHeight = rotated ? options.outWidth : options.outHeight;
1522 int imageWidth = rotated ? options.outHeight : options.outWidth;
1523 return new Dimensions(imageHeight, imageWidth);
1524 }
1525
1526 private Dimensions getVideoDimensions(File file) throws NotAVideoFile {
1527 MediaMetadataRetriever metadataRetriever = new MediaMetadataRetriever();
1528 try {
1529 metadataRetriever.setDataSource(file.getAbsolutePath());
1530 } catch (RuntimeException e) {
1531 throw new NotAVideoFile(e);
1532 }
1533 return getVideoDimensions(metadataRetriever);
1534 }
1535
1536 @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
1537 private Dimensions getPdfDocumentDimensions(final File file) {
1538 final ParcelFileDescriptor fileDescriptor;
1539 try {
1540 fileDescriptor = ParcelFileDescriptor.open(file, ParcelFileDescriptor.MODE_READ_ONLY);
1541 if (fileDescriptor == null) {
1542 return new Dimensions(0, 0);
1543 }
1544 } catch (FileNotFoundException e) {
1545 return new Dimensions(0, 0);
1546 }
1547 try {
1548 final PdfRenderer pdfRenderer = new PdfRenderer(fileDescriptor);
1549 final PdfRenderer.Page page = pdfRenderer.openPage(0);
1550 final int height = page.getHeight();
1551 final int width = page.getWidth();
1552 page.close();
1553 pdfRenderer.close();
1554 return scalePdfDimensions(new Dimensions(height, width));
1555 } catch (IOException | SecurityException e) {
1556 Log.d(Config.LOGTAG, "unable to get dimensions for pdf document", e);
1557 return new Dimensions(0, 0);
1558 }
1559 }
1560
1561 private Dimensions scalePdfDimensions(Dimensions in) {
1562 final DisplayMetrics displayMetrics =
1563 mXmppConnectionService.getResources().getDisplayMetrics();
1564 final int target = (int) (displayMetrics.density * 288);
1565 return scalePdfDimensions(in, target, true);
1566 }
1567
1568 private static Dimensions scalePdfDimensions(
1569 final Dimensions in, final int target, final boolean fit) {
1570 final int w, h;
1571 if (fit == (in.width <= in.height)) {
1572 w = Math.max((int) (in.width / ((double) in.height / target)), 1);
1573 h = target;
1574 } else {
1575 w = target;
1576 h = Math.max((int) (in.height / ((double) in.width / target)), 1);
1577 }
1578 return new Dimensions(h, w);
1579 }
1580
1581 public Bitmap getAvatar(String avatar, int size) {
1582 if (avatar == null) {
1583 return null;
1584 }
1585 Bitmap bm = cropCenter(getAvatarUri(avatar), size, size);
1586 return bm;
1587 }
1588
1589 private static class Dimensions {
1590 public final int width;
1591 public final int height;
1592
1593 Dimensions(int height, int width) {
1594 this.width = width;
1595 this.height = height;
1596 }
1597
1598 public int getMin() {
1599 return Math.min(width, height);
1600 }
1601
1602 public boolean valid() {
1603 return width > 0 && height > 0;
1604 }
1605 }
1606
1607 private static class NotAVideoFile extends Exception {
1608 public NotAVideoFile(Throwable t) {
1609 super(t);
1610 }
1611
1612 public NotAVideoFile() {
1613 super();
1614 }
1615 }
1616
1617 public static class ImageCompressionException extends Exception {
1618
1619 ImageCompressionException(String message) {
1620 super(message);
1621 }
1622 }
1623
1624 public static class FileCopyException extends Exception {
1625 private final int resId;
1626
1627 private FileCopyException(@StringRes int resId) {
1628 this.resId = resId;
1629 }
1630
1631 public @StringRes int getResId() {
1632 return resId;
1633 }
1634 }
1635}