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