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