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