private void populateDirectoryList() { setContentView(R.layout.uploader_layout); String full_path = ""; for (String a : mParents) full_path += a + "/"; Log_OC.d(TAG, "Populating view with content of : " + full_path); mFile = mStorageManager.getFileByPath(full_path); if (mFile != null) { Vector<OCFile> files = mStorageManager.getFolderContent(mFile); List<HashMap<String, Object>> data = new LinkedList<HashMap<String, Object>>(); for (OCFile f : files) { HashMap<String, Object> h = new HashMap<String, Object>(); if (f.isFolder()) { h.put("dirname", f.getFileName()); data.add(h); } } SimpleAdapter sa = new SimpleAdapter( this, data, R.layout.uploader_list_item_layout, new String[] {"dirname"}, new int[] {R.id.textView1}); setListAdapter(sa); Button btn = (Button) findViewById(R.id.uploader_choose_folder); btn.setOnClickListener(this); getListView().setOnItemClickListener(this); } }
/** * Saves a OC File after a successful upload. * * <p>A PROPFIND is necessary to keep the props in the local database synchronized with the * server, specially the modification time and Etag (where available) * * <p>TODO refactor this ugly thing */ private void saveUploadedFile() { OCFile file = mCurrentUpload.getFile(); if (file.fileExists()) { file = mStorageManager.getFileById(file.getFileId()); } long syncDate = System.currentTimeMillis(); file.setLastSyncDateForData(syncDate); // new PROPFIND to keep data consistent with server // in theory, should return the same we already have ReadRemoteFileOperation operation = new ReadRemoteFileOperation(mCurrentUpload.getRemotePath()); RemoteOperationResult result = operation.execute(mUploadClient); if (result.isSuccess()) { updateOCFile(file, (RemoteFile) result.getData().get(0)); file.setLastSyncDateForProperties(syncDate); } // / maybe this would be better as part of UploadFileOperation... or // maybe all this method if (mCurrentUpload.wasRenamed()) { OCFile oldFile = mCurrentUpload.getOldFile(); if (oldFile.fileExists()) { oldFile.setStoragePath(null); mStorageManager.saveFile(oldFile); } // else: it was just an automatic renaming due to a name // coincidence; nothing else is needed, the storagePath is right // in the instance returned by mCurrentUpload.getFile() } mStorageManager.saveFile(file); }
/** Save new directory in local database */ public void saveFolderInDB() { OCFile newDir = new OCFile(mRemotePath); newDir.setMimetype("DIR"); long parentId = mStorageManager.getFileByPath(FileStorageUtils.getParentPath(mRemotePath)).getFileId(); newDir.setParentId(parentId); newDir.setModificationTimestamp(System.currentTimeMillis()); mStorageManager.saveFile(newDir); Log_OC.d(TAG, "Create directory " + mRemotePath + " in Database"); }
@Override public void onNeutral(String callerTag) { FileDataStorageManager fdsm = new FileDataStorageManager(mAccount, getActivity().getContentResolver()); File f = null; if (mFile.isDown() && (f = new File(mFile.getStoragePath())).exists()) { f.delete(); mFile.setStoragePath(null); fdsm.saveFile(mFile); updateFileDetails(mFile, mAccount); } }
public void onDismiss(EditNameFragment dialog) { if (dialog instanceof EditNameFragment) { if (((EditNameFragment) dialog).getResult()) { String newFilename = ((EditNameFragment) dialog).getNewFilename(); Log.d(TAG, "name edit dialog dismissed with new name " + newFilename); if (!newFilename.equals(mFile.getFileName())) { FileDataStorageManager fdsm = new FileDataStorageManager(mAccount, getActivity().getContentResolver()); if (fdsm.getFileById(mFile.getFileId()) != null) { OCFile newFile = new OCFile(fdsm.getFileById(mFile.getParentId()).getRemotePath() + newFilename); newFile.setCreationTimestamp(mFile.getCreationTimestamp()); newFile.setFileId(mFile.getFileId()); newFile.setFileLength(mFile.getFileLength()); newFile.setKeepInSync(mFile.keepInSync()); newFile.setLastSyncDate(mFile.getLastSyncDate()); newFile.setMimetype(mFile.getMimetype()); newFile.setModificationTimestamp(mFile.getModificationTimestamp()); newFile.setParentId(mFile.getParentId()); boolean localRenameFails = false; if (mFile.isDown()) { File f = new File(mFile.getStoragePath()); Log.e(TAG, f.getAbsolutePath()); localRenameFails = !(f.renameTo(new File(f.getParent() + File.separator + newFilename))); Log.e(TAG, f.getParent() + File.separator + newFilename); newFile.setStoragePath(f.getParent() + File.separator + newFilename); } if (localRenameFails) { Toast msg = Toast.makeText(getActivity(), R.string.rename_local_fail_msg, Toast.LENGTH_LONG); msg.show(); } else { new Thread(new RenameRunnable(mFile, newFile, mAccount, new Handler())).start(); boolean inDisplayActivity = getActivity() instanceof FileDisplayActivity; getActivity() .showDialog( (inDisplayActivity) ? FileDisplayActivity.DIALOG_SHORT_WAIT : FileDetailActivity.DIALOG_SHORT_WAIT); } } } } } else { Log.e( TAG, "Unknown dialog instance passed to onDismissDalog: " + dialog.getClass().getCanonicalName()); } }
@Override public void onConfirmation(String callerTag) { if (callerTag.equals(FTAG_CONFIRMATION)) { FileDataStorageManager fdsm = new FileDataStorageManager(mAccount, getActivity().getContentResolver()); if (fdsm.getFileById(mFile.getFileId()) != null) { new Thread(new RemoveRunnable(mFile, mAccount, new Handler())).start(); boolean inDisplayActivity = getActivity() instanceof FileDisplayActivity; getActivity() .showDialog( (inDisplayActivity) ? FileDisplayActivity.DIALOG_SHORT_WAIT : FileDetailActivity.DIALOG_SHORT_WAIT); } } }
/** * Constructor. * * @param fragmentManager {@link FragmentManager} instance that will handle the {@link Fragment}s * provided by the adapter. * @param parentFolder Folder where images will be searched for. * @param storageManager Bridge to database. */ public PreviewImagePagerAdapter( FragmentManager fragmentManager, OCFile parentFolder, Account account, FileDataStorageManager storageManager) { super(fragmentManager); if (fragmentManager == null) { throw new IllegalArgumentException("NULL FragmentManager instance"); } if (parentFolder == null) { throw new IllegalArgumentException("NULL parent folder"); } if (storageManager == null) { throw new IllegalArgumentException("NULL storage manager"); } mAccount = account; mStorageManager = storageManager; mImageFiles = mStorageManager.getFolderImages(parentFolder); mObsoleteFragments = new HashSet<Object>(); mObsoletePositions = new HashSet<Integer>(); mDownloadErrors = new HashSet<Integer>(); // mFragmentManager = fragmentManager; mCachedFragments = new HashMap<Integer, FileFragment>(); }
/** * Called when the ownCloud {@link Account} associated to the Activity was just updated. * * <p>Child classes must grant that state depending on the {@link Account} is updated. */ protected void onAccountSet(boolean stateWasRecovered) { if (getAccount() != null) { mStorageManager = new FileDataStorageManager(getAccount(), getContentResolver()); mCapabilities = mStorageManager.getCapability(mAccount.name); } else { Log_OC.wtf(TAG, "onAccountChanged was called with NULL account associated!"); } }
private void saveLocalDirectory() { mStorageManager.moveFolder(mFile, mNewRemotePath); String localPath = FileStorageUtils.getDefaultSavePathFor(mAccount.name, mFile); File localDir = new File(localPath); if (localDir.exists()) { localDir.renameTo(new File(FileStorageUtils.getSavePath(mAccount.name) + mNewRemotePath)); // TODO - if renameTo fails, children files that are already down will result unlinked } }
@Override public void onNeutral(String callerTag) { File f = null; if (mFile.isDown() && (f = new File(mFile.getStoragePath())).exists()) { f.delete(); mFile.setStoragePath(null); mStorageManager.saveFile(mFile); updateFileDetails(mFile, mAccount); } }
@Override public void onReceive(Context context, Intent intent) { String accountName = intent.getStringExtra(FileUploader.ACCOUNT_NAME); if (!isEmpty() && accountName.equals(mAccount.name)) { boolean uploadWasFine = intent.getBooleanExtra(FileUploader.EXTRA_UPLOAD_RESULT, false); String uploadRemotePath = intent.getStringExtra(FileUploader.EXTRA_REMOTE_PATH); if (mFile.getRemotePath().equals(uploadRemotePath)) { if (uploadWasFine) { FileDataStorageManager fdsm = new FileDataStorageManager( mAccount, getActivity().getApplicationContext().getContentResolver()); mFile = fdsm.getFileByPath(mFile.getRemotePath()); } updateFileDetails(); // it updates the buttons; must be called although !uploadWasFine; // interrupted uploads still leave an incomplete file in the server } } }
private OCFile createLocalFolder(String remotePath) { String parentPath = new File(remotePath).getParent(); parentPath = parentPath.endsWith(OCFile.PATH_SEPARATOR) ? parentPath : parentPath + OCFile.PATH_SEPARATOR; OCFile parent = mStorageManager.getFileByPath(parentPath); if (parent == null) { parent = createLocalFolder(parentPath); } if (parent != null) { OCFile createdFolder = new OCFile(remotePath); createdFolder.setMimetype("DIR"); createdFolder.setParentId(parent.getFileId()); mStorageManager.saveFile(createdFolder); return createdFolder; } return null; }
/** * 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; }
@Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { // click on folder in the list Log_OC.d(TAG, "on item click"); Vector<OCFile> tmpfiles = mStorageManager.getFolderContent(mFile); if (tmpfiles.size() <= 0) return; // filter on dirtype Vector<OCFile> files = new Vector<OCFile>(); for (OCFile f : tmpfiles) if (f.isFolder()) files.add(f); if (files.size() < position) { throw new IndexOutOfBoundsException("Incorrect item selected"); } mParents.push(files.get(position).getFileName()); populateDirectoryList(); }
private void saveLocalFile() { mFile.setFileName(mNewName); // try to rename the local copy of the file if (mFile.isDown()) { File f = new File(mFile.getStoragePath()); String parentStoragePath = f.getParent(); if (!parentStoragePath.endsWith(File.separator)) parentStoragePath += File.separator; if (f.renameTo(new File(parentStoragePath + mNewName))) { mFile.setStoragePath(parentStoragePath + mNewName); } // else - NOTHING: the link to the local file is kept although the local name can't be updated // TODO - study conditions when this could be a problem } mStorageManager.saveFile(mFile); }
@Override public void onConfirmation(String callerTag) { if (callerTag.equals(FTAG_CONFIRMATION)) { if (mStorageManager.getFileById(mFile.getFileId()) != null) { mLastRemoteOperation = new RemoveFileOperation(mFile, true, mStorageManager); WebdavClient wc = OwnCloudClientUtils.createOwnCloudClient( mAccount, getSherlockActivity().getApplicationContext()); mLastRemoteOperation.execute(wc, this, mHandler); boolean inDisplayActivity = getActivity() instanceof FileDisplayActivity; getActivity() .showDialog( (inDisplayActivity) ? FileDisplayActivity.DIALOG_SHORT_WAIT : FileDetailActivity.DIALOG_SHORT_WAIT); } } }
/** * 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(); }
/** * Change the adapted directory for a new one * * @param directory New file to adapt. Can be NULL, meaning "no content to adapt". * @param updatedStorageManager Optional updated storage manager; used to replace mStorageManager * if is different (and not NULL) */ public void swapDirectory(OCFile directory, FileDataStorageManager updatedStorageManager) { mFile = directory; if (updatedStorageManager != null && updatedStorageManager != mStorageManager) { mStorageManager = updatedStorageManager; mAccount = AccountUtils.getCurrentOwnCloudAccount(mContext); } if (mStorageManager != null) { mFiles = mStorageManager.getFolderContent(mFile); mFilesOrig.clear(); mFilesOrig.addAll(mFiles); if (mJustFolders) { mFiles = getFolders(mFiles); } } else { mFiles = null; } mFiles = FileStorageUtils.sortFolder(mFiles); notifyDataSetChanged(); }
/** * Checks the existence of the folder where the current file will be uploaded both in the remote * server and in the local database. * * <p>If the upload is set to enforce the creation of the folder, the method tries to create it * both remote and locally. * * @param pathToGrant Full remote path whose existence will be granted. * @return An {@link OCFile} instance corresponding to the folder where the file will be uploaded. */ private RemoteOperationResult grantFolderExistence(String pathToGrant) { RemoteOperation operation = new ExistenceCheckRemoteOperation(pathToGrant, this, false); RemoteOperationResult result = operation.execute(mUploadClient); if (!result.isSuccess() && result.getCode() == ResultCode.FILE_NOT_FOUND && mCurrentUpload.isRemoteFolderToBeCreated()) { operation = new CreateFolderOperation(pathToGrant, true, mStorageManager); result = operation.execute(mUploadClient); } if (result.isSuccess()) { OCFile parentDir = mStorageManager.getFileByPath(pathToGrant); if (parentDir == null) { parentDir = createLocalFolder(pathToGrant); } if (parentDir != null) { result = new RemoteOperationResult(ResultCode.OK); } else { result = new RemoteOperationResult(ResultCode.UNKNOWN_ERROR); } } return result; }
@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(); }*/ }
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 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(); }*/ }
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(); } } }); } }
@Override public void onClick(View v) { switch (v.getId()) { case R.id.fdDownloadBtn: { 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); } 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); 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( getString(R.string.rename_dialog_title), mFile.getFileName(), 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: { openFile(); break; } case R.id.fdShareBtn: {; 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(); }*/ }
/** * Core upload method: sends the file(s) to upload * * @param uploadKey Key to access the upload to perform, contained in mPendingUploads */ public void uploadFile(String uploadKey) { synchronized (mPendingUploads) { mCurrentUpload = mPendingUploads.get(uploadKey); } if (mCurrentUpload != null) { notifyUploadStart(mCurrentUpload); RemoteOperationResult uploadResult = null, grantResult = null; try { /// prepare client object to send requests to the ownCloud server if (mUploadClient == null || !mLastAccount.equals(mCurrentUpload.getAccount())) { mLastAccount = mCurrentUpload.getAccount(); mStorageManager = new FileDataStorageManager(mLastAccount, getContentResolver()); mUploadClient = OwnCloudClientFactory.createOwnCloudClient(mLastAccount, getApplicationContext()); } /// check the existence of the parent folder for the file to upload String remoteParentPath = new File(mCurrentUpload.getRemotePath()).getParent(); remoteParentPath = remoteParentPath.endsWith(OCFile.PATH_SEPARATOR) ? remoteParentPath : remoteParentPath + OCFile.PATH_SEPARATOR; grantResult = grantFolderExistence(remoteParentPath); /// perform the upload if (grantResult.isSuccess()) { OCFile parent = mStorageManager.getFileByPath(remoteParentPath); mCurrentUpload.getFile().setParentId(parent.getFileId()); uploadResult = mCurrentUpload.execute(mUploadClient); if (uploadResult.isSuccess()) { saveUploadedFile(); } } else { uploadResult = grantResult; } } catch (AccountsException e) { Log_OC.e(TAG, "Error while trying to get autorization for " + mLastAccount.name, e); uploadResult = new RemoteOperationResult(e); } catch (IOException e) { Log_OC.e(TAG, "Error while trying to get autorization for " + mLastAccount.name, e); uploadResult = new RemoteOperationResult(e); } finally { synchronized (mPendingUploads) { mPendingUploads.remove(uploadKey); Log_OC.i(TAG, "Remove CurrentUploadItem from pending upload Item Map."); } if (uploadResult.isException()) { // enforce the creation of a new client object for next uploads; this grant that a new // socket will // be created in the future if the current exception is due to an abrupt lose of network // connection mUploadClient = null; } } /// notify result notifyUploadResult(uploadResult, mCurrentUpload); sendFinalBroadcast(mCurrentUpload, uploadResult); } }