AttachFileToConversationRunnable.java

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