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		return FileProvider.getUriForFile(mXmppConnectionService,"eu.siacs.conversations.files",file);
444	}
445
446	public Avatar getPepAvatar(Uri image, int size, Bitmap.CompressFormat format) {
447		try {
448			Avatar avatar = new Avatar();
449			Bitmap bm = cropCenterSquare(image, size);
450			if (bm == null) {
451				return null;
452			}
453			ByteArrayOutputStream mByteArrayOutputStream = new ByteArrayOutputStream();
454			Base64OutputStream mBase64OutputStream = new Base64OutputStream(
455					mByteArrayOutputStream, Base64.DEFAULT);
456			MessageDigest digest = MessageDigest.getInstance("SHA-1");
457			DigestOutputStream mDigestOutputStream = new DigestOutputStream(
458					mBase64OutputStream, digest);
459			if (!bm.compress(format, 75, mDigestOutputStream)) {
460				return null;
461			}
462			mDigestOutputStream.flush();
463			mDigestOutputStream.close();
464			avatar.sha1sum = CryptoHelper.bytesToHex(digest.digest());
465			avatar.image = new String(mByteArrayOutputStream.toByteArray());
466			return avatar;
467		} catch (NoSuchAlgorithmException e) {
468			return null;
469		} catch (IOException e) {
470			return null;
471		}
472	}
473
474	public Avatar getStoredPepAvatar(String hash) {
475		if (hash == null) {
476			return null;
477		}
478		Avatar avatar = new Avatar();
479		File file = new File(getAvatarPath(hash));
480		FileInputStream is = null;
481		try {
482			BitmapFactory.Options options = new BitmapFactory.Options();
483			options.inJustDecodeBounds = true;
484			BitmapFactory.decodeFile(file.getAbsolutePath(), options);
485			is = new FileInputStream(file);
486			ByteArrayOutputStream mByteArrayOutputStream = new ByteArrayOutputStream();
487			Base64OutputStream mBase64OutputStream = new Base64OutputStream(mByteArrayOutputStream, Base64.DEFAULT);
488			MessageDigest digest = MessageDigest.getInstance("SHA-1");
489			DigestOutputStream os = new DigestOutputStream(mBase64OutputStream, digest);
490			byte[] buffer = new byte[4096];
491			int length;
492			while ((length = is.read(buffer)) > 0) {
493				os.write(buffer, 0, length);
494			}
495			os.flush();
496			os.close();
497			avatar.sha1sum = CryptoHelper.bytesToHex(digest.digest());
498			avatar.image = new String(mByteArrayOutputStream.toByteArray());
499			avatar.height = options.outHeight;
500			avatar.width = options.outWidth;
501			return avatar;
502		} catch (IOException e) {
503			return null;
504		} catch (NoSuchAlgorithmException e) {
505			return null;
506		} finally {
507			close(is);
508		}
509	}
510
511	public boolean isAvatarCached(Avatar avatar) {
512		File file = new File(getAvatarPath(avatar.getFilename()));
513		return file.exists();
514	}
515
516	public boolean save(Avatar avatar) {
517		File file;
518		if (isAvatarCached(avatar)) {
519			file = new File(getAvatarPath(avatar.getFilename()));
520		} else {
521			String filename = getAvatarPath(avatar.getFilename());
522			file = new File(filename + ".tmp");
523			file.getParentFile().mkdirs();
524			OutputStream os = null;
525			try {
526				file.createNewFile();
527				os = new FileOutputStream(file);
528				MessageDigest digest = MessageDigest.getInstance("SHA-1");
529				digest.reset();
530				DigestOutputStream mDigestOutputStream = new DigestOutputStream(os, digest);
531				mDigestOutputStream.write(avatar.getImageAsBytes());
532				mDigestOutputStream.flush();
533				mDigestOutputStream.close();
534				String sha1sum = CryptoHelper.bytesToHex(digest.digest());
535				if (sha1sum.equals(avatar.sha1sum)) {
536					file.renameTo(new File(filename));
537				} else {
538					Log.d(Config.LOGTAG, "sha1sum mismatch for " + avatar.owner);
539					file.delete();
540					return false;
541				}
542			} catch (IllegalArgumentException | IOException | NoSuchAlgorithmException e) {
543				return false;
544			} finally {
545				close(os);
546			}
547		}
548		avatar.size = file.length();
549		return true;
550	}
551
552	public String getAvatarPath(String avatar) {
553		return mXmppConnectionService.getFilesDir().getAbsolutePath()+ "/avatars/" + avatar;
554	}
555
556	public Uri getAvatarUri(String avatar) {
557		return Uri.parse("file:" + getAvatarPath(avatar));
558	}
559
560	public Bitmap cropCenterSquare(Uri image, int size) {
561		if (image == null) {
562			return null;
563		}
564		InputStream is = null;
565		try {
566			BitmapFactory.Options options = new BitmapFactory.Options();
567			options.inSampleSize = calcSampleSize(image, size);
568			is = mXmppConnectionService.getContentResolver().openInputStream(image);
569			if (is == null) {
570				return null;
571			}
572			Bitmap input = BitmapFactory.decodeStream(is, null, options);
573			if (input == null) {
574				return null;
575			} else {
576				input = rotate(input, getRotation(image));
577				return cropCenterSquare(input, size);
578			}
579		} catch (SecurityException e) {
580			return null; // happens for example on Android 6.0 if contacts permissions get revoked
581		} catch (FileNotFoundException e) {
582			return null;
583		} finally {
584			close(is);
585		}
586	}
587
588	public Bitmap cropCenter(Uri image, int newHeight, int newWidth) {
589		if (image == null) {
590			return null;
591		}
592		InputStream is = null;
593		try {
594			BitmapFactory.Options options = new BitmapFactory.Options();
595			options.inSampleSize = calcSampleSize(image, Math.max(newHeight, newWidth));
596			is = mXmppConnectionService.getContentResolver().openInputStream(image);
597			if (is == null) {
598				return null;
599			}
600			Bitmap source = BitmapFactory.decodeStream(is, null, options);
601			if (source == null) {
602				return null;
603			}
604			int sourceWidth = source.getWidth();
605			int sourceHeight = source.getHeight();
606			float xScale = (float) newWidth / sourceWidth;
607			float yScale = (float) newHeight / sourceHeight;
608			float scale = Math.max(xScale, yScale);
609			float scaledWidth = scale * sourceWidth;
610			float scaledHeight = scale * sourceHeight;
611			float left = (newWidth - scaledWidth) / 2;
612			float top = (newHeight - scaledHeight) / 2;
613
614			RectF targetRect = new RectF(left, top, left + scaledWidth, top + scaledHeight);
615			Bitmap dest = Bitmap.createBitmap(newWidth, newHeight, Bitmap.Config.ARGB_8888);
616			Canvas canvas = new Canvas(dest);
617			canvas.drawBitmap(source, null, targetRect, null);
618			if (source != null && !source.isRecycled()) {
619				source.recycle();
620			}
621			return dest;
622		} catch (SecurityException e) {
623			return null; //android 6.0 with revoked permissions for example
624		} catch (FileNotFoundException e) {
625			return null;
626		} finally {
627			close(is);
628		}
629	}
630
631	public Bitmap cropCenterSquare(Bitmap input, int size) {
632		int w = input.getWidth();
633		int h = input.getHeight();
634
635		float scale = Math.max((float) size / h, (float) size / w);
636
637		float outWidth = scale * w;
638		float outHeight = scale * h;
639		float left = (size - outWidth) / 2;
640		float top = (size - outHeight) / 2;
641		RectF target = new RectF(left, top, left + outWidth, top + outHeight);
642
643		Bitmap output = Bitmap.createBitmap(size, size, Bitmap.Config.ARGB_8888);
644		Canvas canvas = new Canvas(output);
645		canvas.drawBitmap(input, null, target, null);
646		if (input != null && !input.isRecycled()) {
647			input.recycle();
648		}
649		return output;
650	}
651
652	private int calcSampleSize(Uri image, int size) throws FileNotFoundException, SecurityException {
653		BitmapFactory.Options options = new BitmapFactory.Options();
654		options.inJustDecodeBounds = true;
655		BitmapFactory.decodeStream(mXmppConnectionService.getContentResolver().openInputStream(image), null, options);
656		return calcSampleSize(options, size);
657	}
658
659	private static int calcSampleSize(File image, int size) {
660		BitmapFactory.Options options = new BitmapFactory.Options();
661		options.inJustDecodeBounds = true;
662		BitmapFactory.decodeFile(image.getAbsolutePath(), options);
663		return calcSampleSize(options, size);
664	}
665
666	public static int calcSampleSize(BitmapFactory.Options options, int size) {
667		int height = options.outHeight;
668		int width = options.outWidth;
669		int inSampleSize = 1;
670
671		if (height > size || width > size) {
672			int halfHeight = height / 2;
673			int halfWidth = width / 2;
674
675			while ((halfHeight / inSampleSize) > size
676					&& (halfWidth / inSampleSize) > size) {
677				inSampleSize *= 2;
678			}
679		}
680		return inSampleSize;
681	}
682
683	public Uri getJingleFileUri(Message message) {
684		File file = getFile(message);
685		return Uri.parse("file://" + file.getAbsolutePath());
686	}
687
688	public void updateFileParams(Message message) {
689		updateFileParams(message,null);
690	}
691
692	public void updateFileParams(Message message, URL url) {
693		DownloadableFile file = getFile(message);
694		final String mime = file.getMimeType();
695		boolean image = message.getType() == Message.TYPE_IMAGE || (mime != null && mime.startsWith("image/"));
696		boolean video = mime != null && mime.startsWith("video/");
697		if (image || video) {
698			try {
699				Dimensions dimensions = image ? getImageDimensions(file) : getVideoDimensions(file);
700				if (url == null) {
701					message.setBody(Long.toString(file.getSize()) + '|' + dimensions.width + '|' + dimensions.height);
702				} else {
703					message.setBody(url.toString() + "|" + Long.toString(file.getSize()) + '|' + dimensions.width + '|' + dimensions.height);
704				}
705				return;
706			} catch (NotAVideoFile notAVideoFile) {
707				Log.d(Config.LOGTAG,"file with mime type "+file.getMimeType()+" was not a video file");
708				//fall threw
709			}
710		}
711		if (url != null) {
712			message.setBody(url.toString()+"|"+Long.toString(file.getSize()));
713		} else {
714			message.setBody(Long.toString(file.getSize()));
715		}
716
717	}
718
719	private Dimensions getImageDimensions(File file) {
720		BitmapFactory.Options options = new BitmapFactory.Options();
721		options.inJustDecodeBounds = true;
722		BitmapFactory.decodeFile(file.getAbsolutePath(), options);
723		int rotation = getRotation(file);
724		boolean rotated = rotation == 90 || rotation == 270;
725		int imageHeight = rotated ? options.outWidth : options.outHeight;
726		int imageWidth = rotated ? options.outHeight : options.outWidth;
727		return new Dimensions(imageHeight, imageWidth);
728	}
729
730	private Dimensions getVideoDimensions(File file) throws NotAVideoFile {
731		MediaMetadataRetriever metadataRetriever = new MediaMetadataRetriever();
732		try {
733			metadataRetriever.setDataSource(file.getAbsolutePath());
734		} catch (Exception e) {
735			throw new NotAVideoFile();
736		}
737		String hasVideo = metadataRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_HAS_VIDEO);
738		if (hasVideo == null) {
739			throw new NotAVideoFile();
740		}
741		int rotation = extractRotationFromMediaRetriever(metadataRetriever);
742		boolean rotated = rotation == 90 || rotation == 270;
743		int height;
744		try {
745			String h = metadataRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_HEIGHT);
746			height = Integer.parseInt(h);
747		} catch (Exception e) {
748			height = -1;
749		}
750		int width;
751		try {
752			String w = metadataRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_WIDTH);
753			width = Integer.parseInt(w);
754		} catch (Exception e) {
755			width = -1;
756		}
757		metadataRetriever.release();
758		Log.d(Config.LOGTAG,"extracted video dims "+width+"x"+height);
759		return rotated ? new Dimensions(width, height) : new Dimensions(height, width);
760	}
761
762	private int extractRotationFromMediaRetriever(MediaMetadataRetriever metadataRetriever) {
763		int rotation;
764		if (Build.VERSION.SDK_INT >= 17) {
765			String r = metadataRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_ROTATION);
766			try {
767				rotation = Integer.parseInt(r);
768			} catch (Exception e) {
769				rotation = 0;
770			}
771		} else {
772			rotation = 0;
773		}
774		return rotation;
775	}
776
777	private class Dimensions {
778		public final int width;
779		public final int height;
780
781		public Dimensions(int height, int width) {
782			this.width = width;
783			this.height = height;
784		}
785	}
786
787	private class NotAVideoFile extends Exception {
788
789	}
790
791	public class FileCopyException extends Exception {
792		private static final long serialVersionUID = -1010013599132881427L;
793		private int resId;
794
795		public FileCopyException(int resId) {
796			this.resId = resId;
797		}
798
799		public int getResId() {
800			return resId;
801		}
802	}
803
804	public Bitmap getAvatar(String avatar, int size) {
805		if (avatar == null) {
806			return null;
807		}
808		Bitmap bm = cropCenter(getAvatarUri(avatar), size, size);
809		if (bm == null) {
810			return null;
811		}
812		return bm;
813	}
814
815	public boolean isFileAvailable(Message message) {
816		return getFile(message).exists();
817	}
818
819	public static void close(Closeable stream) {
820		if (stream != null) {
821			try {
822				stream.close();
823			} catch (IOException e) {
824			}
825		}
826	}
827
828	public static void close(Socket socket) {
829		if (socket != null) {
830			try {
831				socket.close();
832			} catch (IOException e) {
833			}
834		}
835	}
836
837
838	public static boolean weOwnFile(Context context, Uri uri) {
839		if (uri == null || !ContentResolver.SCHEME_FILE.equals(uri.getScheme())) {
840			return false;
841		} else if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
842			return fileIsInFilesDir(context, uri);
843		} else {
844			return weOwnFileLollipop(uri);
845		}
846	}
847
848
849	/**
850	 * This is more than hacky but probably way better than doing nothing
851	 * Further 'optimizations' might contain to get the parents of CacheDir and NoBackupDir
852	 * and check against those as well
853	 */
854	private static boolean fileIsInFilesDir(Context context, Uri uri) {
855		try {
856			final String haystack = context.getFilesDir().getParentFile().getCanonicalPath();
857			final String needle = new File(uri.getPath()).getCanonicalPath();
858			return needle.startsWith(haystack);
859		} catch (IOException e) {
860			return false;
861		}
862	}
863
864	@TargetApi(Build.VERSION_CODES.LOLLIPOP)
865	private static boolean weOwnFileLollipop(Uri uri) {
866		try {
867			File file = new File(uri.getPath());
868			FileDescriptor fd = ParcelFileDescriptor.open(file, ParcelFileDescriptor.MODE_READ_ONLY).getFileDescriptor();
869			StructStat st = Os.fstat(fd);
870			return st.st_uid == android.os.Process.myUid();
871		} catch (FileNotFoundException e) {
872			return false;
873		} catch (Exception e) {
874			return true;
875		}
876	}
877}