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.RectF;
13import android.net.Uri;
14import android.os.Build;
15import android.os.Environment;
16import android.os.ParcelFileDescriptor;
17import android.provider.OpenableColumns;
18import android.system.Os;
19import android.system.StructStat;
20import android.util.Base64;
21import android.util.Base64OutputStream;
22import android.util.Log;
23import android.util.LruCache;
24import android.webkit.MimeTypeMap;
25
26import java.io.ByteArrayOutputStream;
27import java.io.Closeable;
28import java.io.File;
29import java.io.FileDescriptor;
30import java.io.FileInputStream;
31import java.io.FileNotFoundException;
32import java.io.FileOutputStream;
33import java.io.IOException;
34import java.io.InputStream;
35import java.io.OutputStream;
36import java.net.Socket;
37import java.net.URL;
38import java.security.DigestOutputStream;
39import java.security.MessageDigest;
40import java.security.NoSuchAlgorithmException;
41import java.text.SimpleDateFormat;
42import java.util.Date;
43import java.util.List;
44import java.util.Locale;
45
46import eu.siacs.conversations.Config;
47import eu.siacs.conversations.R;
48import eu.siacs.conversations.entities.DownloadableFile;
49import eu.siacs.conversations.entities.Message;
50import eu.siacs.conversations.services.XmppConnectionService;
51import eu.siacs.conversations.utils.CryptoHelper;
52import eu.siacs.conversations.utils.ExifHelper;
53import eu.siacs.conversations.utils.FileUtils;
54import eu.siacs.conversations.xmpp.pep.Avatar;
55
56public class FileBackend {
57 private final SimpleDateFormat imageDateFormat = new SimpleDateFormat("yyyyMMdd_HHmmssSSS", Locale.US);
58
59 private XmppConnectionService mXmppConnectionService;
60
61 public FileBackend(XmppConnectionService service) {
62 this.mXmppConnectionService = service;
63 }
64
65 private void createNoMedia() {
66 final File nomedia = new File(getConversationsFileDirectory()+".nomedia");
67 if (!nomedia.exists()) {
68 try {
69 nomedia.createNewFile();
70 } catch (Exception e) {
71 Log.d(Config.LOGTAG, "could not create nomedia file");
72 }
73 }
74 }
75
76 public void updateMediaScanner(File file) {
77 if (file.getAbsolutePath().startsWith(getConversationsImageDirectory())) {
78 Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
79 intent.setData(Uri.fromFile(file));
80 mXmppConnectionService.sendBroadcast(intent);
81 } else {
82 createNoMedia();
83 }
84 }
85
86 public boolean deleteFile(Message message) {
87 File file = getFile(message);
88 if (file.delete()) {
89 updateMediaScanner(file);
90 return true;
91 } else {
92 return false;
93 }
94 }
95
96 public DownloadableFile getFile(Message message) {
97 return getFile(message, true);
98 }
99
100 public DownloadableFile getFile(Message message, boolean decrypted) {
101 final boolean encrypted = !decrypted
102 && (message.getEncryption() == Message.ENCRYPTION_PGP
103 || message.getEncryption() == Message.ENCRYPTION_DECRYPTED);
104 final DownloadableFile file;
105 String path = message.getRelativeFilePath();
106 if (path == null) {
107 path = message.getUuid();
108 }
109 if (path.startsWith("/")) {
110 file = new DownloadableFile(path);
111 } else {
112 String mime = message.getMimeType();
113 if (mime != null && mime.startsWith("image")) {
114 file = new DownloadableFile(getConversationsImageDirectory() + path);
115 } else {
116 file = new DownloadableFile(getConversationsFileDirectory() + path);
117 }
118 }
119 if (encrypted) {
120 return new DownloadableFile(getConversationsFileDirectory() + file.getName() + ".pgp");
121 } else {
122 return file;
123 }
124 }
125
126 private static long getFileSize(Context context, Uri uri) {
127 Cursor cursor = context.getContentResolver().query(uri, null, null, null, null);
128 if (cursor != null && cursor.moveToFirst()) {
129 return cursor.getLong(cursor.getColumnIndex(OpenableColumns.SIZE));
130 } else {
131 return -1;
132 }
133 }
134
135 public static boolean allFilesUnderSize(Context context, List<Uri> uris, long max) {
136 if (max <= 0) {
137 return true; //exception to be compatible with HTTP Upload < v0.2
138 }
139 for(Uri uri : uris) {
140 if (FileBackend.getFileSize(context, uri) > max) {
141 return false;
142 }
143 }
144 return true;
145 }
146
147 public static String getConversationsFileDirectory() {
148 return Environment.getExternalStorageDirectory().getAbsolutePath()+"/Conversations/";
149 }
150
151 public static String getConversationsImageDirectory() {
152 return Environment.getExternalStoragePublicDirectory(
153 Environment.DIRECTORY_PICTURES).getAbsolutePath()
154 + "/Conversations/";
155 }
156
157 public Bitmap resize(Bitmap originalBitmap, int size) {
158 int w = originalBitmap.getWidth();
159 int h = originalBitmap.getHeight();
160 if (Math.max(w, h) > size) {
161 int scalledW;
162 int scalledH;
163 if (w <= h) {
164 scalledW = (int) (w / ((double) h / size));
165 scalledH = size;
166 } else {
167 scalledW = size;
168 scalledH = (int) (h / ((double) w / size));
169 }
170 Bitmap result = Bitmap.createScaledBitmap(originalBitmap, scalledW, scalledH, true);
171 if (originalBitmap != null && !originalBitmap.isRecycled()) {
172 originalBitmap.recycle();
173 }
174 return result;
175 } else {
176 return originalBitmap;
177 }
178 }
179
180 public static Bitmap rotate(Bitmap bitmap, int degree) {
181 if (degree == 0) {
182 return bitmap;
183 }
184 int w = bitmap.getWidth();
185 int h = bitmap.getHeight();
186 Matrix mtx = new Matrix();
187 mtx.postRotate(degree);
188 Bitmap result = Bitmap.createBitmap(bitmap, 0, 0, w, h, mtx, true);
189 if (bitmap != null && !bitmap.isRecycled()) {
190 bitmap.recycle();
191 }
192 return result;
193 }
194
195 public boolean useImageAsIs(Uri uri) {
196 String path = getOriginalPath(uri);
197 if (path == null) {
198 return false;
199 }
200 File file = new File(path);
201 long size = file.length();
202 if (size == 0 || size >= Config.IMAGE_MAX_SIZE ) {
203 return false;
204 }
205 BitmapFactory.Options options = new BitmapFactory.Options();
206 options.inJustDecodeBounds = true;
207 try {
208 BitmapFactory.decodeStream(mXmppConnectionService.getContentResolver().openInputStream(uri), null, options);
209 if (options == null || options.outMimeType == null || options.outHeight <= 0 || options.outWidth <= 0) {
210 return false;
211 }
212 return (options.outWidth <= Config.IMAGE_SIZE && options.outHeight <= Config.IMAGE_SIZE && options.outMimeType.contains(Config.IMAGE_FORMAT.name().toLowerCase()));
213 } catch (FileNotFoundException e) {
214 return false;
215 }
216 }
217
218 public String getOriginalPath(Uri uri) {
219 return FileUtils.getPath(mXmppConnectionService,uri);
220 }
221
222 public void copyFileToPrivateStorage(File file, Uri uri) throws FileCopyException {
223 file.getParentFile().mkdirs();
224 OutputStream os = null;
225 InputStream is = null;
226 try {
227 file.createNewFile();
228 os = new FileOutputStream(file);
229 is = mXmppConnectionService.getContentResolver().openInputStream(uri);
230 byte[] buffer = new byte[1024];
231 int length;
232 while ((length = is.read(buffer)) > 0) {
233 os.write(buffer, 0, length);
234 }
235 os.flush();
236 } catch(FileNotFoundException e) {
237 throw new FileCopyException(R.string.error_file_not_found);
238 } catch (IOException e) {
239 e.printStackTrace();
240 throw new FileCopyException(R.string.error_io_exception);
241 } finally {
242 close(os);
243 close(is);
244 }
245 Log.d(Config.LOGTAG, "output file name " + file.getAbsolutePath());
246 }
247
248 public void copyFileToPrivateStorage(Message message, Uri uri) throws FileCopyException {
249 Log.d(Config.LOGTAG, "copy " + uri.toString() + " to private storage");
250 String mime = mXmppConnectionService.getContentResolver().getType(uri);
251 String extension = MimeTypeMap.getSingleton().getExtensionFromMimeType(mime);
252 message.setRelativeFilePath(message.getUuid() + "." + extension);
253 copyFileToPrivateStorage(mXmppConnectionService.getFileBackend().getFile(message), uri);
254 }
255
256 private void copyImageToPrivateStorage(File file, Uri image, int sampleSize) throws FileCopyException {
257 file.getParentFile().mkdirs();
258 InputStream is = null;
259 OutputStream os = null;
260 try {
261 file.createNewFile();
262 is = mXmppConnectionService.getContentResolver().openInputStream(image);
263 Bitmap originalBitmap;
264 BitmapFactory.Options options = new BitmapFactory.Options();
265 int inSampleSize = (int) Math.pow(2, sampleSize);
266 Log.d(Config.LOGTAG, "reading bitmap with sample size " + inSampleSize);
267 options.inSampleSize = inSampleSize;
268 originalBitmap = BitmapFactory.decodeStream(is, null, options);
269 is.close();
270 if (originalBitmap == null) {
271 throw new FileCopyException(R.string.error_not_an_image_file);
272 }
273 Bitmap scaledBitmap = resize(originalBitmap, Config.IMAGE_SIZE);
274 int rotation = getRotation(image);
275 scaledBitmap = rotate(scaledBitmap, rotation);
276 boolean targetSizeReached = false;
277 int quality = Config.IMAGE_QUALITY;
278 while(!targetSizeReached) {
279 os = new FileOutputStream(file);
280 boolean success = scaledBitmap.compress(Config.IMAGE_FORMAT, quality, os);
281 if (!success) {
282 throw new FileCopyException(R.string.error_compressing_image);
283 }
284 os.flush();
285 targetSizeReached = file.length() <= Config.IMAGE_MAX_SIZE || quality <= 50;
286 quality -= 5;
287 }
288 scaledBitmap.recycle();
289 return;
290 } catch (FileNotFoundException e) {
291 throw new FileCopyException(R.string.error_file_not_found);
292 } catch (IOException e) {
293 e.printStackTrace();
294 throw new FileCopyException(R.string.error_io_exception);
295 } catch (SecurityException e) {
296 throw new FileCopyException(R.string.error_security_exception_during_image_copy);
297 } catch (OutOfMemoryError e) {
298 ++sampleSize;
299 if (sampleSize <= 3) {
300 copyImageToPrivateStorage(file, image, sampleSize);
301 } else {
302 throw new FileCopyException(R.string.error_out_of_memory);
303 }
304 } catch (NullPointerException e) {
305 throw new FileCopyException(R.string.error_io_exception);
306 } finally {
307 close(os);
308 close(is);
309 }
310 }
311
312 public void copyImageToPrivateStorage(File file, Uri image) throws FileCopyException {
313 copyImageToPrivateStorage(file, image, 0);
314 }
315
316 public void copyImageToPrivateStorage(Message message, Uri image) throws FileCopyException {
317 switch(Config.IMAGE_FORMAT) {
318 case JPEG:
319 message.setRelativeFilePath(message.getUuid()+".jpg");
320 break;
321 case PNG:
322 message.setRelativeFilePath(message.getUuid()+".png");
323 break;
324 case WEBP:
325 message.setRelativeFilePath(message.getUuid()+".webp");
326 break;
327 }
328 copyImageToPrivateStorage(getFile(message), image);
329 updateFileParams(message);
330 }
331
332 private int getRotation(File file) {
333 return getRotation(Uri.parse("file://"+file.getAbsolutePath()));
334 }
335
336 private int getRotation(Uri image) {
337 InputStream is = null;
338 try {
339 is = mXmppConnectionService.getContentResolver().openInputStream(image);
340 return ExifHelper.getOrientation(is);
341 } catch (FileNotFoundException e) {
342 return 0;
343 } finally {
344 close(is);
345 }
346 }
347
348 public Bitmap getThumbnail(Message message, int size, boolean cacheOnly) throws FileNotFoundException {
349 final String uuid = message.getUuid();
350 final LruCache<String,Bitmap> cache = mXmppConnectionService.getBitmapCache();
351 Bitmap thumbnail = cache.get(uuid);
352 if ((thumbnail == null) && (!cacheOnly)) {
353 synchronized (cache) {
354 thumbnail = cache.get(uuid);
355 if (thumbnail != null) {
356 return thumbnail;
357 }
358 File file = getFile(message);
359 BitmapFactory.Options options = new BitmapFactory.Options();
360 options.inSampleSize = calcSampleSize(file, size);
361 Bitmap fullsize = BitmapFactory.decodeFile(file.getAbsolutePath(), options);
362 if (fullsize == null) {
363 throw new FileNotFoundException();
364 }
365 thumbnail = resize(fullsize, size);
366 thumbnail = rotate(thumbnail, getRotation(file));
367 this.mXmppConnectionService.getBitmapCache().put(uuid, thumbnail);
368 }
369 }
370 return thumbnail;
371 }
372
373 public Uri getTakePhotoUri() {
374 StringBuilder pathBuilder = new StringBuilder();
375 pathBuilder.append(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM));
376 pathBuilder.append('/');
377 pathBuilder.append("Camera");
378 pathBuilder.append('/');
379 pathBuilder.append("IMG_" + this.imageDateFormat.format(new Date()) + ".jpg");
380 Uri uri = Uri.parse("file://" + pathBuilder.toString());
381 File file = new File(uri.toString());
382 file.getParentFile().mkdirs();
383 return uri;
384 }
385
386 public Avatar getPepAvatar(Uri image, int size, Bitmap.CompressFormat format) {
387 try {
388 Avatar avatar = new Avatar();
389 Bitmap bm = cropCenterSquare(image, size);
390 if (bm == null) {
391 return null;
392 }
393 ByteArrayOutputStream mByteArrayOutputStream = new ByteArrayOutputStream();
394 Base64OutputStream mBase64OutputSttream = new Base64OutputStream(
395 mByteArrayOutputStream, Base64.DEFAULT);
396 MessageDigest digest = MessageDigest.getInstance("SHA-1");
397 DigestOutputStream mDigestOutputStream = new DigestOutputStream(
398 mBase64OutputSttream, digest);
399 if (!bm.compress(format, 75, mDigestOutputStream)) {
400 return null;
401 }
402 mDigestOutputStream.flush();
403 mDigestOutputStream.close();
404 avatar.sha1sum = CryptoHelper.bytesToHex(digest.digest());
405 avatar.image = new String(mByteArrayOutputStream.toByteArray());
406 return avatar;
407 } catch (NoSuchAlgorithmException e) {
408 return null;
409 } catch (IOException e) {
410 return null;
411 }
412 }
413
414 public Avatar getStoredPepAvatar(String hash) {
415 if (hash == null) {
416 return null;
417 }
418 Avatar avatar = new Avatar();
419 File file = new File(getAvatarPath(hash));
420 FileInputStream is = null;
421 try {
422 BitmapFactory.Options options = new BitmapFactory.Options();
423 options.inJustDecodeBounds = true;
424 BitmapFactory.decodeFile(file.getAbsolutePath(), options);
425 is = new FileInputStream(file);
426 ByteArrayOutputStream mByteArrayOutputStream = new ByteArrayOutputStream();
427 Base64OutputStream mBase64OutputStream = new Base64OutputStream(mByteArrayOutputStream, Base64.DEFAULT);
428 MessageDigest digest = MessageDigest.getInstance("SHA-1");
429 DigestOutputStream os = new DigestOutputStream(mBase64OutputStream, digest);
430 byte[] buffer = new byte[4096];
431 int length;
432 while ((length = is.read(buffer)) > 0) {
433 os.write(buffer, 0, length);
434 }
435 os.flush();
436 os.close();
437 avatar.sha1sum = CryptoHelper.bytesToHex(digest.digest());
438 avatar.image = new String(mByteArrayOutputStream.toByteArray());
439 avatar.height = options.outHeight;
440 avatar.width = options.outWidth;
441 return avatar;
442 } catch (IOException e) {
443 return null;
444 } catch (NoSuchAlgorithmException e) {
445 return null;
446 } finally {
447 close(is);
448 }
449 }
450
451 public boolean isAvatarCached(Avatar avatar) {
452 File file = new File(getAvatarPath(avatar.getFilename()));
453 return file.exists();
454 }
455
456 public boolean save(Avatar avatar) {
457 File file;
458 if (isAvatarCached(avatar)) {
459 file = new File(getAvatarPath(avatar.getFilename()));
460 } else {
461 String filename = getAvatarPath(avatar.getFilename());
462 file = new File(filename + ".tmp");
463 file.getParentFile().mkdirs();
464 OutputStream os = null;
465 try {
466 file.createNewFile();
467 os = new FileOutputStream(file);
468 MessageDigest digest = MessageDigest.getInstance("SHA-1");
469 digest.reset();
470 DigestOutputStream mDigestOutputStream = new DigestOutputStream(os, digest);
471 mDigestOutputStream.write(avatar.getImageAsBytes());
472 mDigestOutputStream.flush();
473 mDigestOutputStream.close();
474 String sha1sum = CryptoHelper.bytesToHex(digest.digest());
475 if (sha1sum.equals(avatar.sha1sum)) {
476 file.renameTo(new File(filename));
477 } else {
478 Log.d(Config.LOGTAG, "sha1sum mismatch for " + avatar.owner);
479 file.delete();
480 return false;
481 }
482 } catch (IllegalArgumentException | IOException | NoSuchAlgorithmException e) {
483 return false;
484 } finally {
485 close(os);
486 }
487 }
488 avatar.size = file.length();
489 return true;
490 }
491
492 public String getAvatarPath(String avatar) {
493 return mXmppConnectionService.getFilesDir().getAbsolutePath()+ "/avatars/" + avatar;
494 }
495
496 public Uri getAvatarUri(String avatar) {
497 return Uri.parse("file:" + getAvatarPath(avatar));
498 }
499
500 public Bitmap cropCenterSquare(Uri image, int size) {
501 if (image == null) {
502 return null;
503 }
504 InputStream is = null;
505 try {
506 BitmapFactory.Options options = new BitmapFactory.Options();
507 options.inSampleSize = calcSampleSize(image, size);
508 is = mXmppConnectionService.getContentResolver().openInputStream(image);
509 if (is == null) {
510 return null;
511 }
512 Bitmap input = BitmapFactory.decodeStream(is, null, options);
513 if (input == null) {
514 return null;
515 } else {
516 input = rotate(input, getRotation(image));
517 return cropCenterSquare(input, size);
518 }
519 } catch (SecurityException e) {
520 return null; // happens for example on Android 6.0 if contacts permissions get revoked
521 } catch (FileNotFoundException e) {
522 return null;
523 } finally {
524 close(is);
525 }
526 }
527
528 public Bitmap cropCenter(Uri image, int newHeight, int newWidth) {
529 if (image == null) {
530 return null;
531 }
532 InputStream is = null;
533 try {
534 BitmapFactory.Options options = new BitmapFactory.Options();
535 options.inSampleSize = calcSampleSize(image, Math.max(newHeight, newWidth));
536 is = mXmppConnectionService.getContentResolver().openInputStream(image);
537 if (is == null) {
538 return null;
539 }
540 Bitmap source = BitmapFactory.decodeStream(is, null, options);
541 if (source == null) {
542 return null;
543 }
544 int sourceWidth = source.getWidth();
545 int sourceHeight = source.getHeight();
546 float xScale = (float) newWidth / sourceWidth;
547 float yScale = (float) newHeight / sourceHeight;
548 float scale = Math.max(xScale, yScale);
549 float scaledWidth = scale * sourceWidth;
550 float scaledHeight = scale * sourceHeight;
551 float left = (newWidth - scaledWidth) / 2;
552 float top = (newHeight - scaledHeight) / 2;
553
554 RectF targetRect = new RectF(left, top, left + scaledWidth, top + scaledHeight);
555 Bitmap dest = Bitmap.createBitmap(newWidth, newHeight, Bitmap.Config.ARGB_8888);
556 Canvas canvas = new Canvas(dest);
557 canvas.drawBitmap(source, null, targetRect, null);
558 if (source != null && !source.isRecycled()) {
559 source.recycle();
560 }
561 return dest;
562 } catch (SecurityException e) {
563 return null; //android 6.0 with revoked permissions for example
564 } catch (FileNotFoundException e) {
565 return null;
566 } finally {
567 close(is);
568 }
569 }
570
571 public Bitmap cropCenterSquare(Bitmap input, int size) {
572 int w = input.getWidth();
573 int h = input.getHeight();
574
575 float scale = Math.max((float) size / h, (float) size / w);
576
577 float outWidth = scale * w;
578 float outHeight = scale * h;
579 float left = (size - outWidth) / 2;
580 float top = (size - outHeight) / 2;
581 RectF target = new RectF(left, top, left + outWidth, top + outHeight);
582
583 Bitmap output = Bitmap.createBitmap(size, size, Bitmap.Config.ARGB_8888);
584 Canvas canvas = new Canvas(output);
585 canvas.drawBitmap(input, null, target, null);
586 if (input != null && !input.isRecycled()) {
587 input.recycle();
588 }
589 return output;
590 }
591
592 private int calcSampleSize(Uri image, int size) throws FileNotFoundException, SecurityException {
593 BitmapFactory.Options options = new BitmapFactory.Options();
594 options.inJustDecodeBounds = true;
595 BitmapFactory.decodeStream(mXmppConnectionService.getContentResolver().openInputStream(image), null, options);
596 return calcSampleSize(options, size);
597 }
598
599 private static int calcSampleSize(File image, int size) {
600 BitmapFactory.Options options = new BitmapFactory.Options();
601 options.inJustDecodeBounds = true;
602 BitmapFactory.decodeFile(image.getAbsolutePath(), options);
603 return calcSampleSize(options, size);
604 }
605
606 public static int calcSampleSize(BitmapFactory.Options options, int size) {
607 int height = options.outHeight;
608 int width = options.outWidth;
609 int inSampleSize = 1;
610
611 if (height > size || width > size) {
612 int halfHeight = height / 2;
613 int halfWidth = width / 2;
614
615 while ((halfHeight / inSampleSize) > size
616 && (halfWidth / inSampleSize) > size) {
617 inSampleSize *= 2;
618 }
619 }
620 return inSampleSize;
621 }
622
623 public Uri getJingleFileUri(Message message) {
624 File file = getFile(message);
625 return Uri.parse("file://" + file.getAbsolutePath());
626 }
627
628 public void updateFileParams(Message message) {
629 updateFileParams(message,null);
630 }
631
632 public void updateFileParams(Message message, URL url) {
633 DownloadableFile file = getFile(message);
634 if (message.getType() == Message.TYPE_IMAGE || file.getMimeType().startsWith("image/")) {
635 BitmapFactory.Options options = new BitmapFactory.Options();
636 options.inJustDecodeBounds = true;
637 BitmapFactory.decodeFile(file.getAbsolutePath(), options);
638 int rotation = getRotation(file);
639 boolean rotated = rotation == 90 || rotation == 270;
640 int imageHeight = rotated ? options.outWidth : options.outHeight;
641 int imageWidth = rotated ? options.outHeight : options.outWidth;
642 if (url == null) {
643 message.setBody(Long.toString(file.getSize()) + '|' + imageWidth + '|' + imageHeight);
644 } else {
645 message.setBody(url.toString()+"|"+Long.toString(file.getSize()) + '|' + imageWidth + '|' + imageHeight);
646 }
647 } else {
648 if (url != null) {
649 message.setBody(url.toString()+"|"+Long.toString(file.getSize()));
650 } else {
651 message.setBody(Long.toString(file.getSize()));
652 }
653 }
654
655 }
656
657 public class FileCopyException extends Exception {
658 private static final long serialVersionUID = -1010013599132881427L;
659 private int resId;
660
661 public FileCopyException(int resId) {
662 this.resId = resId;
663 }
664
665 public int getResId() {
666 return resId;
667 }
668 }
669
670 public Bitmap getAvatar(String avatar, int size) {
671 if (avatar == null) {
672 return null;
673 }
674 Bitmap bm = cropCenter(getAvatarUri(avatar), size, size);
675 if (bm == null) {
676 return null;
677 }
678 return bm;
679 }
680
681 public boolean isFileAvailable(Message message) {
682 return getFile(message).exists();
683 }
684
685 public static void close(Closeable stream) {
686 if (stream != null) {
687 try {
688 stream.close();
689 } catch (IOException e) {
690 }
691 }
692 }
693
694 public static void close(Socket socket) {
695 if (socket != null) {
696 try {
697 socket.close();
698 } catch (IOException e) {
699 }
700 }
701 }
702
703
704 public static boolean weOwnFile(Context context, Uri uri) {
705 if (uri == null || !ContentResolver.SCHEME_FILE.equals(uri.getScheme())) {
706 return false;
707 } else if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
708 return fileIsInFilesDir(context, uri);
709 } else {
710 return weOwnFileLollipop(uri);
711 }
712 }
713
714
715 /**
716 * This is more than hacky but probably way better than doing nothing
717 * Further 'optimizations' might contain to get the parents of CacheDir and NoBackupDir
718 * and check against those as well
719 */
720 private static boolean fileIsInFilesDir(Context context, Uri uri) {
721 try {
722 final String haystack = context.getFilesDir().getParentFile().getCanonicalPath();
723 final String needle = new File(uri.getPath()).getCanonicalPath();
724 return needle.startsWith(haystack);
725 } catch (IOException e) {
726 return false;
727 }
728 }
729
730 @TargetApi(Build.VERSION_CODES.LOLLIPOP)
731 private static boolean weOwnFileLollipop(Uri uri) {
732 try {
733 File file = new File(uri.getPath());
734 FileDescriptor fd = ParcelFileDescriptor.open(file, ParcelFileDescriptor.MODE_READ_ONLY).getFileDescriptor();
735 StructStat st = Os.fstat(fd);
736 return st.st_uid == android.os.Process.myUid();
737 } catch (FileNotFoundException e) {
738 return false;
739 } catch (Exception e) {
740 return true;
741 }
742 }
743}