Search in sources :

Example 1 with Optional

use of com.nextcloud.java.util.Optional in project android by nextcloud.

the class UploadListAdapter method onBindViewHolder.

@Override
public void onBindViewHolder(SectionedViewHolder holder, int section, int relativePosition, int absolutePosition) {
    ItemViewHolder itemViewHolder = (ItemViewHolder) holder;
    OCUpload item = uploadGroups[section].getItem(relativePosition);
    itemViewHolder.binding.uploadName.setText(item.getLocalPath());
    // local file name
    File remoteFile = new File(item.getRemotePath());
    String fileName = remoteFile.getName();
    if (fileName.length() == 0) {
        fileName = File.separator;
    }
    itemViewHolder.binding.uploadName.setText(fileName);
    // remote path to parent folder
    itemViewHolder.binding.uploadRemotePath.setText(new File(item.getRemotePath()).getParent());
    // file size
    if (item.getFileSize() != 0) {
        itemViewHolder.binding.uploadFileSize.setText(String.format("%s, ", DisplayUtils.bytesToHumanReadable(item.getFileSize())));
    } else {
        itemViewHolder.binding.uploadFileSize.setText("");
    }
    // upload date
    long updateTime = item.getUploadEndTimestamp();
    CharSequence dateString = DisplayUtils.getRelativeDateTimeString(parentActivity, updateTime, DateUtils.SECOND_IN_MILLIS, DateUtils.WEEK_IN_MILLIS, 0);
    itemViewHolder.binding.uploadDate.setText(dateString);
    // account
    final Optional<User> optionalUser = accountManager.getUser(item.getAccountName());
    if (showUser) {
        itemViewHolder.binding.uploadAccount.setVisibility(View.VISIBLE);
        if (optionalUser.isPresent()) {
            itemViewHolder.binding.uploadAccount.setText(DisplayUtils.getAccountNameDisplayText(optionalUser.get()));
        } else {
            itemViewHolder.binding.uploadAccount.setText(item.getAccountName());
        }
    } else {
        itemViewHolder.binding.uploadAccount.setVisibility(View.GONE);
    }
    // Reset fields visibility
    itemViewHolder.binding.uploadDate.setVisibility(View.VISIBLE);
    itemViewHolder.binding.uploadRemotePath.setVisibility(View.VISIBLE);
    itemViewHolder.binding.uploadFileSize.setVisibility(View.VISIBLE);
    itemViewHolder.binding.uploadStatus.setVisibility(View.VISIBLE);
    itemViewHolder.binding.uploadProgressBar.setVisibility(View.GONE);
    // Update information depending of upload details
    String status = getStatusText(item);
    switch(item.getUploadStatus()) {
        case UPLOAD_IN_PROGRESS:
            ThemeBarUtils.colorHorizontalProgressBar(itemViewHolder.binding.uploadProgressBar, ThemeColorUtils.primaryAccentColor(parentActivity));
            itemViewHolder.binding.uploadProgressBar.setProgress(0);
            itemViewHolder.binding.uploadProgressBar.setVisibility(View.VISIBLE);
            FileUploader.FileUploaderBinder binder = parentActivity.getFileUploaderBinder();
            if (binder != null) {
                if (binder.isUploadingNow(item)) {
                    // ... unbind the old progress bar, if any; ...
                    if (progressListener != null) {
                        binder.removeDatatransferProgressListener(progressListener, // the one that was added
                        progressListener.getUpload());
                    }
                    // ... then, bind the current progress bar to listen for updates
                    progressListener = new ProgressListener(item, itemViewHolder.binding.uploadProgressBar);
                    binder.addDatatransferProgressListener(progressListener, item);
                } else {
                    // not really uploading; stop listening progress if view is reused!
                    if (progressListener != null && progressListener.isWrapping(itemViewHolder.binding.uploadProgressBar)) {
                        binder.removeDatatransferProgressListener(progressListener, // the one that was added
                        progressListener.getUpload());
                        progressListener = null;
                    }
                }
            } else {
                Log_OC.w(TAG, "FileUploaderBinder not ready yet for upload " + item.getRemotePath());
            }
            itemViewHolder.binding.uploadDate.setVisibility(View.GONE);
            itemViewHolder.binding.uploadFileSize.setVisibility(View.GONE);
            itemViewHolder.binding.uploadProgressBar.invalidate();
            break;
        case UPLOAD_FAILED:
            itemViewHolder.binding.uploadDate.setVisibility(View.GONE);
            break;
        case UPLOAD_SUCCEEDED:
            itemViewHolder.binding.uploadStatus.setVisibility(View.GONE);
            break;
    }
    itemViewHolder.binding.uploadStatus.setText(status);
    // bind listeners to perform actions
    if (item.getUploadStatus() == UploadStatus.UPLOAD_IN_PROGRESS) {
        // Cancel
        itemViewHolder.binding.uploadRightButton.setImageResource(R.drawable.ic_action_cancel_grey);
        itemViewHolder.binding.uploadRightButton.setVisibility(View.VISIBLE);
        itemViewHolder.binding.uploadRightButton.setOnClickListener(v -> {
            FileUploader.FileUploaderBinder uploaderBinder = parentActivity.getFileUploaderBinder();
            if (uploaderBinder != null) {
                uploaderBinder.cancel(item);
                loadUploadItemsFromDb();
            }
        });
    } else if (item.getUploadStatus() == UploadStatus.UPLOAD_FAILED) {
        if (item.getLastResult() == UploadResult.SYNC_CONFLICT) {
            itemViewHolder.binding.uploadRightButton.setImageResource(R.drawable.ic_dots_vertical);
            itemViewHolder.binding.uploadRightButton.setOnClickListener(view -> {
                if (optionalUser.isPresent()) {
                    User user = optionalUser.get();
                    showItemConflictPopup(user, itemViewHolder, item, status, view);
                }
            });
        } else {
            // Delete
            itemViewHolder.binding.uploadRightButton.setImageResource(R.drawable.ic_action_delete_grey);
            itemViewHolder.binding.uploadRightButton.setOnClickListener(v -> removeUpload(item));
        }
        itemViewHolder.binding.uploadRightButton.setVisibility(View.VISIBLE);
    } else {
        // UploadStatus.UPLOAD_SUCCESS
        itemViewHolder.binding.uploadRightButton.setVisibility(View.INVISIBLE);
    }
    itemViewHolder.binding.uploadListItemLayout.setOnClickListener(null);
    // click on item
    if (item.getUploadStatus() == UploadStatus.UPLOAD_FAILED) {
        final UploadResult uploadResult = item.getLastResult();
        itemViewHolder.binding.uploadListItemLayout.setOnClickListener(v -> {
            if (uploadResult == UploadResult.CREDENTIAL_ERROR) {
                final Optional<User> user = accountManager.getUser(item.getAccountName());
                final Account account = user.orElseThrow(RuntimeException::new).toPlatformAccount();
                parentActivity.getFileOperationsHelper().checkCurrentCredentials(account);
                return;
            } else if (uploadResult == UploadResult.SYNC_CONFLICT && optionalUser.isPresent()) {
                User user = optionalUser.get();
                if (checkAndOpenConflictResolutionDialog(user, itemViewHolder, item, status)) {
                    return;
                }
            }
            // not a credentials error
            File file = new File(item.getLocalPath());
            Optional<User> user = accountManager.getUser(item.getAccountName());
            if (file.exists() && user.isPresent()) {
                FileUploader.retryUpload(parentActivity, user.get(), item);
                loadUploadItemsFromDb();
            } else {
                DisplayUtils.showSnackMessage(v.getRootView().findViewById(android.R.id.content), R.string.local_file_not_found_message);
            }
        });
    } else {
        itemViewHolder.binding.uploadListItemLayout.setOnClickListener(v -> onUploadItemClick(item));
    }
    // Set icon or thumbnail
    itemViewHolder.binding.thumbnail.setImageResource(R.drawable.file);
    /*
         * Cancellation needs do be checked and done before changing the drawable in fileIcon, or
         * {@link ThumbnailsCacheManager#cancelPotentialWork} will NEVER cancel any task.
         */
    OCFile fakeFileToCheatThumbnailsCacheManagerInterface = new OCFile(item.getRemotePath());
    fakeFileToCheatThumbnailsCacheManagerInterface.setStoragePath(item.getLocalPath());
    fakeFileToCheatThumbnailsCacheManagerInterface.setMimeType(item.getMimeType());
    boolean allowedToCreateNewThumbnail = ThumbnailsCacheManager.cancelPotentialThumbnailWork(fakeFileToCheatThumbnailsCacheManagerInterface, itemViewHolder.binding.thumbnail);
    // TODO this code is duplicated; refactor to a common place
    if (MimeTypeUtil.isImage(fakeFileToCheatThumbnailsCacheManagerInterface) && fakeFileToCheatThumbnailsCacheManagerInterface.getRemoteId() != null && item.getUploadStatus() == UploadStatus.UPLOAD_SUCCEEDED) {
        // Thumbnail in Cache?
        Bitmap thumbnail = ThumbnailsCacheManager.getBitmapFromDiskCache(String.valueOf(fakeFileToCheatThumbnailsCacheManagerInterface.getRemoteId()));
        if (thumbnail != null && !fakeFileToCheatThumbnailsCacheManagerInterface.isUpdateThumbnailNeeded()) {
            itemViewHolder.binding.thumbnail.setImageBitmap(thumbnail);
        } else {
            // generate new Thumbnail
            Optional<User> user = parentActivity.getUser();
            if (allowedToCreateNewThumbnail && user.isPresent()) {
                final ThumbnailsCacheManager.ThumbnailGenerationTask task = new ThumbnailsCacheManager.ThumbnailGenerationTask(itemViewHolder.binding.thumbnail, parentActivity.getStorageManager(), user.get());
                if (thumbnail == null) {
                    if (MimeTypeUtil.isVideo(fakeFileToCheatThumbnailsCacheManagerInterface)) {
                        thumbnail = ThumbnailsCacheManager.mDefaultVideo;
                    } else {
                        thumbnail = ThumbnailsCacheManager.mDefaultImg;
                    }
                }
                final ThumbnailsCacheManager.AsyncThumbnailDrawable asyncDrawable = new ThumbnailsCacheManager.AsyncThumbnailDrawable(parentActivity.getResources(), thumbnail, task);
                itemViewHolder.binding.thumbnail.setImageDrawable(asyncDrawable);
                task.execute(new ThumbnailsCacheManager.ThumbnailGenerationTaskObject(fakeFileToCheatThumbnailsCacheManagerInterface, null));
            }
        }
        if ("image/png".equals(item.getMimeType())) {
            itemViewHolder.binding.thumbnail.setBackgroundColor(parentActivity.getResources().getColor(R.color.bg_default));
        }
    } else if (MimeTypeUtil.isImage(fakeFileToCheatThumbnailsCacheManagerInterface)) {
        File file = new File(item.getLocalPath());
        // Thumbnail in Cache?
        Bitmap thumbnail = ThumbnailsCacheManager.getBitmapFromDiskCache(String.valueOf(file.hashCode()));
        if (thumbnail != null) {
            itemViewHolder.binding.thumbnail.setImageBitmap(thumbnail);
        } else {
            // generate new Thumbnail
            if (allowedToCreateNewThumbnail) {
                final ThumbnailsCacheManager.ThumbnailGenerationTask task = new ThumbnailsCacheManager.ThumbnailGenerationTask(itemViewHolder.binding.thumbnail);
                if (MimeTypeUtil.isVideo(file)) {
                    thumbnail = ThumbnailsCacheManager.mDefaultVideo;
                } else {
                    thumbnail = ThumbnailsCacheManager.mDefaultImg;
                }
                final ThumbnailsCacheManager.AsyncThumbnailDrawable asyncDrawable = new ThumbnailsCacheManager.AsyncThumbnailDrawable(parentActivity.getResources(), thumbnail, task);
                itemViewHolder.binding.thumbnail.setImageDrawable(asyncDrawable);
                task.execute(new ThumbnailsCacheManager.ThumbnailGenerationTaskObject(file, null));
                Log_OC.v(TAG, "Executing task to generate a new thumbnail");
            }
        }
        if ("image/png".equalsIgnoreCase(item.getMimeType())) {
            itemViewHolder.binding.thumbnail.setBackgroundColor(parentActivity.getResources().getColor(R.color.bg_default));
        }
    } else {
        if (optionalUser.isPresent()) {
            final User user = optionalUser.get();
            final Drawable icon = MimeTypeUtil.getFileTypeIcon(item.getMimeType(), fileName, user, parentActivity);
            itemViewHolder.binding.thumbnail.setImageDrawable(icon);
        }
    }
}
Also used : Context(android.content.Context) User(com.nextcloud.client.account.User) ThumbnailsCacheManager(com.owncloud.android.datamodel.ThumbnailsCacheManager) Arrays(java.util.Arrays) DateUtils(android.text.format.DateUtils) NonNull(androidx.annotation.NonNull) Uri(android.net.Uri) ConnectivityService(com.nextcloud.client.network.ConnectivityService) OCFile(com.owncloud.android.datamodel.OCFile) FileActivity(com.owncloud.android.ui.activity.FileActivity) Intent(android.content.Intent) Drawable(android.graphics.drawable.Drawable) UserAccountManager(com.nextcloud.client.account.UserAccountManager) Clock(com.nextcloud.client.core.Clock) PopupMenu(android.widget.PopupMenu) UploadsStorageManager(com.owncloud.android.datamodel.UploadsStorageManager) View(android.view.View) PowerManagementService(com.nextcloud.client.device.PowerManagementService) ConflictsResolveActivity(com.owncloud.android.ui.activity.ConflictsResolveActivity) OnRemoteOperationListener(com.owncloud.android.lib.common.operations.OnRemoteOperationListener) DisplayUtils(com.owncloud.android.utils.DisplayUtils) RefreshFolderOperation(com.owncloud.android.operations.RefreshFolderOperation) Account(android.accounts.Account) LayoutInflater(android.view.LayoutInflater) SectionedRecyclerViewAdapter(com.afollestad.sectionedrecyclerview.SectionedRecyclerViewAdapter) Optional(com.nextcloud.java.util.Optional) UploadStatus(com.owncloud.android.datamodel.UploadsStorageManager.UploadStatus) OCUpload(com.owncloud.android.db.OCUpload) SectionedViewHolder(com.afollestad.sectionedrecyclerview.SectionedViewHolder) ViewGroup(android.view.ViewGroup) OCUploadComparator(com.owncloud.android.db.OCUploadComparator) File(java.io.File) Log_OC(com.owncloud.android.lib.common.utils.Log_OC) UploadListItemBinding(com.owncloud.android.databinding.UploadListItemBinding) UploadListHeaderBinding(com.owncloud.android.databinding.UploadListHeaderBinding) ThemeColorUtils(com.owncloud.android.utils.theme.ThemeColorUtils) MainApp(com.owncloud.android.MainApp) ActivityNotFoundException(android.content.ActivityNotFoundException) Bitmap(android.graphics.Bitmap) FileDataStorageManager(com.owncloud.android.datamodel.FileDataStorageManager) UploadResult(com.owncloud.android.db.UploadResult) FileUploader(com.owncloud.android.files.services.FileUploader) MimeTypeUtil(com.owncloud.android.utils.MimeTypeUtil) ThemeBarUtils(com.owncloud.android.utils.theme.ThemeBarUtils) R(com.owncloud.android.R) Account(android.accounts.Account) User(com.nextcloud.client.account.User) FileUploader(com.owncloud.android.files.services.FileUploader) OCFile(com.owncloud.android.datamodel.OCFile) OCUpload(com.owncloud.android.db.OCUpload) Bitmap(android.graphics.Bitmap) ThumbnailsCacheManager(com.owncloud.android.datamodel.ThumbnailsCacheManager) Drawable(android.graphics.drawable.Drawable) UploadResult(com.owncloud.android.db.UploadResult) OCFile(com.owncloud.android.datamodel.OCFile) File(java.io.File)

Aggregations

Account (android.accounts.Account)1 ActivityNotFoundException (android.content.ActivityNotFoundException)1 Context (android.content.Context)1 Intent (android.content.Intent)1 Bitmap (android.graphics.Bitmap)1 Drawable (android.graphics.drawable.Drawable)1 Uri (android.net.Uri)1 DateUtils (android.text.format.DateUtils)1 LayoutInflater (android.view.LayoutInflater)1 View (android.view.View)1 ViewGroup (android.view.ViewGroup)1 PopupMenu (android.widget.PopupMenu)1 NonNull (androidx.annotation.NonNull)1 SectionedRecyclerViewAdapter (com.afollestad.sectionedrecyclerview.SectionedRecyclerViewAdapter)1 SectionedViewHolder (com.afollestad.sectionedrecyclerview.SectionedViewHolder)1 User (com.nextcloud.client.account.User)1 UserAccountManager (com.nextcloud.client.account.UserAccountManager)1 Clock (com.nextcloud.client.core.Clock)1 PowerManagementService (com.nextcloud.client.device.PowerManagementService)1 ConnectivityService (com.nextcloud.client.network.ConnectivityService)1