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