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