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