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()); } }
/** * 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); }
@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); } } }
@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); } } }
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; }
@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; }
/** * 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); } }
@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; }