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