/**
  * Request to stop the observance of local updates for a file.
  *
  * @param file OCFile representing the remote file to stop to monitor for local updates
  */
 private void disableObservance(OCFile file) {
   Log.d(TAG, "Disabling observation of remote file" + file.getRemotePath());
   Intent intent = new Intent(mContext, FileObserverService.class);
   intent.putExtra(FileObserverService.KEY_FILE_CMD, FileObserverService.CMD_ADD_DOWNLOADING_FILE);
   intent.putExtra(FileObserverService.KEY_CMD_ARG, file.getRemotePath());
   mContext.startService(intent);
 }
Пример #2
0
  /**
   * Start move file operation
   *
   * @param newfile File where it is going to be moved
   * @param currentFile File with the previous info
   */
  public void moveFile(OCFile newfile, OCFile currentFile) {
    // Move files
    Intent service = new Intent(mFileActivity, OperationsService.class);
    service.setAction(OperationsService.ACTION_MOVE_FILE);
    service.putExtra(OperationsService.EXTRA_NEW_PARENT_PATH, newfile.getRemotePath());
    service.putExtra(OperationsService.EXTRA_REMOTE_PATH, currentFile.getRemotePath());
    service.putExtra(OperationsService.EXTRA_ACCOUNT, mFileActivity.getAccount());
    mWaitingForOpId = mFileActivity.getOperationsServiceBinder().queueNewOperation(service);

    mFileActivity.showLoadingDialog();
  }
Пример #3
0
  /**
   * Performs the rename operation.
   *
   * @param client Client object to communicate with the remote ownCloud server.
   */
  @Override
  protected RemoteOperationResult run(OwnCloudClient client) {
    RemoteOperationResult result = null;

    // check if the new name is valid in the local file system
    try {
      if (!isValidNewName()) {
        return new RemoteOperationResult(ResultCode.INVALID_LOCAL_FILE_NAME);
      }
      String parent = (new File(mFile.getRemotePath())).getParent();
      parent = (parent.endsWith(OCFile.PATH_SEPARATOR)) ? parent : parent + OCFile.PATH_SEPARATOR;
      mNewRemotePath = parent + mNewName;
      if (mFile.isFolder()) {
        mNewRemotePath += OCFile.PATH_SEPARATOR;
      }

      // ckeck local overwrite
      if (mStorageManager.getFileByPath(mNewRemotePath) != null) {
        return new RemoteOperationResult(ResultCode.INVALID_OVERWRITE);
      }

      RenameRemoteFileOperation operation =
          new RenameRemoteFileOperation(
              mFile.getFileName(), mFile.getRemotePath(), mNewName, mFile.isFolder());
      result = operation.execute(client);

      if (result.isSuccess()) {
        if (mFile.isFolder()) {
          saveLocalDirectory();

        } else {
          saveLocalFile();
        }
      }

    } catch (IOException e) {
      Log_OC.e(
          TAG,
          "Rename "
              + mFile.getRemotePath()
              + " to "
              + ((mNewRemotePath == null) ? mNewName : mNewRemotePath)
              + ": "
              + ((result != null) ? result.getLogMessage() : ""),
          e);
    }

    return result;
  }
Пример #4
0
 protected void updateFileFromDB() {
   OCFile file = getFile();
   if (file != null) {
     file = getStorageManager().getFileByPath(file.getRemotePath());
     setFile(file);
   }
 }
Пример #5
0
  public void syncFile(OCFile file) {

    if (!file.isFolder()) {
      Intent intent = new Intent(mFileActivity, OperationsService.class);
      intent.setAction(OperationsService.ACTION_SYNC_FILE);
      intent.putExtra(OperationsService.EXTRA_ACCOUNT, mFileActivity.getAccount());
      intent.putExtra(OperationsService.EXTRA_REMOTE_PATH, file.getRemotePath());
      intent.putExtra(OperationsService.EXTRA_SYNC_FILE_CONTENTS, true);
      mWaitingForOpId = mFileActivity.getOperationsServiceBinder().queueNewOperation(intent);
      mFileActivity.showLoadingDialog();

    } else {
      Intent intent = new Intent(mFileActivity, OperationsService.class);
      intent.setAction(OperationsService.ACTION_SYNC_FOLDER);
      intent.putExtra(OperationsService.EXTRA_ACCOUNT, mFileActivity.getAccount());
      intent.putExtra(OperationsService.EXTRA_REMOTE_PATH, file.getRemotePath());
      mFileActivity.startService(intent);
    }
  }
Пример #6
0
  public void removeFile(OCFile file, boolean onlyLocalCopy) {
    // RemoveFile
    Intent service = new Intent(mFileActivity, OperationsService.class);
    service.setAction(OperationsService.ACTION_REMOVE);
    service.putExtra(OperationsService.EXTRA_ACCOUNT, mFileActivity.getAccount());
    service.putExtra(OperationsService.EXTRA_REMOTE_PATH, file.getRemotePath());
    service.putExtra(OperationsService.EXTRA_REMOVE_ONLY_LOCAL, onlyLocalCopy);
    mWaitingForOpId = mFileActivity.getOperationsServiceBinder().queueNewOperation(service);

    mFileActivity.showLoadingDialog();
  }
Пример #7
0
  public void renameFile(OCFile file, String newFilename) {
    // RenameFile
    Intent service = new Intent(mFileActivity, OperationsService.class);
    service.setAction(OperationsService.ACTION_RENAME);
    service.putExtra(OperationsService.EXTRA_ACCOUNT, mFileActivity.getAccount());
    service.putExtra(OperationsService.EXTRA_REMOTE_PATH, file.getRemotePath());
    service.putExtra(OperationsService.EXTRA_NEWNAME, newFilename);
    mWaitingForOpId = mFileActivity.getOperationsServiceBinder().queueNewOperation(service);

    mFileActivity.showLoadingDialog();
  }
Пример #8
0
  /** Updates the view with all relevant details about that file. */
  public void updateFileDetails() {

    if (mFile != null && mAccount != null && mLayout == R.layout.file_details_fragment) {

      // set file details
      setFilename(mFile.getFileName());
      setFiletype(DisplayUtils.convertMIMEtoPrettyPrint(mFile.getMimetype()));
      setFilesize(mFile.getFileLength());
      if (ocVersionSupportsTimeCreated()) {
        setTimeCreated(mFile.getCreationTimestamp());
      }

      setTimeModified(mFile.getModificationTimestamp());

      CheckBox cb = (CheckBox) getView().findViewById(R.id.fdKeepInSync);
      cb.setChecked(mFile.keepInSync());

      // configure UI for depending upon local state of the file
      if (FileDownloader.isDownloading(mAccount, mFile.getRemotePath())
          || FileUploader.isUploading(mAccount, mFile.getRemotePath())) {
        setButtonsForTransferring();

      } else if (mFile.isDown()) {
        // Update preview
        if (mFile.getMimetype().startsWith("image/")) {
          BitmapLoader bl = new BitmapLoader();
          bl.execute(new String[] {mFile.getStoragePath()});
        }

        setButtonsForDown();

      } else {
        setButtonsForRemote();
      }
    }
  }
Пример #9
0
  public void shareFileWithLinkToApp(OCFile file, String password, Intent sendIntent) {

    if (file != null) {
      mFileActivity.showLoadingDialog();

      Intent service = new Intent(mFileActivity, OperationsService.class);
      service.setAction(OperationsService.ACTION_CREATE_SHARE);
      service.putExtra(OperationsService.EXTRA_ACCOUNT, mFileActivity.getAccount());
      service.putExtra(OperationsService.EXTRA_REMOTE_PATH, file.getRemotePath());
      service.putExtra(OperationsService.EXTRA_PASSWORD_SHARE, password);
      service.putExtra(OperationsService.EXTRA_SEND_INTENT, sendIntent);
      mWaitingForOpId = mFileActivity.getOperationsServiceBinder().queueNewOperation(service);

    } else {
      Log_OC.wtf(TAG, "Trying to open a NULL OCFile");
    }
  }
Пример #10
0
  /**
   * Updates the view with all relevant details about that file.
   *
   * <p>TODO Remove parameter when the transferring state of files is kept in database.
   *
   * <p>TODO REFACTORING! this method called 5 times before every time the fragment is shown!
   *
   * @param transferring Flag signaling if the file should be considered as downloading or
   *     uploading, although {@link FileDownloaderBinder#isDownloading(Account, OCFile)} and {@link
   *     FileUploaderBinder#isUploading(Account, OCFile)} return false.
   * @param refresh If 'true', try to refresh the hold file from the database
   */
  public void updateFileDetails(boolean transferring, boolean refresh) {

    if (readyToShow()) {

      if (refresh && mStorageManager != null) {
        mFile = mStorageManager.getFileByPath(mFile.getRemotePath());
      }

      // set file details
      setFilename(mFile.getFileName());
      setFiletype(mFile.getMimetype());
      setFilesize(mFile.getFileLength());
      if (ocVersionSupportsTimeCreated()) {
        setTimeCreated(mFile.getCreationTimestamp());
      }

      setTimeModified(mFile.getModificationTimestamp());

      CheckBox cb = (CheckBox) getView().findViewById(R.id.fdKeepInSync);
      cb.setChecked(mFile.keepInSync());

      // configure UI for depending upon local state of the file
      // if (FileDownloader.isDownloading(mAccount, mFile.getRemotePath()) ||
      // FileUploader.isUploading(mAccount, mFile.getRemotePath())) {
      FileDownloaderBinder downloaderBinder = mContainerActivity.getFileDownloaderBinder();
      FileUploaderBinder uploaderBinder = mContainerActivity.getFileUploaderBinder();
      if (transferring
          || (downloaderBinder != null && downloaderBinder.isDownloading(mAccount, mFile))
          || (uploaderBinder != null && uploaderBinder.isUploading(mAccount, mFile))) {
        setButtonsForTransferring();

      } else if (mFile.isDown()) {

        setButtonsForDown();

      } else {
        // TODO load default preview image; when the local file is removed, the preview remains
        // there
        setButtonsForRemote();
      }
    }
    getView().invalidate();
  }
Пример #11
0
  public void unshareFileWithLink(OCFile file) {

    if (isSharedSupported()) {
      // Unshare the file
      Intent service = new Intent(mFileActivity, OperationsService.class);
      service.setAction(OperationsService.ACTION_UNSHARE);
      service.putExtra(OperationsService.EXTRA_ACCOUNT, mFileActivity.getAccount());
      service.putExtra(OperationsService.EXTRA_REMOTE_PATH, file.getRemotePath());
      mWaitingForOpId = mFileActivity.getOperationsServiceBinder().queueNewOperation(service);

      mFileActivity.showLoadingDialog();

    } else {
      // Show a Message
      Toast t =
          Toast.makeText(
              mFileActivity,
              mFileActivity.getString(R.string.share_link_no_support_share_api),
              Toast.LENGTH_LONG);
      t.show();
    }
  }
Пример #12
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();
                }
              }
            });
      }
    }
  @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;
  }
Пример #14
0
 /**
  * Returns True when the file described by 'file' in the ownCloud account 'account' is
  * downloading or waiting to download.
  *
  * <p>If 'file' is a directory, returns 'true' if some of its descendant files is downloading or
  * waiting to download.
  *
  * @param account ownCloud account where the remote file is stored.
  * @param file File to check if something is synchronizing / downloading / uploading inside.
  */
 public boolean isSynchronizing(Account account, OCFile file) {
   return mSyncFolderHandler.isSynchronizing(account, file.getRemotePath());
 }
Пример #15
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();
    }*/
  }
Пример #16
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();
                }
              }
            });
      }
    }
Пример #17
0
 /**
  * Builds a key for mPendingUploads from the account and file to upload
  *
  * @param account Account where the file to upload is stored
  * @param file File to upload
  */
 private String buildRemoteName(Account account, OCFile file) {
   return account.name + file.getRemotePath();
 }
Пример #18
0
  @Override
  public View getView(int position, View convertView, ViewGroup parent) {

    View view = convertView;
    OCFile file = null;
    LayoutInflater inflator =
        (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

    if (mFiles != null && mFiles.size() > position) {
      file = mFiles.get(position);
    }

    // Find out which layout should be displayed
    ViewType viewType;
    if (!mGridMode) {
      viewType = ViewType.LIST_ITEM;
    } else if (file.isImage()) {
      viewType = ViewType.GRID_IMAGE;
    } else {
      viewType = ViewType.GRID_ITEM;
    }

    // Create View
    switch (viewType) {
      case GRID_IMAGE:
        view = inflator.inflate(R.layout.grid_image, null);
        break;
      case GRID_ITEM:
        view = inflator.inflate(R.layout.grid_item, null);
        break;
      case LIST_ITEM:
        view = inflator.inflate(R.layout.list_item, null);
        break;
    }

    view.invalidate();

    if (file != null) {

      ImageView fileIcon = (ImageView) view.findViewById(R.id.thumbnail);

      fileIcon.setTag(file.getFileId());
      TextView fileName;
      String name = file.getFileName();

      LinearLayout linearLayout = (LinearLayout) view.findViewById(R.id.ListItemLayout);
      linearLayout.setContentDescription("LinearLayout-" + name);

      switch (viewType) {
        case LIST_ITEM:
          TextView fileSizeV = (TextView) view.findViewById(R.id.file_size);
          TextView lastModV = (TextView) view.findViewById(R.id.last_mod);
          ImageView checkBoxV = (ImageView) view.findViewById(R.id.custom_checkbox);

          lastModV.setVisibility(View.VISIBLE);
          lastModV.setText(showRelativeTimestamp(file));

          checkBoxV.setVisibility(View.GONE);

          fileSizeV.setVisibility(View.VISIBLE);
          fileSizeV.setText(DisplayUtils.bytesToHumanReadable(file.getFileLength()));

          if (!file.isFolder()) {
            AbsListView parentList = (AbsListView) parent;
            if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
              if (parentList.getChoiceMode() == AbsListView.CHOICE_MODE_NONE) {
                checkBoxV.setVisibility(View.GONE);
              } else {
                if (parentList.isItemChecked(position)) {
                  checkBoxV.setImageResource(android.R.drawable.checkbox_on_background);
                } else {
                  checkBoxV.setImageResource(android.R.drawable.checkbox_off_background);
                }
                checkBoxV.setVisibility(View.VISIBLE);
              }
            }

          } else { // Folder
            fileSizeV.setVisibility(View.INVISIBLE);
          }

        case GRID_ITEM:
          // filename
          fileName = (TextView) view.findViewById(R.id.Filename);
          name = file.getFileName();
          fileName.setText(name);

        case GRID_IMAGE:
          // sharedIcon
          ImageView sharedIconV = (ImageView) view.findViewById(R.id.sharedIcon);
          if (file.isShareByLink()) {
            sharedIconV.setVisibility(View.VISIBLE);
            sharedIconV.bringToFront();
          } else {
            sharedIconV.setVisibility(View.GONE);
          }

          // local state
          ImageView localStateView = (ImageView) view.findViewById(R.id.localFileIndicator);
          localStateView.bringToFront();
          FileDownloaderBinder downloaderBinder = mTransferServiceGetter.getFileDownloaderBinder();
          FileUploaderBinder uploaderBinder = mTransferServiceGetter.getFileUploaderBinder();
          boolean downloading =
              (downloaderBinder != null && downloaderBinder.isDownloading(mAccount, file));
          OperationsServiceBinder opsBinder = mTransferServiceGetter.getOperationsServiceBinder();
          downloading |=
              (opsBinder != null && opsBinder.isSynchronizing(mAccount, file.getRemotePath()));
          if (downloading) {
            localStateView.setImageResource(R.drawable.downloading_file_indicator);
            localStateView.setVisibility(View.VISIBLE);
          } else if (uploaderBinder != null && uploaderBinder.isUploading(mAccount, file)) {
            localStateView.setImageResource(R.drawable.uploading_file_indicator);
            localStateView.setVisibility(View.VISIBLE);
          } else if (file.isDown()) {
            localStateView.setImageResource(R.drawable.local_file_indicator);
            localStateView.setVisibility(View.VISIBLE);
          } else {
            localStateView.setVisibility(View.INVISIBLE);
          }

          // share with me icon
          if (!file.isFolder()) {
            ImageView sharedWithMeIconV = (ImageView) view.findViewById(R.id.sharedWithMeIcon);
            sharedWithMeIconV.bringToFront();
            if (checkIfFileIsSharedWithMe(file)) {
              sharedWithMeIconV.setVisibility(View.VISIBLE);
            } else {
              sharedWithMeIconV.setVisibility(View.GONE);
            }
          }

          break;
      }

      // For all Views

      // this if-else is needed even though favorite icon is visible by default
      // because android reuses views in listview
      if (!file.keepInSync()) {
        view.findViewById(R.id.favoriteIcon).setVisibility(View.GONE);
      } else {
        view.findViewById(R.id.favoriteIcon).setVisibility(View.VISIBLE);
      }

      // No Folder
      if (!file.isFolder()) {
        if (file.isImage() && file.getRemoteId() != null) {
          // Thumbnail in Cache?
          Bitmap thumbnail =
              ThumbnailsCacheManager.getBitmapFromDiskCache(String.valueOf(file.getRemoteId()));
          if (thumbnail != null && !file.needsUpdateThumbnail()) {
            fileIcon.setImageBitmap(thumbnail);
          } else {
            // generate new Thumbnail
            if (ThumbnailsCacheManager.cancelPotentialWork(file, fileIcon)) {
              final ThumbnailsCacheManager.ThumbnailGenerationTask task =
                  new ThumbnailsCacheManager.ThumbnailGenerationTask(
                      fileIcon, mStorageManager, mAccount);
              if (thumbnail == null) {
                thumbnail = ThumbnailsCacheManager.mDefaultImg;
              }
              final ThumbnailsCacheManager.AsyncDrawable asyncDrawable =
                  new ThumbnailsCacheManager.AsyncDrawable(
                      mContext.getResources(), thumbnail, task);
              fileIcon.setImageDrawable(asyncDrawable);
              task.execute(file);
            }
          }
        } else {
          fileIcon.setImageResource(
              DisplayUtils.getFileTypeIconId(file.getMimetype(), file.getFileName()));
        }

      } else {
        // Folder
        if (checkIfFileIsSharedWithMe(file)) {
          fileIcon.setImageResource(R.drawable.shared_with_me_folder);
        } else if (file.isShareByLink()) {
          // If folder is sharedByLink, icon folder must be changed to
          // folder-public one
          fileIcon.setImageResource(R.drawable.folder_public);
        } else {
          fileIcon.setImageResource(
              DisplayUtils.getFileTypeIconId(file.getMimetype(), file.getFileName()));
        }
      }
    }

    return view;
  }