AttachFileToConversationRunnable.java

  1package eu.siacs.conversations.services;
  2
  3import android.net.Uri;
  4import android.os.Build;
  5import android.os.ParcelFileDescriptor;
  6import android.util.Log;
  7
  8import net.ypresto.androidtranscoder.MediaTranscoder;
  9import net.ypresto.androidtranscoder.format.MediaFormatStrategy;
 10import net.ypresto.androidtranscoder.format.MediaFormatStrategyPresets;
 11
 12import java.io.File;
 13import java.io.FileDescriptor;
 14import java.io.FileNotFoundException;
 15import java.util.concurrent.ExecutionException;
 16import java.util.concurrent.Future;
 17import java.util.concurrent.atomic.AtomicInteger;
 18
 19import eu.siacs.conversations.Config;
 20import eu.siacs.conversations.R;
 21import eu.siacs.conversations.crypto.PgpEngine;
 22import eu.siacs.conversations.entities.DownloadableFile;
 23import eu.siacs.conversations.entities.Message;
 24import eu.siacs.conversations.persistance.FileBackend;
 25import eu.siacs.conversations.ui.UiCallback;
 26import eu.siacs.conversations.utils.MimeUtils;
 27
 28public class AttachFileToConversationRunnable implements Runnable, MediaTranscoder.Listener {
 29
 30	private final XmppConnectionService mXmppConnectionService;
 31	private final Message message;
 32	private final Uri uri;
 33	private final UiCallback<Message> callback;
 34	private final boolean isVideoMessage;
 35	private final long originalFileSize;
 36	private int currentProgress = -1;
 37
 38	public AttachFileToConversationRunnable(XmppConnectionService xmppConnectionService, Uri uri, Message message, UiCallback<Message> callback) {
 39		this.uri = uri;
 40		this.mXmppConnectionService = xmppConnectionService;
 41		this.message = message;
 42		this.callback = callback;
 43		final String mimeType = MimeUtils.guessMimeTypeFromUri(mXmppConnectionService, uri);
 44		final int autoAcceptFileSize = mXmppConnectionService.getResources().getInteger(R.integer.auto_accept_filesize);
 45		this.originalFileSize = FileBackend.getFileSize(mXmppConnectionService,uri);
 46		this.isVideoMessage = (mimeType != null && mimeType.startsWith("video/")
 47				&& Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2)
 48				&& originalFileSize > autoAcceptFileSize;
 49	}
 50
 51	public boolean isVideoMessage() {
 52		return this.isVideoMessage;
 53	}
 54
 55	private void processAsFile() {
 56		final String path = mXmppConnectionService.getFileBackend().getOriginalPath(uri);
 57		if (path != null) {
 58			message.setRelativeFilePath(path);
 59			mXmppConnectionService.getFileBackend().updateFileParams(message);
 60			if (message.getEncryption() == Message.ENCRYPTION_DECRYPTED) {
 61				mXmppConnectionService.getPgpEngine().encrypt(message, callback);
 62			} else {
 63				callback.success(message);
 64			}
 65		} else {
 66			try {
 67				mXmppConnectionService.getFileBackend().copyFileToPrivateStorage(message, uri);
 68				mXmppConnectionService.getFileBackend().updateFileParams(message);
 69				if (message.getEncryption() == Message.ENCRYPTION_DECRYPTED) {
 70					final PgpEngine pgpEngine = mXmppConnectionService.getPgpEngine();
 71					if (pgpEngine != null) {
 72						pgpEngine.encrypt(message, callback);
 73					} else if (callback != null) {
 74						callback.error(R.string.unable_to_connect_to_keychain, null);
 75					}
 76				} else {
 77					callback.success(message);
 78				}
 79			} catch (FileBackend.FileCopyException e) {
 80				callback.error(e.getResId(), message);
 81			}
 82		}
 83	}
 84
 85	private void processAsVideo() throws FileNotFoundException {
 86		Log.d(Config.LOGTAG,"processing file as video");
 87		mXmppConnectionService.startForcingForegroundNotification();
 88		message.setRelativeFilePath(message.getUuid() + ".mp4");
 89		final DownloadableFile file = mXmppConnectionService.getFileBackend().getFile(message);
 90		final int runtime = mXmppConnectionService.getFileBackend().getMediaRuntime(uri);
 91		MediaFormatStrategy formatStrategy = runtime >= 8000 ? MediaFormatStrategyPresets.createExportPreset960x540Strategy() : MediaFormatStrategyPresets.createAndroid720pStrategy();
 92		file.getParentFile().mkdirs();
 93		final ParcelFileDescriptor parcelFileDescriptor = mXmppConnectionService.getContentResolver().openFileDescriptor(uri, "r");
 94		if (parcelFileDescriptor == null) {
 95			throw new FileNotFoundException("Parcel File Descriptor was null");
 96		}
 97		FileDescriptor fileDescriptor = parcelFileDescriptor.getFileDescriptor();
 98		Future<Void> future = MediaTranscoder.getInstance().transcodeVideo(fileDescriptor, file.getAbsolutePath(), formatStrategy, this);
 99		try {
100			future.get();
101		} catch (InterruptedException e) {
102			throw new AssertionError(e);
103		} catch (ExecutionException e) {
104			Log.d(Config.LOGTAG,"ignoring execution exception. Should get handled by onTranscodeFiled() instead",e);
105		}
106	}
107
108	@Override
109	public void onTranscodeProgress(double progress) {
110		final int p = (int) Math.round(progress * 100);
111		if (p > currentProgress) {
112			currentProgress = p;
113			mXmppConnectionService.getNotificationService().updateFileAddingNotification(p,message);
114		}
115	}
116
117	@Override
118	public void onTranscodeCompleted() {
119		mXmppConnectionService.stopForcingForegroundNotification();
120		final File file = mXmppConnectionService.getFileBackend().getFile(message);
121		long convertedFileSize = mXmppConnectionService.getFileBackend().getFile(message).getSize();
122		Log.d(Config.LOGTAG,"originalFileSize="+originalFileSize+" convertedFileSize="+convertedFileSize);
123		if (originalFileSize != 0 && convertedFileSize >= originalFileSize) {
124			if (file.delete()) {
125				Log.d(Config.LOGTAG,"original file size was smaller. deleting and processing as file");
126				processAsFile();
127				return;
128			} else {
129				Log.d(Config.LOGTAG,"unable to delete converted file");
130			}
131		}
132		mXmppConnectionService.getFileBackend().updateFileParams(message);
133		if (message.getEncryption() == Message.ENCRYPTION_DECRYPTED) {
134			mXmppConnectionService.getPgpEngine().encrypt(message, callback);
135		} else {
136			callback.success(message);
137		}
138	}
139
140	@Override
141	public void onTranscodeCanceled() {
142		mXmppConnectionService.stopForcingForegroundNotification();
143		processAsFile();
144	}
145
146	@Override
147	public void onTranscodeFailed(Exception e) {
148		mXmppConnectionService.stopForcingForegroundNotification();
149		Log.d(Config.LOGTAG,"video transcoding failed",e);
150		processAsFile();
151	}
152
153	@Override
154	public void run() {
155		if (isVideoMessage) {
156			try {
157				processAsVideo();
158			} catch (FileNotFoundException e) {
159				processAsFile();
160			}
161		} else {
162			processAsFile();
163		}
164	}
165
166}