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.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		Log.d(Config.LOGTAG,"get thumbnail for "+uuid+" cacheOnly="+Boolean.toString(cacheOnly));
352		Bitmap thumbnail = cache.get(uuid);
353		if ((thumbnail == null) && (!cacheOnly)) {
354			synchronized (cache) {
355				thumbnail = cache.get(uuid);
356				if (thumbnail != null) {
357					return thumbnail;
358				}
359				File file = getFile(message);
360				BitmapFactory.Options options = new BitmapFactory.Options();
361				options.inSampleSize = calcSampleSize(file, size);
362				Bitmap fullsize = BitmapFactory.decodeFile(file.getAbsolutePath(), options);
363				if (fullsize == null) {
364					throw new FileNotFoundException();
365				}
366				thumbnail = resize(fullsize, size);
367				thumbnail = rotate(thumbnail, getRotation(file));
368				this.mXmppConnectionService.getBitmapCache().put(uuid, thumbnail);
369			}
370		}
371		return thumbnail;
372	}
373
374	public Uri getTakePhotoUri() {
375		StringBuilder pathBuilder = new StringBuilder();
376		pathBuilder.append(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM));
377		pathBuilder.append('/');
378		pathBuilder.append("Camera");
379		pathBuilder.append('/');
380		pathBuilder.append("IMG_" + this.imageDateFormat.format(new Date()) + ".jpg");
381		Uri uri = Uri.parse("file://" + pathBuilder.toString());
382		File file = new File(uri.toString());
383		file.getParentFile().mkdirs();
384		return uri;
385	}
386
387	public Avatar getPepAvatar(Uri image, int size, Bitmap.CompressFormat format) {
388		try {
389			Avatar avatar = new Avatar();
390			Bitmap bm = cropCenterSquare(image, size);
391			if (bm == null) {
392				return null;
393			}
394			ByteArrayOutputStream mByteArrayOutputStream = new ByteArrayOutputStream();
395			Base64OutputStream mBase64OutputSttream = new Base64OutputStream(
396					mByteArrayOutputStream, Base64.DEFAULT);
397			MessageDigest digest = MessageDigest.getInstance("SHA-1");
398			DigestOutputStream mDigestOutputStream = new DigestOutputStream(
399					mBase64OutputSttream, digest);
400			if (!bm.compress(format, 75, mDigestOutputStream)) {
401				return null;
402			}
403			mDigestOutputStream.flush();
404			mDigestOutputStream.close();
405			avatar.sha1sum = CryptoHelper.bytesToHex(digest.digest());
406			avatar.image = new String(mByteArrayOutputStream.toByteArray());
407			return avatar;
408		} catch (NoSuchAlgorithmException e) {
409			return null;
410		} catch (IOException e) {
411			return null;
412		}
413	}
414
415	public Avatar getStoredPepAvatar(String hash) {
416		if (hash == null) {
417			return null;
418		}
419		Avatar avatar = new Avatar();
420		File file = new File(getAvatarPath(hash));
421		FileInputStream is = null;
422		try {
423			BitmapFactory.Options options = new BitmapFactory.Options();
424			options.inJustDecodeBounds = true;
425			BitmapFactory.decodeFile(file.getAbsolutePath(), options);
426			is = new FileInputStream(file);
427			ByteArrayOutputStream mByteArrayOutputStream = new ByteArrayOutputStream();
428			Base64OutputStream mBase64OutputStream = new Base64OutputStream(mByteArrayOutputStream, Base64.DEFAULT);
429			MessageDigest digest = MessageDigest.getInstance("SHA-1");
430			DigestOutputStream os = new DigestOutputStream(mBase64OutputStream, digest);
431			byte[] buffer = new byte[4096];
432			int length;
433			while ((length = is.read(buffer)) > 0) {
434				os.write(buffer, 0, length);
435			}
436			os.flush();
437			os.close();
438			avatar.sha1sum = CryptoHelper.bytesToHex(digest.digest());
439			avatar.image = new String(mByteArrayOutputStream.toByteArray());
440			avatar.height = options.outHeight;
441			avatar.width = options.outWidth;
442			return avatar;
443		} catch (IOException e) {
444			return null;
445		} catch (NoSuchAlgorithmException e) {
446			return null;
447		} finally {
448			close(is);
449		}
450	}
451
452	public boolean isAvatarCached(Avatar avatar) {
453		File file = new File(getAvatarPath(avatar.getFilename()));
454		return file.exists();
455	}
456
457	public boolean save(Avatar avatar) {
458		File file;
459		if (isAvatarCached(avatar)) {
460			file = new File(getAvatarPath(avatar.getFilename()));
461		} else {
462			String filename = getAvatarPath(avatar.getFilename());
463			file = new File(filename + ".tmp");
464			file.getParentFile().mkdirs();
465			OutputStream os = null;
466			try {
467				file.createNewFile();
468				os = new FileOutputStream(file);
469				MessageDigest digest = MessageDigest.getInstance("SHA-1");
470				digest.reset();
471				DigestOutputStream mDigestOutputStream = new DigestOutputStream(os, digest);
472				mDigestOutputStream.write(avatar.getImageAsBytes());
473				mDigestOutputStream.flush();
474				mDigestOutputStream.close();
475				String sha1sum = CryptoHelper.bytesToHex(digest.digest());
476				if (sha1sum.equals(avatar.sha1sum)) {
477					file.renameTo(new File(filename));
478				} else {
479					Log.d(Config.LOGTAG, "sha1sum mismatch for " + avatar.owner);
480					file.delete();
481					return false;
482				}
483			} catch (IllegalArgumentException | IOException | NoSuchAlgorithmException e) {
484				return false;
485			} finally {
486				close(os);
487			}
488		}
489		avatar.size = file.length();
490		return true;
491	}
492
493	public String getAvatarPath(String avatar) {
494		return mXmppConnectionService.getFilesDir().getAbsolutePath()+ "/avatars/" + avatar;
495	}
496
497	public Uri getAvatarUri(String avatar) {
498		return Uri.parse("file:" + getAvatarPath(avatar));
499	}
500
501	public Bitmap cropCenterSquare(Uri image, int size) {
502		if (image == null) {
503			return null;
504		}
505		InputStream is = null;
506		try {
507			BitmapFactory.Options options = new BitmapFactory.Options();
508			options.inSampleSize = calcSampleSize(image, size);
509			is = mXmppConnectionService.getContentResolver().openInputStream(image);
510			if (is == null) {
511				return null;
512			}
513			Bitmap input = BitmapFactory.decodeStream(is, null, options);
514			if (input == null) {
515				return null;
516			} else {
517				input = rotate(input, getRotation(image));
518				return cropCenterSquare(input, size);
519			}
520		} catch (SecurityException e) {
521			return null; // happens for example on Android 6.0 if contacts permissions get revoked
522		} catch (FileNotFoundException e) {
523			return null;
524		} finally {
525			close(is);
526		}
527	}
528
529	public Bitmap cropCenter(Uri image, int newHeight, int newWidth) {
530		if (image == null) {
531			return null;
532		}
533		InputStream is = null;
534		try {
535			BitmapFactory.Options options = new BitmapFactory.Options();
536			options.inSampleSize = calcSampleSize(image, Math.max(newHeight, newWidth));
537			is = mXmppConnectionService.getContentResolver().openInputStream(image);
538			if (is == null) {
539				return null;
540			}
541			Bitmap source = BitmapFactory.decodeStream(is, null, options);
542			if (source == null) {
543				return null;
544			}
545			int sourceWidth = source.getWidth();
546			int sourceHeight = source.getHeight();
547			float xScale = (float) newWidth / sourceWidth;
548			float yScale = (float) newHeight / sourceHeight;
549			float scale = Math.max(xScale, yScale);
550			float scaledWidth = scale * sourceWidth;
551			float scaledHeight = scale * sourceHeight;
552			float left = (newWidth - scaledWidth) / 2;
553			float top = (newHeight - scaledHeight) / 2;
554
555			RectF targetRect = new RectF(left, top, left + scaledWidth, top + scaledHeight);
556			Bitmap dest = Bitmap.createBitmap(newWidth, newHeight, Bitmap.Config.ARGB_8888);
557			Canvas canvas = new Canvas(dest);
558			canvas.drawBitmap(source, null, targetRect, null);
559			if (source != null && !source.isRecycled()) {
560				source.recycle();
561			}
562			return dest;
563		} catch (SecurityException e) {
564			return null; //android 6.0 with revoked permissions for example
565		} catch (FileNotFoundException e) {
566			return null;
567		} finally {
568			close(is);
569		}
570	}
571
572	public Bitmap cropCenterSquare(Bitmap input, int size) {
573		int w = input.getWidth();
574		int h = input.getHeight();
575
576		float scale = Math.max((float) size / h, (float) size / w);
577
578		float outWidth = scale * w;
579		float outHeight = scale * h;
580		float left = (size - outWidth) / 2;
581		float top = (size - outHeight) / 2;
582		RectF target = new RectF(left, top, left + outWidth, top + outHeight);
583
584		Bitmap output = Bitmap.createBitmap(size, size, Bitmap.Config.ARGB_8888);
585		Canvas canvas = new Canvas(output);
586		canvas.drawBitmap(input, null, target, null);
587		if (input != null && !input.isRecycled()) {
588			input.recycle();
589		}
590		return output;
591	}
592
593	private int calcSampleSize(Uri image, int size) throws FileNotFoundException, SecurityException {
594		BitmapFactory.Options options = new BitmapFactory.Options();
595		options.inJustDecodeBounds = true;
596		BitmapFactory.decodeStream(mXmppConnectionService.getContentResolver().openInputStream(image), null, options);
597		return calcSampleSize(options, size);
598	}
599
600	private static int calcSampleSize(File image, int size) {
601		BitmapFactory.Options options = new BitmapFactory.Options();
602		options.inJustDecodeBounds = true;
603		BitmapFactory.decodeFile(image.getAbsolutePath(), options);
604		return calcSampleSize(options, size);
605	}
606
607	public static int calcSampleSize(BitmapFactory.Options options, int size) {
608		int height = options.outHeight;
609		int width = options.outWidth;
610		int inSampleSize = 1;
611
612		if (height > size || width > size) {
613			int halfHeight = height / 2;
614			int halfWidth = width / 2;
615
616			while ((halfHeight / inSampleSize) > size
617					&& (halfWidth / inSampleSize) > size) {
618				inSampleSize *= 2;
619			}
620		}
621		return inSampleSize;
622	}
623
624	public Uri getJingleFileUri(Message message) {
625		File file = getFile(message);
626		return Uri.parse("file://" + file.getAbsolutePath());
627	}
628
629	public void updateFileParams(Message message) {
630		updateFileParams(message,null);
631	}
632
633	public void updateFileParams(Message message, URL url) {
634		DownloadableFile file = getFile(message);
635		if (message.getType() == Message.TYPE_IMAGE || file.getMimeType().startsWith("image/")) {
636			BitmapFactory.Options options = new BitmapFactory.Options();
637			options.inJustDecodeBounds = true;
638			BitmapFactory.decodeFile(file.getAbsolutePath(), options);
639			int rotation = getRotation(file);
640			boolean rotated = rotation == 90 || rotation == 270;
641			int imageHeight = rotated ? options.outWidth : options.outHeight;
642			int imageWidth = rotated ? options.outHeight : options.outWidth;
643			if (url == null) {
644				message.setBody(Long.toString(file.getSize()) + '|' + imageWidth + '|' + imageHeight);
645			} else {
646				message.setBody(url.toString()+"|"+Long.toString(file.getSize()) + '|' + imageWidth + '|' + imageHeight);
647			}
648		} else {
649			if (url != null) {
650				message.setBody(url.toString()+"|"+Long.toString(file.getSize()));
651			} else {
652				message.setBody(Long.toString(file.getSize()));
653			}
654		}
655
656	}
657
658	public class FileCopyException extends Exception {
659		private static final long serialVersionUID = -1010013599132881427L;
660		private int resId;
661
662		public FileCopyException(int resId) {
663			this.resId = resId;
664		}
665
666		public int getResId() {
667			return resId;
668		}
669	}
670
671	public Bitmap getAvatar(String avatar, int size) {
672		if (avatar == null) {
673			return null;
674		}
675		Bitmap bm = cropCenter(getAvatarUri(avatar), size, size);
676		if (bm == null) {
677			return null;
678		}
679		return bm;
680	}
681
682	public boolean isFileAvailable(Message message) {
683		return getFile(message).exists();
684	}
685
686	public static void close(Closeable stream) {
687		if (stream != null) {
688			try {
689				stream.close();
690			} catch (IOException e) {
691			}
692		}
693	}
694
695	public static void close(Socket socket) {
696		if (socket != null) {
697			try {
698				socket.close();
699			} catch (IOException e) {
700			}
701		}
702	}
703
704
705	public static boolean weOwnFile(Context context, Uri uri) {
706		if (uri == null || !ContentResolver.SCHEME_FILE.equals(uri.getScheme())) {
707			return false;
708		} else if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
709			return fileIsInFilesDir(context, uri);
710		} else {
711			return weOwnFileLollipop(uri);
712		}
713	}
714
715
716	/**
717	 * This is more than hacky but probably way better than doing nothing
718	 * Further 'optimizations' might contain to get the parents of CacheDir and NoBackupDir
719	 * and check against those as well
720	 */
721	private static boolean fileIsInFilesDir(Context context, Uri uri) {
722		try {
723			final String haystack = context.getFilesDir().getParentFile().getCanonicalPath();
724			final String needle = new File(uri.getPath()).getCanonicalPath();
725			return needle.startsWith(haystack);
726		} catch (IOException e) {
727			return false;
728		}
729	}
730
731	@TargetApi(Build.VERSION_CODES.LOLLIPOP)
732	private static boolean weOwnFileLollipop(Uri uri) {
733		try {
734			File file = new File(uri.getPath());
735			FileDescriptor fd = ParcelFileDescriptor.open(file, ParcelFileDescriptor.MODE_READ_ONLY).getFileDescriptor();
736			StructStat st = Os.fstat(fd);
737			return st.st_uid == android.os.Process.myUid();
738		} catch (FileNotFoundException e) {
739			return false;
740		} catch (Exception e) {
741			return true;
742		}
743	}
744}