1package eu.siacs.conversations.persistance;
2
3import android.annotation.TargetApi;
4import android.content.ContentResolver;
5import android.content.Context;
6import android.content.Intent;
7import android.database.Cursor;
8import android.graphics.Bitmap;
9import android.graphics.BitmapFactory;
10import android.graphics.Canvas;
11import android.graphics.Color;
12import android.graphics.Matrix;
13import android.graphics.Paint;
14import android.graphics.RectF;
15import android.media.MediaMetadataRetriever;
16import android.net.Uri;
17import android.os.Build;
18import android.os.Environment;
19import android.os.ParcelFileDescriptor;
20import android.provider.MediaStore;
21import android.provider.OpenableColumns;
22import android.support.v4.content.FileProvider;
23import android.system.Os;
24import android.system.StructStat;
25import android.util.Base64;
26import android.util.Base64OutputStream;
27import android.util.Log;
28import android.util.LruCache;
29
30import java.io.ByteArrayOutputStream;
31import java.io.Closeable;
32import java.io.File;
33import java.io.FileDescriptor;
34import java.io.FileInputStream;
35import java.io.FileNotFoundException;
36import java.io.FileOutputStream;
37import java.io.IOException;
38import java.io.InputStream;
39import java.io.OutputStream;
40import java.net.Socket;
41import java.net.URL;
42import java.security.DigestOutputStream;
43import java.security.MessageDigest;
44import java.security.NoSuchAlgorithmException;
45import java.text.SimpleDateFormat;
46import java.util.Date;
47import java.util.List;
48import java.util.Locale;
49import java.util.UUID;
50
51import eu.siacs.conversations.Config;
52import eu.siacs.conversations.R;
53import eu.siacs.conversations.entities.DownloadableFile;
54import eu.siacs.conversations.entities.Message;
55import eu.siacs.conversations.services.XmppConnectionService;
56import eu.siacs.conversations.ui.RecordingActivity;
57import eu.siacs.conversations.ui.util.Attachment;
58import eu.siacs.conversations.utils.CryptoHelper;
59import eu.siacs.conversations.utils.ExifHelper;
60import eu.siacs.conversations.utils.FileUtils;
61import eu.siacs.conversations.utils.FileWriterException;
62import eu.siacs.conversations.utils.MimeUtils;
63import eu.siacs.conversations.xmpp.pep.Avatar;
64
65public class FileBackend {
66
67 private static final Object THUMBNAIL_LOCK = new Object();
68
69 private static final SimpleDateFormat IMAGE_DATE_FORMAT = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.US);
70
71 private static final String FILE_PROVIDER = ".files";
72
73 private XmppConnectionService mXmppConnectionService;
74
75 private static final float IGNORE_PADDING = 0.15f;
76
77 public FileBackend(XmppConnectionService service) {
78 this.mXmppConnectionService = service;
79 }
80
81 private static boolean isInDirectoryThatShouldNotBeScanned(Context context, File file) {
82 return isInDirectoryThatShouldNotBeScanned(context, file.getAbsolutePath());
83 }
84
85 public static boolean isInDirectoryThatShouldNotBeScanned(Context context, String path) {
86 for (String type : new String[]{RecordingActivity.STORAGE_DIRECTORY_TYPE_NAME, "Files"}) {
87 if (path.startsWith(getConversationsDirectory(context, type))) {
88 return true;
89 }
90 }
91 return false;
92 }
93
94 public static long getFileSize(Context context, Uri uri) {
95 try {
96 final Cursor cursor = context.getContentResolver().query(uri, null, null, null, null);
97 if (cursor != null && cursor.moveToFirst()) {
98 long size = cursor.getLong(cursor.getColumnIndex(OpenableColumns.SIZE));
99 cursor.close();
100 return size;
101 } else {
102 return -1;
103 }
104 } catch (Exception e) {
105 return -1;
106 }
107 }
108
109 public static boolean allFilesUnderSize(Context context, List<Attachment> attachments, long max) {
110 if (max <= 0) {
111 Log.d(Config.LOGTAG, "server did not report max file size for http upload");
112 return true; //exception to be compatible with HTTP Upload < v0.2
113 }
114 for (Attachment attachment : attachments) {
115 if (attachment.getType() != Attachment.Type.FILE) {
116 continue;
117 }
118 String mime = attachment.getMime();
119 if (mime != null && mime.startsWith("video/")) {
120 try {
121 Dimensions dimensions = FileBackend.getVideoDimensions(context, attachment.getUri());
122 if (dimensions.getMin() > 720) {
123 Log.d(Config.LOGTAG, "do not consider video file with min width larger than 720 for size check");
124 continue;
125 }
126 } catch (NotAVideoFile notAVideoFile) {
127 //ignore and fall through
128 }
129 }
130 if (FileBackend.getFileSize(context, attachment.getUri()) > max) {
131 Log.d(Config.LOGTAG, "not all files are under " + max + " bytes. suggesting falling back to jingle");
132 return false;
133 }
134 }
135 return true;
136 }
137
138 public static String getConversationsDirectory(Context context, final String type) {
139 if (Config.ONLY_INTERNAL_STORAGE) {
140 return context.getFilesDir().getAbsolutePath() + "/" + type + "/";
141 } else {
142 return getAppMediaDirectory(context) + context.getString(R.string.app_name) + " " + type + "/";
143 }
144 }
145
146 public static String getAppMediaDirectory(Context context) {
147 return Environment.getExternalStorageDirectory().getAbsolutePath() + "/" + context.getString(R.string.app_name) + "/Media/";
148 }
149
150 public static String getConversationsLogsDirectory() {
151 return Environment.getExternalStorageDirectory().getAbsolutePath() + "/Conversations/";
152 }
153
154 private static Bitmap rotate(Bitmap bitmap, int degree) {
155 if (degree == 0) {
156 return bitmap;
157 }
158 int w = bitmap.getWidth();
159 int h = bitmap.getHeight();
160 Matrix mtx = new Matrix();
161 mtx.postRotate(degree);
162 Bitmap result = Bitmap.createBitmap(bitmap, 0, 0, w, h, mtx, true);
163 if (bitmap != null && !bitmap.isRecycled()) {
164 bitmap.recycle();
165 }
166 return result;
167 }
168
169 public static boolean isPathBlacklisted(String path) {
170 final String androidDataPath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/Android/data/";
171 return path.startsWith(androidDataPath);
172 }
173
174 private static Paint createAntiAliasingPaint() {
175 Paint paint = new Paint();
176 paint.setAntiAlias(true);
177 paint.setFilterBitmap(true);
178 paint.setDither(true);
179 return paint;
180 }
181
182 private static String getTakePhotoPath() {
183 return Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM) + "/Camera/";
184 }
185
186 public static Uri getUriForFile(Context context, File file) {
187 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N || Config.ONLY_INTERNAL_STORAGE) {
188 try {
189 return FileProvider.getUriForFile(context, getAuthority(context), file);
190 } catch (IllegalArgumentException e) {
191 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
192 throw new SecurityException(e);
193 } else {
194 return Uri.fromFile(file);
195 }
196 }
197 } else {
198 return Uri.fromFile(file);
199 }
200 }
201
202 public static String getAuthority(Context context) {
203 return context.getPackageName() + FILE_PROVIDER;
204 }
205
206 private static boolean hasAlpha(final Bitmap bitmap) {
207 for (int x = 0; x < bitmap.getWidth(); ++x) {
208 for (int y = 0; y < bitmap.getWidth(); ++y) {
209 if (Color.alpha(bitmap.getPixel(x, y)) < 255) {
210 return true;
211 }
212 }
213 }
214 return false;
215 }
216
217 private static int calcSampleSize(File image, int size) {
218 BitmapFactory.Options options = new BitmapFactory.Options();
219 options.inJustDecodeBounds = true;
220 BitmapFactory.decodeFile(image.getAbsolutePath(), options);
221 return calcSampleSize(options, size);
222 }
223
224
225 private static int calcSampleSize(BitmapFactory.Options options, int size) {
226 int height = options.outHeight;
227 int width = options.outWidth;
228 int inSampleSize = 1;
229
230 if (height > size || width > size) {
231 int halfHeight = height / 2;
232 int halfWidth = width / 2;
233
234 while ((halfHeight / inSampleSize) > size
235 && (halfWidth / inSampleSize) > size) {
236 inSampleSize *= 2;
237 }
238 }
239 return inSampleSize;
240 }
241
242 public Bitmap getPreviewForUri(Attachment attachment, int size, boolean cacheOnly) {
243 final LruCache<String, Bitmap> cache = mXmppConnectionService.getBitmapCache();
244 Bitmap bitmap = cache.get(attachment.getUuid().toString());
245 if (bitmap != null || cacheOnly) {
246 return bitmap;
247 }
248 Log.d(Config.LOGTAG,"attachment mime="+attachment.getMime());
249 if (attachment.getMime() != null && attachment.getMime().startsWith("video/")) {
250 bitmap = cropCenterSquareVideo(attachment.getUri(), size);
251 drawOverlay(bitmap, paintOverlayBlack(bitmap) ? R.drawable.play_video_black : R.drawable.play_video_white, 0.75f);
252 } else {
253 bitmap = cropCenterSquare(attachment.getUri(), size);
254 if ("image/gif".equals(attachment.getMime())) {
255 Bitmap withGifOverlay = bitmap.copy(Bitmap.Config.ARGB_8888, true);
256 drawOverlay(withGifOverlay, paintOverlayBlack(withGifOverlay) ? R.drawable.play_gif_black : R.drawable.play_gif_white, 1.0f);
257 bitmap.recycle();
258 bitmap = withGifOverlay;
259 }
260 }
261 cache.put(attachment.getUuid().toString(), bitmap);
262 return bitmap;
263 }
264
265 private static Dimensions getVideoDimensions(Context context, Uri uri) throws NotAVideoFile {
266 MediaMetadataRetriever mediaMetadataRetriever = new MediaMetadataRetriever();
267 try {
268 mediaMetadataRetriever.setDataSource(context, uri);
269 } catch (RuntimeException e) {
270 throw new NotAVideoFile(e);
271 }
272 return getVideoDimensions(mediaMetadataRetriever);
273 }
274
275 private static Dimensions getVideoDimensionsOfFrame(MediaMetadataRetriever mediaMetadataRetriever) {
276 Bitmap bitmap = null;
277 try {
278 bitmap = mediaMetadataRetriever.getFrameAtTime();
279 return new Dimensions(bitmap.getHeight(), bitmap.getWidth());
280 } catch (Exception e) {
281 return null;
282 } finally {
283 if (bitmap != null) {
284 bitmap.recycle();
285 ;
286 }
287 }
288 }
289
290 private static Dimensions getVideoDimensions(MediaMetadataRetriever metadataRetriever) throws NotAVideoFile {
291 String hasVideo = metadataRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_HAS_VIDEO);
292 if (hasVideo == null) {
293 throw new NotAVideoFile();
294 }
295 Dimensions dimensions = getVideoDimensionsOfFrame(metadataRetriever);
296 if (dimensions != null) {
297 return dimensions;
298 }
299 int rotation = extractRotationFromMediaRetriever(metadataRetriever);
300 boolean rotated = rotation == 90 || rotation == 270;
301 int height;
302 try {
303 String h = metadataRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_HEIGHT);
304 height = Integer.parseInt(h);
305 } catch (Exception e) {
306 height = -1;
307 }
308 int width;
309 try {
310 String w = metadataRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_WIDTH);
311 width = Integer.parseInt(w);
312 } catch (Exception e) {
313 width = -1;
314 }
315 metadataRetriever.release();
316 Log.d(Config.LOGTAG, "extracted video dims " + width + "x" + height);
317 return rotated ? new Dimensions(width, height) : new Dimensions(height, width);
318 }
319
320 private static int extractRotationFromMediaRetriever(MediaMetadataRetriever metadataRetriever) {
321 String r = metadataRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_ROTATION);
322 try {
323 return Integer.parseInt(r);
324 } catch (Exception e) {
325 return 0;
326 }
327 }
328
329 public static void close(Closeable stream) {
330 if (stream != null) {
331 try {
332 stream.close();
333 } catch (IOException e) {
334 }
335 }
336 }
337
338 public static void close(Socket socket) {
339 if (socket != null) {
340 try {
341 socket.close();
342 } catch (IOException e) {
343 }
344 }
345 }
346
347 public static boolean weOwnFile(Context context, Uri uri) {
348 if (uri == null || !ContentResolver.SCHEME_FILE.equals(uri.getScheme())) {
349 return false;
350 } else if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
351 return fileIsInFilesDir(context, uri);
352 } else {
353 return weOwnFileLollipop(uri);
354 }
355 }
356
357 /**
358 * This is more than hacky but probably way better than doing nothing
359 * Further 'optimizations' might contain to get the parents of CacheDir and NoBackupDir
360 * and check against those as well
361 */
362 private static boolean fileIsInFilesDir(Context context, Uri uri) {
363 try {
364 final String haystack = context.getFilesDir().getParentFile().getCanonicalPath();
365 final String needle = new File(uri.getPath()).getCanonicalPath();
366 return needle.startsWith(haystack);
367 } catch (IOException e) {
368 return false;
369 }
370 }
371
372 @TargetApi(Build.VERSION_CODES.LOLLIPOP)
373 private static boolean weOwnFileLollipop(Uri uri) {
374 try {
375 File file = new File(uri.getPath());
376 FileDescriptor fd = ParcelFileDescriptor.open(file, ParcelFileDescriptor.MODE_READ_ONLY).getFileDescriptor();
377 StructStat st = Os.fstat(fd);
378 return st.st_uid == android.os.Process.myUid();
379 } catch (FileNotFoundException e) {
380 return false;
381 } catch (Exception e) {
382 return true;
383 }
384 }
385
386 private void createNoMedia(File diretory) {
387 final File noMedia = new File(diretory, ".nomedia");
388 if (!noMedia.exists()) {
389 try {
390 if (!noMedia.createNewFile()) {
391 Log.d(Config.LOGTAG, "created nomedia file " + noMedia.getAbsolutePath());
392 }
393 } catch (Exception e) {
394 Log.d(Config.LOGTAG, "could not create nomedia file");
395 }
396 }
397 }
398
399 public void updateMediaScanner(File file) {
400 if (!isInDirectoryThatShouldNotBeScanned(mXmppConnectionService, file)) {
401 Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
402 intent.setData(Uri.fromFile(file));
403 mXmppConnectionService.sendBroadcast(intent);
404 } else if (file.getAbsolutePath().startsWith(getAppMediaDirectory(mXmppConnectionService))) {
405 createNoMedia(file.getParentFile());
406 }
407 }
408
409 public boolean deleteFile(Message message) {
410 File file = getFile(message);
411 if (file.delete()) {
412 updateMediaScanner(file);
413 return true;
414 } else {
415 return false;
416 }
417 }
418
419 public DownloadableFile getFile(Message message) {
420 return getFile(message, true);
421 }
422
423 public DownloadableFile getFileForPath(String path, String mime) {
424 final DownloadableFile file;
425 if (path.startsWith("/")) {
426 file = new DownloadableFile(path);
427 } else {
428 if (mime != null && mime.startsWith("image/")) {
429 file = new DownloadableFile(getConversationsDirectory("Images") + path);
430 } else if (mime != null && mime.startsWith("video/")) {
431 file = new DownloadableFile(getConversationsDirectory("Videos") + path);
432 } else {
433 file = new DownloadableFile(getConversationsDirectory("Files") + path);
434 }
435 }
436 return file;
437 }
438
439 public DownloadableFile getFile(Message message, boolean decrypted) {
440 final boolean encrypted = !decrypted
441 && (message.getEncryption() == Message.ENCRYPTION_PGP
442 || message.getEncryption() == Message.ENCRYPTION_DECRYPTED);
443 String path = message.getRelativeFilePath();
444 if (path == null) {
445 path = message.getUuid();
446 }
447 final DownloadableFile file = getFileForPath(path, message.getMimeType());
448 if (encrypted) {
449 return new DownloadableFile(getConversationsDirectory("Files") + file.getName() + ".pgp");
450 } else {
451 return file;
452 }
453 }
454
455 public String getConversationsDirectory(final String type) {
456 return getConversationsDirectory(mXmppConnectionService, type);
457 }
458
459 private Bitmap resize(final Bitmap originalBitmap, int size) throws IOException {
460 int w = originalBitmap.getWidth();
461 int h = originalBitmap.getHeight();
462 if (w <= 0 || h <= 0) {
463 throw new IOException("Decoded bitmap reported bounds smaller 0");
464 } else if (Math.max(w, h) > size) {
465 int scalledW;
466 int scalledH;
467 if (w <= h) {
468 scalledW = Math.max((int) (w / ((double) h / size)), 1);
469 scalledH = size;
470 } else {
471 scalledW = size;
472 scalledH = Math.max((int) (h / ((double) w / size)), 1);
473 }
474 final Bitmap result = Bitmap.createScaledBitmap(originalBitmap, scalledW, scalledH, true);
475 if (!originalBitmap.isRecycled()) {
476 originalBitmap.recycle();
477 }
478 return result;
479 } else {
480 return originalBitmap;
481 }
482 }
483
484 public boolean useImageAsIs(Uri uri) {
485 String path = getOriginalPath(uri);
486 if (path == null || isPathBlacklisted(path)) {
487 return false;
488 }
489 File file = new File(path);
490 long size = file.length();
491 if (size == 0 || size >= mXmppConnectionService.getResources().getInteger(R.integer.auto_accept_filesize)) {
492 return false;
493 }
494 BitmapFactory.Options options = new BitmapFactory.Options();
495 options.inJustDecodeBounds = true;
496 try {
497 BitmapFactory.decodeStream(mXmppConnectionService.getContentResolver().openInputStream(uri), null, options);
498 if (options.outMimeType == null || options.outHeight <= 0 || options.outWidth <= 0) {
499 return false;
500 }
501 return (options.outWidth <= Config.IMAGE_SIZE && options.outHeight <= Config.IMAGE_SIZE && options.outMimeType.contains(Config.IMAGE_FORMAT.name().toLowerCase()));
502 } catch (FileNotFoundException e) {
503 return false;
504 }
505 }
506
507 public String getOriginalPath(Uri uri) {
508 return FileUtils.getPath(mXmppConnectionService, uri);
509 }
510
511 private void copyFileToPrivateStorage(File file, Uri uri) throws FileCopyException {
512 Log.d(Config.LOGTAG, "copy file (" + uri.toString() + ") to private storage " + file.getAbsolutePath());
513 file.getParentFile().mkdirs();
514 OutputStream os = null;
515 InputStream is = null;
516 try {
517 file.createNewFile();
518 os = new FileOutputStream(file);
519 is = mXmppConnectionService.getContentResolver().openInputStream(uri);
520 byte[] buffer = new byte[1024];
521 int length;
522 while ((length = is.read(buffer)) > 0) {
523 try {
524 os.write(buffer, 0, length);
525 } catch (IOException e) {
526 throw new FileWriterException();
527 }
528 }
529 try {
530 os.flush();
531 } catch (IOException e) {
532 throw new FileWriterException();
533 }
534 } catch (FileNotFoundException e) {
535 throw new FileCopyException(R.string.error_file_not_found);
536 } catch (FileWriterException e) {
537 throw new FileCopyException(R.string.error_unable_to_create_temporary_file);
538 } catch (IOException e) {
539 e.printStackTrace();
540 throw new FileCopyException(R.string.error_io_exception);
541 } finally {
542 close(os);
543 close(is);
544 }
545 }
546
547 public void copyFileToPrivateStorage(Message message, Uri uri, String type) throws FileCopyException {
548 String mime = type != null ? type : MimeUtils.guessMimeTypeFromUri(mXmppConnectionService, uri);
549 Log.d(Config.LOGTAG, "copy " + uri.toString() + " to private storage (mime=" + mime + ")");
550 String extension = MimeUtils.guessExtensionFromMimeType(mime);
551 if (extension == null) {
552 Log.d(Config.LOGTAG, "extension from mime type was null");
553 extension = getExtensionFromUri(uri);
554 }
555 if ("ogg".equals(extension) && type != null && type.startsWith("audio/")) {
556 extension = "oga";
557 }
558 message.setRelativeFilePath(message.getUuid() + "." + extension);
559 copyFileToPrivateStorage(mXmppConnectionService.getFileBackend().getFile(message), uri);
560 }
561
562 private String getExtensionFromUri(Uri uri) {
563 String[] projection = {MediaStore.MediaColumns.DATA};
564 String filename = null;
565 Cursor cursor;
566 try {
567 cursor = mXmppConnectionService.getContentResolver().query(uri, projection, null, null, null);
568 } catch (IllegalArgumentException e) {
569 cursor = null;
570 }
571 if (cursor != null) {
572 try {
573 if (cursor.moveToFirst()) {
574 filename = cursor.getString(0);
575 }
576 } catch (Exception e) {
577 filename = null;
578 } finally {
579 cursor.close();
580 }
581 }
582 if (filename == null) {
583 final List<String> segments = uri.getPathSegments();
584 if (segments.size() > 0) {
585 filename = segments.get(segments.size() - 1);
586 }
587 }
588 int pos = filename == null ? -1 : filename.lastIndexOf('.');
589 return pos > 0 ? filename.substring(pos + 1) : null;
590 }
591
592 private void copyImageToPrivateStorage(File file, Uri image, int sampleSize) throws FileCopyException {
593 file.getParentFile().mkdirs();
594 InputStream is = null;
595 OutputStream os = null;
596 try {
597 if (!file.exists() && !file.createNewFile()) {
598 throw new FileCopyException(R.string.error_unable_to_create_temporary_file);
599 }
600 is = mXmppConnectionService.getContentResolver().openInputStream(image);
601 if (is == null) {
602 throw new FileCopyException(R.string.error_not_an_image_file);
603 }
604 Bitmap originalBitmap;
605 BitmapFactory.Options options = new BitmapFactory.Options();
606 int inSampleSize = (int) Math.pow(2, sampleSize);
607 Log.d(Config.LOGTAG, "reading bitmap with sample size " + inSampleSize);
608 options.inSampleSize = inSampleSize;
609 originalBitmap = BitmapFactory.decodeStream(is, null, options);
610 is.close();
611 if (originalBitmap == null) {
612 throw new FileCopyException(R.string.error_not_an_image_file);
613 }
614 Bitmap scaledBitmap = resize(originalBitmap, Config.IMAGE_SIZE);
615 int rotation = getRotation(image);
616 scaledBitmap = rotate(scaledBitmap, rotation);
617 boolean targetSizeReached = false;
618 int quality = Config.IMAGE_QUALITY;
619 final int imageMaxSize = mXmppConnectionService.getResources().getInteger(R.integer.auto_accept_filesize);
620 while (!targetSizeReached) {
621 os = new FileOutputStream(file);
622 boolean success = scaledBitmap.compress(Config.IMAGE_FORMAT, quality, os);
623 if (!success) {
624 throw new FileCopyException(R.string.error_compressing_image);
625 }
626 os.flush();
627 targetSizeReached = file.length() <= imageMaxSize || quality <= 50;
628 quality -= 5;
629 }
630 scaledBitmap.recycle();
631 } catch (FileNotFoundException e) {
632 throw new FileCopyException(R.string.error_file_not_found);
633 } catch (IOException e) {
634 e.printStackTrace();
635 throw new FileCopyException(R.string.error_io_exception);
636 } catch (SecurityException e) {
637 throw new FileCopyException(R.string.error_security_exception_during_image_copy);
638 } catch (OutOfMemoryError e) {
639 ++sampleSize;
640 if (sampleSize <= 3) {
641 copyImageToPrivateStorage(file, image, sampleSize);
642 } else {
643 throw new FileCopyException(R.string.error_out_of_memory);
644 }
645 } finally {
646 close(os);
647 close(is);
648 }
649 }
650
651 public void copyImageToPrivateStorage(File file, Uri image) throws FileCopyException {
652 Log.d(Config.LOGTAG, "copy image (" + image.toString() + ") to private storage " + file.getAbsolutePath());
653 copyImageToPrivateStorage(file, image, 0);
654 }
655
656 public void copyImageToPrivateStorage(Message message, Uri image) throws FileCopyException {
657 switch (Config.IMAGE_FORMAT) {
658 case JPEG:
659 message.setRelativeFilePath(message.getUuid() + ".jpg");
660 break;
661 case PNG:
662 message.setRelativeFilePath(message.getUuid() + ".png");
663 break;
664 case WEBP:
665 message.setRelativeFilePath(message.getUuid() + ".webp");
666 break;
667 }
668 copyImageToPrivateStorage(getFile(message), image);
669 updateFileParams(message);
670 }
671
672 private int getRotation(File file) {
673 return getRotation(Uri.parse("file://" + file.getAbsolutePath()));
674 }
675
676 private int getRotation(Uri image) {
677 InputStream is = null;
678 try {
679 is = mXmppConnectionService.getContentResolver().openInputStream(image);
680 return ExifHelper.getOrientation(is);
681 } catch (FileNotFoundException e) {
682 return 0;
683 } finally {
684 close(is);
685 }
686 }
687
688 public Bitmap getThumbnail(Message message, int size, boolean cacheOnly) throws IOException {
689 final String uuid = message.getUuid();
690 final LruCache<String, Bitmap> cache = mXmppConnectionService.getBitmapCache();
691 Bitmap thumbnail = cache.get(uuid);
692 if ((thumbnail == null) && (!cacheOnly)) {
693 synchronized (THUMBNAIL_LOCK) {
694 thumbnail = cache.get(uuid);
695 if (thumbnail != null) {
696 return thumbnail;
697 }
698 DownloadableFile file = getFile(message);
699 final String mime = file.getMimeType();
700 if (mime.startsWith("video/")) {
701 thumbnail = getVideoPreview(file, size);
702 } else {
703 Bitmap fullsize = getFullsizeImagePreview(file, size);
704 if (fullsize == null) {
705 throw new FileNotFoundException();
706 }
707 thumbnail = resize(fullsize, size);
708 thumbnail = rotate(thumbnail, getRotation(file));
709 if (mime.equals("image/gif")) {
710 Bitmap withGifOverlay = thumbnail.copy(Bitmap.Config.ARGB_8888, true);
711 drawOverlay(withGifOverlay, paintOverlayBlack(withGifOverlay) ? R.drawable.play_gif_black : R.drawable.play_gif_white, 1.0f);
712 thumbnail.recycle();
713 thumbnail = withGifOverlay;
714 }
715 }
716 this.mXmppConnectionService.getBitmapCache().put(uuid, thumbnail);
717 }
718 }
719 return thumbnail;
720 }
721
722 private Bitmap getFullsizeImagePreview(File file, int size) {
723 BitmapFactory.Options options = new BitmapFactory.Options();
724 options.inSampleSize = calcSampleSize(file, size);
725 try {
726 return BitmapFactory.decodeFile(file.getAbsolutePath(), options);
727 } catch (OutOfMemoryError e) {
728 options.inSampleSize *= 2;
729 return BitmapFactory.decodeFile(file.getAbsolutePath(), options);
730 }
731 }
732
733 private void drawOverlay(Bitmap bitmap, int resource, float factor) {
734 Bitmap overlay = BitmapFactory.decodeResource(mXmppConnectionService.getResources(), resource);
735 Canvas canvas = new Canvas(bitmap);
736 float targetSize = Math.min(canvas.getWidth(), canvas.getHeight()) * factor;
737 Log.d(Config.LOGTAG, "target size overlay: " + targetSize + " overlay bitmap size was " + overlay.getHeight());
738 float left = (canvas.getWidth() - targetSize) / 2.0f;
739 float top = (canvas.getHeight() - targetSize) / 2.0f;
740 RectF dst = new RectF(left, top, left + targetSize - 1, top + targetSize - 1);
741 canvas.drawBitmap(overlay, null, dst, createAntiAliasingPaint());
742 }
743
744 /**
745 * https://stackoverflow.com/a/3943023/210897
746 */
747 private boolean paintOverlayBlack(final Bitmap bitmap) {
748 final int h = bitmap.getHeight();
749 final int w = bitmap.getWidth();
750 int record = 0;
751 for (int y = Math.round(h * IGNORE_PADDING); y < h - Math.round(h * IGNORE_PADDING); ++y) {
752 for (int x = Math.round(w * IGNORE_PADDING); x < w - Math.round(w * IGNORE_PADDING); ++x) {
753 int pixel = bitmap.getPixel(x, y);
754 if ((Color.red(pixel) * 0.299 + Color.green(pixel) * 0.587 + Color.blue(pixel) * 0.114) > 186) {
755 --record;
756 } else {
757 ++record;
758 }
759 }
760 }
761 return record < 0;
762 }
763
764 private Bitmap cropCenterSquareVideo(Uri uri, int size) {
765 MediaMetadataRetriever metadataRetriever = new MediaMetadataRetriever();
766 Bitmap frame;
767 try {
768 metadataRetriever.setDataSource(mXmppConnectionService, uri);
769 frame = metadataRetriever.getFrameAtTime(0);
770 metadataRetriever.release();
771 return cropCenterSquare(frame, size);
772 } catch (Exception e) {
773 frame = Bitmap.createBitmap(size, size, Bitmap.Config.ARGB_8888);
774 frame.eraseColor(0xff000000);
775 return frame;
776 }
777 }
778
779 private Bitmap getVideoPreview(File file, int size) {
780 MediaMetadataRetriever metadataRetriever = new MediaMetadataRetriever();
781 Bitmap frame;
782 try {
783 metadataRetriever.setDataSource(file.getAbsolutePath());
784 frame = metadataRetriever.getFrameAtTime(0);
785 metadataRetriever.release();
786 frame = resize(frame, size);
787 } catch (IOException | RuntimeException e) {
788 frame = Bitmap.createBitmap(size, size, Bitmap.Config.ARGB_8888);
789 frame.eraseColor(0xff000000);
790 }
791 drawOverlay(frame, paintOverlayBlack(frame) ? R.drawable.play_video_black : R.drawable.play_video_white, 0.75f);
792 return frame;
793 }
794
795 public Uri getTakePhotoUri() {
796 File file;
797 if (Config.ONLY_INTERNAL_STORAGE) {
798 file = new File(mXmppConnectionService.getCacheDir().getAbsolutePath(), "Camera/IMG_" + this.IMAGE_DATE_FORMAT.format(new Date()) + ".jpg");
799 } else {
800 file = new File(getTakePhotoPath() + "IMG_" + this.IMAGE_DATE_FORMAT.format(new Date()) + ".jpg");
801 }
802 file.getParentFile().mkdirs();
803 return getUriForFile(mXmppConnectionService, file);
804 }
805
806 public Avatar getPepAvatar(Uri image, int size, Bitmap.CompressFormat format) {
807
808 final Avatar uncompressAvatar = getUncompressedAvatar(image);
809 if (uncompressAvatar != null && uncompressAvatar.image.length() <= Config.AVATAR_CHAR_LIMIT) {
810 return uncompressAvatar;
811 }
812 if (uncompressAvatar != null) {
813 Log.d(Config.LOGTAG, "uncompressed avatar exceeded char limit by " + (uncompressAvatar.image.length() - Config.AVATAR_CHAR_LIMIT));
814 }
815
816 Bitmap bm = cropCenterSquare(image, size);
817 if (bm == null) {
818 return null;
819 }
820 if (hasAlpha(bm)) {
821 Log.d(Config.LOGTAG, "alpha in avatar detected; uploading as PNG");
822 bm.recycle();
823 bm = cropCenterSquare(image, 96);
824 return getPepAvatar(bm, Bitmap.CompressFormat.PNG, 100);
825 }
826 return getPepAvatar(bm, format, 100);
827 }
828
829 private Avatar getUncompressedAvatar(Uri uri) {
830 Bitmap bitmap = null;
831 try {
832 bitmap = BitmapFactory.decodeStream(mXmppConnectionService.getContentResolver().openInputStream(uri));
833 return getPepAvatar(bitmap, Bitmap.CompressFormat.PNG, 100);
834 } catch (Exception e) {
835 return null;
836 } finally {
837 if (bitmap != null) {
838 bitmap.recycle();
839 }
840 }
841 }
842
843 private Avatar getPepAvatar(Bitmap bitmap, Bitmap.CompressFormat format, int quality) {
844 try {
845 ByteArrayOutputStream mByteArrayOutputStream = new ByteArrayOutputStream();
846 Base64OutputStream mBase64OutputStream = new Base64OutputStream(mByteArrayOutputStream, Base64.DEFAULT);
847 MessageDigest digest = MessageDigest.getInstance("SHA-1");
848 DigestOutputStream mDigestOutputStream = new DigestOutputStream(mBase64OutputStream, digest);
849 if (!bitmap.compress(format, quality, mDigestOutputStream)) {
850 return null;
851 }
852 mDigestOutputStream.flush();
853 mDigestOutputStream.close();
854 long chars = mByteArrayOutputStream.size();
855 if (format != Bitmap.CompressFormat.PNG && quality >= 50 && chars >= Config.AVATAR_CHAR_LIMIT) {
856 int q = quality - 2;
857 Log.d(Config.LOGTAG, "avatar char length was " + chars + " reducing quality to " + q);
858 return getPepAvatar(bitmap, format, q);
859 }
860 Log.d(Config.LOGTAG, "settled on char length " + chars + " with quality=" + quality);
861 final Avatar avatar = new Avatar();
862 avatar.sha1sum = CryptoHelper.bytesToHex(digest.digest());
863 avatar.image = new String(mByteArrayOutputStream.toByteArray());
864 if (format.equals(Bitmap.CompressFormat.WEBP)) {
865 avatar.type = "image/webp";
866 } else if (format.equals(Bitmap.CompressFormat.JPEG)) {
867 avatar.type = "image/jpeg";
868 } else if (format.equals(Bitmap.CompressFormat.PNG)) {
869 avatar.type = "image/png";
870 }
871 avatar.width = bitmap.getWidth();
872 avatar.height = bitmap.getHeight();
873 return avatar;
874 } catch (OutOfMemoryError e) {
875 Log.d(Config.LOGTAG,"unable to convert avatar to base64 due to low memory");
876 return null;
877 } catch (Exception e) {
878 return null;
879 }
880 }
881
882 public Avatar getStoredPepAvatar(String hash) {
883 if (hash == null) {
884 return null;
885 }
886 Avatar avatar = new Avatar();
887 File file = new File(getAvatarPath(hash));
888 FileInputStream is = null;
889 try {
890 avatar.size = file.length();
891 BitmapFactory.Options options = new BitmapFactory.Options();
892 options.inJustDecodeBounds = true;
893 BitmapFactory.decodeFile(file.getAbsolutePath(), options);
894 is = new FileInputStream(file);
895 ByteArrayOutputStream mByteArrayOutputStream = new ByteArrayOutputStream();
896 Base64OutputStream mBase64OutputStream = new Base64OutputStream(mByteArrayOutputStream, Base64.DEFAULT);
897 MessageDigest digest = MessageDigest.getInstance("SHA-1");
898 DigestOutputStream os = new DigestOutputStream(mBase64OutputStream, digest);
899 byte[] buffer = new byte[4096];
900 int length;
901 while ((length = is.read(buffer)) > 0) {
902 os.write(buffer, 0, length);
903 }
904 os.flush();
905 os.close();
906 avatar.sha1sum = CryptoHelper.bytesToHex(digest.digest());
907 avatar.image = new String(mByteArrayOutputStream.toByteArray());
908 avatar.height = options.outHeight;
909 avatar.width = options.outWidth;
910 avatar.type = options.outMimeType;
911 return avatar;
912 } catch (NoSuchAlgorithmException | IOException e) {
913 return null;
914 } finally {
915 close(is);
916 }
917 }
918
919 public boolean isAvatarCached(Avatar avatar) {
920 File file = new File(getAvatarPath(avatar.getFilename()));
921 return file.exists();
922 }
923
924 public boolean save(final Avatar avatar) {
925 File file;
926 if (isAvatarCached(avatar)) {
927 file = new File(getAvatarPath(avatar.getFilename()));
928 avatar.size = file.length();
929 } else {
930 file = new File(mXmppConnectionService.getCacheDir().getAbsolutePath() + "/" + UUID.randomUUID().toString());
931 if (file.getParentFile().mkdirs()) {
932 Log.d(Config.LOGTAG, "created cache directory");
933 }
934 OutputStream os = null;
935 try {
936 if (!file.createNewFile()) {
937 Log.d(Config.LOGTAG, "unable to create temporary file " + file.getAbsolutePath());
938 }
939 os = new FileOutputStream(file);
940 MessageDigest digest = MessageDigest.getInstance("SHA-1");
941 digest.reset();
942 DigestOutputStream mDigestOutputStream = new DigestOutputStream(os, digest);
943 final byte[] bytes = avatar.getImageAsBytes();
944 mDigestOutputStream.write(bytes);
945 mDigestOutputStream.flush();
946 mDigestOutputStream.close();
947 String sha1sum = CryptoHelper.bytesToHex(digest.digest());
948 if (sha1sum.equals(avatar.sha1sum)) {
949 File outputFile = new File(getAvatarPath(avatar.getFilename()));
950 if (outputFile.getParentFile().mkdirs()) {
951 Log.d(Config.LOGTAG, "created avatar directory");
952 }
953 String filename = getAvatarPath(avatar.getFilename());
954 if (!file.renameTo(new File(filename))) {
955 Log.d(Config.LOGTAG, "unable to rename " + file.getAbsolutePath() + " to " + outputFile);
956 return false;
957 }
958 } else {
959 Log.d(Config.LOGTAG, "sha1sum mismatch for " + avatar.owner);
960 if (!file.delete()) {
961 Log.d(Config.LOGTAG, "unable to delete temporary file");
962 }
963 return false;
964 }
965 avatar.size = bytes.length;
966 } catch (IllegalArgumentException | IOException | NoSuchAlgorithmException e) {
967 return false;
968 } finally {
969 close(os);
970 }
971 }
972 return true;
973 }
974
975 private String getAvatarPath(String avatar) {
976 return mXmppConnectionService.getFilesDir().getAbsolutePath() + "/avatars/" + avatar;
977 }
978
979 public Uri getAvatarUri(String avatar) {
980 return Uri.parse("file:" + getAvatarPath(avatar));
981 }
982
983 public Bitmap cropCenterSquare(Uri image, int size) {
984 if (image == null) {
985 return null;
986 }
987 InputStream is = null;
988 try {
989 BitmapFactory.Options options = new BitmapFactory.Options();
990 options.inSampleSize = calcSampleSize(image, size);
991 is = mXmppConnectionService.getContentResolver().openInputStream(image);
992 if (is == null) {
993 return null;
994 }
995 Bitmap input = BitmapFactory.decodeStream(is, null, options);
996 if (input == null) {
997 return null;
998 } else {
999 input = rotate(input, getRotation(image));
1000 return cropCenterSquare(input, size);
1001 }
1002 } catch (FileNotFoundException | SecurityException e) {
1003 return null;
1004 } finally {
1005 close(is);
1006 }
1007 }
1008
1009 public Bitmap cropCenter(Uri image, int newHeight, int newWidth) {
1010 if (image == null) {
1011 return null;
1012 }
1013 InputStream is = null;
1014 try {
1015 BitmapFactory.Options options = new BitmapFactory.Options();
1016 options.inSampleSize = calcSampleSize(image, Math.max(newHeight, newWidth));
1017 is = mXmppConnectionService.getContentResolver().openInputStream(image);
1018 if (is == null) {
1019 return null;
1020 }
1021 Bitmap source = BitmapFactory.decodeStream(is, null, options);
1022 if (source == null) {
1023 return null;
1024 }
1025 int sourceWidth = source.getWidth();
1026 int sourceHeight = source.getHeight();
1027 float xScale = (float) newWidth / sourceWidth;
1028 float yScale = (float) newHeight / sourceHeight;
1029 float scale = Math.max(xScale, yScale);
1030 float scaledWidth = scale * sourceWidth;
1031 float scaledHeight = scale * sourceHeight;
1032 float left = (newWidth - scaledWidth) / 2;
1033 float top = (newHeight - scaledHeight) / 2;
1034
1035 RectF targetRect = new RectF(left, top, left + scaledWidth, top + scaledHeight);
1036 Bitmap dest = Bitmap.createBitmap(newWidth, newHeight, Bitmap.Config.ARGB_8888);
1037 Canvas canvas = new Canvas(dest);
1038 canvas.drawBitmap(source, null, targetRect, createAntiAliasingPaint());
1039 if (source.isRecycled()) {
1040 source.recycle();
1041 }
1042 return dest;
1043 } catch (SecurityException e) {
1044 return null; //android 6.0 with revoked permissions for example
1045 } catch (FileNotFoundException e) {
1046 return null;
1047 } finally {
1048 close(is);
1049 }
1050 }
1051
1052 public Bitmap cropCenterSquare(Bitmap input, int size) {
1053 int w = input.getWidth();
1054 int h = input.getHeight();
1055
1056 float scale = Math.max((float) size / h, (float) size / w);
1057
1058 float outWidth = scale * w;
1059 float outHeight = scale * h;
1060 float left = (size - outWidth) / 2;
1061 float top = (size - outHeight) / 2;
1062 RectF target = new RectF(left, top, left + outWidth, top + outHeight);
1063
1064 Bitmap output = Bitmap.createBitmap(size, size, Bitmap.Config.ARGB_8888);
1065 Canvas canvas = new Canvas(output);
1066 canvas.drawBitmap(input, null, target, createAntiAliasingPaint());
1067 if (!input.isRecycled()) {
1068 input.recycle();
1069 }
1070 return output;
1071 }
1072
1073 private int calcSampleSize(Uri image, int size) throws FileNotFoundException, SecurityException {
1074 BitmapFactory.Options options = new BitmapFactory.Options();
1075 options.inJustDecodeBounds = true;
1076 BitmapFactory.decodeStream(mXmppConnectionService.getContentResolver().openInputStream(image), null, options);
1077 return calcSampleSize(options, size);
1078 }
1079
1080 public void updateFileParams(Message message) {
1081 updateFileParams(message, null);
1082 }
1083
1084 public void updateFileParams(Message message, URL url) {
1085 DownloadableFile file = getFile(message);
1086 final String mime = file.getMimeType();
1087 boolean image = message.getType() == Message.TYPE_IMAGE || (mime != null && mime.startsWith("image/"));
1088 boolean video = mime != null && mime.startsWith("video/");
1089 boolean audio = mime != null && mime.startsWith("audio/");
1090 final StringBuilder body = new StringBuilder();
1091 if (url != null) {
1092 body.append(url.toString());
1093 }
1094 body.append('|').append(file.getSize());
1095 if (image || video) {
1096 try {
1097 Dimensions dimensions = image ? getImageDimensions(file) : getVideoDimensions(file);
1098 if (dimensions.valid()) {
1099 body.append('|').append(dimensions.width).append('|').append(dimensions.height);
1100 }
1101 } catch (NotAVideoFile notAVideoFile) {
1102 Log.d(Config.LOGTAG, "file with mime type " + file.getMimeType() + " was not a video file");
1103 //fall threw
1104 }
1105 } else if (audio) {
1106 body.append("|0|0|").append(getMediaRuntime(file));
1107 }
1108 message.setBody(body.toString());
1109 }
1110
1111 public int getMediaRuntime(Uri uri) {
1112 try {
1113 MediaMetadataRetriever mediaMetadataRetriever = new MediaMetadataRetriever();
1114 mediaMetadataRetriever.setDataSource(mXmppConnectionService, uri);
1115 return Integer.parseInt(mediaMetadataRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION));
1116 } catch (RuntimeException e) {
1117 return 0;
1118 }
1119 }
1120
1121 private int getMediaRuntime(File file) {
1122 try {
1123 MediaMetadataRetriever mediaMetadataRetriever = new MediaMetadataRetriever();
1124 mediaMetadataRetriever.setDataSource(file.toString());
1125 return Integer.parseInt(mediaMetadataRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION));
1126 } catch (RuntimeException e) {
1127 return 0;
1128 }
1129 }
1130
1131 private Dimensions getImageDimensions(File file) {
1132 BitmapFactory.Options options = new BitmapFactory.Options();
1133 options.inJustDecodeBounds = true;
1134 BitmapFactory.decodeFile(file.getAbsolutePath(), options);
1135 int rotation = getRotation(file);
1136 boolean rotated = rotation == 90 || rotation == 270;
1137 int imageHeight = rotated ? options.outWidth : options.outHeight;
1138 int imageWidth = rotated ? options.outHeight : options.outWidth;
1139 return new Dimensions(imageHeight, imageWidth);
1140 }
1141
1142 private Dimensions getVideoDimensions(File file) throws NotAVideoFile {
1143 MediaMetadataRetriever metadataRetriever = new MediaMetadataRetriever();
1144 try {
1145 metadataRetriever.setDataSource(file.getAbsolutePath());
1146 } catch (RuntimeException e) {
1147 throw new NotAVideoFile(e);
1148 }
1149 return getVideoDimensions(metadataRetriever);
1150 }
1151
1152 public Bitmap getAvatar(String avatar, int size) {
1153 if (avatar == null) {
1154 return null;
1155 }
1156 Bitmap bm = cropCenter(getAvatarUri(avatar), size, size);
1157 if (bm == null) {
1158 return null;
1159 }
1160 return bm;
1161 }
1162
1163 public boolean isFileAvailable(Message message) {
1164 return getFile(message).exists();
1165 }
1166
1167 private static class Dimensions {
1168 public final int width;
1169 public final int height;
1170
1171 Dimensions(int height, int width) {
1172 this.width = width;
1173 this.height = height;
1174 }
1175
1176 public int getMin() {
1177 return Math.min(width, height);
1178 }
1179
1180 public boolean valid() {
1181 return width > 0 && height > 0;
1182 }
1183 }
1184
1185 private static class NotAVideoFile extends Exception {
1186 public NotAVideoFile(Throwable t) {
1187 super(t);
1188 }
1189
1190 public NotAVideoFile() {
1191 super();
1192 }
1193 }
1194
1195 public class FileCopyException extends Exception {
1196 private static final long serialVersionUID = -1010013599132881427L;
1197 private int resId;
1198
1199 public FileCopyException(int resId) {
1200 this.resId = resId;
1201 }
1202
1203 public int getResId() {
1204 return resId;
1205 }
1206 }
1207}