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