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