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