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 = mXmppConnectionService.getContentResolver().query(uri, projection, null, null, null);
538 if (cursor != null) {
539 try {
540 if (cursor.moveToFirst()) {
541 filename = cursor.getString(0);
542 }
543 } catch (Exception e) {
544 filename = null;
545 } finally {
546 cursor.close();
547 }
548 }
549 if (filename == null) {
550 final List<String> segments = uri.getPathSegments();
551 if (segments.size() > 0) {
552 filename = segments.get(segments.size() - 1);
553 }
554 }
555 int pos = filename == null ? -1 : filename.lastIndexOf('.');
556 return pos > 0 ? filename.substring(pos + 1) : null;
557 }
558
559 private void copyImageToPrivateStorage(File file, Uri image, int sampleSize) throws FileCopyException {
560 file.getParentFile().mkdirs();
561 InputStream is = null;
562 OutputStream os = null;
563 try {
564 if (!file.exists() && !file.createNewFile()) {
565 throw new FileCopyException(R.string.error_unable_to_create_temporary_file);
566 }
567 is = mXmppConnectionService.getContentResolver().openInputStream(image);
568 if (is == null) {
569 throw new FileCopyException(R.string.error_not_an_image_file);
570 }
571 Bitmap originalBitmap;
572 BitmapFactory.Options options = new BitmapFactory.Options();
573 int inSampleSize = (int) Math.pow(2, sampleSize);
574 Log.d(Config.LOGTAG, "reading bitmap with sample size " + inSampleSize);
575 options.inSampleSize = inSampleSize;
576 originalBitmap = BitmapFactory.decodeStream(is, null, options);
577 is.close();
578 if (originalBitmap == null) {
579 throw new FileCopyException(R.string.error_not_an_image_file);
580 }
581 Bitmap scaledBitmap = resize(originalBitmap, Config.IMAGE_SIZE);
582 int rotation = getRotation(image);
583 scaledBitmap = rotate(scaledBitmap, rotation);
584 boolean targetSizeReached = false;
585 int quality = Config.IMAGE_QUALITY;
586 final int imageMaxSize = mXmppConnectionService.getResources().getInteger(R.integer.auto_accept_filesize);
587 while (!targetSizeReached) {
588 os = new FileOutputStream(file);
589 boolean success = scaledBitmap.compress(Config.IMAGE_FORMAT, quality, os);
590 if (!success) {
591 throw new FileCopyException(R.string.error_compressing_image);
592 }
593 os.flush();
594 targetSizeReached = file.length() <= imageMaxSize || quality <= 50;
595 quality -= 5;
596 }
597 scaledBitmap.recycle();
598 } catch (FileNotFoundException e) {
599 throw new FileCopyException(R.string.error_file_not_found);
600 } catch (IOException e) {
601 e.printStackTrace();
602 throw new FileCopyException(R.string.error_io_exception);
603 } catch (SecurityException e) {
604 throw new FileCopyException(R.string.error_security_exception_during_image_copy);
605 } catch (OutOfMemoryError e) {
606 ++sampleSize;
607 if (sampleSize <= 3) {
608 copyImageToPrivateStorage(file, image, sampleSize);
609 } else {
610 throw new FileCopyException(R.string.error_out_of_memory);
611 }
612 } finally {
613 close(os);
614 close(is);
615 }
616 }
617
618 public void copyImageToPrivateStorage(File file, Uri image) throws FileCopyException {
619 Log.d(Config.LOGTAG, "copy image (" + image.toString() + ") to private storage " + file.getAbsolutePath());
620 copyImageToPrivateStorage(file, image, 0);
621 }
622
623 public void copyImageToPrivateStorage(Message message, Uri image) throws FileCopyException {
624 switch (Config.IMAGE_FORMAT) {
625 case JPEG:
626 message.setRelativeFilePath(message.getUuid() + ".jpg");
627 break;
628 case PNG:
629 message.setRelativeFilePath(message.getUuid() + ".png");
630 break;
631 case WEBP:
632 message.setRelativeFilePath(message.getUuid() + ".webp");
633 break;
634 }
635 copyImageToPrivateStorage(getFile(message), image);
636 updateFileParams(message);
637 }
638
639 private int getRotation(File file) {
640 return getRotation(Uri.parse("file://" + file.getAbsolutePath()));
641 }
642
643 private int getRotation(Uri image) {
644 InputStream is = null;
645 try {
646 is = mXmppConnectionService.getContentResolver().openInputStream(image);
647 return ExifHelper.getOrientation(is);
648 } catch (FileNotFoundException e) {
649 return 0;
650 } finally {
651 close(is);
652 }
653 }
654
655 public Bitmap getThumbnail(Message message, int size, boolean cacheOnly) throws IOException {
656 final String uuid = message.getUuid();
657 final LruCache<String, Bitmap> cache = mXmppConnectionService.getBitmapCache();
658 Bitmap thumbnail = cache.get(uuid);
659 if ((thumbnail == null) && (!cacheOnly)) {
660 synchronized (THUMBNAIL_LOCK) {
661 thumbnail = cache.get(uuid);
662 if (thumbnail != null) {
663 return thumbnail;
664 }
665 DownloadableFile file = getFile(message);
666 final String mime = file.getMimeType();
667 if (mime.startsWith("video/")) {
668 thumbnail = getVideoPreview(file, size);
669 } else {
670 Bitmap fullsize = getFullsizeImagePreview(file, size);
671 if (fullsize == null) {
672 throw new FileNotFoundException();
673 }
674 thumbnail = resize(fullsize, size);
675 thumbnail = rotate(thumbnail, getRotation(file));
676 if (mime.equals("image/gif")) {
677 Bitmap withGifOverlay = thumbnail.copy(Bitmap.Config.ARGB_8888, true);
678 drawOverlay(withGifOverlay, paintOverlayBlack(withGifOverlay) ? R.drawable.play_gif_black : R.drawable.play_gif_white, 1.0f);
679 thumbnail.recycle();
680 thumbnail = withGifOverlay;
681 }
682 }
683 this.mXmppConnectionService.getBitmapCache().put(uuid, thumbnail);
684 }
685 }
686 return thumbnail;
687 }
688
689 private Bitmap getFullsizeImagePreview(File file, int size) {
690 BitmapFactory.Options options = new BitmapFactory.Options();
691 options.inSampleSize = calcSampleSize(file, size);
692 try {
693 return BitmapFactory.decodeFile(file.getAbsolutePath(), options);
694 } catch (OutOfMemoryError e) {
695 options.inSampleSize *= 2;
696 return BitmapFactory.decodeFile(file.getAbsolutePath(), options);
697 }
698 }
699
700 private void drawOverlay(Bitmap bitmap, int resource, float factor) {
701 Bitmap overlay = BitmapFactory.decodeResource(mXmppConnectionService.getResources(), resource);
702 Canvas canvas = new Canvas(bitmap);
703 float targetSize = Math.min(canvas.getWidth(), canvas.getHeight()) * factor;
704 Log.d(Config.LOGTAG, "target size overlay: " + targetSize + " overlay bitmap size was " + overlay.getHeight());
705 float left = (canvas.getWidth() - targetSize) / 2.0f;
706 float top = (canvas.getHeight() - targetSize) / 2.0f;
707 RectF dst = new RectF(left, top, left + targetSize - 1, top + targetSize - 1);
708 canvas.drawBitmap(overlay, null, dst, createAntiAliasingPaint());
709 }
710
711 /**
712 * https://stackoverflow.com/a/3943023/210897
713 */
714 private boolean paintOverlayBlack(final Bitmap bitmap) {
715 final int h = bitmap.getHeight();
716 final int w = bitmap.getWidth();
717 int record = 0;
718 for (int y = Math.round(h * IGNORE_PADDING); y < h - Math.round(h * IGNORE_PADDING); ++y) {
719 for (int x = Math.round(w * IGNORE_PADDING); x < w - Math.round(w * IGNORE_PADDING); ++x) {
720 int pixel = bitmap.getPixel(x, y);
721 if ((Color.red(pixel) * 0.299 + Color.green(pixel) * 0.587 + Color.blue(pixel) * 0.114) > 186) {
722 --record;
723 } else {
724 ++record;
725 }
726 }
727 }
728 return record < 0;
729 }
730
731 private Bitmap getVideoPreview(File file, int size) {
732 MediaMetadataRetriever metadataRetriever = new MediaMetadataRetriever();
733 Bitmap frame;
734 try {
735 metadataRetriever.setDataSource(file.getAbsolutePath());
736 frame = metadataRetriever.getFrameAtTime(0);
737 metadataRetriever.release();
738 frame = resize(frame, size);
739 } catch (IOException | RuntimeException e) {
740 frame = Bitmap.createBitmap(size, size, Bitmap.Config.ARGB_8888);
741 frame.eraseColor(0xff000000);
742 }
743 drawOverlay(frame, paintOverlayBlack(frame) ? R.drawable.play_video_black : R.drawable.play_video_white, 0.75f);
744 return frame;
745 }
746
747 public Uri getTakePhotoUri() {
748 File file;
749 if (Config.ONLY_INTERNAL_STORAGE) {
750 file = new File(mXmppConnectionService.getCacheDir().getAbsolutePath(), "Camera/IMG_" + this.IMAGE_DATE_FORMAT.format(new Date()) + ".jpg");
751 } else {
752 file = new File(getTakePhotoPath() + "IMG_" + this.IMAGE_DATE_FORMAT.format(new Date()) + ".jpg");
753 }
754 file.getParentFile().mkdirs();
755 return getUriForFile(mXmppConnectionService, file);
756 }
757
758 public Avatar getPepAvatar(Uri image, int size, Bitmap.CompressFormat format) {
759
760 final Avatar uncompressAvatar = getUncompressedAvatar(image);
761 if (uncompressAvatar != null && uncompressAvatar.image.length() <= Config.AVATAR_CHAR_LIMIT) {
762 return uncompressAvatar;
763 }
764 if (uncompressAvatar != null) {
765 Log.d(Config.LOGTAG, "uncompressed avatar exceeded char limit by " + (uncompressAvatar.image.length() - Config.AVATAR_CHAR_LIMIT));
766 }
767
768 Bitmap bm = cropCenterSquare(image, size);
769 if (bm == null) {
770 return null;
771 }
772 if (hasAlpha(bm)) {
773 Log.d(Config.LOGTAG, "alpha in avatar detected; uploading as PNG");
774 bm.recycle();
775 bm = cropCenterSquare(image, 96);
776 return getPepAvatar(bm, Bitmap.CompressFormat.PNG, 100);
777 }
778 return getPepAvatar(bm, format, 100);
779 }
780
781 private Avatar getUncompressedAvatar(Uri uri) {
782 Bitmap bitmap = null;
783 try {
784 bitmap = BitmapFactory.decodeStream(mXmppConnectionService.getContentResolver().openInputStream(uri));
785 return getPepAvatar(bitmap, Bitmap.CompressFormat.PNG, 100);
786 } catch (Exception e) {
787 if (bitmap != null) {
788 bitmap.recycle();
789 }
790 }
791 return null;
792 }
793
794 private Avatar getPepAvatar(Bitmap bitmap, Bitmap.CompressFormat format, int quality) {
795 try {
796 ByteArrayOutputStream mByteArrayOutputStream = new ByteArrayOutputStream();
797 Base64OutputStream mBase64OutputStream = new Base64OutputStream(mByteArrayOutputStream, Base64.DEFAULT);
798 MessageDigest digest = MessageDigest.getInstance("SHA-1");
799 DigestOutputStream mDigestOutputStream = new DigestOutputStream(mBase64OutputStream, digest);
800 if (!bitmap.compress(format, quality, mDigestOutputStream)) {
801 return null;
802 }
803 mDigestOutputStream.flush();
804 mDigestOutputStream.close();
805 long chars = mByteArrayOutputStream.size();
806 if (format != Bitmap.CompressFormat.PNG && quality >= 50 && chars >= Config.AVATAR_CHAR_LIMIT) {
807 int q = quality - 2;
808 Log.d(Config.LOGTAG, "avatar char length was " + chars + " reducing quality to " + q);
809 return getPepAvatar(bitmap, format, q);
810 }
811 Log.d(Config.LOGTAG, "settled on char length " + chars + " with quality=" + quality);
812 final Avatar avatar = new Avatar();
813 avatar.sha1sum = CryptoHelper.bytesToHex(digest.digest());
814 avatar.image = new String(mByteArrayOutputStream.toByteArray());
815 if (format.equals(Bitmap.CompressFormat.WEBP)) {
816 avatar.type = "image/webp";
817 } else if (format.equals(Bitmap.CompressFormat.JPEG)) {
818 avatar.type = "image/jpeg";
819 } else if (format.equals(Bitmap.CompressFormat.PNG)) {
820 avatar.type = "image/png";
821 }
822 avatar.width = bitmap.getWidth();
823 avatar.height = bitmap.getHeight();
824 return avatar;
825 } catch (Exception e) {
826 return null;
827 }
828 }
829
830 public Avatar getStoredPepAvatar(String hash) {
831 if (hash == null) {
832 return null;
833 }
834 Avatar avatar = new Avatar();
835 File file = new File(getAvatarPath(hash));
836 FileInputStream is = null;
837 try {
838 avatar.size = file.length();
839 BitmapFactory.Options options = new BitmapFactory.Options();
840 options.inJustDecodeBounds = true;
841 BitmapFactory.decodeFile(file.getAbsolutePath(), options);
842 is = new FileInputStream(file);
843 ByteArrayOutputStream mByteArrayOutputStream = new ByteArrayOutputStream();
844 Base64OutputStream mBase64OutputStream = new Base64OutputStream(mByteArrayOutputStream, Base64.DEFAULT);
845 MessageDigest digest = MessageDigest.getInstance("SHA-1");
846 DigestOutputStream os = new DigestOutputStream(mBase64OutputStream, digest);
847 byte[] buffer = new byte[4096];
848 int length;
849 while ((length = is.read(buffer)) > 0) {
850 os.write(buffer, 0, length);
851 }
852 os.flush();
853 os.close();
854 avatar.sha1sum = CryptoHelper.bytesToHex(digest.digest());
855 avatar.image = new String(mByteArrayOutputStream.toByteArray());
856 avatar.height = options.outHeight;
857 avatar.width = options.outWidth;
858 avatar.type = options.outMimeType;
859 return avatar;
860 } catch (NoSuchAlgorithmException | IOException e) {
861 return null;
862 } finally {
863 close(is);
864 }
865 }
866
867 public boolean isAvatarCached(Avatar avatar) {
868 File file = new File(getAvatarPath(avatar.getFilename()));
869 return file.exists();
870 }
871
872 public boolean save(final Avatar avatar) {
873 File file;
874 if (isAvatarCached(avatar)) {
875 file = new File(getAvatarPath(avatar.getFilename()));
876 avatar.size = file.length();
877 } else {
878 file = new File(mXmppConnectionService.getCacheDir().getAbsolutePath() + "/" + UUID.randomUUID().toString());
879 if (file.getParentFile().mkdirs()) {
880 Log.d(Config.LOGTAG, "created cache directory");
881 }
882 OutputStream os = null;
883 try {
884 if (!file.createNewFile()) {
885 Log.d(Config.LOGTAG, "unable to create temporary file " + file.getAbsolutePath());
886 }
887 os = new FileOutputStream(file);
888 MessageDigest digest = MessageDigest.getInstance("SHA-1");
889 digest.reset();
890 DigestOutputStream mDigestOutputStream = new DigestOutputStream(os, digest);
891 final byte[] bytes = avatar.getImageAsBytes();
892 mDigestOutputStream.write(bytes);
893 mDigestOutputStream.flush();
894 mDigestOutputStream.close();
895 String sha1sum = CryptoHelper.bytesToHex(digest.digest());
896 if (sha1sum.equals(avatar.sha1sum)) {
897 File outputFile = new File(getAvatarPath(avatar.getFilename()));
898 if (outputFile.getParentFile().mkdirs()) {
899 Log.d(Config.LOGTAG, "created avatar directory");
900 }
901 String filename = getAvatarPath(avatar.getFilename());
902 if (!file.renameTo(new File(filename))) {
903 Log.d(Config.LOGTAG, "unable to rename " + file.getAbsolutePath() + " to " + outputFile);
904 return false;
905 }
906 } else {
907 Log.d(Config.LOGTAG, "sha1sum mismatch for " + avatar.owner);
908 if (!file.delete()) {
909 Log.d(Config.LOGTAG, "unable to delete temporary file");
910 }
911 return false;
912 }
913 avatar.size = bytes.length;
914 } catch (IllegalArgumentException | IOException | NoSuchAlgorithmException e) {
915 return false;
916 } finally {
917 close(os);
918 }
919 }
920 return true;
921 }
922
923 private String getAvatarPath(String avatar) {
924 return mXmppConnectionService.getFilesDir().getAbsolutePath() + "/avatars/" + avatar;
925 }
926
927 public Uri getAvatarUri(String avatar) {
928 return Uri.parse("file:" + getAvatarPath(avatar));
929 }
930
931 public Bitmap cropCenterSquare(Uri image, int size) {
932 if (image == null) {
933 return null;
934 }
935 InputStream is = null;
936 try {
937 BitmapFactory.Options options = new BitmapFactory.Options();
938 options.inSampleSize = calcSampleSize(image, size);
939 is = mXmppConnectionService.getContentResolver().openInputStream(image);
940 if (is == null) {
941 return null;
942 }
943 Bitmap input = BitmapFactory.decodeStream(is, null, options);
944 if (input == null) {
945 return null;
946 } else {
947 input = rotate(input, getRotation(image));
948 return cropCenterSquare(input, size);
949 }
950 } catch (FileNotFoundException | SecurityException e) {
951 return null;
952 } finally {
953 close(is);
954 }
955 }
956
957 public Bitmap cropCenter(Uri image, int newHeight, int newWidth) {
958 if (image == null) {
959 return null;
960 }
961 InputStream is = null;
962 try {
963 BitmapFactory.Options options = new BitmapFactory.Options();
964 options.inSampleSize = calcSampleSize(image, Math.max(newHeight, newWidth));
965 is = mXmppConnectionService.getContentResolver().openInputStream(image);
966 if (is == null) {
967 return null;
968 }
969 Bitmap source = BitmapFactory.decodeStream(is, null, options);
970 if (source == null) {
971 return null;
972 }
973 int sourceWidth = source.getWidth();
974 int sourceHeight = source.getHeight();
975 float xScale = (float) newWidth / sourceWidth;
976 float yScale = (float) newHeight / sourceHeight;
977 float scale = Math.max(xScale, yScale);
978 float scaledWidth = scale * sourceWidth;
979 float scaledHeight = scale * sourceHeight;
980 float left = (newWidth - scaledWidth) / 2;
981 float top = (newHeight - scaledHeight) / 2;
982
983 RectF targetRect = new RectF(left, top, left + scaledWidth, top + scaledHeight);
984 Bitmap dest = Bitmap.createBitmap(newWidth, newHeight, Bitmap.Config.ARGB_8888);
985 Canvas canvas = new Canvas(dest);
986 canvas.drawBitmap(source, null, targetRect, createAntiAliasingPaint());
987 if (source.isRecycled()) {
988 source.recycle();
989 }
990 return dest;
991 } catch (SecurityException e) {
992 return null; //android 6.0 with revoked permissions for example
993 } catch (FileNotFoundException e) {
994 return null;
995 } finally {
996 close(is);
997 }
998 }
999
1000 public Bitmap cropCenterSquare(Bitmap input, int size) {
1001 int w = input.getWidth();
1002 int h = input.getHeight();
1003
1004 float scale = Math.max((float) size / h, (float) size / w);
1005
1006 float outWidth = scale * w;
1007 float outHeight = scale * h;
1008 float left = (size - outWidth) / 2;
1009 float top = (size - outHeight) / 2;
1010 RectF target = new RectF(left, top, left + outWidth, top + outHeight);
1011
1012 Bitmap output = Bitmap.createBitmap(size, size, Bitmap.Config.ARGB_8888);
1013 Canvas canvas = new Canvas(output);
1014 canvas.drawBitmap(input, null, target, createAntiAliasingPaint());
1015 if (!input.isRecycled()) {
1016 input.recycle();
1017 }
1018 return output;
1019 }
1020
1021 private int calcSampleSize(Uri image, int size) throws FileNotFoundException, SecurityException {
1022 BitmapFactory.Options options = new BitmapFactory.Options();
1023 options.inJustDecodeBounds = true;
1024 BitmapFactory.decodeStream(mXmppConnectionService.getContentResolver().openInputStream(image), null, options);
1025 return calcSampleSize(options, size);
1026 }
1027
1028 public void updateFileParams(Message message) {
1029 updateFileParams(message, null);
1030 }
1031
1032 public void updateFileParams(Message message, URL url) {
1033 DownloadableFile file = getFile(message);
1034 final String mime = file.getMimeType();
1035 boolean image = message.getType() == Message.TYPE_IMAGE || (mime != null && mime.startsWith("image/"));
1036 boolean video = mime != null && mime.startsWith("video/");
1037 boolean audio = mime != null && mime.startsWith("audio/");
1038 final StringBuilder body = new StringBuilder();
1039 if (url != null) {
1040 body.append(url.toString());
1041 }
1042 body.append('|').append(file.getSize());
1043 if (image || video) {
1044 try {
1045 Dimensions dimensions = image ? getImageDimensions(file) : getVideoDimensions(file);
1046 if (dimensions.valid()) {
1047 body.append('|').append(dimensions.width).append('|').append(dimensions.height);
1048 }
1049 } catch (NotAVideoFile notAVideoFile) {
1050 Log.d(Config.LOGTAG, "file with mime type " + file.getMimeType() + " was not a video file");
1051 //fall threw
1052 }
1053 } else if (audio) {
1054 body.append("|0|0|").append(getMediaRuntime(file));
1055 }
1056 message.setBody(body.toString());
1057 }
1058
1059 public int getMediaRuntime(Uri uri) {
1060 try {
1061 MediaMetadataRetriever mediaMetadataRetriever = new MediaMetadataRetriever();
1062 mediaMetadataRetriever.setDataSource(mXmppConnectionService, uri);
1063 return Integer.parseInt(mediaMetadataRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION));
1064 } catch (RuntimeException e) {
1065 return 0;
1066 }
1067 }
1068
1069 private int getMediaRuntime(File file) {
1070 try {
1071 MediaMetadataRetriever mediaMetadataRetriever = new MediaMetadataRetriever();
1072 mediaMetadataRetriever.setDataSource(file.toString());
1073 return Integer.parseInt(mediaMetadataRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION));
1074 } catch (RuntimeException e) {
1075 return 0;
1076 }
1077 }
1078
1079 private Dimensions getImageDimensions(File file) {
1080 BitmapFactory.Options options = new BitmapFactory.Options();
1081 options.inJustDecodeBounds = true;
1082 BitmapFactory.decodeFile(file.getAbsolutePath(), options);
1083 int rotation = getRotation(file);
1084 boolean rotated = rotation == 90 || rotation == 270;
1085 int imageHeight = rotated ? options.outWidth : options.outHeight;
1086 int imageWidth = rotated ? options.outHeight : options.outWidth;
1087 return new Dimensions(imageHeight, imageWidth);
1088 }
1089
1090 private Dimensions getVideoDimensions(File file) throws NotAVideoFile {
1091 MediaMetadataRetriever metadataRetriever = new MediaMetadataRetriever();
1092 try {
1093 metadataRetriever.setDataSource(file.getAbsolutePath());
1094 } catch (RuntimeException e) {
1095 throw new NotAVideoFile(e);
1096 }
1097 return getVideoDimensions(metadataRetriever);
1098 }
1099
1100 public Bitmap getAvatar(String avatar, int size) {
1101 if (avatar == null) {
1102 return null;
1103 }
1104 Bitmap bm = cropCenter(getAvatarUri(avatar), size, size);
1105 if (bm == null) {
1106 return null;
1107 }
1108 return bm;
1109 }
1110
1111 public boolean isFileAvailable(Message message) {
1112 return getFile(message).exists();
1113 }
1114
1115 private static class Dimensions {
1116 public final int width;
1117 public final int height;
1118
1119 Dimensions(int height, int width) {
1120 this.width = width;
1121 this.height = height;
1122 }
1123
1124 public int getMin() {
1125 return Math.min(width, height);
1126 }
1127
1128 public boolean valid() {
1129 return width > 0 && height > 0;
1130 }
1131 }
1132
1133 private static class NotAVideoFile extends Exception {
1134 public NotAVideoFile(Throwable t) {
1135 super(t);
1136 }
1137
1138 public NotAVideoFile() {
1139 super();
1140 }
1141 }
1142
1143 public class FileCopyException extends Exception {
1144 private static final long serialVersionUID = -1010013599132881427L;
1145 private int resId;
1146
1147 public FileCopyException(int resId) {
1148 this.resId = resId;
1149 }
1150
1151 public int getResId() {
1152 return resId;
1153 }
1154 }
1155}