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