diff --git a/src/org/kde/kdeconnect/Plugins/SharePlugin/CompositeReceiveFileJob.java b/src/org/kde/kdeconnect/Plugins/SharePlugin/CompositeReceiveFileJob.java index 1a63081e..394dfbe2 100644 --- a/src/org/kde/kdeconnect/Plugins/SharePlugin/CompositeReceiveFileJob.java +++ b/src/org/kde/kdeconnect/Plugins/SharePlugin/CompositeReceiveFileJob.java @@ -1,357 +1,357 @@ /* * Copyright 2018 Erik Duisters * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License as * published by the Free Software Foundation; either version 2 of * the License or (at your option) version 3 or any later version * accepted by the membership of KDE e.V. (or its successor approved * by the membership of KDE e.V.), which shall act as a proxy * defined in Section 14 of version 3 of the license. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ package org.kde.kdeconnect.Plugins.SharePlugin; import android.app.DownloadManager; import android.content.ActivityNotFoundException; import android.content.Context; import android.content.Intent; import android.net.Uri; import android.os.Build; import android.util.Log; import org.kde.kdeconnect.Device; import org.kde.kdeconnect.Helpers.FilesHelper; import org.kde.kdeconnect.Helpers.MediaStoreHelper; import org.kde.kdeconnect.NetworkPacket; import org.kde.kdeconnect.async.BackgroundJob; import org.kde.kdeconnect_tp.R; import java.io.BufferedOutputStream; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.ArrayList; import java.util.List; import androidx.annotation.GuardedBy; import androidx.core.content.FileProvider; import androidx.documentfile.provider.DocumentFile; /** * A type of {@link BackgroundJob} that reads Files from another device. * *

* We receive the requests as {@link NetworkPacket}s. *

*

* Each packet should have a 'filename' property and a payload. If the payload is missing, * we'll just create an empty file. You can add new packets anytime via * {@link #addNetworkPacket(NetworkPacket)}. *

*

* The I/O-part of this file reading is handled by {@link #receiveFile(InputStream, OutputStream)}. *

* * @see CompositeUploadFileJob */ public class CompositeReceiveFileJob extends BackgroundJob { private final ReceiveNotification receiveNotification; private NetworkPacket currentNetworkPacket; private String currentFileName; private int currentFileNum; private long totalReceived; private long lastProgressTimeMillis; private long prevProgressPercentage; private final Object lock; //Use to protect concurrent access to the variables below @GuardedBy("lock") private final List networkPacketList; @GuardedBy("lock") private int totalNumFiles; @GuardedBy("lock") private long totalPayloadSize; private boolean isRunning; CompositeReceiveFileJob(Device device, BackgroundJob.Callback callBack) { super(device, callBack); lock = new Object(); networkPacketList = new ArrayList<>(); receiveNotification = new ReceiveNotification(device, getId()); currentFileNum = 0; totalNumFiles = 0; totalPayloadSize = 0; totalReceived = 0; lastProgressTimeMillis = 0; prevProgressPercentage = 0; } private Device getDevice() { return requestInfo; } boolean isRunning() { return isRunning; } void updateTotals(int numberOfFiles, long totalPayloadSize) { synchronized (lock) { this.totalNumFiles = numberOfFiles; this.totalPayloadSize = totalPayloadSize; receiveNotification.setTitle(getDevice().getContext().getResources() .getQuantityString(R.plurals.incoming_file_title, totalNumFiles, totalNumFiles, getDevice().getName())); } } void addNetworkPacket(NetworkPacket networkPacket) { synchronized (lock) { if (!networkPacketList.contains(networkPacket)) { networkPacketList.add(networkPacket); totalNumFiles = networkPacket.getInt(SharePlugin.KEY_NUMBER_OF_FILES, 1); totalPayloadSize = networkPacket.getLong(SharePlugin.KEY_TOTAL_PAYLOAD_SIZE); receiveNotification.setTitle(getDevice().getContext().getResources() .getQuantityString(R.plurals.incoming_file_title, totalNumFiles, totalNumFiles, getDevice().getName())); } } } @Override public void run() { boolean done; OutputStream outputStream = null; synchronized (lock) { done = networkPacketList.isEmpty(); } try { DocumentFile fileDocument = null; isRunning = true; while (!done && !canceled) { synchronized (lock) { currentNetworkPacket = networkPacketList.get(0); } currentFileName = currentNetworkPacket.getString("filename", Long.toString(System.currentTimeMillis())); currentFileNum++; setProgress((int)prevProgressPercentage); - fileDocument = getDocumentFileFor(currentFileName, currentNetworkPacket.getBoolean("open")); + fileDocument = getDocumentFileFor(currentFileName, currentNetworkPacket.getBoolean("open", false)); if (currentNetworkPacket.hasPayload()) { outputStream = new BufferedOutputStream(getDevice().getContext().getContentResolver().openOutputStream(fileDocument.getUri())); InputStream inputStream = currentNetworkPacket.getPayload().getInputStream(); long received = receiveFile(inputStream, outputStream); currentNetworkPacket.getPayload().close(); if ( received != currentNetworkPacket.getPayloadSize()) { fileDocument.delete(); if (!canceled) { throw new RuntimeException("Failed to receive: " + currentFileName + " received:" + received + " bytes, expected: " + currentNetworkPacket.getPayloadSize() + " bytes"); } } else { publishFile(fileDocument, received); } } else { //TODO: Only set progress to 100 if this is the only file/packet to send setProgress(100); publishFile(fileDocument, 0); } boolean listIsEmpty; synchronized (lock) { networkPacketList.remove(0); listIsEmpty = networkPacketList.isEmpty(); } if (listIsEmpty && !canceled) { try { Thread.sleep(1000); } catch (InterruptedException ignored) {} synchronized (lock) { if (currentFileNum < totalNumFiles && networkPacketList.isEmpty()) { throw new RuntimeException("Failed to receive " + (totalNumFiles - currentFileNum + 1) + " files"); } } } synchronized (lock) { done = networkPacketList.isEmpty(); } } isRunning = false; if (canceled) { receiveNotification.cancel(); return; } int numFiles; synchronized (lock) { numFiles = totalNumFiles; } if (numFiles == 1 && currentNetworkPacket.getBoolean("open", false)) { receiveNotification.cancel(); openFile(fileDocument); } else { //Update the notification and allow to open the file from it receiveNotification.setFinished(getDevice().getContext().getResources().getQuantityString(R.plurals.received_files_title, numFiles, getDevice().getName(), numFiles)); if (totalNumFiles == 1 && fileDocument != null) { receiveNotification.setURI(fileDocument.getUri(), fileDocument.getType(), fileDocument.getName()); } receiveNotification.show(); } reportResult(null); } catch (ActivityNotFoundException e) { receiveNotification.setFinished(getDevice().getContext().getString(R.string.no_app_for_opening)); receiveNotification.show(); } catch (Exception e) { isRunning = false; Log.e("Shareplugin", "Error receiving file", e); int failedFiles; synchronized (lock) { failedFiles = (totalNumFiles - currentFileNum + 1); } receiveNotification.setFinished(getDevice().getContext().getResources().getQuantityString(R.plurals.received_files_fail_title, failedFiles, getDevice().getName(), failedFiles, totalNumFiles)); receiveNotification.show(); reportError(e); } finally { closeAllInputStreams(); networkPacketList.clear(); if (outputStream != null) { try { outputStream.close(); } catch (IOException ignored) {} } } } private DocumentFile getDocumentFileFor(final String filename, final boolean open) throws RuntimeException { final DocumentFile destinationFolderDocument; String filenameToUse = filename; //We need to check for already existing files only when storing in the default path. //User-defined paths use the new Storage Access Framework that already handles this. //If the file should be opened immediately store it in the standard location to avoid the FileProvider trouble (See ReceiveNotification::setURI) if (open || !ShareSettingsFragment.isCustomDestinationEnabled(getDevice().getContext())) { final String defaultPath = ShareSettingsFragment.getDefaultDestinationDirectory().getAbsolutePath(); filenameToUse = FilesHelper.findNonExistingNameForNewFile(defaultPath, filenameToUse); destinationFolderDocument = DocumentFile.fromFile(new File(defaultPath)); } else { destinationFolderDocument = ShareSettingsFragment.getDestinationDirectory(getDevice().getContext()); } String displayName = FilesHelper.getFileNameWithoutExt(filenameToUse); String mimeType = FilesHelper.getMimeTypeFromFile(filenameToUse); if ("*/*".equals(mimeType)) { displayName = filenameToUse; } DocumentFile fileDocument = destinationFolderDocument.createFile(mimeType, displayName); if (fileDocument == null) { throw new RuntimeException(getDevice().getContext().getString(R.string.cannot_create_file, filenameToUse)); } return fileDocument; } private long receiveFile(InputStream input, OutputStream output) throws IOException { byte[] data = new byte[4096]; int count; long received = 0; while ((count = input.read(data)) >= 0 && !canceled) { received += count; totalReceived += count; output.write(data, 0, count); long progressPercentage; synchronized (lock) { progressPercentage = (totalReceived * 100 / totalPayloadSize); } long curTimeMillis = System.currentTimeMillis(); if (progressPercentage != prevProgressPercentage && (progressPercentage == 100 || curTimeMillis - lastProgressTimeMillis >= 500)) { prevProgressPercentage = progressPercentage; lastProgressTimeMillis = curTimeMillis; setProgress((int)progressPercentage); } } output.flush(); return received; } private void closeAllInputStreams() { for (NetworkPacket np : networkPacketList) { np.getPayload().close(); } } private void setProgress(int progress) { synchronized (lock) { receiveNotification.setProgress(progress, getDevice().getContext().getResources() .getQuantityString(R.plurals.incoming_files_text, totalNumFiles, currentFileName, currentFileNum, totalNumFiles)); } receiveNotification.show(); } private void publishFile(DocumentFile fileDocument, long size) { if (!ShareSettingsFragment.isCustomDestinationEnabled(getDevice().getContext())) { Log.i("SharePlugin", "Adding to downloads"); DownloadManager manager = (DownloadManager) getDevice().getContext().getSystemService(Context.DOWNLOAD_SERVICE); manager.addCompletedDownload(fileDocument.getUri().getLastPathSegment(), getDevice().getName(), true, fileDocument.getType(), fileDocument.getUri().getPath(), size, false); } else { //Make sure it is added to the Android Gallery anyway Log.i("SharePlugin", "Adding to gallery"); MediaStoreHelper.indexFile(getDevice().getContext(), fileDocument.getUri()); } } private void openFile(DocumentFile fileDocument) { String mimeType = FilesHelper.getMimeTypeFromFile(fileDocument.getName()); Intent intent = new Intent(Intent.ACTION_VIEW); if (Build.VERSION.SDK_INT >= 24) { //Nougat and later require "content://" uris instead of "file://" uris File file = new File(fileDocument.getUri().getPath()); Uri contentUri = FileProvider.getUriForFile(getDevice().getContext(), "org.kde.kdeconnect_tp.fileprovider", file); intent.setDataAndType(contentUri, mimeType); intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_ACTIVITY_NEW_TASK); } else { intent.setDataAndType(fileDocument.getUri(), mimeType); } getDevice().getContext().startActivity(intent); } } diff --git a/src/org/kde/kdeconnect/Plugins/SharePlugin/SharePlugin.java b/src/org/kde/kdeconnect/Plugins/SharePlugin/SharePlugin.java index 2d3f99a3..b318201d 100644 --- a/src/org/kde/kdeconnect/Plugins/SharePlugin/SharePlugin.java +++ b/src/org/kde/kdeconnect/Plugins/SharePlugin/SharePlugin.java @@ -1,342 +1,342 @@ /* * Copyright 2014 Albert Vaca Cintora * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License as * published by the Free Software Foundation; either version 2 of * the License or (at your option) version 3 or any later version * accepted by the membership of KDE e.V. (or its successor approved * by the membership of KDE e.V.), which shall act as a proxy * defined in Section 14 of version 3 of the license. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ package org.kde.kdeconnect.Plugins.SharePlugin; import android.Manifest; import android.app.Activity; import android.content.ClipboardManager; import android.content.Context; import android.content.Intent; import android.graphics.drawable.Drawable; import android.net.Uri; import android.os.Bundle; import android.os.Handler; import android.os.Looper; import android.util.Log; import android.widget.Toast; import org.kde.kdeconnect.Helpers.FilesHelper; import org.kde.kdeconnect.NetworkPacket; import org.kde.kdeconnect.Plugins.Plugin; import org.kde.kdeconnect.Plugins.PluginFactory; import org.kde.kdeconnect.UserInterface.PluginSettingsFragment; import org.kde.kdeconnect.async.BackgroundJob; import org.kde.kdeconnect.async.BackgroundJobHandler; import org.kde.kdeconnect_tp.R; import java.net.URL; import java.util.ArrayList; import androidx.annotation.NonNull; import androidx.annotation.WorkerThread; import androidx.core.content.ContextCompat; /** * A Plugin for sharing and receiving files and uris. *

* All of the associated I/O work is scheduled on background * threads by {@link BackgroundJobHandler}. *

*/ @PluginFactory.LoadablePlugin public class SharePlugin extends Plugin { final static String ACTION_CANCEL_SHARE = "org.kde.kdeconnect.Plugins.SharePlugin.CancelShare"; final static String CANCEL_SHARE_DEVICE_ID_EXTRA = "deviceId"; final static String CANCEL_SHARE_BACKGROUND_JOB_ID_EXTRA = "backgroundJobId"; private final static String PACKET_TYPE_SHARE_REQUEST = "kdeconnect.share.request"; final static String PACKET_TYPE_SHARE_REQUEST_UPDATE = "kdeconnect.share.request.update"; final static String KEY_NUMBER_OF_FILES = "numberOfFiles"; final static String KEY_TOTAL_PAYLOAD_SIZE = "totalPayloadSize"; private BackgroundJobHandler backgroundJobHandler; private final Handler handler; private CompositeReceiveFileJob receiveFileJob; private CompositeUploadFileJob uploadFileJob; private final Callback receiveFileJobCallback; public SharePlugin() { backgroundJobHandler = BackgroundJobHandler.newFixedThreadPoolBackgroundJobHander(5); handler = new Handler(Looper.getMainLooper()); receiveFileJobCallback = new Callback(); } @Override public boolean onCreate() { optionalPermissionExplanation = R.string.share_optional_permission_explanation; return true; } @Override public String getDisplayName() { return context.getResources().getString(R.string.pref_plugin_sharereceiver); } @Override public Drawable getIcon() { return ContextCompat.getDrawable(context, R.drawable.share_plugin_action); } @Override public String getDescription() { return context.getResources().getString(R.string.pref_plugin_sharereceiver_desc); } @Override public boolean hasMainActivity() { return true; } @Override public String getActionName() { return context.getString(R.string.send_files); } @Override public void startMainActivity(Activity parentActivity) { Intent intent = new Intent(parentActivity, SendFileActivity.class); intent.putExtra("deviceId", device.getDeviceId()); parentActivity.startActivity(intent); } @Override public boolean hasSettings() { return true; } @Override @WorkerThread public boolean onPacketReceived(NetworkPacket np) { try { if (np.getType().equals(PACKET_TYPE_SHARE_REQUEST_UPDATE)) { if (receiveFileJob != null && receiveFileJob.isRunning()) { receiveFileJob.updateTotals(np.getInt(KEY_NUMBER_OF_FILES), np.getLong(KEY_TOTAL_PAYLOAD_SIZE)); } else { Log.d("SharePlugin", "Received update packet but CompositeUploadJob is null or not running"); } return true; } if (np.has("filename")) { if (isPermissionGranted(Manifest.permission.WRITE_EXTERNAL_STORAGE)) { receiveFile(np); } else { Log.i("SharePlugin", "no Permission for Storage"); } } else if (np.has("text")) { Log.i("SharePlugin", "hasText"); receiveText(np); } else if (np.has("url")) { receiveUrl(np); } else { Log.e("SharePlugin", "Error: Nothing attached!"); } } catch (Exception e) { Log.e("SharePlugin", "Exception"); e.printStackTrace(); } return true; } private void receiveUrl(NetworkPacket np) { String url = np.getString("url"); Log.i("SharePlugin", "hasUrl: " + url); Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(url)); browserIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); context.startActivity(browserIntent); } private void receiveText(NetworkPacket np) { String text = np.getString("text"); ClipboardManager cm = (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE); cm.setText(text); handler.post(() -> Toast.makeText(context, R.string.shareplugin_text_saved, Toast.LENGTH_LONG).show()); } @WorkerThread private void receiveFile(NetworkPacket np) { CompositeReceiveFileJob job; boolean hasNumberOfFiles = np.has(KEY_NUMBER_OF_FILES); - boolean hasOpen = np.has("open"); + boolean isOpen = np.getBoolean("open", false); - if (hasNumberOfFiles && !hasOpen && receiveFileJob != null) { + if (hasNumberOfFiles && !isOpen && receiveFileJob != null) { job = receiveFileJob; } else { job = new CompositeReceiveFileJob(device, receiveFileJobCallback); } if (!hasNumberOfFiles) { np.set(KEY_NUMBER_OF_FILES, 1); np.set(KEY_TOTAL_PAYLOAD_SIZE, np.getPayloadSize()); } job.addNetworkPacket(np); if (job != receiveFileJob) { - if (hasNumberOfFiles && !hasOpen) { + if (hasNumberOfFiles && !isOpen) { receiveFileJob = job; } backgroundJobHandler.runJob(job); } } @Override public PluginSettingsFragment getSettingsFragment(Activity activity) { return ShareSettingsFragment.newInstance(getPluginKey()); } void sendUriList(final ArrayList uriList) { CompositeUploadFileJob job; if (uploadFileJob == null) { job = new CompositeUploadFileJob(device, this.receiveFileJobCallback); } else { job = uploadFileJob; } //Read all the data early, as we only have permissions to do it while the activity is alive for (Uri uri : uriList) { NetworkPacket np = FilesHelper.uriToNetworkPacket(context, uri, PACKET_TYPE_SHARE_REQUEST); if (np != null) { job.addNetworkPacket(np); } } if (job != uploadFileJob) { uploadFileJob = job; backgroundJobHandler.runJob(uploadFileJob); } } public void share(Intent intent) { Bundle extras = intent.getExtras(); if (extras != null) { if (extras.containsKey(Intent.EXTRA_STREAM)) { try { ArrayList uriList; if (!Intent.ACTION_SEND.equals(intent.getAction())) { uriList = intent.getParcelableArrayListExtra(Intent.EXTRA_STREAM); } else { Uri uri = extras.getParcelable(Intent.EXTRA_STREAM); uriList = new ArrayList<>(); uriList.add(uri); } sendUriList(uriList); } catch (Exception e) { Log.e("ShareActivity", "Exception"); e.printStackTrace(); } } else if (extras.containsKey(Intent.EXTRA_TEXT)) { String text = extras.getString(Intent.EXTRA_TEXT); String subject = extras.getString(Intent.EXTRA_SUBJECT); //Hack: Detect shared youtube videos, so we can open them in the browser instead of as text if (subject != null && subject.endsWith("YouTube")) { int index = text.indexOf(": http://youtu.be/"); if (index > 0) { text = text.substring(index + 2); //Skip ": " } } boolean isUrl; try { new URL(text); isUrl = true; } catch (Exception e) { isUrl = false; } NetworkPacket np = new NetworkPacket(SharePlugin.PACKET_TYPE_SHARE_REQUEST); if (isUrl) { np.set("url", text); } else { np.set("text", text); } device.sendPacket(np); } } } @Override public String[] getSupportedPacketTypes() { return new String[]{PACKET_TYPE_SHARE_REQUEST, PACKET_TYPE_SHARE_REQUEST_UPDATE}; } @Override public String[] getOutgoingPacketTypes() { return new String[]{PACKET_TYPE_SHARE_REQUEST}; } @Override public String[] getOptionalPermissions() { return new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}; } private class Callback implements BackgroundJob.Callback { @Override public void onResult(@NonNull BackgroundJob job, Void result) { if (job == receiveFileJob) { receiveFileJob = null; } else if (job == uploadFileJob) { uploadFileJob = null; } } @Override public void onError(@NonNull BackgroundJob job, @NonNull Throwable error) { if (job == receiveFileJob) { receiveFileJob = null; } else if (job == uploadFileJob) { uploadFileJob = null; } } } void cancelJob(long jobId) { if (backgroundJobHandler.isRunning(jobId)) { BackgroundJob job = backgroundJobHandler.getJob(jobId); if (job != null) { job.cancel(); if (job == receiveFileJob) { receiveFileJob = null; } else if (job == uploadFileJob) { uploadFileJob = null; } } } } }