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