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) throws FileCopyException {
678 Log.d(
679 Config.LOGTAG,
680 "copy file (" + file + ") to " + df);
681 try (final InputStream is = new FileInputStream(file);
682 final OutputStream os =
683 mXmppConnectionService.getContentResolver().openOutputStream(df.getUri())) {
684 if (is == null) {
685 throw new FileCopyException(R.string.error_file_not_found);
686 }
687 try {
688 ByteStreams.copy(is, os);
689 os.flush();
690 } catch (IOException e) {
691 throw new FileWriterException(file);
692 }
693 } catch (final FileNotFoundException e) {
694 throw new FileCopyException(R.string.error_file_not_found);
695 } catch (final FileWriterException e) {
696 throw new FileCopyException(R.string.error_unable_to_create_temporary_file);
697 } catch (final SecurityException | IllegalStateException e) {
698 throw new FileCopyException(R.string.error_security_exception);
699 } catch (final IOException e) {
700 throw new FileCopyException(R.string.error_io_exception);
701 }
702 }
703
704 private void copyFileToPrivateStorage(File file, Uri uri) throws FileCopyException {
705 Log.d(
706 Config.LOGTAG,
707 "copy file (" + uri.toString() + ") to private storage " + file.getAbsolutePath());
708 file.getParentFile().mkdirs();
709 try {
710 file.createNewFile();
711 } catch (IOException e) {
712 throw new FileCopyException(R.string.error_unable_to_create_temporary_file);
713 }
714 try (final OutputStream os = new FileOutputStream(file);
715 final InputStream is =
716 mXmppConnectionService.getContentResolver().openInputStream(uri)) {
717 if (is == null) {
718 throw new FileCopyException(R.string.error_file_not_found);
719 }
720 try {
721 ByteStreams.copy(is, os);
722 } catch (IOException e) {
723 throw new FileWriterException(file);
724 }
725 try {
726 os.flush();
727 } catch (IOException e) {
728 throw new FileWriterException(file);
729 }
730 } catch (final FileNotFoundException e) {
731 cleanup(file);
732 throw new FileCopyException(R.string.error_file_not_found);
733 } catch (final FileWriterException e) {
734 cleanup(file);
735 throw new FileCopyException(R.string.error_unable_to_create_temporary_file);
736 } catch (final SecurityException | IllegalStateException e) {
737 cleanup(file);
738 throw new FileCopyException(R.string.error_security_exception);
739 } catch (final IOException e) {
740 cleanup(file);
741 throw new FileCopyException(R.string.error_io_exception);
742 }
743 }
744
745 public void copyFileToPrivateStorage(Message message, Uri uri, String type)
746 throws FileCopyException {
747 String mime = MimeUtils.guessMimeTypeFromUriAndMime(mXmppConnectionService, uri, type);
748 Log.d(Config.LOGTAG, "copy " + uri.toString() + " to private storage (mime=" + mime + ")");
749 String extension = MimeUtils.guessExtensionFromMimeType(mime);
750 if (extension == null) {
751 Log.d(Config.LOGTAG, "extension from mime type was null");
752 extension = getExtensionFromUri(uri);
753 }
754 if ("ogg".equals(extension) && type != null && type.startsWith("audio/")) {
755 extension = "oga";
756 }
757
758 try {
759 setupRelativeFilePath(message, uri, extension);
760 copyFileToPrivateStorage(mXmppConnectionService.getFileBackend().getFile(message), uri);
761 } catch (final XmppConnectionService.BlockedMediaException e) {
762 message.setRelativeFilePath(null);
763 message.setDeleted(true);
764 }
765 }
766
767 private String getExtensionFromUri(final Uri uri) {
768 final String[] projection = {MediaStore.MediaColumns.DATA};
769 String filename = null;
770 try (final Cursor cursor =
771 mXmppConnectionService
772 .getContentResolver()
773 .query(uri, projection, null, null, null)) {
774 if (cursor != null && cursor.moveToFirst()) {
775 filename = cursor.getString(0);
776 }
777 } catch (final Exception e) {
778 filename = null;
779 }
780 if (filename == null) {
781 final List<String> segments = uri.getPathSegments();
782 if (segments.size() > 0) {
783 filename = segments.get(segments.size() - 1);
784 }
785 }
786 final int pos = filename == null ? -1 : filename.lastIndexOf('.');
787 return pos > 0 ? filename.substring(pos + 1) : null;
788 }
789
790 private void copyImageToPrivateStorage(File file, Uri image, int sampleSize)
791 throws FileCopyException, ImageCompressionException {
792 final File parent = file.getParentFile();
793 if (parent != null && parent.mkdirs()) {
794 Log.d(Config.LOGTAG, "created parent directory");
795 }
796 InputStream is = null;
797 OutputStream os = null;
798 try {
799 if (!file.exists() && !file.createNewFile()) {
800 throw new FileCopyException(R.string.error_unable_to_create_temporary_file);
801 }
802 is = mXmppConnectionService.getContentResolver().openInputStream(image);
803 if (is == null) {
804 throw new FileCopyException(R.string.error_not_an_image_file);
805 }
806 final Bitmap originalBitmap;
807 final BitmapFactory.Options options = new BitmapFactory.Options();
808 final int inSampleSize = (int) Math.pow(2, sampleSize);
809 Log.d(Config.LOGTAG, "reading bitmap with sample size " + inSampleSize);
810 options.inSampleSize = inSampleSize;
811 originalBitmap = BitmapFactory.decodeStream(is, null, options);
812 is.close();
813 if (originalBitmap == null) {
814 throw new ImageCompressionException("Source file was not an image");
815 }
816 if (!"image/jpeg".equals(options.outMimeType) && hasAlpha(originalBitmap)) {
817 originalBitmap.recycle();
818 throw new ImageCompressionException("Source file had alpha channel");
819 }
820 Bitmap scaledBitmap = resize(originalBitmap, Config.IMAGE_SIZE);
821 final int rotation = getRotation(image);
822 scaledBitmap = rotate(scaledBitmap, rotation);
823 boolean targetSizeReached = false;
824 int quality = Config.IMAGE_QUALITY;
825 final int imageMaxSize =
826 mXmppConnectionService
827 .getResources()
828 .getInteger(R.integer.auto_accept_filesize);
829 while (!targetSizeReached) {
830 os = new FileOutputStream(file);
831 Log.d(Config.LOGTAG, "compressing image with quality " + quality);
832 boolean success = scaledBitmap.compress(Config.IMAGE_FORMAT, quality, os);
833 if (!success) {
834 throw new FileCopyException(R.string.error_compressing_image);
835 }
836 os.flush();
837 final long fileSize = file.length();
838 Log.d(Config.LOGTAG, "achieved file size of " + fileSize);
839 targetSizeReached = fileSize <= imageMaxSize || quality <= 50;
840 quality -= 5;
841 }
842 scaledBitmap.recycle();
843 } catch (final FileNotFoundException e) {
844 cleanup(file);
845 throw new FileCopyException(R.string.error_file_not_found);
846 } catch (final IOException e) {
847 cleanup(file);
848 throw new FileCopyException(R.string.error_io_exception);
849 } catch (SecurityException e) {
850 cleanup(file);
851 throw new FileCopyException(R.string.error_security_exception_during_image_copy);
852 } catch (final OutOfMemoryError e) {
853 ++sampleSize;
854 if (sampleSize <= 3) {
855 copyImageToPrivateStorage(file, image, sampleSize);
856 } else {
857 throw new FileCopyException(R.string.error_out_of_memory);
858 }
859 } finally {
860 close(os);
861 close(is);
862 }
863 }
864
865 private static void cleanup(final File file) {
866 try {
867 file.delete();
868 } catch (Exception e) {
869
870 }
871 }
872
873 public void copyImageToPrivateStorage(File file, Uri image)
874 throws FileCopyException, ImageCompressionException {
875 Log.d(
876 Config.LOGTAG,
877 "copy image ("
878 + image.toString()
879 + ") to private storage "
880 + file.getAbsolutePath());
881 copyImageToPrivateStorage(file, image, 0);
882 }
883
884 public void copyImageToPrivateStorage(Message message, Uri image)
885 throws FileCopyException, ImageCompressionException {
886 final String filename;
887 switch (Config.IMAGE_FORMAT) {
888 case JPEG:
889 filename = String.format("%s.%s", message.getUuid(), "jpg");
890 break;
891 case PNG:
892 filename = String.format("%s.%s", message.getUuid(), "png");
893 break;
894 case WEBP:
895 filename = String.format("%s.%s", message.getUuid(), "webp");
896 break;
897 default:
898 throw new IllegalStateException("Unknown image format");
899 }
900 setupRelativeFilePath(message, filename);
901 final File tmp = getFile(message);
902 copyImageToPrivateStorage(tmp, image);
903 final String extension = MimeUtils.extractRelevantExtension(filename);
904 try {
905 setupRelativeFilePath(message, new FileInputStream(tmp), extension);
906 } catch (final FileNotFoundException e) {
907 throw new FileCopyException(R.string.error_file_not_found);
908 } catch (final IOException e) {
909 throw new FileCopyException(R.string.error_io_exception);
910 } catch (final XmppConnectionService.BlockedMediaException e) {
911 tmp.delete();
912 message.setRelativeFilePath(null);
913 message.setDeleted(true);
914 return;
915 }
916 tmp.renameTo(getFile(message));
917 updateFileParams(message, null, false);
918 }
919
920 public void setupRelativeFilePath(final Message message, final Uri uri, final String extension) throws FileCopyException, XmppConnectionService.BlockedMediaException {
921 try {
922 setupRelativeFilePath(message, mXmppConnectionService.getContentResolver().openInputStream(uri), extension);
923 } catch (final FileNotFoundException e) {
924 throw new FileCopyException(R.string.error_file_not_found);
925 } catch (final IOException e) {
926 throw new FileCopyException(R.string.error_io_exception);
927 }
928 }
929
930 public Cid[] calculateCids(final InputStream is) throws IOException {
931 try {
932 return CryptoHelper.cid(is, new String[]{"SHA-256", "SHA-1", "SHA-512"});
933 } catch (final NoSuchAlgorithmException e) {
934 throw new AssertionError(e);
935 }
936 }
937
938 public void setupRelativeFilePath(final Message message, final InputStream is, final String extension) throws IOException, XmppConnectionService.BlockedMediaException {
939 message.setRelativeFilePath(getStorageLocation(is, extension).getAbsolutePath());
940 }
941
942 public void setupRelativeFilePath(final Message message, final String filename) {
943 final String extension = MimeUtils.extractRelevantExtension(filename);
944 final String mime = MimeUtils.guessMimeTypeFromExtension(extension);
945 setupRelativeFilePath(message, filename, mime);
946 }
947
948 public File getStorageLocation(final InputStream is, final String extension) throws IOException, XmppConnectionService.BlockedMediaException {
949 final String mime = MimeUtils.guessMimeTypeFromExtension(extension);
950 Cid[] cids = calculateCids(is);
951
952 File file = getStorageLocation(String.format("%s.%s", cids[0], extension), mime);
953 for (int i = 0; i < cids.length; i++) {
954 mXmppConnectionService.saveCid(cids[i], file);
955 }
956 return file;
957 }
958
959 public File getStorageLocation(final String filename, final String mime) {
960 final File parentDirectory;
961 if (Strings.isNullOrEmpty(mime)) {
962 parentDirectory =
963 Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
964 } else if (mime.startsWith("image/")) {
965 parentDirectory =
966 Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
967 } else if (mime.startsWith("video/")) {
968 parentDirectory =
969 Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MOVIES);
970 } else if (MediaAdapter.DOCUMENT_MIMES.contains(mime)) {
971 parentDirectory =
972 Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS);
973 } else {
974 parentDirectory =
975 Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
976 }
977 final File appDirectory =
978 new File(parentDirectory, mXmppConnectionService.getString(R.string.app_name));
979 return new File(appDirectory, filename);
980 }
981
982 public static boolean inConversationsDirectory(final Context context, String path) {
983 final File fileDirectory = new File(path).getParentFile();
984 for (final String type : STORAGE_TYPES) {
985 final File typeDirectory =
986 new File(
987 Environment.getExternalStoragePublicDirectory(type),
988 context.getString(R.string.app_name));
989 if (typeDirectory.equals(fileDirectory)) {
990 return true;
991 }
992 }
993 return false;
994 }
995
996 public void setupRelativeFilePath(
997 final Message message, final String filename, final String mime) {
998 final File file = getStorageLocation(filename, mime);
999 message.setRelativeFilePath(file.getAbsolutePath());
1000 }
1001
1002 public boolean unusualBounds(final Uri image) {
1003 try {
1004 final BitmapFactory.Options options = new BitmapFactory.Options();
1005 options.inJustDecodeBounds = true;
1006 final InputStream inputStream =
1007 mXmppConnectionService.getContentResolver().openInputStream(image);
1008 BitmapFactory.decodeStream(inputStream, null, options);
1009 close(inputStream);
1010 float ratio = (float) options.outHeight / options.outWidth;
1011 return ratio > (21.0f / 9.0f) || ratio < (9.0f / 21.0f);
1012 } catch (final Exception e) {
1013 Log.w(Config.LOGTAG, "unable to detect image bounds", e);
1014 return false;
1015 }
1016 }
1017
1018 private int getRotation(final File file) {
1019 try (final InputStream inputStream = new FileInputStream(file)) {
1020 return getRotation(inputStream);
1021 } catch (Exception e) {
1022 return 0;
1023 }
1024 }
1025
1026 private int getRotation(final Uri image) {
1027 try (final InputStream is =
1028 mXmppConnectionService.getContentResolver().openInputStream(image)) {
1029 return is == null ? 0 : getRotation(is);
1030 } catch (final Exception e) {
1031 return 0;
1032 }
1033 }
1034
1035 private static int getRotation(final InputStream inputStream) throws IOException {
1036 final ExifInterface exif = new ExifInterface(inputStream);
1037 final int orientation =
1038 exif.getAttributeInt(
1039 ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_UNDEFINED);
1040 switch (orientation) {
1041 case ExifInterface.ORIENTATION_ROTATE_180:
1042 return 180;
1043 case ExifInterface.ORIENTATION_ROTATE_90:
1044 return 90;
1045 case ExifInterface.ORIENTATION_ROTATE_270:
1046 return 270;
1047 default:
1048 return 0;
1049 }
1050 }
1051
1052 public BitmapDrawable getFallbackThumbnail(final Message message, int size) {
1053 List<Element> thumbs = message.getFileParams() != null ? message.getFileParams().getThumbnails() : null;
1054 if (thumbs != null && !thumbs.isEmpty()) {
1055 for (Element thumb : thumbs) {
1056 Uri uri = Uri.parse(thumb.getAttribute("uri"));
1057 if (uri.getScheme().equals("data")) {
1058 String[] parts = uri.getSchemeSpecificPart().split(",", 2);
1059 if (parts[0].equals("image/blurhash")) {
1060 final LruCache<String, Drawable> cache = mXmppConnectionService.getDrawableCache();
1061 BitmapDrawable cached = (BitmapDrawable) cache.get(parts[1]);
1062 if (cached != null) return cached;
1063
1064 int width = message.getFileParams().width;
1065 if (width < 1 && thumb.getAttribute("width") != null) width = Integer.parseInt(thumb.getAttribute("width"));
1066 if (width < 1) width = 1920;
1067
1068 int height = message.getFileParams().height;
1069 if (height < 1 && thumb.getAttribute("height") != null) height = Integer.parseInt(thumb.getAttribute("height"));
1070 if (height < 1) height = 1080;
1071 Rect r = rectForSize(width, height, size);
1072
1073 Bitmap blurhash = BlurHashDecoder.INSTANCE.decode(parts[1], r.width(), r.height(), 1.0f, false);
1074 if (blurhash != null) {
1075 cached = new BitmapDrawable(blurhash);
1076 cache.put(parts[1], cached);
1077 return cached;
1078 }
1079 }
1080 }
1081 }
1082 }
1083
1084 return null;
1085 }
1086
1087 public Drawable getThumbnail(Message message, Resources res, int size, boolean cacheOnly) throws IOException {
1088 final LruCache<String, Drawable> cache = mXmppConnectionService.getDrawableCache();
1089 DownloadableFile file = getFile(message);
1090 Drawable thumbnail = cache.get(file.getAbsolutePath());
1091 if (thumbnail != null) return thumbnail;
1092
1093 if ((thumbnail == null) && (!cacheOnly)) {
1094 synchronized (THUMBNAIL_LOCK) {
1095 List<Element> thumbs = message.getFileParams() != null ? message.getFileParams().getThumbnails() : null;
1096 if (thumbs != null && !thumbs.isEmpty()) {
1097 for (Element thumb : thumbs) {
1098 Uri uri = Uri.parse(thumb.getAttribute("uri"));
1099 if (uri.getScheme().equals("data")) {
1100 if (android.os.Build.VERSION.SDK_INT < 28) continue;
1101 String[] parts = uri.getSchemeSpecificPart().split(",", 2);
1102 if (parts[0].equals("image/blurhash")) continue; // blurhash only for fallback
1103
1104 byte[] data;
1105 if (Arrays.asList(parts[0].split(";")).contains("base64")) {
1106 data = Base64.decode(parts[1], 0);
1107 } else {
1108 data = parts[1].getBytes("UTF-8");
1109 }
1110
1111 ImageDecoder.Source source = ImageDecoder.createSource(ByteBuffer.wrap(data));
1112 thumbnail = ImageDecoder.decodeDrawable(source, (decoder, info, src) -> {
1113 int w = info.getSize().getWidth();
1114 int h = info.getSize().getHeight();
1115 Rect r = rectForSize(w, h, size);
1116 decoder.setTargetSize(r.width(), r.height());
1117 });
1118
1119 if (thumbnail != null) {
1120 cache.put(file.getAbsolutePath(), thumbnail);
1121 return thumbnail;
1122 }
1123 } else if (uri.getScheme().equals("cid")) {
1124 Cid cid = BobTransfer.cid(uri);
1125 if (cid == null) continue;
1126 DownloadableFile f = mXmppConnectionService.getFileForCid(cid);
1127 if (f != null && f.canRead()) {
1128 return getThumbnail(f, res, size, cacheOnly);
1129 }
1130 }
1131 }
1132 }
1133 }
1134 }
1135
1136 return getThumbnail(file, res, size, cacheOnly);
1137 }
1138
1139 public Drawable getThumbnail(DownloadableFile file, Resources res, int size, boolean cacheOnly) throws IOException {
1140 final LruCache<String, Drawable> cache = mXmppConnectionService.getDrawableCache();
1141 Drawable thumbnail = cache.get(file.getAbsolutePath());
1142 if ((thumbnail == null) && (!cacheOnly)) {
1143 synchronized (THUMBNAIL_LOCK) {
1144 thumbnail = cache.get(file.getAbsolutePath());
1145 if (thumbnail != null) {
1146 return thumbnail;
1147 }
1148 final String mime = file.getMimeType();
1149 if ("application/pdf".equals(mime)) {
1150 thumbnail = new BitmapDrawable(res, getPdfDocumentPreview(file, size));
1151 } else if (mime.startsWith("video/")) {
1152 thumbnail = new BitmapDrawable(res, getVideoPreview(file, size));
1153 } else {
1154 thumbnail = getImagePreview(file, res, size, mime);
1155 if (thumbnail == null) {
1156 throw new FileNotFoundException();
1157 }
1158 }
1159 cache.put(file.getAbsolutePath(), thumbnail);
1160 }
1161 }
1162 return thumbnail;
1163 }
1164
1165 public Bitmap getThumbnailBitmap(Message message, Resources res, int size) throws IOException {
1166 final Drawable drawable = getThumbnail(message, res, size, false);
1167 if (drawable == null) return null;
1168 return drawDrawable(drawable);
1169 }
1170
1171 public static Rect rectForSize(int w, int h, int size) {
1172 int scalledW;
1173 int scalledH;
1174 if (w <= h) {
1175 scalledW = Math.max((int) (w / ((double) h / size)), 1);
1176 scalledH = size;
1177 } else {
1178 scalledW = size;
1179 scalledH = Math.max((int) (h / ((double) w / size)), 1);
1180 }
1181
1182 if (scalledW > w || scalledH > h) return new Rect(0, 0, w, h);
1183
1184 return new Rect(0, 0, scalledW, scalledH);
1185 }
1186
1187 private Drawable getImagePreview(File file, Resources res, int size, final String mime) throws IOException {
1188 if (android.os.Build.VERSION.SDK_INT >= 28) {
1189 ImageDecoder.Source source = ImageDecoder.createSource(file);
1190 return ImageDecoder.decodeDrawable(source, (decoder, info, src) -> {
1191 int w = info.getSize().getWidth();
1192 int h = info.getSize().getHeight();
1193 Rect r = rectForSize(w, h, size);
1194 decoder.setTargetSize(r.width(), r.height());
1195 });
1196 } else {
1197 BitmapFactory.Options options = new BitmapFactory.Options();
1198 options.inSampleSize = calcSampleSize(file, size);
1199 Bitmap bitmap = null;
1200 try {
1201 bitmap = BitmapFactory.decodeFile(file.getAbsolutePath(), options);
1202 } catch (OutOfMemoryError e) {
1203 options.inSampleSize *= 2;
1204 bitmap = BitmapFactory.decodeFile(file.getAbsolutePath(), options);
1205 }
1206 if (bitmap == null) return null;
1207
1208 bitmap = resize(bitmap, size);
1209 bitmap = rotate(bitmap, getRotation(file));
1210 if (mime.equals("image/gif")) {
1211 Bitmap withGifOverlay = bitmap.copy(Bitmap.Config.ARGB_8888, true);
1212 drawOverlay(withGifOverlay, paintOverlayBlack(withGifOverlay) ? R.drawable.play_gif_black : R.drawable.play_gif_white, 1.0f);
1213 bitmap.recycle();
1214 bitmap = withGifOverlay;
1215 }
1216 return new BitmapDrawable(res, bitmap);
1217 }
1218 }
1219
1220 protected Bitmap drawDrawable(Drawable drawable) {
1221 Bitmap bitmap = null;
1222
1223 if (drawable instanceof BitmapDrawable) {
1224 bitmap = ((BitmapDrawable) drawable).getBitmap();
1225 if (bitmap != null) return bitmap;
1226 }
1227
1228 bitmap = Bitmap.createBitmap(drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight(), Bitmap.Config.ARGB_8888);
1229 Canvas canvas = new Canvas(bitmap);
1230 drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
1231 drawable.draw(canvas);
1232 return bitmap;
1233 }
1234
1235 private void drawOverlay(Bitmap bitmap, int resource, float factor) {
1236 Bitmap overlay =
1237 BitmapFactory.decodeResource(mXmppConnectionService.getResources(), resource);
1238 Canvas canvas = new Canvas(bitmap);
1239 float targetSize = Math.min(canvas.getWidth(), canvas.getHeight()) * factor;
1240 Log.d(
1241 Config.LOGTAG,
1242 "target size overlay: "
1243 + targetSize
1244 + " overlay bitmap size was "
1245 + overlay.getHeight());
1246 float left = (canvas.getWidth() - targetSize) / 2.0f;
1247 float top = (canvas.getHeight() - targetSize) / 2.0f;
1248 RectF dst = new RectF(left, top, left + targetSize - 1, top + targetSize - 1);
1249 canvas.drawBitmap(overlay, null, dst, createAntiAliasingPaint());
1250 }
1251
1252 /** https://stackoverflow.com/a/3943023/210897 */
1253 private boolean paintOverlayBlack(final Bitmap bitmap) {
1254 final int h = bitmap.getHeight();
1255 final int w = bitmap.getWidth();
1256 int record = 0;
1257 for (int y = Math.round(h * IGNORE_PADDING); y < h - Math.round(h * IGNORE_PADDING); ++y) {
1258 for (int x = Math.round(w * IGNORE_PADDING);
1259 x < w - Math.round(w * IGNORE_PADDING);
1260 ++x) {
1261 int pixel = bitmap.getPixel(x, y);
1262 if ((Color.red(pixel) * 0.299
1263 + Color.green(pixel) * 0.587
1264 + Color.blue(pixel) * 0.114)
1265 > 186) {
1266 --record;
1267 } else {
1268 ++record;
1269 }
1270 }
1271 }
1272 return record < 0;
1273 }
1274
1275 private boolean paintOverlayBlackPdf(final Bitmap bitmap) {
1276 final int h = bitmap.getHeight();
1277 final int w = bitmap.getWidth();
1278 int white = 0;
1279 for (int y = 0; y < h; ++y) {
1280 for (int x = 0; x < w; ++x) {
1281 int pixel = bitmap.getPixel(x, y);
1282 if ((Color.red(pixel) * 0.299
1283 + Color.green(pixel) * 0.587
1284 + Color.blue(pixel) * 0.114)
1285 > 186) {
1286 white++;
1287 }
1288 }
1289 }
1290 return white > (h * w * 0.4f);
1291 }
1292
1293 private Bitmap cropCenterSquareVideo(Uri uri, int size) {
1294 MediaMetadataRetriever metadataRetriever = new MediaMetadataRetriever();
1295 Bitmap frame;
1296 try {
1297 metadataRetriever.setDataSource(mXmppConnectionService, uri);
1298 frame = metadataRetriever.getFrameAtTime(0);
1299 metadataRetriever.release();
1300 return cropCenterSquare(frame, size);
1301 } catch (Exception e) {
1302 frame = Bitmap.createBitmap(size, size, Bitmap.Config.ARGB_8888);
1303 frame.eraseColor(0xff000000);
1304 return frame;
1305 }
1306 }
1307
1308 private Bitmap getVideoPreview(final File file, final int size) {
1309 final MediaMetadataRetriever metadataRetriever = new MediaMetadataRetriever();
1310 Bitmap frame;
1311 try {
1312 metadataRetriever.setDataSource(file.getAbsolutePath());
1313 frame = metadataRetriever.getFrameAtTime(0);
1314 metadataRetriever.release();
1315 frame = resize(frame, size);
1316 } catch (IOException | RuntimeException e) {
1317 frame = Bitmap.createBitmap(size, size, Bitmap.Config.ARGB_8888);
1318 frame.eraseColor(0xff000000);
1319 }
1320 drawOverlay(
1321 frame,
1322 paintOverlayBlack(frame)
1323 ? R.drawable.play_video_black
1324 : R.drawable.play_video_white,
1325 0.75f);
1326 return frame;
1327 }
1328
1329 @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
1330 private Bitmap getPdfDocumentPreview(final File file, final int size) {
1331 try {
1332 final ParcelFileDescriptor fileDescriptor =
1333 ParcelFileDescriptor.open(file, ParcelFileDescriptor.MODE_READ_ONLY);
1334 final Bitmap rendered = renderPdfDocument(fileDescriptor, size, true);
1335 drawOverlay(
1336 rendered,
1337 paintOverlayBlackPdf(rendered)
1338 ? R.drawable.open_pdf_black
1339 : R.drawable.open_pdf_white,
1340 0.75f);
1341 return rendered;
1342 } catch (final IOException | SecurityException e) {
1343 Log.d(Config.LOGTAG, "unable to render PDF document preview", e);
1344 final Bitmap placeholder = Bitmap.createBitmap(size, size, Bitmap.Config.ARGB_8888);
1345 placeholder.eraseColor(0xff000000);
1346 return placeholder;
1347 }
1348 }
1349
1350 @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
1351 private Bitmap cropCenterSquarePdf(final Uri uri, final int size) {
1352 try {
1353 ParcelFileDescriptor fileDescriptor =
1354 mXmppConnectionService.getContentResolver().openFileDescriptor(uri, "r");
1355 final Bitmap bitmap = renderPdfDocument(fileDescriptor, size, false);
1356 return cropCenterSquare(bitmap, size);
1357 } catch (Exception e) {
1358 final Bitmap placeholder = Bitmap.createBitmap(size, size, Bitmap.Config.ARGB_8888);
1359 placeholder.eraseColor(0xff000000);
1360 return placeholder;
1361 }
1362 }
1363
1364 @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
1365 private Bitmap renderPdfDocument(
1366 ParcelFileDescriptor fileDescriptor, int targetSize, boolean fit) throws IOException {
1367 final PdfRenderer pdfRenderer = new PdfRenderer(fileDescriptor);
1368 final PdfRenderer.Page page = pdfRenderer.openPage(0);
1369 final Dimensions dimensions =
1370 scalePdfDimensions(
1371 new Dimensions(page.getHeight(), page.getWidth()), targetSize, fit);
1372 final Bitmap rendered =
1373 Bitmap.createBitmap(dimensions.width, dimensions.height, Bitmap.Config.ARGB_8888);
1374 rendered.eraseColor(0xffffffff);
1375 page.render(rendered, null, null, PdfRenderer.Page.RENDER_MODE_FOR_DISPLAY);
1376 page.close();
1377 pdfRenderer.close();
1378 fileDescriptor.close();
1379 return rendered;
1380 }
1381
1382 public Uri getTakePhotoUri() {
1383 final String filename =
1384 String.format("IMG_%s.%s", IMAGE_DATE_FORMAT.format(new Date()), "jpg");
1385 final File directory;
1386 if (Config.ONLY_INTERNAL_STORAGE) {
1387 directory = new File(mXmppConnectionService.getCacheDir(), "Camera");
1388 } else {
1389 directory =
1390 new File(
1391 Environment.getExternalStoragePublicDirectory(
1392 Environment.DIRECTORY_DCIM),
1393 "Camera");
1394 }
1395 final File file = new File(directory, filename);
1396 file.getParentFile().mkdirs();
1397 return getUriForFile(mXmppConnectionService, file);
1398 }
1399
1400 public Avatar getPepAvatar(Uri image, int size, Bitmap.CompressFormat format) {
1401
1402 final Avatar uncompressAvatar = getUncompressedAvatar(image);
1403 if (uncompressAvatar != null
1404 && uncompressAvatar.image.length() <= Config.AVATAR_CHAR_LIMIT) {
1405 return uncompressAvatar;
1406 }
1407 if (uncompressAvatar != null) {
1408 Log.d(
1409 Config.LOGTAG,
1410 "uncompressed avatar exceeded char limit by "
1411 + (uncompressAvatar.image.length() - Config.AVATAR_CHAR_LIMIT));
1412 }
1413
1414 Bitmap bm = cropCenterSquare(image, size);
1415 if (bm == null) {
1416 return null;
1417 }
1418 if (hasAlpha(bm)) {
1419 Log.d(Config.LOGTAG, "alpha in avatar detected; uploading as PNG");
1420 bm.recycle();
1421 bm = cropCenterSquare(image, 96);
1422 return getPepAvatar(bm, Bitmap.CompressFormat.PNG, 100);
1423 }
1424 return getPepAvatar(bm, format, 100);
1425 }
1426
1427 private Avatar getUncompressedAvatar(Uri uri) {
1428 Bitmap bitmap = null;
1429 try {
1430 bitmap =
1431 BitmapFactory.decodeStream(
1432 mXmppConnectionService.getContentResolver().openInputStream(uri));
1433 return getPepAvatar(bitmap, Bitmap.CompressFormat.PNG, 100);
1434 } catch (Exception e) {
1435 return null;
1436 } finally {
1437 if (bitmap != null) {
1438 bitmap.recycle();
1439 }
1440 }
1441 }
1442
1443 private Avatar getPepAvatar(Bitmap bitmap, Bitmap.CompressFormat format, int quality) {
1444 try {
1445 ByteArrayOutputStream mByteArrayOutputStream = new ByteArrayOutputStream();
1446 Base64OutputStream mBase64OutputStream =
1447 new Base64OutputStream(mByteArrayOutputStream, Base64.DEFAULT);
1448 MessageDigest digest = MessageDigest.getInstance("SHA-1");
1449 DigestOutputStream mDigestOutputStream =
1450 new DigestOutputStream(mBase64OutputStream, digest);
1451 if (!bitmap.compress(format, quality, mDigestOutputStream)) {
1452 return null;
1453 }
1454 mDigestOutputStream.flush();
1455 mDigestOutputStream.close();
1456 long chars = mByteArrayOutputStream.size();
1457 if (format != Bitmap.CompressFormat.PNG
1458 && quality >= 50
1459 && chars >= Config.AVATAR_CHAR_LIMIT) {
1460 int q = quality - 2;
1461 Log.d(
1462 Config.LOGTAG,
1463 "avatar char length was " + chars + " reducing quality to " + q);
1464 return getPepAvatar(bitmap, format, q);
1465 }
1466 Log.d(Config.LOGTAG, "settled on char length " + chars + " with quality=" + quality);
1467 final Avatar avatar = new Avatar();
1468 avatar.sha1sum = CryptoHelper.bytesToHex(digest.digest());
1469 avatar.image = new String(mByteArrayOutputStream.toByteArray());
1470 if (format.equals(Bitmap.CompressFormat.WEBP)) {
1471 avatar.type = "image/webp";
1472 } else if (format.equals(Bitmap.CompressFormat.JPEG)) {
1473 avatar.type = "image/jpeg";
1474 } else if (format.equals(Bitmap.CompressFormat.PNG)) {
1475 avatar.type = "image/png";
1476 }
1477 avatar.width = bitmap.getWidth();
1478 avatar.height = bitmap.getHeight();
1479 return avatar;
1480 } catch (OutOfMemoryError e) {
1481 Log.d(Config.LOGTAG, "unable to convert avatar to base64 due to low memory");
1482 return null;
1483 } catch (Exception e) {
1484 return null;
1485 }
1486 }
1487
1488 public Avatar getStoredPepAvatar(String hash) {
1489 if (hash == null) {
1490 return null;
1491 }
1492 Avatar avatar = new Avatar();
1493 final File file = getAvatarFile(hash);
1494 FileInputStream is = null;
1495 try {
1496 avatar.size = file.length();
1497 BitmapFactory.Options options = new BitmapFactory.Options();
1498 options.inJustDecodeBounds = true;
1499 BitmapFactory.decodeFile(file.getAbsolutePath(), options);
1500 is = new FileInputStream(file);
1501 ByteArrayOutputStream mByteArrayOutputStream = new ByteArrayOutputStream();
1502 Base64OutputStream mBase64OutputStream =
1503 new Base64OutputStream(mByteArrayOutputStream, Base64.DEFAULT);
1504 MessageDigest digest = MessageDigest.getInstance("SHA-1");
1505 DigestOutputStream os = new DigestOutputStream(mBase64OutputStream, digest);
1506 byte[] buffer = new byte[4096];
1507 int length;
1508 while ((length = is.read(buffer)) > 0) {
1509 os.write(buffer, 0, length);
1510 }
1511 os.flush();
1512 os.close();
1513 avatar.sha1sum = CryptoHelper.bytesToHex(digest.digest());
1514 avatar.image = new String(mByteArrayOutputStream.toByteArray());
1515 avatar.height = options.outHeight;
1516 avatar.width = options.outWidth;
1517 avatar.type = options.outMimeType;
1518 return avatar;
1519 } catch (NoSuchAlgorithmException | IOException e) {
1520 return null;
1521 } finally {
1522 close(is);
1523 }
1524 }
1525
1526 public boolean isAvatarCached(Avatar avatar) {
1527 final File file = getAvatarFile(avatar.getFilename());
1528 return file.exists();
1529 }
1530
1531 public boolean save(final Avatar avatar) {
1532 File file;
1533 if (isAvatarCached(avatar)) {
1534 file = getAvatarFile(avatar.getFilename());
1535 avatar.size = file.length();
1536 } else {
1537 file =
1538 new File(
1539 mXmppConnectionService.getCacheDir().getAbsolutePath()
1540 + "/"
1541 + UUID.randomUUID().toString());
1542 if (file.getParentFile().mkdirs()) {
1543 Log.d(Config.LOGTAG, "created cache directory");
1544 }
1545 OutputStream os = null;
1546 try {
1547 if (!file.createNewFile()) {
1548 Log.d(
1549 Config.LOGTAG,
1550 "unable to create temporary file " + file.getAbsolutePath());
1551 }
1552 os = new FileOutputStream(file);
1553 MessageDigest digest = MessageDigest.getInstance("SHA-1");
1554 digest.reset();
1555 DigestOutputStream mDigestOutputStream = new DigestOutputStream(os, digest);
1556 final byte[] bytes = avatar.getImageAsBytes();
1557 mDigestOutputStream.write(bytes);
1558 mDigestOutputStream.flush();
1559 mDigestOutputStream.close();
1560 String sha1sum = CryptoHelper.bytesToHex(digest.digest());
1561 if (sha1sum.equals(avatar.sha1sum)) {
1562 final File outputFile = getAvatarFile(avatar.getFilename());
1563 if (outputFile.getParentFile().mkdirs()) {
1564 Log.d(Config.LOGTAG, "created avatar directory");
1565 }
1566 final File avatarFile = getAvatarFile(avatar.getFilename());
1567 if (!file.renameTo(avatarFile)) {
1568 Log.d(
1569 Config.LOGTAG,
1570 "unable to rename " + file.getAbsolutePath() + " to " + outputFile);
1571 return false;
1572 }
1573 } else {
1574 Log.d(Config.LOGTAG, "sha1sum mismatch for " + avatar.owner);
1575 if (!file.delete()) {
1576 Log.d(Config.LOGTAG, "unable to delete temporary file");
1577 }
1578 return false;
1579 }
1580 avatar.size = bytes.length;
1581 } catch (IllegalArgumentException | IOException | NoSuchAlgorithmException e) {
1582 return false;
1583 } finally {
1584 close(os);
1585 }
1586 }
1587 return true;
1588 }
1589
1590 public void deleteHistoricAvatarPath() {
1591 delete(getHistoricAvatarPath());
1592 }
1593
1594 private void delete(final File file) {
1595 if (file.isDirectory()) {
1596 final File[] files = file.listFiles();
1597 if (files != null) {
1598 for (final File f : files) {
1599 delete(f);
1600 }
1601 }
1602 }
1603 if (file.delete()) {
1604 Log.d(Config.LOGTAG, "deleted " + file.getAbsolutePath());
1605 }
1606 }
1607
1608 private File getHistoricAvatarPath() {
1609 return new File(mXmppConnectionService.getFilesDir(), "/avatars/");
1610 }
1611
1612 public File getAvatarFile(String avatar) {
1613 return new File(mXmppConnectionService.getCacheDir(), "/avatars/" + avatar);
1614 }
1615
1616 public Uri getAvatarUri(String avatar) {
1617 return Uri.fromFile(getAvatarFile(avatar));
1618 }
1619
1620 public Bitmap cropCenterSquare(Uri image, int size) {
1621 if (image == null) {
1622 return null;
1623 }
1624 InputStream is = null;
1625 try {
1626 BitmapFactory.Options options = new BitmapFactory.Options();
1627 options.inSampleSize = calcSampleSize(image, size);
1628 is = mXmppConnectionService.getContentResolver().openInputStream(image);
1629 if (is == null) {
1630 return null;
1631 }
1632 Bitmap input = BitmapFactory.decodeStream(is, null, options);
1633 if (input == null) {
1634 return null;
1635 } else {
1636 input = rotate(input, getRotation(image));
1637 return cropCenterSquare(input, size);
1638 }
1639 } catch (FileNotFoundException | SecurityException e) {
1640 Log.d(Config.LOGTAG, "unable to open file " + image.toString(), e);
1641 return null;
1642 } finally {
1643 close(is);
1644 }
1645 }
1646
1647 public Bitmap cropCenter(Uri image, int newHeight, int newWidth) {
1648 if (image == null) {
1649 return null;
1650 }
1651 InputStream is = null;
1652 try {
1653 BitmapFactory.Options options = new BitmapFactory.Options();
1654 options.inSampleSize = calcSampleSize(image, Math.max(newHeight, newWidth));
1655 is = mXmppConnectionService.getContentResolver().openInputStream(image);
1656 if (is == null) {
1657 return null;
1658 }
1659 Bitmap source = BitmapFactory.decodeStream(is, null, options);
1660 if (source == null) {
1661 return null;
1662 }
1663 int sourceWidth = source.getWidth();
1664 int sourceHeight = source.getHeight();
1665 float xScale = (float) newWidth / sourceWidth;
1666 float yScale = (float) newHeight / sourceHeight;
1667 float scale = Math.max(xScale, yScale);
1668 float scaledWidth = scale * sourceWidth;
1669 float scaledHeight = scale * sourceHeight;
1670 float left = (newWidth - scaledWidth) / 2;
1671 float top = (newHeight - scaledHeight) / 2;
1672
1673 RectF targetRect = new RectF(left, top, left + scaledWidth, top + scaledHeight);
1674 Bitmap dest = Bitmap.createBitmap(newWidth, newHeight, Bitmap.Config.ARGB_8888);
1675 Canvas canvas = new Canvas(dest);
1676 canvas.drawBitmap(source, null, targetRect, createAntiAliasingPaint());
1677 if (source.isRecycled()) {
1678 source.recycle();
1679 }
1680 return dest;
1681 } catch (SecurityException e) {
1682 return null; // android 6.0 with revoked permissions for example
1683 } catch (FileNotFoundException e) {
1684 return null;
1685 } finally {
1686 close(is);
1687 }
1688 }
1689
1690 public Bitmap cropCenterSquare(Bitmap input, int size) {
1691 int w = input.getWidth();
1692 int h = input.getHeight();
1693
1694 float scale = Math.max((float) size / h, (float) size / w);
1695
1696 float outWidth = scale * w;
1697 float outHeight = scale * h;
1698 float left = (size - outWidth) / 2;
1699 float top = (size - outHeight) / 2;
1700 RectF target = new RectF(left, top, left + outWidth, top + outHeight);
1701
1702 Bitmap output = Bitmap.createBitmap(size, size, Bitmap.Config.ARGB_8888);
1703 Canvas canvas = new Canvas(output);
1704 canvas.drawBitmap(input, null, target, createAntiAliasingPaint());
1705 if (!input.isRecycled()) {
1706 input.recycle();
1707 }
1708 return output;
1709 }
1710
1711 private int calcSampleSize(Uri image, int size)
1712 throws FileNotFoundException, SecurityException {
1713 final BitmapFactory.Options options = new BitmapFactory.Options();
1714 options.inJustDecodeBounds = true;
1715 final InputStream inputStream =
1716 mXmppConnectionService.getContentResolver().openInputStream(image);
1717 BitmapFactory.decodeStream(inputStream, null, options);
1718 close(inputStream);
1719 return calcSampleSize(options, size);
1720 }
1721
1722 public void updateFileParams(Message message) {
1723 updateFileParams(message, null);
1724 }
1725
1726 public void updateFileParams(final Message message, final String url) {
1727 updateFileParams(message, url, true);
1728 }
1729
1730 public void updateFileParams(final Message message, final String url, boolean updateCids) {
1731 final boolean encrypted =
1732 message.getEncryption() == Message.ENCRYPTION_PGP
1733 || message.getEncryption() == Message.ENCRYPTION_DECRYPTED;
1734 final DownloadableFile file = getFile(message);
1735 final String mime = file.getMimeType();
1736 final boolean privateMessage = message.isPrivateMessage();
1737 final boolean image =
1738 message.getType() == Message.TYPE_IMAGE
1739 || (mime != null && mime.startsWith("image/"));
1740 Message.FileParams fileParams = message.getFileParams();
1741 if (fileParams == null) fileParams = new Message.FileParams();
1742 if (url != null) {
1743 fileParams.url = url;
1744 }
1745 if (encrypted && !file.exists()) {
1746 Log.d(Config.LOGTAG, "skipping updateFileParams because file is encrypted");
1747 final DownloadableFile encryptedFile = getFile(message, false);
1748 fileParams.size = encryptedFile.getSize();
1749 } else {
1750 Log.d(Config.LOGTAG, "running updateFileParams");
1751 final boolean ambiguous = MimeUtils.AMBIGUOUS_CONTAINER_FORMATS.contains(mime);
1752 final boolean video = mime != null && mime.startsWith("video/");
1753 final boolean audio = mime != null && mime.startsWith("audio/");
1754 final boolean pdf = "application/pdf".equals(mime);
1755 fileParams.size = file.getSize();
1756 if (ambiguous) {
1757 try {
1758 final Dimensions dimensions = getVideoDimensions(file);
1759 if (dimensions.valid()) {
1760 Log.d(Config.LOGTAG, "ambiguous file " + mime + " is video");
1761 fileParams.width = dimensions.width;
1762 fileParams.height = dimensions.height;
1763 } else {
1764 Log.d(Config.LOGTAG, "ambiguous file " + mime + " is audio");
1765 fileParams.runtime = getMediaRuntime(file);
1766 }
1767 } catch (final NotAVideoFile e) {
1768 Log.d(Config.LOGTAG, "ambiguous file " + mime + " is audio");
1769 fileParams.runtime = getMediaRuntime(file);
1770 }
1771 } else if (image || video || pdf) {
1772 try {
1773 final Dimensions dimensions;
1774 if (video) {
1775 dimensions = getVideoDimensions(file);
1776 } else if (pdf) {
1777 dimensions = getPdfDocumentDimensions(file);
1778 } else {
1779 dimensions = getImageDimensions(file);
1780 }
1781 if (dimensions.valid()) {
1782 fileParams.width = dimensions.width;
1783 fileParams.height = dimensions.height;
1784 }
1785 } catch (NotAVideoFile notAVideoFile) {
1786 Log.d(
1787 Config.LOGTAG,
1788 "file with mime type " + file.getMimeType() + " was not a video file");
1789 // fall threw
1790 }
1791 } else if (audio) {
1792 fileParams.runtime = getMediaRuntime(file);
1793 }
1794 }
1795 message.setFileParams(fileParams);
1796 message.setDeleted(false);
1797 message.setType(
1798 privateMessage
1799 ? Message.TYPE_PRIVATE_FILE
1800 : (image ? Message.TYPE_IMAGE : Message.TYPE_FILE));
1801
1802 if (updateCids) {
1803 try {
1804 Cid[] cids = calculateCids(new FileInputStream(getFile(message)));
1805 for (int i = 0; i < cids.length; i++) {
1806 mXmppConnectionService.saveCid(cids[i], file);
1807 }
1808 } catch (final IOException | XmppConnectionService.BlockedMediaException e) { }
1809 }
1810 }
1811
1812 private int getMediaRuntime(final File file) {
1813 try {
1814 final MediaMetadataRetriever mediaMetadataRetriever = new MediaMetadataRetriever();
1815 mediaMetadataRetriever.setDataSource(file.toString());
1816 final String value =
1817 mediaMetadataRetriever.extractMetadata(
1818 MediaMetadataRetriever.METADATA_KEY_DURATION);
1819 if (Strings.isNullOrEmpty(value)) {
1820 return 0;
1821 }
1822 return Integer.parseInt(value);
1823 } catch (final Exception e) {
1824 return 0;
1825 }
1826 }
1827
1828 private Dimensions getImageDimensions(File file) {
1829 final BitmapFactory.Options options = new BitmapFactory.Options();
1830 options.inJustDecodeBounds = true;
1831 BitmapFactory.decodeFile(file.getAbsolutePath(), options);
1832 final int rotation = getRotation(file);
1833 final boolean rotated = rotation == 90 || rotation == 270;
1834 final int imageHeight = rotated ? options.outWidth : options.outHeight;
1835 final int imageWidth = rotated ? options.outHeight : options.outWidth;
1836 return new Dimensions(imageHeight, imageWidth);
1837 }
1838
1839 private Dimensions getVideoDimensions(File file) throws NotAVideoFile {
1840 MediaMetadataRetriever metadataRetriever = new MediaMetadataRetriever();
1841 try {
1842 metadataRetriever.setDataSource(file.getAbsolutePath());
1843 } catch (RuntimeException e) {
1844 throw new NotAVideoFile(e);
1845 }
1846 return getVideoDimensions(metadataRetriever);
1847 }
1848
1849 private Dimensions getPdfDocumentDimensions(final File file) {
1850 final ParcelFileDescriptor fileDescriptor;
1851 try {
1852 fileDescriptor = ParcelFileDescriptor.open(file, ParcelFileDescriptor.MODE_READ_ONLY);
1853 if (fileDescriptor == null) {
1854 return new Dimensions(0, 0);
1855 }
1856 } catch (final FileNotFoundException e) {
1857 return new Dimensions(0, 0);
1858 }
1859 try {
1860 final PdfRenderer pdfRenderer = new PdfRenderer(fileDescriptor);
1861 final PdfRenderer.Page page = pdfRenderer.openPage(0);
1862 final int height = page.getHeight();
1863 final int width = page.getWidth();
1864 page.close();
1865 pdfRenderer.close();
1866 return scalePdfDimensions(new Dimensions(height, width));
1867 } catch (final IOException | SecurityException e) {
1868 Log.d(Config.LOGTAG, "unable to get dimensions for pdf document", e);
1869 return new Dimensions(0, 0);
1870 }
1871 }
1872
1873 private Dimensions scalePdfDimensions(Dimensions in) {
1874 final DisplayMetrics displayMetrics =
1875 mXmppConnectionService.getResources().getDisplayMetrics();
1876 final int target = (int) (displayMetrics.density * 288);
1877 return scalePdfDimensions(in, target, true);
1878 }
1879
1880 private static Dimensions scalePdfDimensions(
1881 final Dimensions in, final int target, final boolean fit) {
1882 final int w, h;
1883 if (fit == (in.width <= in.height)) {
1884 w = Math.max((int) (in.width / ((double) in.height / target)), 1);
1885 h = target;
1886 } else {
1887 w = target;
1888 h = Math.max((int) (in.height / ((double) in.width / target)), 1);
1889 }
1890 return new Dimensions(h, w);
1891 }
1892
1893 public Bitmap getAvatar(String avatar, int size) {
1894 if (avatar == null) {
1895 return null;
1896 }
1897 Bitmap bm = cropCenter(getAvatarUri(avatar), size, size);
1898 return bm;
1899 }
1900
1901 private static class Dimensions {
1902 public final int width;
1903 public final int height;
1904
1905 Dimensions(int height, int width) {
1906 this.width = width;
1907 this.height = height;
1908 }
1909
1910 public int getMin() {
1911 return Math.min(width, height);
1912 }
1913
1914 public boolean valid() {
1915 return width > 0 && height > 0;
1916 }
1917 }
1918
1919 private static class NotAVideoFile extends Exception {
1920 public NotAVideoFile(Throwable t) {
1921 super(t);
1922 }
1923
1924 public NotAVideoFile() {
1925 super();
1926 }
1927 }
1928
1929 public static class ImageCompressionException extends Exception {
1930
1931 ImageCompressionException(String message) {
1932 super(message);
1933 }
1934 }
1935
1936 public static class FileCopyException extends Exception {
1937 private final int resId;
1938
1939 private FileCopyException(@StringRes int resId) {
1940 this.resId = resId;
1941 }
1942
1943 public @StringRes int getResId() {
1944 return resId;
1945 }
1946 }
1947}