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