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