FileBackend.java

  1package eu.siacs.conversations.persistance;
  2
  3import java.io.ByteArrayOutputStream;
  4import java.io.File;
  5import java.io.FileNotFoundException;
  6import java.io.FileOutputStream;
  7import java.io.IOException;
  8import java.io.InputStream;
  9import java.io.OutputStream;
 10import java.security.DigestOutputStream;
 11import java.security.MessageDigest;
 12import java.security.NoSuchAlgorithmException;
 13import java.text.SimpleDateFormat;
 14import java.util.Date;
 15import java.util.Locale;
 16
 17import android.database.Cursor;
 18import android.graphics.Bitmap;
 19import android.graphics.BitmapFactory;
 20import android.graphics.Canvas;
 21import android.graphics.Matrix;
 22import android.graphics.RectF;
 23import android.net.Uri;
 24import android.os.Environment;
 25import android.provider.MediaStore;
 26import android.util.Base64;
 27import android.util.Base64OutputStream;
 28import android.util.Log;
 29import eu.siacs.conversations.Config;
 30import eu.siacs.conversations.R;
 31import eu.siacs.conversations.entities.DownloadableFile;
 32import eu.siacs.conversations.entities.Message;
 33import eu.siacs.conversations.services.XmppConnectionService;
 34import eu.siacs.conversations.utils.CryptoHelper;
 35import eu.siacs.conversations.utils.ExifHelper;
 36import eu.siacs.conversations.xmpp.pep.Avatar;
 37
 38public class FileBackend {
 39
 40	private static int IMAGE_SIZE = 1920;
 41
 42	private SimpleDateFormat imageDateFormat = new SimpleDateFormat(
 43			"yyyyMMdd_HHmmssSSS", Locale.US);
 44
 45	private XmppConnectionService mXmppConnectionService;
 46
 47	public FileBackend(XmppConnectionService service) {
 48		this.mXmppConnectionService = service;
 49	}
 50
 51	public DownloadableFile getFile(Message message) {
 52		return getFile(message, true);
 53	}
 54
 55	public DownloadableFile getFile(Message message, boolean decrypted) {
 56		StringBuilder filename = new StringBuilder();
 57		filename.append(getConversationsDirectory());
 58		filename.append(message.getUuid());
 59		if ((decrypted) || (message.getEncryption() == Message.ENCRYPTION_NONE)) {
 60			filename.append(".webp");
 61		} else {
 62			if (message.getEncryption() == Message.ENCRYPTION_OTR) {
 63				filename.append(".webp");
 64			} else {
 65				filename.append(".webp.pgp");
 66			}
 67		}
 68		return new DownloadableFile(filename.toString());
 69	}
 70
 71	public static String getConversationsDirectory() {
 72		return Environment.getExternalStoragePublicDirectory(
 73				Environment.DIRECTORY_PICTURES).getAbsolutePath()
 74				+ "/Conversations/";
 75	}
 76
 77	public Bitmap resize(Bitmap originalBitmap, int size) {
 78		int w = originalBitmap.getWidth();
 79		int h = originalBitmap.getHeight();
 80		if (Math.max(w, h) > size) {
 81			int scalledW;
 82			int scalledH;
 83			if (w <= h) {
 84				scalledW = (int) (w / ((double) h / size));
 85				scalledH = size;
 86			} else {
 87				scalledW = size;
 88				scalledH = (int) (h / ((double) w / size));
 89			}
 90			Bitmap scalledBitmap = Bitmap.createScaledBitmap(originalBitmap,
 91					scalledW, scalledH, true);
 92			return scalledBitmap;
 93		} else {
 94			return originalBitmap;
 95		}
 96	}
 97
 98	public Bitmap rotate(Bitmap bitmap, int degree) {
 99		int w = bitmap.getWidth();
100		int h = bitmap.getHeight();
101		Matrix mtx = new Matrix();
102		mtx.postRotate(degree);
103		return Bitmap.createBitmap(bitmap, 0, 0, w, h, mtx, true);
104	}
105
106	public DownloadableFile copyImageToPrivateStorage(Message message, Uri image)
107			throws ImageCopyException {
108		return this.copyImageToPrivateStorage(message, image, 0);
109	}
110
111	private DownloadableFile copyImageToPrivateStorage(Message message,
112			Uri image, int sampleSize) throws ImageCopyException {
113		try {
114			InputStream is = mXmppConnectionService.getContentResolver()
115					.openInputStream(image);
116			DownloadableFile file = getFile(message);
117			file.getParentFile().mkdirs();
118			file.createNewFile();
119			Bitmap originalBitmap;
120			BitmapFactory.Options options = new BitmapFactory.Options();
121			int inSampleSize = (int) Math.pow(2, sampleSize);
122			Log.d(Config.LOGTAG, "reading bitmap with sample size "
123					+ inSampleSize);
124			options.inSampleSize = inSampleSize;
125			originalBitmap = BitmapFactory.decodeStream(is, null, options);
126			is.close();
127			if (originalBitmap == null) {
128				throw new ImageCopyException(R.string.error_not_an_image_file);
129			}
130			Bitmap scalledBitmap = resize(originalBitmap, IMAGE_SIZE);
131			originalBitmap = null;
132			int rotation = getRotation(image);
133			if (rotation > 0) {
134				scalledBitmap = rotate(scalledBitmap, rotation);
135			}
136			OutputStream os = new FileOutputStream(file);
137			boolean success = scalledBitmap.compress(
138					Bitmap.CompressFormat.WEBP, 75, os);
139			if (!success) {
140				throw new ImageCopyException(R.string.error_compressing_image);
141			}
142			os.flush();
143			os.close();
144			long size = file.getSize();
145			int width = scalledBitmap.getWidth();
146			int height = scalledBitmap.getHeight();
147			message.setBody(Long.toString(size) + ',' + width + ',' + height);
148			return file;
149		} catch (FileNotFoundException e) {
150			throw new ImageCopyException(R.string.error_file_not_found);
151		} catch (IOException e) {
152			throw new ImageCopyException(R.string.error_io_exception);
153		} catch (SecurityException e) {
154			throw new ImageCopyException(
155					R.string.error_security_exception_during_image_copy);
156		} catch (OutOfMemoryError e) {
157			++sampleSize;
158			if (sampleSize <= 3) {
159				return copyImageToPrivateStorage(message, image, sampleSize);
160			} else {
161				throw new ImageCopyException(R.string.error_out_of_memory);
162			}
163		}
164	}
165
166	private int getRotation(Uri image) {
167		if ("content".equals(image.getScheme())) {
168			try {
169				Cursor cursor = mXmppConnectionService
170						.getContentResolver()
171						.query(image,
172								new String[] { MediaStore.Images.ImageColumns.ORIENTATION },
173								null, null, null);
174				if (cursor.getCount() != 1) {
175					return -1;
176				}
177				cursor.moveToFirst();
178				return cursor.getInt(0);
179			} catch (IllegalArgumentException e) {
180				return -1;
181			}
182		} else {
183			try {
184				InputStream is = mXmppConnectionService.getContentResolver()
185						.openInputStream(image);
186				return ExifHelper.getOrientation(is);
187			} catch (FileNotFoundException e) {
188				return 0;
189			}
190		}
191	}
192
193	public Bitmap getImageFromMessage(Message message) {
194		return BitmapFactory.decodeFile(getFile(message).getAbsolutePath());
195	}
196
197	public Bitmap getThumbnail(Message message, int size, boolean cacheOnly)
198			throws FileNotFoundException {
199		Bitmap thumbnail = mXmppConnectionService.getBitmapCache().get(
200				message.getUuid());
201		if ((thumbnail == null) && (!cacheOnly)) {
202			File file = getFile(message);
203			BitmapFactory.Options options = new BitmapFactory.Options();
204			options.inSampleSize = calcSampleSize(file, size);
205			Bitmap fullsize = BitmapFactory.decodeFile(file.getAbsolutePath(),
206					options);
207			if (fullsize == null) {
208				throw new FileNotFoundException();
209			}
210			thumbnail = resize(fullsize, size);
211			this.mXmppConnectionService.getBitmapCache().put(message.getUuid(),
212					thumbnail);
213		}
214		return thumbnail;
215	}
216
217	public Uri getTakePhotoUri() {
218		StringBuilder pathBuilder = new StringBuilder();
219		pathBuilder.append(Environment
220				.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM));
221		pathBuilder.append('/');
222		pathBuilder.append("Camera");
223		pathBuilder.append('/');
224		pathBuilder.append("IMG_" + this.imageDateFormat.format(new Date())
225				+ ".jpg");
226		Uri uri = Uri.parse("file://" + pathBuilder.toString());
227		File file = new File(uri.toString());
228		file.getParentFile().mkdirs();
229		return uri;
230	}
231
232	public Avatar getPepAvatar(Uri image, int size, Bitmap.CompressFormat format) {
233		try {
234			Avatar avatar = new Avatar();
235			Bitmap bm = cropCenterSquare(image, size);
236			if (bm == null) {
237				return null;
238			}
239			ByteArrayOutputStream mByteArrayOutputStream = new ByteArrayOutputStream();
240			Base64OutputStream mBase64OutputSttream = new Base64OutputStream(
241					mByteArrayOutputStream, Base64.DEFAULT);
242			MessageDigest digest = MessageDigest.getInstance("SHA-1");
243			DigestOutputStream mDigestOutputStream = new DigestOutputStream(
244					mBase64OutputSttream, digest);
245			if (!bm.compress(format, 75, mDigestOutputStream)) {
246				return null;
247			}
248			mDigestOutputStream.flush();
249			mDigestOutputStream.close();
250			avatar.sha1sum = CryptoHelper.bytesToHex(digest.digest());
251			avatar.image = new String(mByteArrayOutputStream.toByteArray());
252			return avatar;
253		} catch (NoSuchAlgorithmException e) {
254			return null;
255		} catch (IOException e) {
256			return null;
257		}
258	}
259
260	public boolean isAvatarCached(Avatar avatar) {
261		File file = new File(getAvatarPath(avatar.getFilename()));
262		return file.exists();
263	}
264
265	public boolean save(Avatar avatar) {
266		if (isAvatarCached(avatar)) {
267			return true;
268		}
269		String filename = getAvatarPath(avatar.getFilename());
270		File file = new File(filename + ".tmp");
271		file.getParentFile().mkdirs();
272		try {
273			file.createNewFile();
274			FileOutputStream mFileOutputStream = new FileOutputStream(file);
275			MessageDigest digest = MessageDigest.getInstance("SHA-1");
276			digest.reset();
277			DigestOutputStream mDigestOutputStream = new DigestOutputStream(
278					mFileOutputStream, digest);
279			mDigestOutputStream.write(avatar.getImageAsBytes());
280			mDigestOutputStream.flush();
281			mDigestOutputStream.close();
282			avatar.size = file.length();
283			String sha1sum = CryptoHelper.bytesToHex(digest.digest());
284			if (sha1sum.equals(avatar.sha1sum)) {
285				file.renameTo(new File(filename));
286				return true;
287			} else {
288				Log.d(Config.LOGTAG, "sha1sum mismatch for " + avatar.owner);
289				file.delete();
290				return false;
291			}
292		} catch (FileNotFoundException e) {
293			return false;
294		} catch (IOException e) {
295			return false;
296		} catch (NoSuchAlgorithmException e) {
297			return false;
298		}
299	}
300
301	public String getAvatarPath(String avatar) {
302		return mXmppConnectionService.getFilesDir().getAbsolutePath()
303				+ "/avatars/" + avatar;
304	}
305
306	public Uri getAvatarUri(String avatar) {
307		return Uri.parse("file:" + getAvatarPath(avatar));
308	}
309
310	public Bitmap cropCenterSquare(Uri image, int size) {
311		try {
312			BitmapFactory.Options options = new BitmapFactory.Options();
313			options.inSampleSize = calcSampleSize(image, size);
314			InputStream is = mXmppConnectionService.getContentResolver()
315					.openInputStream(image);
316			Bitmap input = BitmapFactory.decodeStream(is, null, options);
317			if (input == null) {
318				return null;
319			} else {
320				int rotation = getRotation(image);
321				if (rotation > 0) {
322					input = rotate(input, rotation);
323				}
324				return cropCenterSquare(input, size);
325			}
326		} catch (FileNotFoundException e) {
327			return null;
328		}
329	}
330
331	public Bitmap cropCenter(Uri image, int newHeight, int newWidth) {
332		try {
333			BitmapFactory.Options options = new BitmapFactory.Options();
334			options.inSampleSize = calcSampleSize(image,
335					Math.max(newHeight, newWidth));
336			InputStream is = mXmppConnectionService.getContentResolver()
337					.openInputStream(image);
338			Bitmap source = BitmapFactory.decodeStream(is, null, options);
339
340			int sourceWidth = source.getWidth();
341			int sourceHeight = source.getHeight();
342			float xScale = (float) newWidth / sourceWidth;
343			float yScale = (float) newHeight / sourceHeight;
344			float scale = Math.max(xScale, yScale);
345			float scaledWidth = scale * sourceWidth;
346			float scaledHeight = scale * sourceHeight;
347			float left = (newWidth - scaledWidth) / 2;
348			float top = (newHeight - scaledHeight) / 2;
349
350			RectF targetRect = new RectF(left, top, left + scaledWidth, top
351					+ scaledHeight);
352			Bitmap dest = Bitmap.createBitmap(newWidth, newHeight,
353					source.getConfig());
354			Canvas canvas = new Canvas(dest);
355			canvas.drawBitmap(source, null, targetRect, null);
356
357			return dest;
358		} catch (FileNotFoundException e) {
359			return null;
360		}
361
362	}
363
364	public Bitmap cropCenterSquare(Bitmap input, int size) {
365		int w = input.getWidth();
366		int h = input.getHeight();
367
368		float scale = Math.max((float) size / h, (float) size / w);
369
370		float outWidth = scale * w;
371		float outHeight = scale * h;
372		float left = (size - outWidth) / 2;
373		float top = (size - outHeight) / 2;
374		RectF target = new RectF(left, top, left + outWidth, top + outHeight);
375
376		Bitmap output = Bitmap.createBitmap(size, size, input.getConfig());
377		Canvas canvas = new Canvas(output);
378		canvas.drawBitmap(input, null, target, null);
379		return output;
380	}
381
382	private int calcSampleSize(Uri image, int size)
383			throws FileNotFoundException {
384		BitmapFactory.Options options = new BitmapFactory.Options();
385		options.inJustDecodeBounds = true;
386		BitmapFactory.decodeStream(mXmppConnectionService.getContentResolver()
387				.openInputStream(image), null, options);
388		return calcSampleSize(options, size);
389	}
390
391	private int calcSampleSize(File image, int size) {
392		BitmapFactory.Options options = new BitmapFactory.Options();
393		options.inJustDecodeBounds = true;
394		BitmapFactory.decodeFile(image.getAbsolutePath(), options);
395		return calcSampleSize(options, size);
396	}
397
398	private int calcSampleSize(BitmapFactory.Options options, int size) {
399		int height = options.outHeight;
400		int width = options.outWidth;
401		int inSampleSize = 1;
402
403		if (height > size || width > size) {
404			int halfHeight = height / 2;
405			int halfWidth = width / 2;
406
407			while ((halfHeight / inSampleSize) > size
408					&& (halfWidth / inSampleSize) > size) {
409				inSampleSize *= 2;
410			}
411		}
412		return inSampleSize;
413	}
414
415	public Uri getJingleFileUri(Message message) {
416		File file = getFile(message);
417		return Uri.parse("file://" + file.getAbsolutePath());
418	}
419
420	public class ImageCopyException extends Exception {
421		private static final long serialVersionUID = -1010013599132881427L;
422		private int resId;
423
424		public ImageCopyException(int resId) {
425			this.resId = resId;
426		}
427
428		public int getResId() {
429			return resId;
430		}
431	}
432
433	public Bitmap getAvatar(String avatar, int size) {
434		if (avatar == null) {
435			return null;
436		}
437		Bitmap bm = cropCenter(getAvatarUri(avatar), size, size);
438		if (bm == null) {
439			return null;
440		}
441		return bm;
442	}
443
444	public boolean isFileAvailable(Message message) {
445		return getFile(message).exists();
446	}
447}