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