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