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