Search in sources :

Example 21 with User

use of com.nextcloud.client.account.User in project android by nextcloud.

the class AuthenticatorActivity method createAccount.

/**
 * Creates a new account through the Account Authenticator that started this activity.
 * <p>
 * This makes the account permanent.
 * <p>
 * TODO Decide how to name the OAuth accounts
 */
@SuppressFBWarnings("DMI")
@SuppressLint("TrulyRandom")
protected boolean createAccount(RemoteOperationResult<UserInfo> authResult) {
    String accountType = MainApp.getAccountType(this);
    // create and save new ownCloud account
    String lastPermanentLocation = authResult.getLastPermanentLocation();
    if (lastPermanentLocation != null) {
        mServerInfo.mBaseUrl = AuthenticatorUrlUtils.trimWebdavSuffix(lastPermanentLocation);
    }
    Uri uri = Uri.parse(mServerInfo.mBaseUrl);
    // used for authenticate on every login/network connection, determined by first login (weblogin/old login)
    // can be anything: email, name, name with whitespaces
    String loginName = webViewUser;
    String accountName = com.owncloud.android.lib.common.accounts.AccountUtils.buildAccountName(uri, loginName);
    Account newAccount = new Account(accountName, accountType);
    if (accountManager.exists(newAccount)) {
        // fail - not a new account, but an existing one; disallow
        RemoteOperationResult result = new RemoteOperationResult(ResultCode.ACCOUNT_NOT_NEW);
        updateAuthStatusIconAndText(result);
        showAuthStatus();
        Log_OC.d(TAG, result.getLogMessage());
        return false;
    } else {
        UserInfo userInfo = authResult.getResultData();
        if (userInfo == null) {
            Log_OC.e(this, "Could not read user data!");
            return false;
        }
        mAccount = newAccount;
        mAccountMgr.addAccountExplicitly(mAccount, webViewPassword, null);
        mAccountMgr.notifyAccountAuthenticated(mAccount);
        // add the new account as default in preferences, if there is none already
        User defaultAccount = accountManager.getUser();
        if (defaultAccount.isAnonymous()) {
            SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(this).edit();
            editor.putString("select_oc_account", accountName);
            editor.apply();
        }
        // / prepare result to return to the Authenticator
        // TODO check again what the Authenticator makes with it; probably has the same
        // effect as addAccountExplicitly, but it's not well done
        final Intent intent = new Intent();
        intent.putExtra(AccountManager.KEY_ACCOUNT_TYPE, accountType);
        intent.putExtra(AccountManager.KEY_ACCOUNT_NAME, mAccount.name);
        intent.putExtra(AccountManager.KEY_USERDATA, loginName);
        // / add user data to the new account; TODO probably can be done in the last parameter
        // addAccountExplicitly, or in KEY_USERDATA
        mAccountMgr.setUserData(mAccount, Constants.KEY_OC_VERSION, mServerInfo.mVersion.getVersion());
        mAccountMgr.setUserData(mAccount, Constants.KEY_OC_BASE_URL, mServerInfo.mBaseUrl);
        mAccountMgr.setUserData(mAccount, Constants.KEY_DISPLAY_NAME, userInfo.getDisplayName());
        mAccountMgr.setUserData(mAccount, Constants.KEY_USER_ID, userInfo.getId());
        mAccountMgr.setUserData(mAccount, Constants.KEY_OC_ACCOUNT_VERSION, Integer.toString(UserAccountManager.ACCOUNT_VERSION_WITH_PROPER_ID));
        setAccountAuthenticatorResult(intent.getExtras());
        setResult(RESULT_OK, intent);
        // notify Document Provider
        DocumentsStorageProvider.notifyRootsChanged(this);
        return true;
    }
}
Also used : Account(android.accounts.Account) OwnCloudAccount(com.owncloud.android.lib.common.OwnCloudAccount) User(com.nextcloud.client.account.User) SharedPreferences(android.content.SharedPreferences) RemoteOperationResult(com.owncloud.android.lib.common.operations.RemoteOperationResult) UserInfo(com.owncloud.android.lib.common.UserInfo) Intent(android.content.Intent) Uri(android.net.Uri) SuppressFBWarnings(edu.umd.cs.findbugs.annotations.SuppressFBWarnings) SuppressLint(android.annotation.SuppressLint)

Example 22 with User

use of com.nextcloud.client.account.User in project android by nextcloud.

the class AppPreferencesImpl method setSortOrder.

@Override
public void setSortOrder(FileSortOrder.Type type, FileSortOrder sortOrder) {
    User user = currentAccountProvider.getUser();
    ArbitraryDataProvider dataProvider = new ArbitraryDataProvider(context.getContentResolver());
    dataProvider.storeOrUpdateKeyValue(user.getAccountName(), PREF__FOLDER_SORT_ORDER + "_" + type, sortOrder.name);
}
Also used : User(com.nextcloud.client.account.User) ArbitraryDataProvider(com.owncloud.android.datamodel.ArbitraryDataProvider)

Example 23 with User

use of com.nextcloud.client.account.User in project android by nextcloud.

the class RootCursor method addRoot.

public void addRoot(DocumentsStorageProvider.Document document, Context context) {
    User user = document.getUser();
    int rootFlags = Root.FLAG_SUPPORTS_CREATE | Root.FLAG_SUPPORTS_RECENTS | Root.FLAG_SUPPORTS_SEARCH | Root.FLAG_SUPPORTS_IS_CHILD;
    newRow().add(Root.COLUMN_ROOT_ID, user.getAccountName()).add(Root.COLUMN_DOCUMENT_ID, document.getDocumentId()).add(Root.COLUMN_SUMMARY, user.getAccountName()).add(Root.COLUMN_TITLE, context.getString(R.string.app_name)).add(Root.COLUMN_ICON, R.mipmap.ic_launcher).add(Root.COLUMN_FLAGS, rootFlags);
}
Also used : User(com.nextcloud.client.account.User)

Example 24 with User

use of com.nextcloud.client.account.User in project android by nextcloud.

the class OCFileListAdapter method onBindViewHolder.

@Override
public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {
    if (holder instanceof OCFileListFooterViewHolder) {
        OCFileListFooterViewHolder footerViewHolder = (OCFileListFooterViewHolder) holder;
        footerViewHolder.binding.footerText.setText(getFooterText());
        footerViewHolder.binding.loadingProgressBar.getIndeterminateDrawable().setColorFilter(ThemeColorUtils.primaryColor(activity), PorterDuff.Mode.SRC_IN);
        footerViewHolder.binding.loadingProgressBar.setVisibility(ocFileListFragmentInterface.isLoading() ? View.VISIBLE : View.GONE);
    } else if (holder instanceof OCFileListHeaderViewHolder) {
        OCFileListHeaderViewHolder headerViewHolder = (OCFileListHeaderViewHolder) holder;
        String text = currentDirectory.getRichWorkspace();
        PreviewTextFragment.setText(headerViewHolder.binding.headerText, text, null, activity, true, true);
        headerViewHolder.binding.headerView.setOnClickListener(v -> ocFileListFragmentInterface.onHeaderClicked());
    } else {
        ListGridImageViewHolder gridViewHolder = (ListGridImageViewHolder) holder;
        OCFile file = getItem(position);
        boolean gridImage = MimeTypeUtil.isImage(file) || MimeTypeUtil.isVideo(file);
        gridViewHolder.getThumbnail().setTag(file.getFileId());
        setThumbnail(file, gridViewHolder.getThumbnail(), user, mStorageManager, asyncTasks, gridView, activity, gridViewHolder.getShimmerThumbnail(), preferences);
        if (highlightedItem != null && file.getFileId() == highlightedItem.getFileId()) {
            gridViewHolder.getItemLayout().setBackgroundColor(activity.getResources().getColor(R.color.selected_item_background));
        } else if (isCheckedFile(file)) {
            gridViewHolder.getItemLayout().setBackgroundColor(activity.getResources().getColor(R.color.selected_item_background));
            gridViewHolder.getCheckbox().setImageDrawable(ThemeDrawableUtils.tintDrawable(R.drawable.ic_checkbox_marked, ThemeColorUtils.primaryColor(activity)));
        } else {
            gridViewHolder.getItemLayout().setBackgroundColor(activity.getResources().getColor(R.color.bg_default));
            gridViewHolder.getCheckbox().setImageResource(R.drawable.ic_checkbox_blank_outline);
        }
        gridViewHolder.getItemLayout().setOnClickListener(v -> ocFileListFragmentInterface.onItemClicked(file));
        if (!hideItemOptions) {
            gridViewHolder.getItemLayout().setLongClickable(true);
            gridViewHolder.getItemLayout().setOnLongClickListener(v -> ocFileListFragmentInterface.onLongItemClicked(file));
        }
        // unread comments
        if (file.getUnreadCommentsCount() > 0) {
            gridViewHolder.getUnreadComments().setVisibility(View.VISIBLE);
            gridViewHolder.getUnreadComments().setOnClickListener(view -> ocFileListFragmentInterface.showActivityDetailView(file));
        } else {
            gridViewHolder.getUnreadComments().setVisibility(View.GONE);
        }
        if (holder instanceof ListItemViewHolder) {
            ListItemViewHolder itemViewHolder = (ListItemViewHolder) holder;
            if ((file.isSharedWithMe() || file.isSharedWithSharee()) && !multiSelect && !gridView && !hideItemOptions) {
                itemViewHolder.getSharedAvatars().setVisibility(View.VISIBLE);
                itemViewHolder.getSharedAvatars().removeAllViews();
                String fileOwner = file.getOwnerId();
                List<ShareeUser> sharees = file.getSharees();
                // use fileOwner if not oneself, then add at first
                ShareeUser fileOwnerSharee = new ShareeUser(fileOwner, file.getOwnerDisplayName(), ShareType.USER);
                if (!TextUtils.isEmpty(fileOwner) && !fileOwner.equals(userId) && !sharees.contains(fileOwnerSharee)) {
                    sharees.add(fileOwnerSharee);
                }
                Collections.reverse(sharees);
                Log_OC.d(this, "sharees of " + file.getFileName() + ": " + sharees);
                itemViewHolder.getSharedAvatars().setAvatars(user, sharees);
                itemViewHolder.getSharedAvatars().setOnClickListener(view -> ocFileListFragmentInterface.onShareIconClick(file));
            } else {
                itemViewHolder.getSharedAvatars().setVisibility(View.GONE);
                itemViewHolder.getSharedAvatars().removeAllViews();
            }
            // npe fix: looks like file without local storage path somehow get here
            final String storagePath = file.getStoragePath();
            if (onlyOnDevice && storagePath != null) {
                File localFile = new File(storagePath);
                long localSize;
                if (localFile.isDirectory()) {
                    localSize = FileStorageUtils.getFolderSize(localFile);
                } else {
                    localSize = localFile.length();
                }
                itemViewHolder.getFileSize().setText(DisplayUtils.bytesToHumanReadable(localSize));
            } else {
                itemViewHolder.getFileSize().setText(DisplayUtils.bytesToHumanReadable(file.getFileLength()));
            }
            itemViewHolder.getLastModification().setText(DisplayUtils.getRelativeTimestamp(activity, file.getModificationTimestamp()));
            if (multiSelect || gridView || hideItemOptions) {
                itemViewHolder.getOverflowMenu().setVisibility(View.GONE);
            } else {
                itemViewHolder.getOverflowMenu().setVisibility(View.VISIBLE);
                itemViewHolder.getOverflowMenu().setOnClickListener(view -> ocFileListFragmentInterface.onOverflowIconClicked(file, view));
            }
        }
        // default first
        gridViewHolder.getLocalFileIndicator().setVisibility(View.INVISIBLE);
        if (showMetadata) {
            OperationsService.OperationsServiceBinder operationsServiceBinder = transferServiceGetter.getOperationsServiceBinder();
            FileDownloader.FileDownloaderBinder fileDownloaderBinder = transferServiceGetter.getFileDownloaderBinder();
            FileUploader.FileUploaderBinder fileUploaderBinder = transferServiceGetter.getFileUploaderBinder();
            if (operationsServiceBinder != null && operationsServiceBinder.isSynchronizing(user, file)) {
                // synchronizing
                gridViewHolder.getLocalFileIndicator().setImageResource(R.drawable.ic_synchronizing);
                gridViewHolder.getLocalFileIndicator().setVisibility(View.VISIBLE);
            } else if (fileDownloaderBinder != null && fileDownloaderBinder.isDownloading(user, file)) {
                // downloading
                gridViewHolder.getLocalFileIndicator().setImageResource(R.drawable.ic_synchronizing);
                gridViewHolder.getLocalFileIndicator().setVisibility(View.VISIBLE);
            } else if (fileUploaderBinder != null && fileUploaderBinder.isUploading(user, file)) {
                // uploading
                gridViewHolder.getLocalFileIndicator().setImageResource(R.drawable.ic_synchronizing);
                gridViewHolder.getLocalFileIndicator().setVisibility(View.VISIBLE);
            } else if (file.getEtagInConflict() != null) {
                // conflict
                gridViewHolder.getLocalFileIndicator().setImageResource(R.drawable.ic_synchronizing_error);
                gridViewHolder.getLocalFileIndicator().setVisibility(View.VISIBLE);
            } else if (file.isDown()) {
                gridViewHolder.getLocalFileIndicator().setImageResource(R.drawable.ic_synced);
                gridViewHolder.getLocalFileIndicator().setVisibility(View.VISIBLE);
            }
            gridViewHolder.getFavorite().setVisibility(file.isFavorite() ? View.VISIBLE : View.GONE);
        }
        if (multiSelect) {
            gridViewHolder.getCheckbox().setVisibility(View.VISIBLE);
        } else {
            gridViewHolder.getCheckbox().setVisibility(View.GONE);
        }
        if (holder instanceof ListGridItemViewHolder) {
            ListGridItemViewHolder gridItemViewHolder = (ListGridItemViewHolder) holder;
            gridItemViewHolder.getFileName().setText(file.getDecryptedFileName());
            if (gridView && gridImage) {
                gridItemViewHolder.getFileName().setVisibility(View.GONE);
            } else {
                if (gridView && ocFileListFragmentInterface.getColumnsCount() > showFilenameColumnThreshold) {
                    gridItemViewHolder.getFileName().setVisibility(View.GONE);
                } else {
                    gridItemViewHolder.getFileName().setVisibility(View.VISIBLE);
                }
            }
        }
        if (gridView || hideItemOptions || (file.isFolder() && !file.canReshare())) {
            gridViewHolder.getShared().setVisibility(View.GONE);
        } else {
            showShareIcon(gridViewHolder, file);
        }
    }
}
Also used : User(com.nextcloud.client.account.User) ThumbnailsCacheManager(com.owncloud.android.datamodel.ThumbnailsCacheManager) RemoteFile(com.owncloud.android.lib.resources.files.model.RemoteFile) NonNull(androidx.annotation.NonNull) WindowManager(android.view.WindowManager) FrameLayout(android.widget.FrameLayout) ImageView(android.widget.ImageView) OCFile(com.owncloud.android.datamodel.OCFile) Drawable(android.graphics.drawable.Drawable) RemoteOperationResult(com.owncloud.android.lib.common.operations.RemoteOperationResult) Vector(java.util.Vector) OCShare(com.owncloud.android.lib.resources.shares.OCShare) AvatarGroupLayout(com.owncloud.android.ui.AvatarGroupLayout) Locale(java.util.Locale) Handler(android.os.Handler) Looper(android.os.Looper) View(android.view.View) FileSortOrder(com.owncloud.android.utils.FileSortOrder) RecyclerView(androidx.recyclerview.widget.RecyclerView) DisplayUtils(com.owncloud.android.utils.DisplayUtils) ThemeDrawableUtils(com.owncloud.android.utils.theme.ThemeDrawableUtils) AccountManager(android.accounts.AccountManager) ListHeaderBinding(com.owncloud.android.databinding.ListHeaderBinding) RefreshFolderOperation(com.owncloud.android.operations.RefreshFolderOperation) SearchType(com.owncloud.android.ui.fragment.SearchType) Set(java.util.Set) AppPreferences(com.nextcloud.client.preferences.AppPreferences) PorterDuff(android.graphics.PorterDuff) ViewGroup(android.view.ViewGroup) GridItemBinding(com.owncloud.android.databinding.GridItemBinding) Log_OC(com.owncloud.android.lib.common.utils.Log_OC) List(java.util.List) TextView(android.widget.TextView) GridImageBinding(com.owncloud.android.databinding.GridImageBinding) ShareType(com.owncloud.android.lib.resources.shares.ShareType) BitmapUtils(com.owncloud.android.utils.BitmapUtils) ThemeColorUtils(com.owncloud.android.utils.theme.ThemeColorUtils) Nullable(androidx.annotation.Nullable) MainApp(com.owncloud.android.MainApp) FileDataStorageManager(com.owncloud.android.datamodel.FileDataStorageManager) VirtualFolderType(com.owncloud.android.datamodel.VirtualFolderType) FileUploader(com.owncloud.android.files.services.FileUploader) MimeTypeUtil(com.owncloud.android.utils.MimeTypeUtil) ContentValues(android.content.ContentValues) R(com.owncloud.android.R) Context(android.content.Context) ResourcesCompat(androidx.core.content.res.ResourcesCompat) Filter(android.widget.Filter) ComponentsGetter(com.owncloud.android.ui.activity.ComponentsGetter) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) FileDownloader(com.owncloud.android.files.services.FileDownloader) LoaderImageView(com.elyeproj.loaderviewlibrary.LoaderImageView) OCFileListFragmentInterface(com.owncloud.android.ui.interfaces.OCFileListFragmentInterface) LayoutInflater(android.view.LayoutInflater) RemoteOperationFailedException(com.owncloud.android.operations.RemoteOperationFailedException) PreviewTextFragment(com.owncloud.android.ui.preview.PreviewTextFragment) Point(android.graphics.Point) TextUtils(android.text.TextUtils) ListItemBinding(com.owncloud.android.databinding.ListItemBinding) RemoteOperation(com.owncloud.android.lib.common.operations.RemoteOperation) ReadFileRemoteOperation(com.owncloud.android.lib.resources.files.ReadFileRemoteOperation) File(java.io.File) ListFooterBinding(com.owncloud.android.databinding.ListFooterBinding) OperationsService(com.owncloud.android.services.OperationsService) FileStorageUtils(com.owncloud.android.utils.FileStorageUtils) Bitmap(android.graphics.Bitmap) ShareeUser(com.owncloud.android.lib.resources.shares.ShareeUser) ProviderMeta(com.owncloud.android.db.ProviderMeta) Activity(android.app.Activity) Collections(java.util.Collections) VisibleForTesting(androidx.annotation.VisibleForTesting) Resources(android.content.res.Resources) OCFile(com.owncloud.android.datamodel.OCFile) ShareeUser(com.owncloud.android.lib.resources.shares.ShareeUser) List(java.util.List) ArrayList(java.util.ArrayList) RemoteFile(com.owncloud.android.lib.resources.files.model.RemoteFile) OCFile(com.owncloud.android.datamodel.OCFile) File(java.io.File)

Example 25 with User

use of com.nextcloud.client.account.User 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

User (com.nextcloud.client.account.User)84 OCFile (com.owncloud.android.datamodel.OCFile)21 FileDataStorageManager (com.owncloud.android.datamodel.FileDataStorageManager)19 RemoteOperationResult (com.owncloud.android.lib.common.operations.RemoteOperationResult)19 Intent (android.content.Intent)14 Account (android.accounts.Account)12 ArrayList (java.util.ArrayList)12 Context (android.content.Context)9 Fragment (androidx.fragment.app.Fragment)9 OwnCloudAccount (com.owncloud.android.lib.common.OwnCloudAccount)9 File (java.io.File)9 ArbitraryDataProvider (com.owncloud.android.datamodel.ArbitraryDataProvider)7 Uri (android.net.Uri)6 Bundle (android.os.Bundle)6 OCCapability (com.owncloud.android.lib.resources.status.OCCapability)6 GalleryFragment (com.owncloud.android.ui.fragment.GalleryFragment)6 PreviewTextFileFragment (com.owncloud.android.ui.preview.PreviewTextFileFragment)6 PreviewTextFragment (com.owncloud.android.ui.preview.PreviewTextFragment)6 PreviewTextStringFragment (com.owncloud.android.ui.preview.PreviewTextStringFragment)6 View (android.view.View)5