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