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