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		Bitmap frame;
410		try {
411			metadataRetriever.setDataSource(file.getAbsolutePath());
412			frame = metadataRetriever.getFrameAtTime(0);
413			metadataRetriever.release();
414			frame = resize(frame, size);
415		} catch(IllegalArgumentException e) {
416			frame = Bitmap.createBitmap(size,size, Bitmap.Config.ARGB_8888);
417			frame.eraseColor(0xff000000);
418		}
419		Canvas canvas = new Canvas(frame);
420		Bitmap play = BitmapFactory.decodeResource(mXmppConnectionService.getResources(), R.drawable.play_video);
421		float x = (frame.getWidth() - play.getWidth()) / 2.0f;
422		float y = (frame.getHeight() - play.getHeight()) / 2.0f;
423		canvas.drawBitmap(play,x,y,null);
424		return frame;
425	}
426
427	public Uri getTakePhotoUri() {
428		StringBuilder pathBuilder = new StringBuilder();
429		pathBuilder.append(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM));
430		pathBuilder.append('/');
431		pathBuilder.append("Camera");
432		pathBuilder.append('/');
433		pathBuilder.append("IMG_" + this.imageDateFormat.format(new Date()) + ".jpg");
434		Uri uri = Uri.parse("file://" + pathBuilder.toString());
435		File file = new File(uri.toString());
436		file.getParentFile().mkdirs();
437		return uri;
438	}
439
440	public Avatar getPepAvatar(Uri image, int size, Bitmap.CompressFormat format) {
441		try {
442			Avatar avatar = new Avatar();
443			Bitmap bm = cropCenterSquare(image, size);
444			if (bm == null) {
445				return null;
446			}
447			ByteArrayOutputStream mByteArrayOutputStream = new ByteArrayOutputStream();
448			Base64OutputStream mBase64OutputSttream = new Base64OutputStream(
449					mByteArrayOutputStream, Base64.DEFAULT);
450			MessageDigest digest = MessageDigest.getInstance("SHA-1");
451			DigestOutputStream mDigestOutputStream = new DigestOutputStream(
452					mBase64OutputSttream, digest);
453			if (!bm.compress(format, 75, mDigestOutputStream)) {
454				return null;
455			}
456			mDigestOutputStream.flush();
457			mDigestOutputStream.close();
458			avatar.sha1sum = CryptoHelper.bytesToHex(digest.digest());
459			avatar.image = new String(mByteArrayOutputStream.toByteArray());
460			return avatar;
461		} catch (NoSuchAlgorithmException e) {
462			return null;
463		} catch (IOException e) {
464			return null;
465		}
466	}
467
468	public Avatar getStoredPepAvatar(String hash) {
469		if (hash == null) {
470			return null;
471		}
472		Avatar avatar = new Avatar();
473		File file = new File(getAvatarPath(hash));
474		FileInputStream is = null;
475		try {
476			BitmapFactory.Options options = new BitmapFactory.Options();
477			options.inJustDecodeBounds = true;
478			BitmapFactory.decodeFile(file.getAbsolutePath(), options);
479			is = new FileInputStream(file);
480			ByteArrayOutputStream mByteArrayOutputStream = new ByteArrayOutputStream();
481			Base64OutputStream mBase64OutputStream = new Base64OutputStream(mByteArrayOutputStream, Base64.DEFAULT);
482			MessageDigest digest = MessageDigest.getInstance("SHA-1");
483			DigestOutputStream os = new DigestOutputStream(mBase64OutputStream, digest);
484			byte[] buffer = new byte[4096];
485			int length;
486			while ((length = is.read(buffer)) > 0) {
487				os.write(buffer, 0, length);
488			}
489			os.flush();
490			os.close();
491			avatar.sha1sum = CryptoHelper.bytesToHex(digest.digest());
492			avatar.image = new String(mByteArrayOutputStream.toByteArray());
493			avatar.height = options.outHeight;
494			avatar.width = options.outWidth;
495			return avatar;
496		} catch (IOException e) {
497			return null;
498		} catch (NoSuchAlgorithmException e) {
499			return null;
500		} finally {
501			close(is);
502		}
503	}
504
505	public boolean isAvatarCached(Avatar avatar) {
506		File file = new File(getAvatarPath(avatar.getFilename()));
507		return file.exists();
508	}
509
510	public boolean save(Avatar avatar) {
511		File file;
512		if (isAvatarCached(avatar)) {
513			file = new File(getAvatarPath(avatar.getFilename()));
514		} else {
515			String filename = getAvatarPath(avatar.getFilename());
516			file = new File(filename + ".tmp");
517			file.getParentFile().mkdirs();
518			OutputStream os = null;
519			try {
520				file.createNewFile();
521				os = new FileOutputStream(file);
522				MessageDigest digest = MessageDigest.getInstance("SHA-1");
523				digest.reset();
524				DigestOutputStream mDigestOutputStream = new DigestOutputStream(os, digest);
525				mDigestOutputStream.write(avatar.getImageAsBytes());
526				mDigestOutputStream.flush();
527				mDigestOutputStream.close();
528				String sha1sum = CryptoHelper.bytesToHex(digest.digest());
529				if (sha1sum.equals(avatar.sha1sum)) {
530					file.renameTo(new File(filename));
531				} else {
532					Log.d(Config.LOGTAG, "sha1sum mismatch for " + avatar.owner);
533					file.delete();
534					return false;
535				}
536			} catch (IllegalArgumentException | IOException | NoSuchAlgorithmException e) {
537				return false;
538			} finally {
539				close(os);
540			}
541		}
542		avatar.size = file.length();
543		return true;
544	}
545
546	public String getAvatarPath(String avatar) {
547		return mXmppConnectionService.getFilesDir().getAbsolutePath()+ "/avatars/" + avatar;
548	}
549
550	public Uri getAvatarUri(String avatar) {
551		return Uri.parse("file:" + getAvatarPath(avatar));
552	}
553
554	public Bitmap cropCenterSquare(Uri image, int size) {
555		if (image == null) {
556			return null;
557		}
558		InputStream is = null;
559		try {
560			BitmapFactory.Options options = new BitmapFactory.Options();
561			options.inSampleSize = calcSampleSize(image, size);
562			is = mXmppConnectionService.getContentResolver().openInputStream(image);
563			if (is == null) {
564				return null;
565			}
566			Bitmap input = BitmapFactory.decodeStream(is, null, options);
567			if (input == null) {
568				return null;
569			} else {
570				input = rotate(input, getRotation(image));
571				return cropCenterSquare(input, size);
572			}
573		} catch (SecurityException e) {
574			return null; // happens for example on Android 6.0 if contacts permissions get revoked
575		} catch (FileNotFoundException e) {
576			return null;
577		} finally {
578			close(is);
579		}
580	}
581
582	public Bitmap cropCenter(Uri image, int newHeight, int newWidth) {
583		if (image == null) {
584			return null;
585		}
586		InputStream is = null;
587		try {
588			BitmapFactory.Options options = new BitmapFactory.Options();
589			options.inSampleSize = calcSampleSize(image, Math.max(newHeight, newWidth));
590			is = mXmppConnectionService.getContentResolver().openInputStream(image);
591			if (is == null) {
592				return null;
593			}
594			Bitmap source = BitmapFactory.decodeStream(is, null, options);
595			if (source == null) {
596				return null;
597			}
598			int sourceWidth = source.getWidth();
599			int sourceHeight = source.getHeight();
600			float xScale = (float) newWidth / sourceWidth;
601			float yScale = (float) newHeight / sourceHeight;
602			float scale = Math.max(xScale, yScale);
603			float scaledWidth = scale * sourceWidth;
604			float scaledHeight = scale * sourceHeight;
605			float left = (newWidth - scaledWidth) / 2;
606			float top = (newHeight - scaledHeight) / 2;
607
608			RectF targetRect = new RectF(left, top, left + scaledWidth, top + scaledHeight);
609			Bitmap dest = Bitmap.createBitmap(newWidth, newHeight, Bitmap.Config.ARGB_8888);
610			Canvas canvas = new Canvas(dest);
611			canvas.drawBitmap(source, null, targetRect, null);
612			if (source != null && !source.isRecycled()) {
613				source.recycle();
614			}
615			return dest;
616		} catch (SecurityException e) {
617			return null; //android 6.0 with revoked permissions for example
618		} catch (FileNotFoundException e) {
619			return null;
620		} finally {
621			close(is);
622		}
623	}
624
625	public Bitmap cropCenterSquare(Bitmap input, int size) {
626		int w = input.getWidth();
627		int h = input.getHeight();
628
629		float scale = Math.max((float) size / h, (float) size / w);
630
631		float outWidth = scale * w;
632		float outHeight = scale * h;
633		float left = (size - outWidth) / 2;
634		float top = (size - outHeight) / 2;
635		RectF target = new RectF(left, top, left + outWidth, top + outHeight);
636
637		Bitmap output = Bitmap.createBitmap(size, size, Bitmap.Config.ARGB_8888);
638		Canvas canvas = new Canvas(output);
639		canvas.drawBitmap(input, null, target, null);
640		if (input != null && !input.isRecycled()) {
641			input.recycle();
642		}
643		return output;
644	}
645
646	private int calcSampleSize(Uri image, int size) throws FileNotFoundException, SecurityException {
647		BitmapFactory.Options options = new BitmapFactory.Options();
648		options.inJustDecodeBounds = true;
649		BitmapFactory.decodeStream(mXmppConnectionService.getContentResolver().openInputStream(image), null, options);
650		return calcSampleSize(options, size);
651	}
652
653	private static int calcSampleSize(File image, int size) {
654		BitmapFactory.Options options = new BitmapFactory.Options();
655		options.inJustDecodeBounds = true;
656		BitmapFactory.decodeFile(image.getAbsolutePath(), options);
657		return calcSampleSize(options, size);
658	}
659
660	public static int calcSampleSize(BitmapFactory.Options options, int size) {
661		int height = options.outHeight;
662		int width = options.outWidth;
663		int inSampleSize = 1;
664
665		if (height > size || width > size) {
666			int halfHeight = height / 2;
667			int halfWidth = width / 2;
668
669			while ((halfHeight / inSampleSize) > size
670					&& (halfWidth / inSampleSize) > size) {
671				inSampleSize *= 2;
672			}
673		}
674		return inSampleSize;
675	}
676
677	public Uri getJingleFileUri(Message message) {
678		File file = getFile(message);
679		return Uri.parse("file://" + file.getAbsolutePath());
680	}
681
682	public void updateFileParams(Message message) {
683		updateFileParams(message,null);
684	}
685
686	public void updateFileParams(Message message, URL url) {
687		DownloadableFile file = getFile(message);
688		final String mime = file.getMimeType();
689		boolean image = message.getType() == Message.TYPE_IMAGE || (mime != null && mime.startsWith("image/"));
690		boolean video = mime != null && mime.startsWith("video/");
691		if (image || video) {
692			try {
693				Dimensions dimensions = image ? getImageDimensions(file) : getVideoDimensions(file);
694				if (url == null) {
695					message.setBody(Long.toString(file.getSize()) + '|' + dimensions.width + '|' + dimensions.height);
696				} else {
697					message.setBody(url.toString() + "|" + Long.toString(file.getSize()) + '|' + dimensions.width + '|' + dimensions.height);
698				}
699				return;
700			} catch (NotAVideoFile notAVideoFile) {
701				Log.d(Config.LOGTAG,"file with mime type "+file.getMimeType()+" was not a video file");
702				//fall threw
703			}
704		}
705		if (url != null) {
706			message.setBody(url.toString()+"|"+Long.toString(file.getSize()));
707		} else {
708			message.setBody(Long.toString(file.getSize()));
709		}
710
711	}
712
713	private Dimensions getImageDimensions(File file) {
714		BitmapFactory.Options options = new BitmapFactory.Options();
715		options.inJustDecodeBounds = true;
716		BitmapFactory.decodeFile(file.getAbsolutePath(), options);
717		int rotation = getRotation(file);
718		boolean rotated = rotation == 90 || rotation == 270;
719		int imageHeight = rotated ? options.outWidth : options.outHeight;
720		int imageWidth = rotated ? options.outHeight : options.outWidth;
721		return new Dimensions(imageHeight, imageWidth);
722	}
723
724	private Dimensions getVideoDimensions(File file) throws NotAVideoFile {
725		MediaMetadataRetriever metadataRetriever = new MediaMetadataRetriever();
726		metadataRetriever.setDataSource(file.getAbsolutePath());
727		String hasVideo = metadataRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_HAS_VIDEO);
728		if (hasVideo == null) {
729			throw new NotAVideoFile();
730		}
731		int rotation = extractRotationFromMediaRetriever(metadataRetriever);
732		boolean rotated = rotation == 90 || rotation == 270;
733		int height;
734		try {
735			String h = metadataRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_HEIGHT);
736			height = Integer.parseInt(h);
737		} catch (Exception e) {
738			height = -1;
739		}
740		int width;
741		try {
742			String w = metadataRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_WIDTH);
743			width = Integer.parseInt(w);
744		} catch (Exception e) {
745			width = -1;
746		}
747		metadataRetriever.release();
748		Log.d(Config.LOGTAG,"extracted video dims "+width+"x"+height);
749		return rotated ? new Dimensions(width, height) : new Dimensions(height, width);
750	}
751
752	private int extractRotationFromMediaRetriever(MediaMetadataRetriever metadataRetriever) {
753		int rotation;
754		if (Build.VERSION.SDK_INT >= 17) {
755			String r = metadataRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_ROTATION);
756			try {
757				rotation = Integer.parseInt(r);
758			} catch (Exception e) {
759				rotation = 0;
760			}
761		} else {
762			rotation = 0;
763		}
764		return rotation;
765	}
766
767	private class Dimensions {
768		public final int width;
769		public final int height;
770
771		public Dimensions(int height, int width) {
772			this.width = width;
773			this.height = height;
774		}
775	}
776
777	private class NotAVideoFile extends Exception {
778
779	}
780
781	public class FileCopyException extends Exception {
782		private static final long serialVersionUID = -1010013599132881427L;
783		private int resId;
784
785		public FileCopyException(int resId) {
786			this.resId = resId;
787		}
788
789		public int getResId() {
790			return resId;
791		}
792	}
793
794	public Bitmap getAvatar(String avatar, int size) {
795		if (avatar == null) {
796			return null;
797		}
798		Bitmap bm = cropCenter(getAvatarUri(avatar), size, size);
799		if (bm == null) {
800			return null;
801		}
802		return bm;
803	}
804
805	public boolean isFileAvailable(Message message) {
806		return getFile(message).exists();
807	}
808
809	public static void close(Closeable stream) {
810		if (stream != null) {
811			try {
812				stream.close();
813			} catch (IOException e) {
814			}
815		}
816	}
817
818	public static void close(Socket socket) {
819		if (socket != null) {
820			try {
821				socket.close();
822			} catch (IOException e) {
823			}
824		}
825	}
826
827
828	public static boolean weOwnFile(Context context, Uri uri) {
829		if (uri == null || !ContentResolver.SCHEME_FILE.equals(uri.getScheme())) {
830			return false;
831		} else if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
832			return fileIsInFilesDir(context, uri);
833		} else {
834			return weOwnFileLollipop(uri);
835		}
836	}
837
838
839	/**
840	 * This is more than hacky but probably way better than doing nothing
841	 * Further 'optimizations' might contain to get the parents of CacheDir and NoBackupDir
842	 * and check against those as well
843	 */
844	private static boolean fileIsInFilesDir(Context context, Uri uri) {
845		try {
846			final String haystack = context.getFilesDir().getParentFile().getCanonicalPath();
847			final String needle = new File(uri.getPath()).getCanonicalPath();
848			return needle.startsWith(haystack);
849		} catch (IOException e) {
850			return false;
851		}
852	}
853
854	@TargetApi(Build.VERSION_CODES.LOLLIPOP)
855	private static boolean weOwnFileLollipop(Uri uri) {
856		try {
857			File file = new File(uri.getPath());
858			FileDescriptor fd = ParcelFileDescriptor.open(file, ParcelFileDescriptor.MODE_READ_ONLY).getFileDescriptor();
859			StructStat st = Os.fstat(fd);
860			return st.st_uid == android.os.Process.myUid();
861		} catch (FileNotFoundException e) {
862			return false;
863		} catch (Exception e) {
864			return true;
865		}
866	}
867}