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