瀏覽代碼

Retrieve & show file via intent

Signed-off-by: tobiasKaminsky <tobias@kaminsky.me>
tobiasKaminsky 6 年之前
父節點
當前提交
2c0ee6ace3

+ 1 - 1
scripts/analysis/lint-results.txt

@@ -1,2 +1,2 @@
 DO NOT TOUCH; GENERATED BY DRONE
-      <span class="mdl-layout-title">Lint Report: 58 warnings</span>
+      <span class="mdl-layout-title">Lint Report: 59 warnings</span>

+ 4 - 0
src/main/java/com/nextcloud/client/account/UserAccountManager.java

@@ -22,6 +22,7 @@ package com.nextcloud.client.account;
 import android.accounts.Account;
 
 import androidx.annotation.NonNull;
+import androidx.annotation.Nullable;
 
 public interface UserAccountManager extends CurrentAccountProvider {
 
@@ -47,6 +48,9 @@ public interface UserAccountManager extends CurrentAccountProvider {
      */
     void updateAccountVersion();
 
+    @Nullable
+    Account getAccountByName(String name);
+
     /**
      * Extract username from account.
      *

+ 12 - 0
src/main/java/com/nextcloud/client/account/UserAccountManagerImpl.java

@@ -68,6 +68,18 @@ public class UserAccountManagerImpl implements UserAccountManager {
         return AccountUtils.getCurrentOwnCloudAccount(context);
     }
 
+    @Override
+    @Nullable
+    public Account getAccountByName(String name) {
+        for (Account account : getAccounts()) {
+            if (account.name.equals(name)) {
+                return account;
+            }
+        }
+
+        return null;
+    }
+
     public void updateAccountVersion() {
         Account currentAccount = AccountUtils.getCurrentOwnCloudAccount(context);
 

+ 3 - 1
src/main/java/com/owncloud/android/ui/activity/BaseActivity.java

@@ -60,7 +60,9 @@ public abstract class BaseActivity extends AppCompatActivity implements Injectab
     }
 
     @Override
-    protected void onNewIntent (Intent intent) {
+    protected void onNewIntent(Intent intent) {
+        super.onNewIntent(intent);
+
         Log_OC.v(TAG, "onNewIntent() start");
         Account current = accountManager.getCurrentAccount();
         if (current != null && mCurrentAccount != null && !mCurrentAccount.name.equals(current.name)) {

+ 1 - 1
src/main/java/com/owncloud/android/ui/activity/FileActivity.java

@@ -576,7 +576,7 @@ public abstract class FileActivity extends DrawerActivity
         fetchExternalLinks(false);
     }
 
-    protected OCFile getCurrentDir() {
+    public OCFile getCurrentDir() {
         OCFile file = getFile();
         if (file != null) {
             if (file.isFolder()) {

+ 69 - 18
src/main/java/com/owncloud/android/ui/activity/FileDisplayActivity.java

@@ -27,6 +27,7 @@ package com.owncloud.android.ui.activity;
 
 import android.Manifest;
 import android.accounts.Account;
+import android.accounts.AccountManager;
 import android.accounts.AuthenticatorException;
 import android.annotation.TargetApi;
 import android.app.Activity;
@@ -99,6 +100,7 @@ import com.owncloud.android.operations.UploadFileOperation;
 import com.owncloud.android.providers.UsersAndGroupsSearchProvider;
 import com.owncloud.android.syncadapter.FileSyncAdapter;
 import com.owncloud.android.ui.asynctasks.CheckAvailableSpaceTask;
+import com.owncloud.android.ui.asynctasks.FetchRemoteFileTask;
 import com.owncloud.android.ui.dialog.SendShareDialog;
 import com.owncloud.android.ui.dialog.SortingOrderDialogFragment;
 import com.owncloud.android.ui.events.SyncEventFinished;
@@ -268,6 +270,10 @@ public class FileDisplayActivity extends FileActivity
             fm.beginTransaction()
                     .add(taskRetainerFragment, TaskRetainerFragment.FTAG_TASK_RETAINER_FRAGMENT).commit();
         }   // else, Fragment already created and retained across configuration change
+
+        if (Intent.ACTION_VIEW.equals(getIntent().getAction())) {
+            handleOpenFileViaIntent(getIntent());
+        }
     }
 
     @Override
@@ -498,30 +504,34 @@ public class FileDisplayActivity extends FileActivity
             /// First fragment
             OCFileListFragment listOfFiles = getListOfFilesFragment();
             if (listOfFiles != null && TextUtils.isEmpty(searchQuery)) {
-                listOfFiles.listDirectory(getCurrentDir(), MainApp.isOnlyOnDevice(), false);
+                listOfFiles.listDirectory(getCurrentDir(), getFile(), MainApp.isOnlyOnDevice(), false);
             } else {
-                Log_OC.e(TAG, "Still have a chance to lose the initializacion of list fragment >(");
+                Log_OC.e(TAG, "Still have a chance to lose the initialization of list fragment >(");
             }
 
             /// Second fragment
-            OCFile file = getFile();
+            if (mDualPane) {
+                OCFile file = getFile();
 
-            Fragment secondFragment = getSecondFragment();
-            if (secondFragment == null) {
-                secondFragment = chooseInitialSecondFragment(file);
-            }
+                Fragment secondFragment = getSecondFragment();
+                if (secondFragment == null) {
+                    secondFragment = chooseInitialSecondFragment(file);
+                }
 
-            if (secondFragment != null) {
-                setSecondFragment(secondFragment);
-                updateFragmentsVisibility(true);
-                updateActionBarTitleAndHomeButton(file);
+                if (secondFragment != null) {
+                    setSecondFragment(secondFragment);
+                    updateFragmentsVisibility(true);
+                    updateActionBarTitleAndHomeButton(file);
+                } else {
+                    cleanSecondFragment();
+                    if (file.isDown() && MimeTypeUtil.isVCard(file.getMimeType())) {
+                        startContactListFragment(file);
+                    } else if (file.isDown() && PreviewTextFragment.canBePreviewed(file)) {
+                        startTextPreview(file, false);
+                    }
+                }
             } else {
                 cleanSecondFragment();
-                if (file.isDown() && MimeTypeUtil.isVCard(file.getMimeType())) {
-                    startContactListFragment(file);
-                } else if (file.isDown() && PreviewTextFragment.canBePreviewed(file)) {
-                    startTextPreview(file, false);
-                }
             }
 
         } else {
@@ -543,6 +553,8 @@ public class FileDisplayActivity extends FileActivity
         if (ACTION_DETAILS.equalsIgnoreCase(intent.getAction())) {
             setIntent(intent);
             setFile(intent.getParcelableExtra(EXTRA_FILE));
+        } else if (Intent.ACTION_VIEW.equals(intent.getAction())) {
+            handleOpenFileViaIntent(intent);
         } else if (RESTART.equals(intent.getAction())) {
             finish();
             startActivity(intent);
@@ -665,7 +677,7 @@ public class FileDisplayActivity extends FileActivity
     }
 
 
-    private OCFileListFragment getListOfFilesFragment() {
+    public OCFileListFragment getListOfFilesFragment() {
         Fragment listOfFiles = getSupportFragmentManager().findFragmentByTag(
                 FileDisplayActivity.TAG_LIST_OF_FILES);
         if (listOfFiles != null) {
@@ -1692,7 +1704,7 @@ public class FileDisplayActivity extends FileActivity
     }
 
     @Override
-    protected void updateActionBarTitleAndHomeButton(OCFile chosenFile) {
+    public void updateActionBarTitleAndHomeButton(OCFile chosenFile) {
         if (chosenFile == null) {
             chosenFile = getFile();     // if no file is passed, current file decides
         }
@@ -2595,4 +2607,43 @@ public class FileDisplayActivity extends FileActivity
         searchQuery = query;
     }
 
+    private void handleOpenFileViaIntent(Intent intent) {
+        showLoadingDialog("Retrieving file…");
+
+        String accountName = intent.getStringExtra("KEY_ACCOUNT");
+
+        Account newAccount = getUserAccountManager().getAccountByName(accountName);
+
+        if (newAccount == null) {
+            dismissLoadingDialog();
+            DisplayUtils.showSnackMessage(this, "Associated account not found!");
+            return;
+        }
+
+        setAccount(newAccount);
+
+        String fileId = String.valueOf(intent.getStringExtra("KEY_FILE_ID"));
+
+        if ("null".equals(fileId)) {
+            dismissLoadingDialog();
+            DisplayUtils.showSnackMessage(this, "Error retrieving file");
+            return;
+        }
+
+        AccountManager am = AccountManager.get(this);
+        String userId = am.getUserData(getAccount(), AccountUtils.Constants.KEY_USER_ID);
+
+        FileDataStorageManager storageManager = getStorageManager();
+
+        if (storageManager == null) {
+            storageManager = new FileDataStorageManager(newAccount, getContentResolver());
+        }
+
+        FetchRemoteFileTask fetchRemoteFileTask = new FetchRemoteFileTask(newAccount,
+                                                                          fileId,
+                                                                          userId,
+                                                                          storageManager,
+                                                                          this);
+        fetchRemoteFileTask.execute();
+    }
 }

+ 10 - 12
src/main/java/com/owncloud/android/ui/adapter/OCFileListAdapter.java

@@ -92,6 +92,7 @@ import androidx.core.graphics.drawable.RoundedBitmapDrawableFactory;
 import androidx.recyclerview.widget.RecyclerView;
 import butterknife.BindView;
 import butterknife.ButterKnife;
+import lombok.Setter;
 
 /**
  * This Adapter populates a RecyclerView with all files and folders in a Nextcloud instance.
@@ -128,6 +129,7 @@ public class OCFileListAdapter extends RecyclerView.Adapter<RecyclerView.ViewHol
     private List<ThumbnailsCacheManager.ThumbnailGenerationTask> asyncTasks = new ArrayList<>();
     private boolean onlyOnDevice;
     private boolean showShareAvatar;
+    @Setter private OCFile highlightedItem;
 
     public OCFileListAdapter(
         Context context,
@@ -185,6 +187,7 @@ public class OCFileListAdapter extends RecyclerView.Adapter<RecyclerView.ViewHol
 
     public void addCheckedFile(OCFile file) {
         checkedFiles.add(file);
+        highlightedItem = null;
     }
 
     public void addAllFilesToCheckedFiles() {
@@ -314,7 +317,10 @@ public class OCFileListAdapter extends RecyclerView.Adapter<RecyclerView.ViewHol
             gridViewHolder.thumbnail.setTag(file.getFileId());
             setThumbnail(file, gridViewHolder.thumbnail);
 
-            if (isCheckedFile(file)) {
+            if (highlightedItem != null && file.getFileId() == highlightedItem.getFileId()) {
+                gridViewHolder.itemLayout.setBackgroundColor(mContext.getResources()
+                                                                 .getColor(R.color.selected_item_background));
+            } else if (isCheckedFile(file)) {
                 gridViewHolder.itemLayout.setBackgroundColor(mContext.getResources()
                                                                  .getColor(R.color.selected_item_background));
                 gridViewHolder.checkbox.setImageDrawable(ThemeUtils.tintDrawable(R.drawable.ic_checkbox_marked,
@@ -708,15 +714,7 @@ public class OCFileListAdapter extends RecyclerView.Adapter<RecyclerView.ViewHol
         notifyDataSetChanged();
     }
 
-    private void searchForLocalFileInDefaultPath(OCFile file) {
-        if (file.getStoragePath() == null && !file.isFolder()) {
-            File f = new File(FileStorageUtils.getDefaultSavePathFor(account.name, file));
-            if (f.exists()) {
-                file.setStoragePath(f.getAbsolutePath());
-                file.setLastSyncDateForData(f.lastModified());
-            }
-        }
-    }
+
 
     public void setData(List<Object> objects, ExtendedListFragment.SearchType searchType,
                         FileDataStorageManager storageManager, OCFile folder) {
@@ -766,7 +764,7 @@ public class OCFileListAdapter extends RecyclerView.Adapter<RecyclerView.ViewHol
 
                 if (result.isSuccess()) {
                     OCFile file = FileStorageUtils.fillOCFile((RemoteFile) result.getData().get(0));
-                    searchForLocalFileInDefaultPath(file);
+                    FileStorageUtils.searchForLocalFileInDefaultPath(file, account);
                     file = mStorageManager.saveFileWithParent(file, mContext);
 
                     ShareType newShareType = ocShare.getShareType();
@@ -812,7 +810,7 @@ public class OCFileListAdapter extends RecyclerView.Adapter<RecyclerView.ViewHol
 
         for (Object remoteFile : objects) {
             OCFile ocFile = FileStorageUtils.fillOCFile((RemoteFile) remoteFile);
-            searchForLocalFileInDefaultPath(ocFile);
+            FileStorageUtils.searchForLocalFileInDefaultPath(ocFile, account);
 
             try {
                 ocFile = mStorageManager.saveFileWithParent(ocFile, mContext);

+ 140 - 0
src/main/java/com/owncloud/android/ui/asynctasks/FetchRemoteFileTask.java

@@ -0,0 +1,140 @@
+/*
+ * Nextcloud Android client application
+ *
+ * @author Tobias Kaminsky
+ * Copyright (C) 2019 Tobias Kaminsky
+ * Copyright (C) 2019 Nextcloud GmbH
+ *
+ * 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 3 of the License, or
+ * (at your option) any later version.
+ *
+ * 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 <https://www.gnu.org/licenses/>.
+ */
+
+package com.owncloud.android.ui.asynctasks;
+
+import android.accounts.Account;
+import android.os.AsyncTask;
+import android.text.TextUtils;
+
+import com.owncloud.android.MainApp;
+import com.owncloud.android.datamodel.FileDataStorageManager;
+import com.owncloud.android.datamodel.OCFile;
+import com.owncloud.android.lib.common.operations.RemoteOperation;
+import com.owncloud.android.lib.common.operations.RemoteOperationResult;
+import com.owncloud.android.lib.resources.files.ReadFileRemoteOperation;
+import com.owncloud.android.lib.resources.files.SearchRemoteOperation;
+import com.owncloud.android.lib.resources.files.model.RemoteFile;
+import com.owncloud.android.operations.RefreshFolderOperation;
+import com.owncloud.android.ui.activity.FileDisplayActivity;
+import com.owncloud.android.ui.fragment.OCFileListFragment;
+import com.owncloud.android.utils.DisplayUtils;
+import com.owncloud.android.utils.FileStorageUtils;
+
+import static com.owncloud.android.lib.resources.files.SearchRemoteOperation.SearchType.FILE_ID_SEARCH;
+
+public class FetchRemoteFileTask extends AsyncTask<Void, Void, String> {
+    private Account account;
+    private String fileId;
+    private String userId;
+    private FileDataStorageManager storageManager;
+    private FileDisplayActivity fileDisplayActivity;
+
+    public FetchRemoteFileTask(Account account,
+                               String fileId,
+                               String userId,
+                               FileDataStorageManager storageManager,
+                               FileDisplayActivity fileDisplayActivity) {
+        this.account = account;
+        this.fileId = fileId;
+        this.userId = userId;
+        this.storageManager = storageManager;
+        this.fileDisplayActivity = fileDisplayActivity;
+    }
+
+    @Override
+    protected String doInBackground(Void... voids) {
+
+
+        SearchRemoteOperation searchRemoteOperation = new SearchRemoteOperation(fileId,
+                                                                                FILE_ID_SEARCH,
+                                                                                false,
+                                                                                userId);
+        RemoteOperationResult remoteOperationResult = searchRemoteOperation.execute(account, fileDisplayActivity);
+
+        if (remoteOperationResult.isSuccess() && remoteOperationResult.getData() != null) {
+            String remotePath = ((RemoteFile) remoteOperationResult.getData().get(0)).getRemotePath();
+
+            ReadFileRemoteOperation operation = new ReadFileRemoteOperation(remotePath);
+            RemoteOperationResult result = operation.execute(account, fileDisplayActivity);
+
+            if (!result.isSuccess()) {
+                Exception exception = result.getException();
+                String message = "Fetching file " + remotePath + " fails with: " + result.getLogMessage();
+
+                if (exception != null) {
+                    return exception.getMessage();
+                } else {
+                    return message;
+                }
+            }
+
+            RemoteFile remoteFile = (RemoteFile) result.getData().get(0);
+
+            OCFile ocFile = FileStorageUtils.fillOCFile(remoteFile);
+            FileStorageUtils.searchForLocalFileInDefaultPath(ocFile, account);
+            ocFile = storageManager.saveFileWithParent(ocFile, fileDisplayActivity);
+
+            // also sync folder content
+            OCFile toSync;
+            if (ocFile.isFolder()) {
+                toSync = ocFile;
+            } else {
+                toSync = storageManager.getFileById(ocFile.getParentId());
+            }
+
+            long currentSyncTime = System.currentTimeMillis();
+            RemoteOperation refreshFolderOperation = new RefreshFolderOperation(toSync,
+                                                                                currentSyncTime,
+                                                                                true,
+                                                                                true,
+                                                                                storageManager,
+                                                                                account,
+                                                                                fileDisplayActivity);
+            refreshFolderOperation.execute(account, fileDisplayActivity);
+
+            fileDisplayActivity.setFile(ocFile);
+        } else {
+            return remoteOperationResult.getLogMessage();
+        }
+
+        return "";
+    }
+
+    @Override
+    protected void onPostExecute(String message) {
+        super.onPostExecute(message);
+
+        fileDisplayActivity.dismissLoadingDialog();
+
+        OCFileListFragment listOfFiles = fileDisplayActivity.getListOfFilesFragment();
+        if (listOfFiles != null) {
+            if (TextUtils.isEmpty(message)) {
+                OCFile temp = fileDisplayActivity.getFile();
+                fileDisplayActivity.setFile(fileDisplayActivity.getCurrentDir());
+                listOfFiles.listDirectory(fileDisplayActivity.getCurrentDir(), temp, MainApp.isOnlyOnDevice(), false);
+                fileDisplayActivity.updateActionBarTitleAndHomeButton(null);
+            } else {
+                DisplayUtils.showSnackMessage(listOfFiles.getView(), message);
+            }
+        }
+    }
+}

+ 13 - 4
src/main/java/com/owncloud/android/ui/fragment/OCFileListFragment.java

@@ -1125,6 +1125,10 @@ public class OCFileListFragment extends ExtendedListFragment implements
         listDirectory(getCurrentFile(), MainApp.isOnlyOnDevice(), false);
     }
 
+    public void listDirectory(OCFile directory, boolean onlyOnDevice, boolean fromSearch) {
+        listDirectory(directory, null, onlyOnDevice, fromSearch);
+    }
+
     /**
      * Lists the given directory on the view. When the input parameter is null,
      * it will either refresh the last known directory. list the root
@@ -1132,7 +1136,7 @@ public class OCFileListFragment extends ExtendedListFragment implements
      *
      * @param directory File to be listed
      */
-    public void listDirectory(OCFile directory, boolean onlyOnDevice, boolean fromSearch) {
+    public void listDirectory(OCFile directory, OCFile file, boolean onlyOnDevice, boolean fromSearch) {
         if (!searchFragment) {
             FileDataStorageManager storageManager = mContainerActivity.getStorageManager();
             if (storageManager != null) {
@@ -1184,12 +1188,17 @@ public class OCFileListFragment extends ExtendedListFragment implements
                     onlyOnDevice,
                     mLimitToMimeType
                 );
-                if (mFile == null || !mFile.equals(directory)) {
-                    getRecyclerView().scrollToPosition(0);
-                }
                 mFile = directory;
 
                 updateLayout();
+
+                mAdapter.setHighlightedItem(file);
+                int position = mAdapter.getItemPosition(file);
+                if (position == -1) {
+                    getRecyclerView().scrollToPosition(0);
+                } else {
+                    getRecyclerView().scrollToPosition(position);
+                }
             }
         }
     }