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