FileBackend.java

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