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