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