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