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