FileBackend.java

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