FileBackend.java

  1package eu.siacs.conversations.persistance;
  2
  3import android.graphics.Bitmap;
  4import android.graphics.BitmapFactory;
  5import android.graphics.Canvas;
  6import android.graphics.Matrix;
  7import android.graphics.RectF;
  8import android.net.Uri;
  9import android.os.Environment;
 10import android.util.Base64;
 11import android.util.Base64OutputStream;
 12import android.util.Log;
 13import android.webkit.MimeTypeMap;
 14
 15import java.io.ByteArrayOutputStream;
 16import java.io.Closeable;
 17import java.io.File;
 18import java.io.FileNotFoundException;
 19import java.io.FileOutputStream;
 20import java.io.IOException;
 21import java.io.InputStream;
 22import java.io.OutputStream;
 23import java.net.Socket;
 24import java.net.URL;
 25import java.security.DigestOutputStream;
 26import java.security.MessageDigest;
 27import java.security.NoSuchAlgorithmException;
 28import java.text.SimpleDateFormat;
 29import java.util.Arrays;
 30import java.util.Date;
 31import java.util.Locale;
 32
 33import eu.siacs.conversations.Config;
 34import eu.siacs.conversations.R;
 35import eu.siacs.conversations.entities.DownloadableFile;
 36import eu.siacs.conversations.entities.Message;
 37import eu.siacs.conversations.entities.Transferable;
 38import eu.siacs.conversations.services.XmppConnectionService;
 39import eu.siacs.conversations.utils.CryptoHelper;
 40import eu.siacs.conversations.utils.ExifHelper;
 41import eu.siacs.conversations.utils.FileUtils;
 42import eu.siacs.conversations.xmpp.pep.Avatar;
 43
 44public class FileBackend {
 45	private final SimpleDateFormat imageDateFormat = new SimpleDateFormat("yyyyMMdd_HHmmssSSS", Locale.US);
 46
 47	private XmppConnectionService mXmppConnectionService;
 48
 49	public FileBackend(XmppConnectionService service) {
 50		this.mXmppConnectionService = service;
 51	}
 52
 53	public DownloadableFile getFile(Message message) {
 54		return getFile(message, true);
 55	}
 56
 57	public DownloadableFile getFile(Message message, boolean decrypted) {
 58		final boolean encrypted = !decrypted
 59				&& (message.getEncryption() == Message.ENCRYPTION_PGP
 60				|| message.getEncryption() == Message.ENCRYPTION_DECRYPTED);
 61		final DownloadableFile file;
 62		String path = message.getRelativeFilePath();
 63		if (path == null) {
 64			path = message.getUuid();
 65		}
 66		if (path.startsWith("/")) {
 67			file = new DownloadableFile(path);
 68		} else {
 69			String mime = message.getMimeType();
 70			if (mime != null && mime.startsWith("image")) {
 71				file = new DownloadableFile(getConversationsImageDirectory() + path);
 72			} else {
 73				file = new DownloadableFile(getConversationsFileDirectory() + path);
 74			}
 75		}
 76		if (encrypted) {
 77			return new DownloadableFile(getConversationsFileDirectory() + file.getName() + ".pgp");
 78		} else {
 79			return file;
 80		}
 81	}
 82
 83	public static String getConversationsFileDirectory() {
 84		return  Environment.getExternalStorageDirectory().getAbsolutePath()+"/Conversations/";
 85	}
 86
 87	public static String getConversationsImageDirectory() {
 88		return Environment.getExternalStoragePublicDirectory(
 89			Environment.DIRECTORY_PICTURES).getAbsolutePath()
 90			+ "/Conversations/";
 91	}
 92
 93	public Bitmap resize(Bitmap originalBitmap, int size) {
 94		int w = originalBitmap.getWidth();
 95		int h = originalBitmap.getHeight();
 96		if (Math.max(w, h) > size) {
 97			int scalledW;
 98			int scalledH;
 99			if (w <= h) {
100				scalledW = (int) (w / ((double) h / size));
101				scalledH = size;
102			} else {
103				scalledW = size;
104				scalledH = (int) (h / ((double) w / size));
105			}
106			Bitmap result = Bitmap.createScaledBitmap(originalBitmap, scalledW, scalledH, true);
107			if (originalBitmap != null && !originalBitmap.isRecycled()) {
108				originalBitmap.recycle();
109			}
110			return result;
111		} else {
112			return originalBitmap;
113		}
114	}
115
116	public static Bitmap rotate(Bitmap bitmap, int degree) {
117		if (degree == 0) {
118			return bitmap;
119		}
120		int w = bitmap.getWidth();
121		int h = bitmap.getHeight();
122		Matrix mtx = new Matrix();
123		mtx.postRotate(degree);
124		Bitmap result = Bitmap.createBitmap(bitmap, 0, 0, w, h, mtx, true);
125		if (bitmap != null && !bitmap.isRecycled()) {
126			bitmap.recycle();
127		}
128		return result;
129	}
130
131	public boolean useImageAsIs(Uri uri) {
132		String path = getOriginalPath(uri);
133		if (path == null) {
134			return false;
135		}
136		File file = new File(path);
137		long size = file.length();
138		if (size == 0 || size >= 524288 ) {
139			return false;
140		}
141		BitmapFactory.Options options = new BitmapFactory.Options();
142		options.inJustDecodeBounds = true;
143		try {
144			BitmapFactory.decodeStream(mXmppConnectionService.getContentResolver().openInputStream(uri), null, options);
145			if (options == null || options.outMimeType == null || options.outHeight <= 0 || options.outWidth <= 0) {
146				return false;
147			}
148			return (options.outWidth <= Config.IMAGE_SIZE && options.outHeight <= Config.IMAGE_SIZE && options.outMimeType.contains(Config.IMAGE_FORMAT.name().toLowerCase()));
149		} catch (FileNotFoundException e) {
150			return false;
151		}
152	}
153
154	public String getOriginalPath(Uri uri) {
155		return FileUtils.getPath(mXmppConnectionService,uri);
156	}
157
158	public DownloadableFile copyFileToPrivateStorage(Message message, Uri uri) throws FileCopyException {
159		Log.d(Config.LOGTAG, "copy " + uri.toString() + " to private storage");
160		String mime = mXmppConnectionService.getContentResolver().getType(uri);
161		String extension = MimeTypeMap.getSingleton().getExtensionFromMimeType(mime);
162		message.setRelativeFilePath(message.getUuid() + "." + extension);
163		DownloadableFile file = mXmppConnectionService.getFileBackend().getFile(message);
164		file.getParentFile().mkdirs();
165		OutputStream os = null;
166		InputStream is = null;
167		try {
168			file.createNewFile();
169			os = new FileOutputStream(file);
170			is = mXmppConnectionService.getContentResolver().openInputStream(uri);
171			byte[] buffer = new byte[1024];
172			int length;
173			while ((length = is.read(buffer)) > 0) {
174				os.write(buffer, 0, length);
175			}
176			os.flush();
177		} catch(FileNotFoundException e) {
178			throw new FileCopyException(R.string.error_file_not_found);
179		} catch (IOException e) {
180			e.printStackTrace();
181			throw new FileCopyException(R.string.error_io_exception);
182		} finally {
183			close(os);
184			close(is);
185		}
186		Log.d(Config.LOGTAG, "output file name " + mXmppConnectionService.getFileBackend().getFile(message));
187		return file;
188	}
189
190	public DownloadableFile copyImageToPrivateStorage(Message message, Uri image)
191			throws FileCopyException {
192		return this.copyImageToPrivateStorage(message, image, 0);
193	}
194
195	private DownloadableFile copyImageToPrivateStorage(Message message,Uri image, int sampleSize) throws FileCopyException {
196		switch(Config.IMAGE_FORMAT) {
197			case JPEG:
198				message.setRelativeFilePath(message.getUuid()+".jpg");
199				break;
200			case PNG:
201				message.setRelativeFilePath(message.getUuid()+".png");
202				break;
203			case WEBP:
204				message.setRelativeFilePath(message.getUuid()+".webp");
205				break;
206		}
207		DownloadableFile file = getFile(message);
208		file.getParentFile().mkdirs();
209		InputStream is = null;
210		OutputStream os = null;
211		try {
212			file.createNewFile();
213			is = mXmppConnectionService.getContentResolver().openInputStream(image);
214			os = new FileOutputStream(file);
215
216			Bitmap originalBitmap;
217			BitmapFactory.Options options = new BitmapFactory.Options();
218			int inSampleSize = (int) Math.pow(2, sampleSize);
219			Log.d(Config.LOGTAG, "reading bitmap with sample size " + inSampleSize);
220			options.inSampleSize = inSampleSize;
221			originalBitmap = BitmapFactory.decodeStream(is, null, options);
222			is.close();
223			if (originalBitmap == null) {
224				throw new FileCopyException(R.string.error_not_an_image_file);
225			}
226			Bitmap scaledBitmap = resize(originalBitmap, Config.IMAGE_SIZE);
227			int rotation = getRotation(image);
228			scaledBitmap = rotate(scaledBitmap, rotation);
229			boolean success = scaledBitmap.compress(Config.IMAGE_FORMAT, Config.IMAGE_QUALITY, os);
230			if (!success) {
231				throw new FileCopyException(R.string.error_compressing_image);
232			}
233			os.flush();
234			long size = file.getSize();
235			int width = scaledBitmap.getWidth();
236			int height = scaledBitmap.getHeight();
237			message.setBody(Long.toString(size) + '|' + width + '|' + height);
238			return file;
239		} catch (FileNotFoundException e) {
240			throw new FileCopyException(R.string.error_file_not_found);
241		} catch (IOException e) {
242			e.printStackTrace();
243			throw new FileCopyException(R.string.error_io_exception);
244		} catch (SecurityException e) {
245			throw new FileCopyException(R.string.error_security_exception_during_image_copy);
246		} catch (OutOfMemoryError e) {
247			++sampleSize;
248			if (sampleSize <= 3) {
249				return copyImageToPrivateStorage(message, image, sampleSize);
250			} else {
251				throw new FileCopyException(R.string.error_out_of_memory);
252			}
253		} catch (NullPointerException e) {
254			throw new FileCopyException(R.string.error_io_exception);
255		} finally {
256			close(os);
257			close(is);
258		}
259	}
260
261	private int getRotation(File file) {
262		return getRotation(Uri.parse("file://"+file.getAbsolutePath()));
263	}
264
265	private int getRotation(Uri image) {
266		InputStream is = null;
267		try {
268			is = mXmppConnectionService.getContentResolver().openInputStream(image);
269			return ExifHelper.getOrientation(is);
270		} catch (FileNotFoundException e) {
271			return 0;
272		} finally {
273			close(is);
274		}
275	}
276
277	public Bitmap getThumbnail(Message message, int size, boolean cacheOnly)
278			throws FileNotFoundException {
279		Bitmap thumbnail = mXmppConnectionService.getBitmapCache().get(message.getUuid());
280		if ((thumbnail == null) && (!cacheOnly)) {
281			File file = getFile(message);
282			BitmapFactory.Options options = new BitmapFactory.Options();
283			options.inSampleSize = calcSampleSize(file, size);
284			Bitmap fullsize = BitmapFactory.decodeFile(file.getAbsolutePath(),options);
285			if (fullsize == null) {
286				throw new FileNotFoundException();
287			}
288			thumbnail = resize(fullsize, size);
289			thumbnail = rotate(thumbnail, getRotation(file));
290			this.mXmppConnectionService.getBitmapCache().put(message.getUuid(),thumbnail);
291		}
292		return thumbnail;
293	}
294
295	public Uri getTakePhotoUri() {
296		StringBuilder pathBuilder = new StringBuilder();
297		pathBuilder.append(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM));
298		pathBuilder.append('/');
299		pathBuilder.append("Camera");
300		pathBuilder.append('/');
301		pathBuilder.append("IMG_" + this.imageDateFormat.format(new Date()) + ".jpg");
302		Uri uri = Uri.parse("file://" + pathBuilder.toString());
303		File file = new File(uri.toString());
304		file.getParentFile().mkdirs();
305		return uri;
306	}
307
308	public Avatar getPepAvatar(Uri image, int size, Bitmap.CompressFormat format) {
309		try {
310			Avatar avatar = new Avatar();
311			Bitmap bm = cropCenterSquare(image, size);
312			if (bm == null) {
313				return null;
314			}
315			ByteArrayOutputStream mByteArrayOutputStream = new ByteArrayOutputStream();
316			Base64OutputStream mBase64OutputSttream = new Base64OutputStream(
317					mByteArrayOutputStream, Base64.DEFAULT);
318			MessageDigest digest = MessageDigest.getInstance("SHA-1");
319			DigestOutputStream mDigestOutputStream = new DigestOutputStream(
320					mBase64OutputSttream, digest);
321			if (!bm.compress(format, 75, mDigestOutputStream)) {
322				return null;
323			}
324			mDigestOutputStream.flush();
325			mDigestOutputStream.close();
326			avatar.sha1sum = CryptoHelper.bytesToHex(digest.digest());
327			avatar.image = new String(mByteArrayOutputStream.toByteArray());
328			return avatar;
329		} catch (NoSuchAlgorithmException e) {
330			return null;
331		} catch (IOException e) {
332			return null;
333		}
334	}
335
336	public boolean isAvatarCached(Avatar avatar) {
337		File file = new File(getAvatarPath(avatar.getFilename()));
338		return file.exists();
339	}
340
341	public boolean save(Avatar avatar) {
342		File file;
343		if (isAvatarCached(avatar)) {
344			file = new File(getAvatarPath(avatar.getFilename()));
345		} else {
346			String filename = getAvatarPath(avatar.getFilename());
347			file = new File(filename + ".tmp");
348			file.getParentFile().mkdirs();
349			OutputStream os = null;
350			try {
351				file.createNewFile();
352				os = new FileOutputStream(file);
353				MessageDigest digest = MessageDigest.getInstance("SHA-1");
354				digest.reset();
355				DigestOutputStream mDigestOutputStream = new DigestOutputStream(os, digest);
356				mDigestOutputStream.write(avatar.getImageAsBytes());
357				mDigestOutputStream.flush();
358				mDigestOutputStream.close();
359				String sha1sum = CryptoHelper.bytesToHex(digest.digest());
360				if (sha1sum.equals(avatar.sha1sum)) {
361					file.renameTo(new File(filename));
362				} else {
363					Log.d(Config.LOGTAG, "sha1sum mismatch for " + avatar.owner);
364					file.delete();
365					return false;
366				}
367			} catch (IllegalArgumentException | IOException | NoSuchAlgorithmException e) {
368				return false;
369			} finally {
370				close(os);
371			}
372		}
373		avatar.size = file.length();
374		return true;
375	}
376
377	public String getAvatarPath(String avatar) {
378		return mXmppConnectionService.getFilesDir().getAbsolutePath()+ "/avatars/" + avatar;
379	}
380
381	public Uri getAvatarUri(String avatar) {
382		return Uri.parse("file:" + getAvatarPath(avatar));
383	}
384
385	public Bitmap cropCenterSquare(Uri image, int size) {
386		if (image == null) {
387			return null;
388		}
389		InputStream is = null;
390		try {
391			BitmapFactory.Options options = new BitmapFactory.Options();
392			options.inSampleSize = calcSampleSize(image, size);
393			is = mXmppConnectionService.getContentResolver().openInputStream(image);
394			if (is == null) {
395				return null;
396			}
397			Bitmap input = BitmapFactory.decodeStream(is, null, options);
398			if (input == null) {
399				return null;
400			} else {
401				input = rotate(input, getRotation(image));
402				return cropCenterSquare(input, size);
403			}
404		} catch (SecurityException e) {
405			return null; // happens for example on Android 6.0 if contacts permissions get revoked
406		} catch (FileNotFoundException e) {
407			return null;
408		} finally {
409			close(is);
410		}
411	}
412
413	public Bitmap cropCenter(Uri image, int newHeight, int newWidth) {
414		if (image == null) {
415			return null;
416		}
417		InputStream is = null;
418		try {
419			BitmapFactory.Options options = new BitmapFactory.Options();
420			options.inSampleSize = calcSampleSize(image, Math.max(newHeight, newWidth));
421			is = mXmppConnectionService.getContentResolver().openInputStream(image);
422			if (is == null) {
423				return null;
424			}
425			Bitmap source = BitmapFactory.decodeStream(is, null, options);
426			if (source == null) {
427				return null;
428			}
429			int sourceWidth = source.getWidth();
430			int sourceHeight = source.getHeight();
431			float xScale = (float) newWidth / sourceWidth;
432			float yScale = (float) newHeight / sourceHeight;
433			float scale = Math.max(xScale, yScale);
434			float scaledWidth = scale * sourceWidth;
435			float scaledHeight = scale * sourceHeight;
436			float left = (newWidth - scaledWidth) / 2;
437			float top = (newHeight - scaledHeight) / 2;
438
439			RectF targetRect = new RectF(left, top, left + scaledWidth, top + scaledHeight);
440			Bitmap dest = Bitmap.createBitmap(newWidth, newHeight, Bitmap.Config.ARGB_8888);
441			Canvas canvas = new Canvas(dest);
442			canvas.drawBitmap(source, null, targetRect, null);
443			if (source != null && !source.isRecycled()) {
444				source.recycle();
445			}
446			return dest;
447		} catch (SecurityException e) {
448			return null; //android 6.0 with revoked permissions for example
449		} catch (FileNotFoundException e) {
450			return null;
451		} finally {
452			close(is);
453		}
454	}
455
456	public Bitmap cropCenterSquare(Bitmap input, int size) {
457		int w = input.getWidth();
458		int h = input.getHeight();
459
460		float scale = Math.max((float) size / h, (float) size / w);
461
462		float outWidth = scale * w;
463		float outHeight = scale * h;
464		float left = (size - outWidth) / 2;
465		float top = (size - outHeight) / 2;
466		RectF target = new RectF(left, top, left + outWidth, top + outHeight);
467
468		Bitmap output = Bitmap.createBitmap(size, size, Bitmap.Config.ARGB_8888);
469		Canvas canvas = new Canvas(output);
470		canvas.drawBitmap(input, null, target, null);
471		if (input != null && !input.isRecycled()) {
472			input.recycle();
473		}
474		return output;
475	}
476
477	private int calcSampleSize(Uri image, int size) throws FileNotFoundException, SecurityException {
478		BitmapFactory.Options options = new BitmapFactory.Options();
479		options.inJustDecodeBounds = true;
480		BitmapFactory.decodeStream(mXmppConnectionService.getContentResolver().openInputStream(image), null, options);
481		return calcSampleSize(options, size);
482	}
483
484	private static int calcSampleSize(File image, int size) {
485		BitmapFactory.Options options = new BitmapFactory.Options();
486		options.inJustDecodeBounds = true;
487		BitmapFactory.decodeFile(image.getAbsolutePath(), options);
488		return calcSampleSize(options, size);
489	}
490
491	public static int calcSampleSize(BitmapFactory.Options options, int size) {
492		int height = options.outHeight;
493		int width = options.outWidth;
494		int inSampleSize = 1;
495
496		if (height > size || width > size) {
497			int halfHeight = height / 2;
498			int halfWidth = width / 2;
499
500			while ((halfHeight / inSampleSize) > size
501					&& (halfWidth / inSampleSize) > size) {
502				inSampleSize *= 2;
503			}
504		}
505		return inSampleSize;
506	}
507
508	public Uri getJingleFileUri(Message message) {
509		File file = getFile(message);
510		return Uri.parse("file://" + file.getAbsolutePath());
511	}
512
513	public void updateFileParams(Message message) {
514		updateFileParams(message,null);
515	}
516
517	public void updateFileParams(Message message, URL url) {
518		DownloadableFile file = getFile(message);
519		if (message.getType() == Message.TYPE_IMAGE || file.getMimeType().startsWith("image/")) {
520			BitmapFactory.Options options = new BitmapFactory.Options();
521			options.inJustDecodeBounds = true;
522			BitmapFactory.decodeFile(file.getAbsolutePath(), options);
523			int rotation = getRotation(file);
524			boolean rotated = rotation == 90 || rotation == 270;
525			int imageHeight = rotated ? options.outWidth : options.outHeight;
526			int imageWidth = rotated ? options.outHeight : options.outWidth;
527			if (url == null) {
528				message.setBody(Long.toString(file.getSize()) + '|' + imageWidth + '|' + imageHeight);
529			} else {
530				message.setBody(url.toString()+"|"+Long.toString(file.getSize()) + '|' + imageWidth + '|' + imageHeight);
531			}
532		} else {
533			if (url != null) {
534				message.setBody(url.toString()+"|"+Long.toString(file.getSize()));
535			} else {
536				message.setBody(Long.toString(file.getSize()));
537			}
538		}
539
540	}
541
542	public class FileCopyException extends Exception {
543		private static final long serialVersionUID = -1010013599132881427L;
544		private int resId;
545
546		public FileCopyException(int resId) {
547			this.resId = resId;
548		}
549
550		public int getResId() {
551			return resId;
552		}
553	}
554
555	public Bitmap getAvatar(String avatar, int size) {
556		if (avatar == null) {
557			return null;
558		}
559		Bitmap bm = cropCenter(getAvatarUri(avatar), size, size);
560		if (bm == null) {
561			return null;
562		}
563		return bm;
564	}
565
566	public boolean isFileAvailable(Message message) {
567		return getFile(message).exists();
568	}
569
570	public static void close(Closeable stream) {
571		if (stream != null) {
572			try {
573				stream.close();
574			} catch (IOException e) {
575			}
576		}
577	}
578
579	public static void close(Socket socket) {
580		if (socket != null) {
581			try {
582				socket.close();
583			} catch (IOException e) {
584			}
585		}
586	}
587}