FileBackend.java

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