@Override
  protected RemoteOperationResult run(WebdavClient client) {
    RemoteOperationResult result = null;

    // code before in FileSyncAdapter.fetchData
    PropFindMethod query = null;
    try {
      Log.d(TAG, "Synchronizing " + mAccount.name + ", fetching files in " + mRemotePath);

      // remote request
      query = new PropFindMethod(client.getBaseUri() + WebdavUtils.encodePath(mRemotePath));
      int status = client.executeMethod(query);

      // check and process response   - /// TODO take into account all the possible status per
      // child-resource
      if (isMultiStatus(status)) {
        MultiStatus resp = query.getResponseBodyAsMultiStatus();

        // synchronize properties of the parent folder, if necessary
        if (mParentId == DataStorageManager.ROOT_PARENT_ID) {
          WebdavEntry we = new WebdavEntry(resp.getResponses()[0], client.getBaseUri().getPath());
          OCFile parent = fillOCFile(we);
          parent.setParentId(mParentId);
          mStorageManager.saveFile(parent);
          mParentId = parent.getFileId();
        }

        // read contents in folder
        List<OCFile> updatedFiles = new Vector<OCFile>(resp.getResponses().length - 1);
        for (int i = 1; i < resp.getResponses().length; ++i) {
          WebdavEntry we = new WebdavEntry(resp.getResponses()[i], client.getBaseUri().getPath());
          OCFile file = fillOCFile(we);
          file.setParentId(mParentId);
          OCFile oldFile = mStorageManager.getFileByPath(file.getRemotePath());
          if (oldFile != null) {
            if (oldFile.keepInSync()
                && file.getModificationTimestamp() > oldFile.getModificationTimestamp()) {
              disableObservance(
                  file); // first disable observer so we won't get file upload right after download
              requestContentDownload(file);
            }
            file.setKeepInSync(oldFile.keepInSync());
          }

          updatedFiles.add(file);
        }

        // save updated contents in local database; all at once, trying to get a best performance in
        // database update (not a big deal, indeed)
        mStorageManager.saveFiles(updatedFiles);

        // removal of obsolete files
        mChildren = mStorageManager.getDirectoryContent(mStorageManager.getFileById(mParentId));
        OCFile file;
        String currentSavePath = FileDownloader.getSavePath(mAccount.name);
        for (int i = 0; i < mChildren.size(); ) {
          file = mChildren.get(i);
          if (file.getLastSyncDate() != mCurrentSyncTime) {
            Log.d(TAG, "removing file: " + file);
            mStorageManager.removeFile(
                file, (file.isDown() && file.getStoragePath().startsWith(currentSavePath)));
            mChildren.remove(i);
          } else {
            i++;
          }
        }

      } else {
        client.exhaustResponse(query.getResponseBodyAsStream());
      }

      // prepare result object
      result = new RemoteOperationResult(isMultiStatus(status), status);
      Log.i(
          TAG,
          "Synchronizing "
              + mAccount.name
              + ", folder "
              + mRemotePath
              + ": "
              + result.getLogMessage());

    } catch (Exception e) {
      result = new RemoteOperationResult(e);
      Log.e(
          TAG,
          "Synchronizing "
              + mAccount.name
              + ", folder "
              + mRemotePath
              + ": "
              + result.getLogMessage(),
          result.getException());

    } finally {
      if (query != null)
        query.releaseConnection(); // let the connection available for other methods
    }

    return result;
  }
예제 #2
0
  @Override
  public void onClick(View v) {
    switch (v.getId()) {
      case R.id.fdDownloadBtn:
        {
          // if (FileDownloader.isDownloading(mAccount, mFile.getRemotePath())) {
          FileDownloaderBinder downloaderBinder = mContainerActivity.getFileDownloaderBinder();
          FileUploaderBinder uploaderBinder = mContainerActivity.getFileUploaderBinder();
          if (downloaderBinder != null && downloaderBinder.isDownloading(mAccount, mFile)) {
            downloaderBinder.cancel(mAccount, mFile);
            if (mFile.isDown()) {
              setButtonsForDown();
            } else {
              setButtonsForRemote();
            }

          } else if (uploaderBinder != null && uploaderBinder.isUploading(mAccount, mFile)) {
            uploaderBinder.cancel(mAccount, mFile);
            if (!mFile.fileExists()) {
              // TODO make something better
              if (getActivity() instanceof FileDisplayActivity) {
                // double pane
                FragmentTransaction transaction =
                    getActivity().getSupportFragmentManager().beginTransaction();
                transaction.replace(
                    R.id.file_details_container,
                    new FileDetailFragment(null, null),
                    FTAG); // empty FileDetailFragment
                transaction.commit();
                mContainerActivity.onFileStateChanged();
              } else {
                getActivity().finish();
              }

            } else if (mFile.isDown()) {
              setButtonsForDown();
            } else {
              setButtonsForRemote();
            }

          } else {
            mLastRemoteOperation =
                new SynchronizeFileOperation(
                    mFile, null, mStorageManager, mAccount, true, false, getActivity());
            WebdavClient wc =
                OwnCloudClientUtils.createOwnCloudClient(
                    mAccount, getSherlockActivity().getApplicationContext());
            mLastRemoteOperation.execute(wc, this, mHandler);

            // update ui
            boolean inDisplayActivity = getActivity() instanceof FileDisplayActivity;
            getActivity()
                .showDialog(
                    (inDisplayActivity)
                        ? FileDisplayActivity.DIALOG_SHORT_WAIT
                        : FileDetailActivity.DIALOG_SHORT_WAIT);
            setButtonsForTransferring(); // disable button immediately, although the synchronization
                                         // does not result in a file transference
          }
          break;
        }
      case R.id.fdKeepInSync:
        {
          CheckBox cb = (CheckBox) getView().findViewById(R.id.fdKeepInSync);
          mFile.setKeepInSync(cb.isChecked());
          mStorageManager.saveFile(mFile);

          /// register the OCFile instance in the observer service to monitor local updates;
          /// if necessary, the file is download
          Intent intent =
              new Intent(getActivity().getApplicationContext(), FileObserverService.class);
          intent.putExtra(
              FileObserverService.KEY_FILE_CMD,
              (cb.isChecked()
                  ? FileObserverService.CMD_ADD_OBSERVED_FILE
                  : FileObserverService.CMD_DEL_OBSERVED_FILE));
          intent.putExtra(FileObserverService.KEY_CMD_ARG_FILE, mFile);
          intent.putExtra(FileObserverService.KEY_CMD_ARG_ACCOUNT, mAccount);
          Log.e(TAG, "starting observer service");
          getActivity().startService(intent);

          if (mFile.keepInSync()) {
            onClick(
                getView().findViewById(R.id.fdDownloadBtn)); // force an immediate synchronization
          }
          break;
        }
      case R.id.fdRenameBtn:
        {
          EditNameDialog dialog = EditNameDialog.newInstance(mFile.getFileName());
          dialog.setOnDismissListener(this);
          dialog.show(getFragmentManager(), "nameeditdialog");
          break;
        }
      case R.id.fdRemoveBtn:
        {
          ConfirmationDialogFragment confDialog =
              ConfirmationDialogFragment.newInstance(
                  R.string.confirmation_remove_alert,
                  new String[] {mFile.getFileName()},
                  mFile.isDown()
                      ? R.string.confirmation_remove_remote_and_local
                      : R.string.confirmation_remove_remote,
                  mFile.isDown() ? R.string.confirmation_remove_local : -1,
                  R.string.common_cancel);
          confDialog.setOnConfirmationListener(this);
          confDialog.show(getFragmentManager(), FTAG_CONFIRMATION);
          break;
        }
      case R.id.fdOpenBtn:
        {
          String storagePath = mFile.getStoragePath();
          String encodedStoragePath = WebdavUtils.encodePath(storagePath);
          try {
            Intent i = new Intent(Intent.ACTION_VIEW);
            i.setDataAndType(Uri.parse("file://" + encodedStoragePath), mFile.getMimetype());
            i.setFlags(
                Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
            startActivity(i);

          } catch (Throwable t) {
            Log.e(
                TAG,
                "Fail when trying to open with the mimeType provided from the ownCloud server: "
                    + mFile.getMimetype());
            boolean toastIt = true;
            String mimeType = "";
            try {
              Intent i = new Intent(Intent.ACTION_VIEW);
              mimeType =
                  MimeTypeMap.getSingleton()
                      .getMimeTypeFromExtension(
                          storagePath.substring(storagePath.lastIndexOf('.') + 1));
              if (mimeType != null && !mimeType.equals(mFile.getMimetype())) {
                i.setDataAndType(Uri.parse("file://" + encodedStoragePath), mimeType);
                i.setFlags(
                    Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
                startActivity(i);
                toastIt = false;
              }

            } catch (IndexOutOfBoundsException e) {
              Log.e(
                  TAG, "Trying to find out MIME type of a file without extension: " + storagePath);

            } catch (ActivityNotFoundException e) {
              Log.e(
                  TAG,
                  "No activity found to handle: "
                      + storagePath
                      + " with MIME type "
                      + mimeType
                      + " obtained from extension");

            } catch (Throwable th) {
              Log.e(TAG, "Unexpected problem when opening: " + storagePath, th);

            } finally {
              if (toastIt) {
                Toast.makeText(
                        getActivity(),
                        "There is no application to handle file " + mFile.getFileName(),
                        Toast.LENGTH_SHORT)
                    .show();
              }
            }
          }
          break;
        }
      default:
        Log.e(TAG, "Incorrect view clicked!");
    }

    /* else if (v.getId() == R.id.fdShareBtn) {
        Thread t = new Thread(new ShareRunnable(mFile.getRemotePath()));
        t.start();
    }*/
  }
예제 #3
0
    public void run() {
      WebdavClient wc =
          OwnCloudClientUtils.createOwnCloudClient(
              mAccount, getSherlockActivity().getApplicationContext());
      AccountManager am = AccountManager.get(getSherlockActivity());
      String baseUrl = am.getUserData(mAccount, AccountAuthenticator.KEY_OC_BASE_URL);
      OwnCloudVersion ocv =
          new OwnCloudVersion(am.getUserData(mAccount, AccountAuthenticator.KEY_OC_VERSION));
      String webdav_path = AccountUtils.getWebdavPath(ocv);
      Log.d("ASD", "" + baseUrl + webdav_path + WebdavUtils.encodePath(mOld.getRemotePath()));

      Log.e(
          "ASD",
          Uri.parse(baseUrl).getPath() == null
              ? ""
              : Uri.parse(baseUrl).getPath()
                  + webdav_path
                  + WebdavUtils.encodePath(mNew.getRemotePath()));
      LocalMoveMethod move =
          new LocalMoveMethod(
              baseUrl + webdav_path + WebdavUtils.encodePath(mOld.getRemotePath()),
              Uri.parse(baseUrl).getPath() == null
                  ? ""
                  : Uri.parse(baseUrl).getPath()
                      + webdav_path
                      + WebdavUtils.encodePath(mNew.getRemotePath()));

      boolean success = false;
      try {
        int status = wc.executeMethod(move);
        success = move.succeeded();
        move.getResponseBodyAsString(); // exhaust response, although not interesting
        Log.d(TAG, "Move returned status: " + status);

      } catch (HttpException e) {
        Log.e(
            TAG,
            "HTTP Exception renaming file " + mOld.getRemotePath() + " to " + mNew.getRemotePath(),
            e);

      } catch (IOException e) {
        Log.e(
            TAG,
            "I/O Exception renaming file " + mOld.getRemotePath() + " to " + mNew.getRemotePath(),
            e);

      } catch (Exception e) {
        Log.e(
            TAG,
            "Unexpected exception renaming file "
                + mOld.getRemotePath()
                + " to "
                + mNew.getRemotePath(),
            e);

      } finally {
        move.releaseConnection();
      }

      if (success) {
        FileDataStorageManager fdsm =
            new FileDataStorageManager(mAccount, getActivity().getContentResolver());
        fdsm.removeFile(mOld, false);
        fdsm.saveFile(mNew);
        mFile = mNew;
        mHandler.post(
            new Runnable() {
              @Override
              public void run() {
                boolean inDisplayActivity = getActivity() instanceof FileDisplayActivity;
                getActivity()
                    .dismissDialog(
                        (inDisplayActivity)
                            ? FileDisplayActivity.DIALOG_SHORT_WAIT
                            : FileDetailActivity.DIALOG_SHORT_WAIT);
                updateFileDetails(mFile, mAccount);
                mContainerActivity.onFileStateChanged();
              }
            });

      } else {
        mHandler.post(
            new Runnable() {
              @Override
              public void run() {
                // undo the local rename
                if (mNew.isDown()) {
                  File f = new File(mNew.getStoragePath());
                  if (!f.renameTo(new File(mOld.getStoragePath()))) {
                    // the local rename undoing failed; last chance: save the new local storage path
                    // in the old file
                    mFile.setStoragePath(mNew.getStoragePath());
                    FileDataStorageManager fdsm =
                        new FileDataStorageManager(mAccount, getActivity().getContentResolver());
                    fdsm.saveFile(mFile);
                  }
                }
                boolean inDisplayActivity = getActivity() instanceof FileDisplayActivity;
                getActivity()
                    .dismissDialog(
                        (inDisplayActivity)
                            ? FileDisplayActivity.DIALOG_SHORT_WAIT
                            : FileDetailActivity.DIALOG_SHORT_WAIT);
                try {
                  Toast msg =
                      Toast.makeText(
                          getActivity(), R.string.rename_server_fail_msg, Toast.LENGTH_LONG);
                  msg.show();

                } catch (NotFoundException e) {
                  e.printStackTrace();
                }
              }
            });
      }
    }
예제 #4
0
  @Override
  public void onClick(View v) {
    switch (v.getId()) {
      case R.id.fdDownloadBtn:
        {
          Intent i = new Intent(getActivity(), FileDownloader.class);
          i.putExtra(FileDownloader.EXTRA_ACCOUNT, mAccount);
          i.putExtra(FileDownloader.EXTRA_REMOTE_PATH, mFile.getRemotePath());
          i.putExtra(FileDownloader.EXTRA_FILE_PATH, mFile.getRemotePath());
          i.putExtra(FileDownloader.EXTRA_FILE_SIZE, mFile.getFileLength());

          // update ui
          setButtonsForTransferring();

          getActivity().startService(i);
          mContainerActivity
              .onFileStateChanged(); // this is not working; it is performed before the
          // fileDownloadService registers it as 'in progress'
          break;
        }
      case R.id.fdKeepInSync:
        {
          CheckBox cb = (CheckBox) getView().findViewById(R.id.fdKeepInSync);
          mFile.setKeepInSync(cb.isChecked());
          FileDataStorageManager fdsm =
              new FileDataStorageManager(
                  mAccount, getActivity().getApplicationContext().getContentResolver());
          fdsm.saveFile(mFile);
          if (mFile.keepInSync()) {
            onClick(getView().findViewById(R.id.fdDownloadBtn));
          } else {
            mContainerActivity
                .onFileStateChanged(); // put inside 'else' to not call it twice (here, and in the
            // virtual click on fdDownloadBtn)
          }
          Intent intent =
              new Intent(getActivity().getApplicationContext(), FileObserverService.class);
          intent.putExtra(
              FileObserverService.KEY_FILE_CMD,
              (cb.isChecked()
                  ? FileObserverService.CMD_ADD_OBSERVED_FILE
                  : FileObserverService.CMD_DEL_OBSERVED_FILE));
          intent.putExtra(FileObserverService.KEY_CMD_ARG, mFile.getStoragePath());
          getActivity().startService(intent);
          break;
        }
      case R.id.fdRenameBtn:
        {
          EditNameFragment dialog = EditNameFragment.newInstance(mFile.getFileName());
          dialog.show(getFragmentManager(), "nameeditdialog");
          dialog.setOnDismissListener(this);
          break;
        }
      case R.id.fdRemoveBtn:
        {
          ConfirmationDialogFragment confDialog =
              ConfirmationDialogFragment.newInstance(
                  R.string.confirmation_remove_alert,
                  new String[] {mFile.getFileName()},
                  mFile.isDown()
                      ? R.string.confirmation_remove_remote_and_local
                      : R.string.confirmation_remove_remote,
                  mFile.isDown() ? R.string.confirmation_remove_local : -1,
                  R.string.common_cancel);
          confDialog.setOnConfirmationListener(this);
          confDialog.show(getFragmentManager(), FTAG_CONFIRMATION);
          break;
        }
      case R.id.fdOpenBtn:
        {
          String storagePath = mFile.getStoragePath();
          String encodedStoragePath = WebdavUtils.encodePath(storagePath);
          try {
            Intent i = new Intent(Intent.ACTION_VIEW);
            i.setDataAndType(Uri.parse("file://" + encodedStoragePath), mFile.getMimetype());
            i.setFlags(
                Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
            startActivity(i);

          } catch (Throwable t) {
            Log.e(
                TAG,
                "Fail when trying to open with the mimeType provided from the ownCloud server: "
                    + mFile.getMimetype());
            boolean toastIt = true;
            String mimeType = "";
            try {
              Intent i = new Intent(Intent.ACTION_VIEW);
              mimeType =
                  MimeTypeMap.getSingleton()
                      .getMimeTypeFromExtension(
                          storagePath.substring(storagePath.lastIndexOf('.') + 1));
              if (mimeType != null && !mimeType.equals(mFile.getMimetype())) {
                i.setDataAndType(Uri.parse("file://" + encodedStoragePath), mimeType);
                i.setFlags(
                    Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
                startActivity(i);
                toastIt = false;
              }

            } catch (IndexOutOfBoundsException e) {
              Log.e(
                  TAG, "Trying to find out MIME type of a file without extension: " + storagePath);

            } catch (ActivityNotFoundException e) {
              Log.e(
                  TAG,
                  "No activity found to handle: "
                      + storagePath
                      + " with MIME type "
                      + mimeType
                      + " obtained from extension");

            } catch (Throwable th) {
              Log.e(TAG, "Unexpected problem when opening: " + storagePath, th);

            } finally {
              if (toastIt) {
                Toast.makeText(
                        getActivity(),
                        "There is no application to handle file " + mFile.getFileName(),
                        Toast.LENGTH_SHORT)
                    .show();
              }
            }
          }
          break;
        }
      default:
        Log.e(TAG, "Incorrect view clicked!");
    }

    /* else if (v.getId() == R.id.fdShareBtn) {
        Thread t = new Thread(new ShareRunnable(mFile.getRemotePath()));
        t.start();
    }*/
  }
예제 #5
0
    public void run() {
      WebdavClient wc =
          OwnCloudClientUtils.createOwnCloudClient(
              mAccount, getSherlockActivity().getApplicationContext());
      AccountManager am = AccountManager.get(getSherlockActivity());
      String baseUrl = am.getUserData(mAccount, AccountAuthenticator.KEY_OC_BASE_URL);
      OwnCloudVersion ocv =
          new OwnCloudVersion(am.getUserData(mAccount, AccountAuthenticator.KEY_OC_VERSION));
      String webdav_path = AccountUtils.getWebdavPath(ocv);
      Log.d(
          "ASD",
          "" + baseUrl + webdav_path + WebdavUtils.encodePath(mFileToRemove.getRemotePath()));

      DeleteMethod delete =
          new DeleteMethod(
              baseUrl + webdav_path + WebdavUtils.encodePath(mFileToRemove.getRemotePath()));

      boolean success = false;
      int status = -1;
      try {
        status = wc.executeMethod(delete);
        success = (delete.succeeded());
        delete.getResponseBodyAsString(); // exhaust the response, although not interesting
        Log.d(TAG, "Delete: returned status " + status);

      } catch (HttpException e) {
        Log.e(TAG, "HTTP Exception removing file " + mFileToRemove.getRemotePath(), e);

      } catch (IOException e) {
        Log.e(TAG, "I/O Exception removing file " + mFileToRemove.getRemotePath(), e);

      } catch (Exception e) {
        Log.e(TAG, "Unexpected exception removing file " + mFileToRemove.getRemotePath(), e);

      } finally {
        delete.releaseConnection();
      }

      if (success) {
        FileDataStorageManager fdsm =
            new FileDataStorageManager(mAccount, getActivity().getContentResolver());
        fdsm.removeFile(mFileToRemove, true);
        mHandler.post(
            new Runnable() {
              @Override
              public void run() {
                boolean inDisplayActivity = getActivity() instanceof FileDisplayActivity;
                getActivity()
                    .dismissDialog(
                        (inDisplayActivity)
                            ? FileDisplayActivity.DIALOG_SHORT_WAIT
                            : FileDetailActivity.DIALOG_SHORT_WAIT);
                try {
                  Toast msg =
                      Toast.makeText(
                          getActivity().getApplicationContext(),
                          R.string.remove_success_msg,
                          Toast.LENGTH_LONG);
                  msg.show();
                  if (inDisplayActivity) {
                    // double pane
                    FragmentTransaction transaction =
                        getActivity().getSupportFragmentManager().beginTransaction();
                    transaction.replace(
                        R.id.file_details_container,
                        new FileDetailFragment(null, null)); // empty FileDetailFragment
                    transaction.commit();
                    mContainerActivity.onFileStateChanged();

                  } else {
                    getActivity().finish();
                  }

                } catch (NotFoundException e) {
                  e.printStackTrace();
                }
              }
            });

      } else {
        mHandler.post(
            new Runnable() {
              @Override
              public void run() {
                boolean inDisplayActivity = getActivity() instanceof FileDisplayActivity;
                getActivity()
                    .dismissDialog(
                        (inDisplayActivity)
                            ? FileDisplayActivity.DIALOG_SHORT_WAIT
                            : FileDetailActivity.DIALOG_SHORT_WAIT);
                try {
                  Toast msg =
                      Toast.makeText(getActivity(), R.string.remove_fail_msg, Toast.LENGTH_LONG);
                  msg.show();

                } catch (NotFoundException e) {
                  e.printStackTrace();
                }
              }
            });
      }
    }
예제 #6
0
  /** Opens mFile. */
  private void openFile() {

    String storagePath = mFile.getStoragePath();
    String encodedStoragePath = WebdavUtils.encodePath(storagePath);
    try {
      Intent i = new Intent(Intent.ACTION_VIEW);
      i.setDataAndType(Uri.parse("file://" + encodedStoragePath), mFile.getMimetype());
      i.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
      startActivity(i);

    } catch (Throwable t) {
      Log.e(
          TAG,
          "Fail when trying to open with the mimeType provided from the ownCloud server: "
              + mFile.getMimetype());
      boolean toastIt = true;
      String mimeType = "";
      try {
        Intent i = new Intent(Intent.ACTION_VIEW);
        mimeType =
            MimeTypeMap.getSingleton()
                .getMimeTypeFromExtension(storagePath.substring(storagePath.lastIndexOf('.') + 1));
        if (mimeType == null || !mimeType.equals(mFile.getMimetype())) {
          if (mimeType != null) {
            i.setDataAndType(Uri.parse("file://" + encodedStoragePath), mimeType);
          } else {
            // desperate try
            i.setDataAndType(Uri.parse("file://" + encodedStoragePath), "*/*");
          }
          i.setFlags(
              Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
          startActivity(i);
          toastIt = false;
        }

      } catch (IndexOutOfBoundsException e) {
        Log.e(TAG, "Trying to find out MIME type of a file without extension: " + storagePath);

      } catch (ActivityNotFoundException e) {
        Log.e(
            TAG,
            "No activity found to handle: "
                + storagePath
                + " with MIME type "
                + mimeType
                + " obtained from extension");

      } catch (Throwable th) {
        Log.e(TAG, "Unexpected problem when opening: " + storagePath, th);

      } finally {
        if (toastIt) {
          Toast.makeText(
                  getActivity(),
                  "There is no application to handle file " + mFile.getFileName(),
                  Toast.LENGTH_SHORT)
              .show();
        }
      }
    }
  }