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;
29import android.webkit.MimeTypeMap;
30
31import java.io.ByteArrayOutputStream;
32import java.io.Closeable;
33import java.io.File;
34import java.io.FileDescriptor;
35import java.io.FileInputStream;
36import java.io.FileNotFoundException;
37import java.io.FileOutputStream;
38import java.io.IOException;
39import java.io.InputStream;
40import java.io.OutputStream;
41import java.net.Socket;
42import java.net.URL;
43import java.security.DigestOutputStream;
44import java.security.MessageDigest;
45import java.security.NoSuchAlgorithmException;
46import java.text.SimpleDateFormat;
47import java.util.Arrays;
48import java.util.Date;
49import java.util.List;
50import java.util.Locale;
51import java.util.UUID;
52
53import eu.siacs.conversations.Config;
54import eu.siacs.conversations.R;
55import eu.siacs.conversations.entities.DownloadableFile;
56import eu.siacs.conversations.entities.Message;
57import eu.siacs.conversations.services.XmppConnectionService;
58import eu.siacs.conversations.ui.RecordingActivity;
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 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, R.drawable.play_gif, 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 private Bitmap getVideoPreview(File file, int size) {
712 MediaMetadataRetriever metadataRetriever = new MediaMetadataRetriever();
713 Bitmap frame;
714 try {
715 metadataRetriever.setDataSource(file.getAbsolutePath());
716 frame = metadataRetriever.getFrameAtTime(0);
717 metadataRetriever.release();
718 frame = resize(frame, size);
719 } catch (IOException | RuntimeException e) {
720 frame = Bitmap.createBitmap(size, size, Bitmap.Config.ARGB_8888);
721 frame.eraseColor(0xff000000);
722 }
723 drawOverlay(frame, R.drawable.play_video, 0.75f);
724 return frame;
725 }
726
727 public Uri getTakePhotoUri() {
728 File file;
729 if (Config.ONLY_INTERNAL_STORAGE) {
730 file = new File(mXmppConnectionService.getCacheDir().getAbsolutePath(), "Camera/IMG_" + this.IMAGE_DATE_FORMAT.format(new Date()) + ".jpg");
731 } else {
732 file = new File(getTakePhotoPath() + "IMG_" + this.IMAGE_DATE_FORMAT.format(new Date()) + ".jpg");
733 }
734 file.getParentFile().mkdirs();
735 return getUriForFile(mXmppConnectionService, file);
736 }
737
738 public Avatar getPepAvatar(Uri image, int size, Bitmap.CompressFormat format) {
739 Bitmap bm = cropCenterSquare(image, size);
740 if (bm == null) {
741 return null;
742 }
743 if (hasAlpha(bm)) {
744 Log.d(Config.LOGTAG, "alpha in avatar detected; uploading as PNG");
745 bm.recycle();
746 bm = cropCenterSquare(image, 96);
747 return getPepAvatar(bm, Bitmap.CompressFormat.PNG, 100);
748 }
749 return getPepAvatar(bm, format, 100);
750 }
751
752 private Avatar getPepAvatar(Bitmap bitmap, Bitmap.CompressFormat format, int quality) {
753 try {
754 ByteArrayOutputStream mByteArrayOutputStream = new ByteArrayOutputStream();
755 Base64OutputStream mBase64OutputStream = new Base64OutputStream(mByteArrayOutputStream, Base64.DEFAULT);
756 MessageDigest digest = MessageDigest.getInstance("SHA-1");
757 DigestOutputStream mDigestOutputStream = new DigestOutputStream(mBase64OutputStream, digest);
758 if (!bitmap.compress(format, quality, mDigestOutputStream)) {
759 return null;
760 }
761 mDigestOutputStream.flush();
762 mDigestOutputStream.close();
763 long chars = mByteArrayOutputStream.size();
764 if (format != Bitmap.CompressFormat.PNG && quality >= 50 && chars >= Config.AVATAR_CHAR_LIMIT) {
765 int q = quality - 2;
766 Log.d(Config.LOGTAG, "avatar char length was " + chars + " reducing quality to " + q);
767 return getPepAvatar(bitmap, format, q);
768 }
769 Log.d(Config.LOGTAG, "settled on char length " + chars + " with quality=" + quality);
770 final Avatar avatar = new Avatar();
771 avatar.sha1sum = CryptoHelper.bytesToHex(digest.digest());
772 avatar.image = new String(mByteArrayOutputStream.toByteArray());
773 if (format.equals(Bitmap.CompressFormat.WEBP)) {
774 avatar.type = "image/webp";
775 } else if (format.equals(Bitmap.CompressFormat.JPEG)) {
776 avatar.type = "image/jpeg";
777 } else if (format.equals(Bitmap.CompressFormat.PNG)) {
778 avatar.type = "image/png";
779 }
780 avatar.width = bitmap.getWidth();
781 avatar.height = bitmap.getHeight();
782 return avatar;
783 } catch (Exception e) {
784 return null;
785 }
786 }
787
788 public Avatar getStoredPepAvatar(String hash) {
789 if (hash == null) {
790 return null;
791 }
792 Avatar avatar = new Avatar();
793 File file = new File(getAvatarPath(hash));
794 FileInputStream is = null;
795 try {
796 avatar.size = file.length();
797 BitmapFactory.Options options = new BitmapFactory.Options();
798 options.inJustDecodeBounds = true;
799 BitmapFactory.decodeFile(file.getAbsolutePath(), options);
800 is = new FileInputStream(file);
801 ByteArrayOutputStream mByteArrayOutputStream = new ByteArrayOutputStream();
802 Base64OutputStream mBase64OutputStream = new Base64OutputStream(mByteArrayOutputStream, Base64.DEFAULT);
803 MessageDigest digest = MessageDigest.getInstance("SHA-1");
804 DigestOutputStream os = new DigestOutputStream(mBase64OutputStream, digest);
805 byte[] buffer = new byte[4096];
806 int length;
807 while ((length = is.read(buffer)) > 0) {
808 os.write(buffer, 0, length);
809 }
810 os.flush();
811 os.close();
812 avatar.sha1sum = CryptoHelper.bytesToHex(digest.digest());
813 avatar.image = new String(mByteArrayOutputStream.toByteArray());
814 avatar.height = options.outHeight;
815 avatar.width = options.outWidth;
816 avatar.type = options.outMimeType;
817 return avatar;
818 } catch (NoSuchAlgorithmException | IOException e) {
819 return null;
820 } finally {
821 close(is);
822 }
823 }
824
825 public boolean isAvatarCached(Avatar avatar) {
826 File file = new File(getAvatarPath(avatar.getFilename()));
827 return file.exists();
828 }
829
830 public boolean save(final Avatar avatar) {
831 File file;
832 if (isAvatarCached(avatar)) {
833 file = new File(getAvatarPath(avatar.getFilename()));
834 avatar.size = file.length();
835 } else {
836 file = new File(mXmppConnectionService.getCacheDir().getAbsolutePath() + "/" + UUID.randomUUID().toString());
837 if (file.getParentFile().mkdirs()) {
838 Log.d(Config.LOGTAG, "created cache directory");
839 }
840 OutputStream os = null;
841 try {
842 if (!file.createNewFile()) {
843 Log.d(Config.LOGTAG, "unable to create temporary file " + file.getAbsolutePath());
844 }
845 os = new FileOutputStream(file);
846 MessageDigest digest = MessageDigest.getInstance("SHA-1");
847 digest.reset();
848 DigestOutputStream mDigestOutputStream = new DigestOutputStream(os, digest);
849 final byte[] bytes = avatar.getImageAsBytes();
850 mDigestOutputStream.write(bytes);
851 mDigestOutputStream.flush();
852 mDigestOutputStream.close();
853 String sha1sum = CryptoHelper.bytesToHex(digest.digest());
854 if (sha1sum.equals(avatar.sha1sum)) {
855 File outputFile = new File(getAvatarPath(avatar.getFilename()));
856 if (outputFile.getParentFile().mkdirs()) {
857 Log.d(Config.LOGTAG, "created avatar directory");
858 }
859 String filename = getAvatarPath(avatar.getFilename());
860 if (!file.renameTo(new File(filename))) {
861 Log.d(Config.LOGTAG, "unable to rename " + file.getAbsolutePath() + " to " + outputFile);
862 return false;
863 }
864 } else {
865 Log.d(Config.LOGTAG, "sha1sum mismatch for " + avatar.owner);
866 if (!file.delete()) {
867 Log.d(Config.LOGTAG, "unable to delete temporary file");
868 }
869 return false;
870 }
871 avatar.size = bytes.length;
872 } catch (IllegalArgumentException | IOException | NoSuchAlgorithmException e) {
873 return false;
874 } finally {
875 close(os);
876 }
877 }
878 return true;
879 }
880
881 private String getAvatarPath(String avatar) {
882 return mXmppConnectionService.getFilesDir().getAbsolutePath() + "/avatars/" + avatar;
883 }
884
885 public Uri getAvatarUri(String avatar) {
886 return Uri.parse("file:" + getAvatarPath(avatar));
887 }
888
889 public Bitmap cropCenterSquare(Uri image, int size) {
890 if (image == null) {
891 return null;
892 }
893 InputStream is = null;
894 try {
895 BitmapFactory.Options options = new BitmapFactory.Options();
896 options.inSampleSize = calcSampleSize(image, size);
897 is = mXmppConnectionService.getContentResolver().openInputStream(image);
898 if (is == null) {
899 return null;
900 }
901 Bitmap input = BitmapFactory.decodeStream(is, null, options);
902 if (input == null) {
903 return null;
904 } else {
905 input = rotate(input, getRotation(image));
906 return cropCenterSquare(input, size);
907 }
908 } catch (FileNotFoundException | SecurityException e) {
909 return null;
910 } finally {
911 close(is);
912 }
913 }
914
915 public Bitmap cropCenter(Uri image, int newHeight, int newWidth) {
916 if (image == null) {
917 return null;
918 }
919 InputStream is = null;
920 try {
921 BitmapFactory.Options options = new BitmapFactory.Options();
922 options.inSampleSize = calcSampleSize(image, Math.max(newHeight, newWidth));
923 is = mXmppConnectionService.getContentResolver().openInputStream(image);
924 if (is == null) {
925 return null;
926 }
927 Bitmap source = BitmapFactory.decodeStream(is, null, options);
928 if (source == null) {
929 return null;
930 }
931 int sourceWidth = source.getWidth();
932 int sourceHeight = source.getHeight();
933 float xScale = (float) newWidth / sourceWidth;
934 float yScale = (float) newHeight / sourceHeight;
935 float scale = Math.max(xScale, yScale);
936 float scaledWidth = scale * sourceWidth;
937 float scaledHeight = scale * sourceHeight;
938 float left = (newWidth - scaledWidth) / 2;
939 float top = (newHeight - scaledHeight) / 2;
940
941 RectF targetRect = new RectF(left, top, left + scaledWidth, top + scaledHeight);
942 Bitmap dest = Bitmap.createBitmap(newWidth, newHeight, Bitmap.Config.ARGB_8888);
943 Canvas canvas = new Canvas(dest);
944 canvas.drawBitmap(source, null, targetRect, createAntiAliasingPaint());
945 if (source.isRecycled()) {
946 source.recycle();
947 }
948 return dest;
949 } catch (SecurityException e) {
950 return null; //android 6.0 with revoked permissions for example
951 } catch (FileNotFoundException e) {
952 return null;
953 } finally {
954 close(is);
955 }
956 }
957
958 public Bitmap cropCenterSquare(Bitmap input, int size) {
959 int w = input.getWidth();
960 int h = input.getHeight();
961
962 float scale = Math.max((float) size / h, (float) size / w);
963
964 float outWidth = scale * w;
965 float outHeight = scale * h;
966 float left = (size - outWidth) / 2;
967 float top = (size - outHeight) / 2;
968 RectF target = new RectF(left, top, left + outWidth, top + outHeight);
969
970 Bitmap output = Bitmap.createBitmap(size, size, Bitmap.Config.ARGB_8888);
971 Canvas canvas = new Canvas(output);
972 canvas.drawBitmap(input, null, target, createAntiAliasingPaint());
973 if (!input.isRecycled()) {
974 input.recycle();
975 }
976 return output;
977 }
978
979 private int calcSampleSize(Uri image, int size) throws FileNotFoundException, SecurityException {
980 BitmapFactory.Options options = new BitmapFactory.Options();
981 options.inJustDecodeBounds = true;
982 BitmapFactory.decodeStream(mXmppConnectionService.getContentResolver().openInputStream(image), null, options);
983 return calcSampleSize(options, size);
984 }
985
986 public void updateFileParams(Message message) {
987 updateFileParams(message, null);
988 }
989
990 public void updateFileParams(Message message, URL url) {
991 DownloadableFile file = getFile(message);
992 final String mime = file.getMimeType();
993 boolean image = message.getType() == Message.TYPE_IMAGE || (mime != null && mime.startsWith("image/"));
994 boolean video = mime != null && mime.startsWith("video/");
995 boolean audio = mime != null && mime.startsWith("audio/");
996 final StringBuilder body = new StringBuilder();
997 if (url != null) {
998 body.append(url.toString());
999 }
1000 body.append('|').append(file.getSize());
1001 if (image || video) {
1002 try {
1003 Dimensions dimensions = image ? getImageDimensions(file) : getVideoDimensions(file);
1004 if (dimensions.valid()) {
1005 body.append('|').append(dimensions.width).append('|').append(dimensions.height);
1006 }
1007 } catch (NotAVideoFile notAVideoFile) {
1008 Log.d(Config.LOGTAG, "file with mime type " + file.getMimeType() + " was not a video file");
1009 //fall threw
1010 }
1011 } else if (audio) {
1012 body.append("|0|0|").append(getMediaRuntime(file));
1013 }
1014 message.setBody(body.toString());
1015 }
1016
1017 public int getMediaRuntime(Uri uri) {
1018 try {
1019 MediaMetadataRetriever mediaMetadataRetriever = new MediaMetadataRetriever();
1020 mediaMetadataRetriever.setDataSource(mXmppConnectionService, uri);
1021 return Integer.parseInt(mediaMetadataRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION));
1022 } catch (RuntimeException e) {
1023 return 0;
1024 }
1025 }
1026
1027 private int getMediaRuntime(File file) {
1028 try {
1029 MediaMetadataRetriever mediaMetadataRetriever = new MediaMetadataRetriever();
1030 mediaMetadataRetriever.setDataSource(file.toString());
1031 return Integer.parseInt(mediaMetadataRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION));
1032 } catch (RuntimeException e) {
1033 return 0;
1034 }
1035 }
1036
1037 private Dimensions getImageDimensions(File file) {
1038 BitmapFactory.Options options = new BitmapFactory.Options();
1039 options.inJustDecodeBounds = true;
1040 BitmapFactory.decodeFile(file.getAbsolutePath(), options);
1041 int rotation = getRotation(file);
1042 boolean rotated = rotation == 90 || rotation == 270;
1043 int imageHeight = rotated ? options.outWidth : options.outHeight;
1044 int imageWidth = rotated ? options.outHeight : options.outWidth;
1045 return new Dimensions(imageHeight, imageWidth);
1046 }
1047
1048 private Dimensions getVideoDimensions(File file) throws NotAVideoFile {
1049 MediaMetadataRetriever metadataRetriever = new MediaMetadataRetriever();
1050 try {
1051 metadataRetriever.setDataSource(file.getAbsolutePath());
1052 } catch (RuntimeException e) {
1053 throw new NotAVideoFile(e);
1054 }
1055 return getVideoDimensions(metadataRetriever);
1056 }
1057
1058 public Bitmap getAvatar(String avatar, int size) {
1059 if (avatar == null) {
1060 return null;
1061 }
1062 Bitmap bm = cropCenter(getAvatarUri(avatar), size, size);
1063 if (bm == null) {
1064 return null;
1065 }
1066 return bm;
1067 }
1068
1069 public boolean isFileAvailable(Message message) {
1070 return getFile(message).exists();
1071 }
1072
1073 private static class Dimensions {
1074 public final int width;
1075 public final int height;
1076
1077 Dimensions(int height, int width) {
1078 this.width = width;
1079 this.height = height;
1080 }
1081
1082 public int getMin() {
1083 return Math.min(width, height);
1084 }
1085
1086 public boolean valid() {
1087 return width > 0 && height > 0;
1088 }
1089 }
1090
1091 private static class NotAVideoFile extends Exception {
1092 public NotAVideoFile(Throwable t) {
1093 super(t);
1094 }
1095
1096 public NotAVideoFile() {
1097 super();
1098 }
1099 }
1100
1101 public class FileCopyException extends Exception {
1102 private static final long serialVersionUID = -1010013599132881427L;
1103 private int resId;
1104
1105 public FileCopyException(int resId) {
1106 this.resId = resId;
1107 }
1108
1109 public int getResId() {
1110 return resId;
1111 }
1112 }
1113}