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