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