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