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.Matrix;
12import android.graphics.Paint;
13import android.graphics.RectF;
14import android.media.MediaMetadataRetriever;
15import android.net.Uri;
16import android.os.Build;
17import android.os.Environment;
18import android.os.ParcelFileDescriptor;
19import android.provider.MediaStore;
20import android.provider.OpenableColumns;
21import android.support.v4.content.FileProvider;
22import android.system.Os;
23import android.system.StructStat;
24import android.util.Base64;
25import android.util.Base64OutputStream;
26import android.util.Log;
27import android.util.LruCache;
28import android.webkit.MimeTypeMap;
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;
49
50import eu.siacs.conversations.Config;
51import eu.siacs.conversations.R;
52import eu.siacs.conversations.entities.DownloadableFile;
53import eu.siacs.conversations.entities.Message;
54import eu.siacs.conversations.services.XmppConnectionService;
55import eu.siacs.conversations.utils.CryptoHelper;
56import eu.siacs.conversations.utils.ExifHelper;
57import eu.siacs.conversations.utils.FileUtils;
58import eu.siacs.conversations.utils.FileWriterException;
59import eu.siacs.conversations.utils.MimeUtils;
60import eu.siacs.conversations.xmpp.pep.Avatar;
61
62public class FileBackend {
63 private static final SimpleDateFormat IMAGE_DATE_FORMAT = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.US);
64
65 private static final String FILE_PROVIDER = ".files";
66
67 private XmppConnectionService mXmppConnectionService;
68
69 public FileBackend(XmppConnectionService service) {
70 this.mXmppConnectionService = service;
71 }
72
73 private void createNoMedia() {
74 final File nomedia = new File(getConversationsFileDirectory()+".nomedia");
75 if (!nomedia.exists()) {
76 try {
77 nomedia.createNewFile();
78 } catch (Exception e) {
79 Log.d(Config.LOGTAG, "could not create nomedia file");
80 }
81 }
82 }
83
84 public void updateMediaScanner(File file) {
85 if (file.getAbsolutePath().startsWith(getConversationsImageDirectory())) {
86 Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
87 intent.setData(Uri.fromFile(file));
88 mXmppConnectionService.sendBroadcast(intent);
89 } else {
90 createNoMedia();
91 }
92 }
93
94 public boolean deleteFile(Message message) {
95 File file = getFile(message);
96 if (file.delete()) {
97 updateMediaScanner(file);
98 return true;
99 } else {
100 return false;
101 }
102 }
103
104 public DownloadableFile getFile(Message message) {
105 return getFile(message, true);
106 }
107
108 public DownloadableFile getFile(Message message, boolean decrypted) {
109 final boolean encrypted = !decrypted
110 && (message.getEncryption() == Message.ENCRYPTION_PGP
111 || message.getEncryption() == Message.ENCRYPTION_DECRYPTED);
112 final DownloadableFile file;
113 String path = message.getRelativeFilePath();
114 if (path == null) {
115 path = message.getUuid();
116 }
117 if (path.startsWith("/")) {
118 file = new DownloadableFile(path);
119 } else {
120 String mime = message.getMimeType();
121 if (mime != null && mime.startsWith("image")) {
122 file = new DownloadableFile(getConversationsImageDirectory() + path);
123 } else {
124 file = new DownloadableFile(getConversationsFileDirectory() + path);
125 }
126 }
127 if (encrypted) {
128 return new DownloadableFile(getConversationsFileDirectory() + file.getName() + ".pgp");
129 } else {
130 return file;
131 }
132 }
133
134 private static long getFileSize(Context context, Uri uri) {
135 Cursor cursor = context.getContentResolver().query(uri, null, null, null, null);
136 if (cursor != null && cursor.moveToFirst()) {
137 return cursor.getLong(cursor.getColumnIndex(OpenableColumns.SIZE));
138 } else {
139 return -1;
140 }
141 }
142
143 public static boolean allFilesUnderSize(Context context, List<Uri> uris, long max) {
144 if (max <= 0) {
145 Log.d(Config.LOGTAG,"server did not report max file size for http upload");
146 return true; //exception to be compatible with HTTP Upload < v0.2
147 }
148 for(Uri uri : uris) {
149 if (FileBackend.getFileSize(context, uri) > max) {
150 Log.d(Config.LOGTAG,"not all files are under "+max+" bytes. suggesting falling back to jingle");
151 return false;
152 }
153 }
154 return true;
155 }
156
157 public String getConversationsFileDirectory() {
158 if (Config.ONLY_INTERNAL_STORAGE) {
159 return mXmppConnectionService.getFilesDir().getAbsolutePath() + "/Files/";
160 } else {
161 return Environment.getExternalStorageDirectory().getAbsolutePath() + "/Conversations/";
162 }
163 }
164
165 public String getConversationsImageDirectory() {
166 if (Config.ONLY_INTERNAL_STORAGE) {
167 return mXmppConnectionService.getFilesDir().getAbsolutePath()+"/Pictures/";
168 } else {
169 return Environment.getExternalStoragePublicDirectory(
170 Environment.DIRECTORY_PICTURES).getAbsolutePath()
171 + "/Conversations/";
172 }
173 }
174
175 public static String getConversationsLogsDirectory() {
176 return Environment.getExternalStorageDirectory().getAbsolutePath()+"/Conversations/";
177 }
178
179 public Bitmap resize(Bitmap originalBitmap, int size) {
180 int w = originalBitmap.getWidth();
181 int h = originalBitmap.getHeight();
182 if (Math.max(w, h) > size) {
183 int scalledW;
184 int scalledH;
185 if (w <= h) {
186 scalledW = (int) (w / ((double) h / size));
187 scalledH = size;
188 } else {
189 scalledW = size;
190 scalledH = (int) (h / ((double) w / size));
191 }
192 Bitmap result = Bitmap.createScaledBitmap(originalBitmap, scalledW, scalledH, true);
193 if (originalBitmap != null && !originalBitmap.isRecycled()) {
194 originalBitmap.recycle();
195 }
196 return result;
197 } else {
198 return originalBitmap;
199 }
200 }
201
202 public static Bitmap rotate(Bitmap bitmap, int degree) {
203 if (degree == 0) {
204 return bitmap;
205 }
206 int w = bitmap.getWidth();
207 int h = bitmap.getHeight();
208 Matrix mtx = new Matrix();
209 mtx.postRotate(degree);
210 Bitmap result = Bitmap.createBitmap(bitmap, 0, 0, w, h, mtx, true);
211 if (bitmap != null && !bitmap.isRecycled()) {
212 bitmap.recycle();
213 }
214 return result;
215 }
216
217 public boolean useImageAsIs(Uri uri) {
218 String path = getOriginalPath(uri);
219 if (path == null) {
220 return false;
221 }
222 File file = new File(path);
223 long size = file.length();
224 if (size == 0 || size >= Config.IMAGE_MAX_SIZE ) {
225 return false;
226 }
227 BitmapFactory.Options options = new BitmapFactory.Options();
228 options.inJustDecodeBounds = true;
229 try {
230 BitmapFactory.decodeStream(mXmppConnectionService.getContentResolver().openInputStream(uri), null, options);
231 if (options == null || options.outMimeType == null || options.outHeight <= 0 || options.outWidth <= 0) {
232 return false;
233 }
234 return (options.outWidth <= Config.IMAGE_SIZE && options.outHeight <= Config.IMAGE_SIZE && options.outMimeType.contains(Config.IMAGE_FORMAT.name().toLowerCase()));
235 } catch (FileNotFoundException e) {
236 return false;
237 }
238 }
239
240 public String getOriginalPath(Uri uri) {
241 return FileUtils.getPath(mXmppConnectionService,uri);
242 }
243
244 public void copyFileToPrivateStorage(File file, Uri uri) throws FileCopyException {
245 Log.d(Config.LOGTAG,"copy file ("+uri.toString()+") to private storage "+file.getAbsolutePath());
246 file.getParentFile().mkdirs();
247 OutputStream os = null;
248 InputStream is = null;
249 try {
250 file.createNewFile();
251 os = new FileOutputStream(file);
252 is = mXmppConnectionService.getContentResolver().openInputStream(uri);
253 byte[] buffer = new byte[1024];
254 int length;
255 while ((length = is.read(buffer)) > 0) {
256 try {
257 os.write(buffer, 0, length);
258 } catch (IOException e) {
259 throw new FileWriterException();
260 }
261 }
262 try {
263 os.flush();
264 } catch (IOException e) {
265 throw new FileWriterException();
266 }
267 } catch(FileNotFoundException e) {
268 throw new FileCopyException(R.string.error_file_not_found);
269 } catch(FileWriterException e) {
270 throw new FileCopyException(R.string.error_unable_to_create_temporary_file);
271 } catch (IOException e) {
272 e.printStackTrace();
273 throw new FileCopyException(R.string.error_io_exception);
274 } finally {
275 close(os);
276 close(is);
277 }
278 }
279
280 public void copyFileToPrivateStorage(Message message, Uri uri) throws FileCopyException {
281 String mime = MimeUtils.guessMimeTypeFromUri(mXmppConnectionService, uri);
282 Log.d(Config.LOGTAG, "copy " + uri.toString() + " to private storage (mime="+mime+")");
283 String extension = MimeTypeMap.getSingleton().getExtensionFromMimeType(mime);
284 if (extension == null) {
285 extension = getExtensionFromUri(uri);
286 }
287 message.setRelativeFilePath(message.getUuid() + "." + extension);
288 copyFileToPrivateStorage(mXmppConnectionService.getFileBackend().getFile(message), uri);
289 }
290
291 private String getExtensionFromUri(Uri uri) {
292 String[] projection = {MediaStore.MediaColumns.DATA};
293 String filename = null;
294 Cursor cursor = mXmppConnectionService.getContentResolver().query(uri, projection, null, null, null);
295 if (cursor != null) {
296 try {
297 if (cursor.moveToFirst()) {
298 filename = cursor.getString(0);
299 }
300 } catch (Exception e) {
301 filename = null;
302 } finally {
303 cursor.close();
304 }
305 }
306 int pos = filename == null ? -1 : filename.lastIndexOf('.');
307 return pos > 0 ? filename.substring(pos+1) : null;
308 }
309
310 private void copyImageToPrivateStorage(File file, Uri image, int sampleSize) throws FileCopyException {
311 file.getParentFile().mkdirs();
312 InputStream is = null;
313 OutputStream os = null;
314 try {
315 if (!file.exists() && !file.createNewFile()) {
316 throw new FileCopyException(R.string.error_unable_to_create_temporary_file);
317 }
318 is = mXmppConnectionService.getContentResolver().openInputStream(image);
319 if (is == null) {
320 throw new FileCopyException(R.string.error_not_an_image_file);
321 }
322 Bitmap originalBitmap;
323 BitmapFactory.Options options = new BitmapFactory.Options();
324 int inSampleSize = (int) Math.pow(2, sampleSize);
325 Log.d(Config.LOGTAG, "reading bitmap with sample size " + inSampleSize);
326 options.inSampleSize = inSampleSize;
327 originalBitmap = BitmapFactory.decodeStream(is, null, options);
328 is.close();
329 if (originalBitmap == null) {
330 throw new FileCopyException(R.string.error_not_an_image_file);
331 }
332 Bitmap scaledBitmap = resize(originalBitmap, Config.IMAGE_SIZE);
333 int rotation = getRotation(image);
334 scaledBitmap = rotate(scaledBitmap, rotation);
335 boolean targetSizeReached = false;
336 int quality = Config.IMAGE_QUALITY;
337 while(!targetSizeReached) {
338 os = new FileOutputStream(file);
339 boolean success = scaledBitmap.compress(Config.IMAGE_FORMAT, quality, os);
340 if (!success) {
341 throw new FileCopyException(R.string.error_compressing_image);
342 }
343 os.flush();
344 targetSizeReached = file.length() <= Config.IMAGE_MAX_SIZE || quality <= 50;
345 quality -= 5;
346 }
347 scaledBitmap.recycle();
348 } catch (FileNotFoundException e) {
349 throw new FileCopyException(R.string.error_file_not_found);
350 } catch (IOException e) {
351 e.printStackTrace();
352 throw new FileCopyException(R.string.error_io_exception);
353 } catch (SecurityException e) {
354 throw new FileCopyException(R.string.error_security_exception_during_image_copy);
355 } catch (OutOfMemoryError e) {
356 ++sampleSize;
357 if (sampleSize <= 3) {
358 copyImageToPrivateStorage(file, image, sampleSize);
359 } else {
360 throw new FileCopyException(R.string.error_out_of_memory);
361 }
362 } finally {
363 close(os);
364 close(is);
365 }
366 }
367
368 public void copyImageToPrivateStorage(File file, Uri image) throws FileCopyException {
369 Log.d(Config.LOGTAG,"copy image ("+image.toString()+") to private storage "+file.getAbsolutePath());
370 copyImageToPrivateStorage(file, image, 0);
371 }
372
373 public void copyImageToPrivateStorage(Message message, Uri image) throws FileCopyException {
374 switch(Config.IMAGE_FORMAT) {
375 case JPEG:
376 message.setRelativeFilePath(message.getUuid()+".jpg");
377 break;
378 case PNG:
379 message.setRelativeFilePath(message.getUuid()+".png");
380 break;
381 case WEBP:
382 message.setRelativeFilePath(message.getUuid()+".webp");
383 break;
384 }
385 copyImageToPrivateStorage(getFile(message), image);
386 updateFileParams(message);
387 }
388
389 private int getRotation(File file) {
390 return getRotation(Uri.parse("file://"+file.getAbsolutePath()));
391 }
392
393 private int getRotation(Uri image) {
394 InputStream is = null;
395 try {
396 is = mXmppConnectionService.getContentResolver().openInputStream(image);
397 return ExifHelper.getOrientation(is);
398 } catch (FileNotFoundException e) {
399 return 0;
400 } finally {
401 close(is);
402 }
403 }
404
405 public Bitmap getThumbnail(Message message, int size, boolean cacheOnly) throws FileNotFoundException {
406 final String uuid = message.getUuid();
407 final LruCache<String,Bitmap> cache = mXmppConnectionService.getBitmapCache();
408 Bitmap thumbnail = cache.get(uuid);
409 if ((thumbnail == null) && (!cacheOnly)) {
410 synchronized (cache) {
411 thumbnail = cache.get(uuid);
412 if (thumbnail != null) {
413 return thumbnail;
414 }
415 DownloadableFile file = getFile(message);
416 final String mime = file.getMimeType();
417 if (mime.startsWith("video/")) {
418 thumbnail = getVideoPreview(file, size);
419 } else {
420 Bitmap fullsize = getFullsizeImagePreview(file, size);
421 if (fullsize == null) {
422 throw new FileNotFoundException();
423 }
424 thumbnail = resize(fullsize, size);
425 thumbnail = rotate(thumbnail, getRotation(file));
426 if (mime.equals("image/gif")) {
427 Bitmap withGifOverlay = thumbnail.copy(Bitmap.Config.ARGB_8888,true);
428 drawOverlay(withGifOverlay,R.drawable.play_gif,1.0f);
429 thumbnail.recycle();
430 thumbnail = withGifOverlay;
431 }
432 }
433 this.mXmppConnectionService.getBitmapCache().put(uuid, thumbnail);
434 }
435 }
436 return thumbnail;
437 }
438
439 private Bitmap getFullsizeImagePreview(File file, int size) {
440 BitmapFactory.Options options = new BitmapFactory.Options();
441 options.inSampleSize = calcSampleSize(file, size);
442 try {
443 return BitmapFactory.decodeFile(file.getAbsolutePath(), options);
444 } catch (OutOfMemoryError e) {
445 options.inSampleSize *= 2;
446 return BitmapFactory.decodeFile(file.getAbsolutePath(), options);
447 }
448 }
449
450 private void drawOverlay(Bitmap bitmap, int resource, float factor) {
451 Bitmap overlay = BitmapFactory.decodeResource(mXmppConnectionService.getResources(), resource);
452 Canvas canvas = new Canvas(bitmap);
453 Paint paint = new Paint();
454 paint.setAntiAlias(true);
455 paint.setFilterBitmap(true);
456 paint.setDither(true);
457 float targetSize = Math.min(canvas.getWidth(),canvas.getHeight()) * factor;
458 Log.d(Config.LOGTAG,"target size overlay: "+targetSize+" overlay bitmap size was "+overlay.getHeight());
459 float left = (canvas.getWidth() - targetSize) / 2.0f;
460 float top = (canvas.getHeight() - targetSize) / 2.0f;
461 RectF dst = new RectF(left,top,left+targetSize-1,top+targetSize-1);
462 canvas.drawBitmap(overlay,null,dst,paint);
463 }
464
465 private Bitmap getVideoPreview(File file, int size) {
466 MediaMetadataRetriever metadataRetriever = new MediaMetadataRetriever();
467 Bitmap frame;
468 try {
469 metadataRetriever.setDataSource(file.getAbsolutePath());
470 frame = metadataRetriever.getFrameAtTime(0);
471 metadataRetriever.release();
472 frame = resize(frame, size);
473 } catch(IllegalArgumentException | NullPointerException e) {
474 frame = Bitmap.createBitmap(size,size, Bitmap.Config.ARGB_8888);
475 frame.eraseColor(0xff000000);
476 }
477 drawOverlay(frame,R.drawable.play_video,0.75f);
478 return frame;
479 }
480
481 private static String getTakePhotoPath() {
482 return Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM)+"/Camera/";
483 }
484
485 public Uri getTakePhotoUri() {
486 File file;
487 if (Config.ONLY_INTERNAL_STORAGE) {
488 file = new File(mXmppConnectionService.getCacheDir().getAbsolutePath(), "Camera/IMG_" + this.IMAGE_DATE_FORMAT.format(new Date()) + ".jpg");
489 } else {
490 file = new File(getTakePhotoPath() + "IMG_" + this.IMAGE_DATE_FORMAT.format(new Date()) + ".jpg");
491 }
492 file.getParentFile().mkdirs();
493 return getUriForFile(mXmppConnectionService,file);
494 }
495
496 public static Uri getUriForFile(Context context, File file) {
497 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N || Config.ONLY_INTERNAL_STORAGE) {
498 try {
499 String packageId = context.getPackageName();
500 return FileProvider.getUriForFile(context, packageId + FILE_PROVIDER, file);
501 } catch(IllegalArgumentException e) {
502 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
503 throw new SecurityException();
504 } else {
505 return Uri.fromFile(file);
506 }
507 }
508 } else {
509 return Uri.fromFile(file);
510 }
511 }
512
513 public static Uri getIndexableTakePhotoUri(Uri original) {
514 if (Config.ONLY_INTERNAL_STORAGE || "file".equals(original.getScheme())) {
515 return original;
516 } else {
517 List<String> segments = original.getPathSegments();
518 return Uri.parse("file://"+getTakePhotoPath()+segments.get(segments.size() - 1));
519 }
520 }
521
522 public Avatar getPepAvatar(Uri image, int size, Bitmap.CompressFormat format) {
523 try {
524 Avatar avatar = new Avatar();
525 Bitmap bm = cropCenterSquare(image, size);
526 if (bm == null) {
527 return null;
528 }
529 ByteArrayOutputStream mByteArrayOutputStream = new ByteArrayOutputStream();
530 Base64OutputStream mBase64OutputStream = new Base64OutputStream(
531 mByteArrayOutputStream, Base64.DEFAULT);
532 MessageDigest digest = MessageDigest.getInstance("SHA-1");
533 DigestOutputStream mDigestOutputStream = new DigestOutputStream(
534 mBase64OutputStream, digest);
535 if (!bm.compress(format, 75, mDigestOutputStream)) {
536 return null;
537 }
538 mDigestOutputStream.flush();
539 mDigestOutputStream.close();
540 avatar.sha1sum = CryptoHelper.bytesToHex(digest.digest());
541 avatar.image = new String(mByteArrayOutputStream.toByteArray());
542 return avatar;
543 } catch (NoSuchAlgorithmException e) {
544 return null;
545 } catch (IOException e) {
546 return null;
547 }
548 }
549
550 public Avatar getStoredPepAvatar(String hash) {
551 if (hash == null) {
552 return null;
553 }
554 Avatar avatar = new Avatar();
555 File file = new File(getAvatarPath(hash));
556 FileInputStream is = null;
557 try {
558 avatar.size = file.length();
559 BitmapFactory.Options options = new BitmapFactory.Options();
560 options.inJustDecodeBounds = true;
561 BitmapFactory.decodeFile(file.getAbsolutePath(), options);
562 is = new FileInputStream(file);
563 ByteArrayOutputStream mByteArrayOutputStream = new ByteArrayOutputStream();
564 Base64OutputStream mBase64OutputStream = new Base64OutputStream(mByteArrayOutputStream, Base64.DEFAULT);
565 MessageDigest digest = MessageDigest.getInstance("SHA-1");
566 DigestOutputStream os = new DigestOutputStream(mBase64OutputStream, digest);
567 byte[] buffer = new byte[4096];
568 int length;
569 while ((length = is.read(buffer)) > 0) {
570 os.write(buffer, 0, length);
571 }
572 os.flush();
573 os.close();
574 avatar.sha1sum = CryptoHelper.bytesToHex(digest.digest());
575 avatar.image = new String(mByteArrayOutputStream.toByteArray());
576 avatar.height = options.outHeight;
577 avatar.width = options.outWidth;
578 avatar.type = options.outMimeType;
579 return avatar;
580 } catch (IOException e) {
581 return null;
582 } catch (NoSuchAlgorithmException e) {
583 return null;
584 } finally {
585 close(is);
586 }
587 }
588
589 public boolean isAvatarCached(Avatar avatar) {
590 File file = new File(getAvatarPath(avatar.getFilename()));
591 return file.exists();
592 }
593
594 public boolean save(Avatar avatar) {
595 File file;
596 if (isAvatarCached(avatar)) {
597 file = new File(getAvatarPath(avatar.getFilename()));
598 avatar.size = file.length();
599 } else {
600 String filename = getAvatarPath(avatar.getFilename());
601 file = new File(filename + ".tmp");
602 file.getParentFile().mkdirs();
603 OutputStream os = null;
604 try {
605 file.createNewFile();
606 os = new FileOutputStream(file);
607 MessageDigest digest = MessageDigest.getInstance("SHA-1");
608 digest.reset();
609 DigestOutputStream mDigestOutputStream = new DigestOutputStream(os, digest);
610 final byte[] bytes = avatar.getImageAsBytes();
611 mDigestOutputStream.write(bytes);
612 mDigestOutputStream.flush();
613 mDigestOutputStream.close();
614 String sha1sum = CryptoHelper.bytesToHex(digest.digest());
615 if (sha1sum.equals(avatar.sha1sum)) {
616 file.renameTo(new File(filename));
617 } else {
618 Log.d(Config.LOGTAG, "sha1sum mismatch for " + avatar.owner);
619 file.delete();
620 return false;
621 }
622 avatar.size = bytes.length;
623 } catch (IllegalArgumentException | IOException | NoSuchAlgorithmException e) {
624 return false;
625 } finally {
626 close(os);
627 }
628 }
629 return true;
630 }
631
632 public String getAvatarPath(String avatar) {
633 return mXmppConnectionService.getFilesDir().getAbsolutePath()+ "/avatars/" + avatar;
634 }
635
636 public Uri getAvatarUri(String avatar) {
637 return Uri.parse("file:" + getAvatarPath(avatar));
638 }
639
640 public Bitmap cropCenterSquare(Uri image, int size) {
641 if (image == null) {
642 return null;
643 }
644 InputStream is = null;
645 try {
646 BitmapFactory.Options options = new BitmapFactory.Options();
647 options.inSampleSize = calcSampleSize(image, size);
648 is = mXmppConnectionService.getContentResolver().openInputStream(image);
649 if (is == null) {
650 return null;
651 }
652 Bitmap input = BitmapFactory.decodeStream(is, null, options);
653 if (input == null) {
654 return null;
655 } else {
656 input = rotate(input, getRotation(image));
657 return cropCenterSquare(input, size);
658 }
659 } catch (SecurityException e) {
660 return null; // happens for example on Android 6.0 if contacts permissions get revoked
661 } catch (FileNotFoundException e) {
662 return null;
663 } finally {
664 close(is);
665 }
666 }
667
668 public Bitmap cropCenter(Uri image, int newHeight, int newWidth) {
669 if (image == null) {
670 return null;
671 }
672 InputStream is = null;
673 try {
674 BitmapFactory.Options options = new BitmapFactory.Options();
675 options.inSampleSize = calcSampleSize(image, Math.max(newHeight, newWidth));
676 is = mXmppConnectionService.getContentResolver().openInputStream(image);
677 if (is == null) {
678 return null;
679 }
680 Bitmap source = BitmapFactory.decodeStream(is, null, options);
681 if (source == null) {
682 return null;
683 }
684 int sourceWidth = source.getWidth();
685 int sourceHeight = source.getHeight();
686 float xScale = (float) newWidth / sourceWidth;
687 float yScale = (float) newHeight / sourceHeight;
688 float scale = Math.max(xScale, yScale);
689 float scaledWidth = scale * sourceWidth;
690 float scaledHeight = scale * sourceHeight;
691 float left = (newWidth - scaledWidth) / 2;
692 float top = (newHeight - scaledHeight) / 2;
693
694 RectF targetRect = new RectF(left, top, left + scaledWidth, top + scaledHeight);
695 Bitmap dest = Bitmap.createBitmap(newWidth, newHeight, Bitmap.Config.ARGB_8888);
696 Canvas canvas = new Canvas(dest);
697 canvas.drawBitmap(source, null, targetRect, null);
698 if (source.isRecycled()) {
699 source.recycle();
700 }
701 return dest;
702 } catch (SecurityException e) {
703 return null; //android 6.0 with revoked permissions for example
704 } catch (FileNotFoundException e) {
705 return null;
706 } finally {
707 close(is);
708 }
709 }
710
711 public Bitmap cropCenterSquare(Bitmap input, int size) {
712 int w = input.getWidth();
713 int h = input.getHeight();
714
715 float scale = Math.max((float) size / h, (float) size / w);
716
717 float outWidth = scale * w;
718 float outHeight = scale * h;
719 float left = (size - outWidth) / 2;
720 float top = (size - outHeight) / 2;
721 RectF target = new RectF(left, top, left + outWidth, top + outHeight);
722
723 Bitmap output = Bitmap.createBitmap(size, size, Bitmap.Config.ARGB_8888);
724 Canvas canvas = new Canvas(output);
725 canvas.drawBitmap(input, null, target, null);
726 if (input != null && !input.isRecycled()) {
727 input.recycle();
728 }
729 return output;
730 }
731
732 private int calcSampleSize(Uri image, int size) throws FileNotFoundException, SecurityException {
733 BitmapFactory.Options options = new BitmapFactory.Options();
734 options.inJustDecodeBounds = true;
735 BitmapFactory.decodeStream(mXmppConnectionService.getContentResolver().openInputStream(image), null, options);
736 return calcSampleSize(options, size);
737 }
738
739 private static int calcSampleSize(File image, int size) {
740 BitmapFactory.Options options = new BitmapFactory.Options();
741 options.inJustDecodeBounds = true;
742 BitmapFactory.decodeFile(image.getAbsolutePath(), options);
743 return calcSampleSize(options, size);
744 }
745
746 public static int calcSampleSize(BitmapFactory.Options options, int size) {
747 int height = options.outHeight;
748 int width = options.outWidth;
749 int inSampleSize = 1;
750
751 if (height > size || width > size) {
752 int halfHeight = height / 2;
753 int halfWidth = width / 2;
754
755 while ((halfHeight / inSampleSize) > size
756 && (halfWidth / inSampleSize) > size) {
757 inSampleSize *= 2;
758 }
759 }
760 return inSampleSize;
761 }
762
763 public void updateFileParams(Message message) {
764 updateFileParams(message,null);
765 }
766
767 public void updateFileParams(Message message, URL url) {
768 DownloadableFile file = getFile(message);
769 final String mime = file.getMimeType();
770 boolean image = message.getType() == Message.TYPE_IMAGE || (mime != null && mime.startsWith("image/"));
771 boolean video = mime != null && mime.startsWith("video/");
772 if (image || video) {
773 try {
774 Dimensions dimensions = image ? getImageDimensions(file) : getVideoDimensions(file);
775 if (url == null) {
776 message.setBody(Long.toString(file.getSize()) + '|' + dimensions.width + '|' + dimensions.height);
777 } else {
778 message.setBody(url.toString() + "|" + Long.toString(file.getSize()) + '|' + dimensions.width + '|' + dimensions.height);
779 }
780 return;
781 } catch (NotAVideoFile notAVideoFile) {
782 Log.d(Config.LOGTAG,"file with mime type "+file.getMimeType()+" was not a video file");
783 //fall threw
784 }
785 }
786 if (url != null) {
787 message.setBody(url.toString()+"|"+Long.toString(file.getSize()));
788 } else {
789 message.setBody(Long.toString(file.getSize()));
790 }
791
792 }
793
794 private Dimensions getImageDimensions(File file) {
795 BitmapFactory.Options options = new BitmapFactory.Options();
796 options.inJustDecodeBounds = true;
797 BitmapFactory.decodeFile(file.getAbsolutePath(), options);
798 int rotation = getRotation(file);
799 boolean rotated = rotation == 90 || rotation == 270;
800 int imageHeight = rotated ? options.outWidth : options.outHeight;
801 int imageWidth = rotated ? options.outHeight : options.outWidth;
802 return new Dimensions(imageHeight, imageWidth);
803 }
804
805 private Dimensions getVideoDimensions(File file) throws NotAVideoFile {
806 MediaMetadataRetriever metadataRetriever = new MediaMetadataRetriever();
807 try {
808 metadataRetriever.setDataSource(file.getAbsolutePath());
809 } catch (Exception e) {
810 throw new NotAVideoFile();
811 }
812 String hasVideo = metadataRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_HAS_VIDEO);
813 if (hasVideo == null) {
814 throw new NotAVideoFile();
815 }
816 int rotation = extractRotationFromMediaRetriever(metadataRetriever);
817 boolean rotated = rotation == 90 || rotation == 270;
818 int height;
819 try {
820 String h = metadataRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_HEIGHT);
821 height = Integer.parseInt(h);
822 } catch (Exception e) {
823 height = -1;
824 }
825 int width;
826 try {
827 String w = metadataRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_WIDTH);
828 width = Integer.parseInt(w);
829 } catch (Exception e) {
830 width = -1;
831 }
832 metadataRetriever.release();
833 Log.d(Config.LOGTAG,"extracted video dims "+width+"x"+height);
834 return rotated ? new Dimensions(width, height) : new Dimensions(height, width);
835 }
836
837 private int extractRotationFromMediaRetriever(MediaMetadataRetriever metadataRetriever) {
838 int rotation;
839 if (Build.VERSION.SDK_INT >= 17) {
840 String r = metadataRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_ROTATION);
841 try {
842 rotation = Integer.parseInt(r);
843 } catch (Exception e) {
844 rotation = 0;
845 }
846 } else {
847 rotation = 0;
848 }
849 return rotation;
850 }
851
852 private class Dimensions {
853 public final int width;
854 public final int height;
855
856 public Dimensions(int height, int width) {
857 this.width = width;
858 this.height = height;
859 }
860 }
861
862 private class NotAVideoFile extends Exception {
863
864 }
865
866 public class FileCopyException extends Exception {
867 private static final long serialVersionUID = -1010013599132881427L;
868 private int resId;
869
870 public FileCopyException(int resId) {
871 this.resId = resId;
872 }
873
874 public int getResId() {
875 return resId;
876 }
877 }
878
879 public Bitmap getAvatar(String avatar, int size) {
880 if (avatar == null) {
881 return null;
882 }
883 Bitmap bm = cropCenter(getAvatarUri(avatar), size, size);
884 if (bm == null) {
885 return null;
886 }
887 return bm;
888 }
889
890 public boolean isFileAvailable(Message message) {
891 return getFile(message).exists();
892 }
893
894 public static void close(Closeable stream) {
895 if (stream != null) {
896 try {
897 stream.close();
898 } catch (IOException e) {
899 }
900 }
901 }
902
903 public static void close(Socket socket) {
904 if (socket != null) {
905 try {
906 socket.close();
907 } catch (IOException e) {
908 }
909 }
910 }
911
912
913 public static boolean weOwnFile(Context context, Uri uri) {
914 if (uri == null || !ContentResolver.SCHEME_FILE.equals(uri.getScheme())) {
915 return false;
916 } else if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
917 return fileIsInFilesDir(context, uri);
918 } else {
919 return weOwnFileLollipop(uri);
920 }
921 }
922
923
924 /**
925 * This is more than hacky but probably way better than doing nothing
926 * Further 'optimizations' might contain to get the parents of CacheDir and NoBackupDir
927 * and check against those as well
928 */
929 private static boolean fileIsInFilesDir(Context context, Uri uri) {
930 try {
931 final String haystack = context.getFilesDir().getParentFile().getCanonicalPath();
932 final String needle = new File(uri.getPath()).getCanonicalPath();
933 return needle.startsWith(haystack);
934 } catch (IOException e) {
935 return false;
936 }
937 }
938
939 @TargetApi(Build.VERSION_CODES.LOLLIPOP)
940 private static boolean weOwnFileLollipop(Uri uri) {
941 try {
942 File file = new File(uri.getPath());
943 FileDescriptor fd = ParcelFileDescriptor.open(file, ParcelFileDescriptor.MODE_READ_ONLY).getFileDescriptor();
944 StructStat st = Os.fstat(fd);
945 return st.st_uid == android.os.Process.myUid();
946 } catch (FileNotFoundException e) {
947 return false;
948 } catch (Exception e) {
949 return true;
950 }
951 }
952}