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