Search in sources :

Example 36 with User

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

the class FileUploader method uploadFile.

/**
 * 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) {
    mCurrentUpload = mPendingUploads.get(uploadKey);
    if (mCurrentUpload != null) {
        // / Check account existence
        if (!accountManager.exists(mCurrentUpload.getAccount())) {
            Log_OC.w(TAG, "Account " + mCurrentUpload.getAccount().name + " does not exist anymore -> cancelling all its uploads");
            cancelUploadsForAccount(mCurrentUpload.getAccount());
            return;
        }
        // / OK, let's upload
        mUploadsStorageManager.updateDatabaseUploadStart(mCurrentUpload);
        notifyUploadStart(mCurrentUpload);
        sendBroadcastUploadStarted(mCurrentUpload);
        RemoteOperationResult uploadResult = null;
        try {
            // / prepare client object to send the request to the ownCloud server
            if (mCurrentAccount == null || !mCurrentAccount.equals(mCurrentUpload.getAccount())) {
                mCurrentAccount = mCurrentUpload.getAccount();
                mStorageManager = new FileDataStorageManager(getCurrentUser().get(), getContentResolver());
            }
            // else, reuse storage manager from previous operation
            // always get client from client manager, to get fresh credentials in case of update
            OwnCloudAccount ocAccount = new OwnCloudAccount(mCurrentAccount, this);
            mUploadClient = OwnCloudClientManagerFactory.getDefaultSingleton().getClientFor(ocAccount, this);
            // // If parent folder is encrypted, upload file encrypted
            // OCFile parent = mStorageManager.getFileByPath(mCurrentUpload.getFile().getParentRemotePath());
            // if (parent.isEncrypted()) {
            // UploadEncryptedFileOperation uploadEncryptedFileOperation =
            // new UploadEncryptedFileOperation(parent, mCurrentUpload);
            // 
            // uploadResult = uploadEncryptedFileOperation.execute(mUploadClient, mStorageManager);
            // } else {
            // / perform the regular upload
            uploadResult = mCurrentUpload.execute(mUploadClient);
        // }
        } catch (Exception e) {
            Log_OC.e(TAG, "Error uploading", e);
            uploadResult = new RemoteOperationResult(e);
        } finally {
            Pair<UploadFileOperation, String> removeResult;
            if (mCurrentUpload.wasRenamed()) {
                removeResult = mPendingUploads.removePayload(mCurrentAccount.name, mCurrentUpload.getOldFile().getRemotePath());
            // TODO: grant that name is also updated for mCurrentUpload.getOCUploadId
            } else {
                removeResult = mPendingUploads.removePayload(mCurrentAccount.name, mCurrentUpload.getDecryptedRemotePath());
            }
            mUploadsStorageManager.updateDatabaseUploadResult(uploadResult, mCurrentUpload);
            // / notify result
            notifyUploadResult(mCurrentUpload, uploadResult);
            sendBroadcastUploadFinished(mCurrentUpload, uploadResult, removeResult.second);
        }
        // generate new Thumbnail
        Optional<User> user = getCurrentUser();
        if (user.isPresent()) {
            final ThumbnailsCacheManager.ThumbnailGenerationTask task = new ThumbnailsCacheManager.ThumbnailGenerationTask(mStorageManager, user.get());
            File file = new File(mCurrentUpload.getOriginalStoragePath());
            String remoteId = mCurrentUpload.getFile().getRemoteId();
            task.execute(new ThumbnailsCacheManager.ThumbnailGenerationTaskObject(file, remoteId));
        }
    }
}
Also used : User(com.nextcloud.client.account.User) RemoteOperationResult(com.owncloud.android.lib.common.operations.RemoteOperationResult) OwnCloudAccount(com.owncloud.android.lib.common.OwnCloudAccount) UploadFileOperation(com.owncloud.android.operations.UploadFileOperation) ThumbnailsCacheManager(com.owncloud.android.datamodel.ThumbnailsCacheManager) FileDataStorageManager(com.owncloud.android.datamodel.FileDataStorageManager) OCFile(com.owncloud.android.datamodel.OCFile) File(java.io.File)

Example 37 with User

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

the class FileDownloader method onStartCommand.

/**
 * Entry point to add one or several files to the queue of downloads.
 *
 * New downloads are added calling to startService(), resulting in a call to this method.
 * This ensures the service will keep on working although the caller activity goes away.
 */
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    Log_OC.d(TAG, "Starting command with id " + startId);
    startForeground(FOREGROUND_SERVICE_ID, mNotification);
    if (intent == null || !intent.hasExtra(EXTRA_USER) || !intent.hasExtra(EXTRA_FILE)) {
        Log_OC.e(TAG, "Not enough information provided in intent");
        return START_NOT_STICKY;
    } else {
        final User user = intent.getParcelableExtra(EXTRA_USER);
        final OCFile file = intent.getParcelableExtra(EXTRA_FILE);
        final String behaviour = intent.getStringExtra(OCFileListFragment.DOWNLOAD_BEHAVIOUR);
        String activityName = intent.getStringExtra(SendShareDialog.ACTIVITY_NAME);
        String packageName = intent.getStringExtra(SendShareDialog.PACKAGE_NAME);
        conflictUploadId = intent.getLongExtra(ConflictsResolveActivity.EXTRA_CONFLICT_UPLOAD_ID, -1);
        AbstractList<String> requestedDownloads = new Vector<String>();
        try {
            DownloadFileOperation newDownload = new DownloadFileOperation(user, file, behaviour, activityName, packageName, getBaseContext());
            newDownload.addDatatransferProgressListener(this);
            newDownload.addDatatransferProgressListener((FileDownloaderBinder) mBinder);
            Pair<String, String> putResult = mPendingDownloads.putIfAbsent(user.getAccountName(), file.getRemotePath(), newDownload);
            if (putResult != null) {
                String downloadKey = putResult.first;
                requestedDownloads.add(downloadKey);
                sendBroadcastNewDownload(newDownload, putResult.second);
            }
        // else, file already in the queue of downloads; don't repeat the request
        } catch (IllegalArgumentException e) {
            Log_OC.e(TAG, "Not enough information provided in intent: " + e.getMessage());
            return START_NOT_STICKY;
        }
        if (requestedDownloads.size() > 0) {
            Message msg = mServiceHandler.obtainMessage();
            msg.arg1 = startId;
            msg.obj = requestedDownloads;
            mServiceHandler.sendMessage(msg);
        }
    }
    return START_NOT_STICKY;
}
Also used : OCFile(com.owncloud.android.datamodel.OCFile) DownloadFileOperation(com.owncloud.android.operations.DownloadFileOperation) User(com.nextcloud.client.account.User) Message(android.os.Message) Vector(java.util.Vector)

Example 38 with User

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

the class FileDownloader method downloadFile.

/**
 * Core download method: requests a file to download and stores it.
 *
 * @param downloadKey Key to access the download to perform, contained in mPendingDownloads
 */
private void downloadFile(String downloadKey) {
    mStartedDownload = true;
    mCurrentDownload = mPendingDownloads.get(downloadKey);
    if (mCurrentDownload != null) {
        // Detect if the account exists
        if (accountManager.exists(mCurrentDownload.getAccount())) {
            Log_OC.d(TAG, "Account " + mCurrentDownload.getAccount().name + " exists");
            notifyDownloadStart(mCurrentDownload);
            RemoteOperationResult downloadResult = null;
            try {
                // / prepare client object to send the request to the ownCloud server
                Account currentDownloadAccount = mCurrentDownload.getAccount();
                Optional<User> currentDownloadUser = accountManager.getUser(currentDownloadAccount.name);
                if (!currentUser.equals(currentDownloadUser)) {
                    currentUser = currentDownloadUser;
                    mStorageManager = new FileDataStorageManager(currentUser.get(), getContentResolver());
                }
                // else, reuse storage manager from previous operation
                // always get client from client manager, to get fresh credentials in case
                // of update
                OwnCloudAccount ocAccount = currentDownloadUser.get().toOwnCloudAccount();
                mDownloadClient = OwnCloudClientManagerFactory.getDefaultSingleton().getClientFor(ocAccount, this);
                // / perform the download
                downloadResult = mCurrentDownload.execute(mDownloadClient);
                if (downloadResult.isSuccess()) {
                    saveDownloadedFile();
                }
            } catch (Exception e) {
                Log_OC.e(TAG, "Error downloading", e);
                downloadResult = new RemoteOperationResult(e);
            } finally {
                Pair<DownloadFileOperation, String> removeResult = mPendingDownloads.removePayload(mCurrentDownload.getUser().getAccountName(), mCurrentDownload.getRemotePath());
                if (downloadResult == null) {
                    downloadResult = new RemoteOperationResult(new RuntimeException("Error downloading…"));
                }
                // / notify result
                notifyDownloadResult(mCurrentDownload, downloadResult);
                sendBroadcastDownloadFinished(mCurrentDownload, downloadResult, removeResult.second);
            }
        } else {
            // Cancel the transfer
            Log_OC.d(TAG, "Account " + mCurrentDownload.getAccount() + " doesn't exist");
            cancelDownloadsForAccount(mCurrentDownload.getAccount());
        }
    }
}
Also used : Account(android.accounts.Account) OwnCloudAccount(com.owncloud.android.lib.common.OwnCloudAccount) DownloadFileOperation(com.owncloud.android.operations.DownloadFileOperation) User(com.nextcloud.client.account.User) RemoteOperationResult(com.owncloud.android.lib.common.operations.RemoteOperationResult) FileDataStorageManager(com.owncloud.android.datamodel.FileDataStorageManager) OwnCloudAccount(com.owncloud.android.lib.common.OwnCloudAccount)

Example 39 with User

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

the class ChooseTemplateDialogFragment method onCreateDialog.

@NonNull
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
    Bundle arguments = getArguments();
    if (arguments == null) {
        throw new IllegalArgumentException("Arguments may not be null");
    }
    Activity activity = getActivity();
    if (activity == null) {
        throw new IllegalArgumentException("Activity may not be null");
    }
    parentFolder = arguments.getParcelable(ARG_PARENT_FOLDER);
    creator = arguments.getParcelable(ARG_CREATOR);
    title = arguments.getString(ARG_HEADLINE, getString(R.string.select_template));
    if (savedInstanceState == null) {
        title = arguments.getString(ARG_HEADLINE);
    } else {
        title = savedInstanceState.getString(ARG_HEADLINE);
    }
    // Inflate the layout for the dialog
    LayoutInflater inflater = requireActivity().getLayoutInflater();
    binding = ChooseTemplateBinding.inflate(inflater, null, false);
    View view = binding.getRoot();
    binding.filename.requestFocus();
    ThemeTextInputUtils.colorTextInput(binding.filenameContainer, binding.filename, ThemeColorUtils.primaryColor(getContext()));
    binding.filename.setOnKeyListener((v, keyCode, event) -> {
        checkEnablingCreateButton();
        return false;
    });
    binding.filename.addTextChangedListener(new TextWatcher() {

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        // generated method stub
        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
        // generated method stub
        }

        @Override
        public void afterTextChanged(Editable s) {
            checkEnablingCreateButton();
        }
    });
    try {
        User user = currentAccount.getUser();
        new FetchTemplateTask(this, clientFactory, user, creator).execute();
    } catch (Exception e) {
        Log_OC.e(TAG, "Loading stream url not possible: " + e);
    }
    binding.list.setHasFixedSize(true);
    binding.list.setLayoutManager(new GridLayoutManager(activity, 2));
    adapter = new TemplateAdapter(creator.getMimetype(), this, getContext(), currentAccount, clientFactory);
    binding.list.setAdapter(adapter);
    // Build the dialog
    AlertDialog.Builder builder = new AlertDialog.Builder(activity);
    builder.setView(view).setPositiveButton(R.string.create, null).setNeutralButton(R.string.common_cancel, null).setTitle(title);
    Dialog dialog = builder.create();
    Window window = dialog.getWindow();
    if (window != null) {
        window.setSoftInputMode(LayoutParams.SOFT_INPUT_STATE_VISIBLE);
    }
    return dialog;
}
Also used : AlertDialog(androidx.appcompat.app.AlertDialog) Window(android.view.Window) User(com.nextcloud.client.account.User) Bundle(android.os.Bundle) Activity(android.app.Activity) View(android.view.View) ExternalSiteWebView(com.owncloud.android.ui.activity.ExternalSiteWebView) TextEditorWebView(com.owncloud.android.ui.activity.TextEditorWebView) GridLayoutManager(androidx.recyclerview.widget.GridLayoutManager) AlertDialog(androidx.appcompat.app.AlertDialog) Dialog(android.app.Dialog) LayoutInflater(android.view.LayoutInflater) TextWatcher(android.text.TextWatcher) Editable(android.text.Editable) TemplateAdapter(com.owncloud.android.ui.adapter.TemplateAdapter) NonNull(androidx.annotation.NonNull)

Example 40 with User

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

the class ConflictsResolveDialog method onCreateDialog.

@NonNull
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
    // Inflate the layout for the dialog
    binding = ConflictResolveDialogBinding.inflate(requireActivity().getLayoutInflater());
    ThemeCheckableUtils.tintCheckbox(ThemeColorUtils.primaryColor(getContext()), binding.newCheckbox, binding.existingCheckbox);
    // Build the dialog
    AlertDialog.Builder builder = new AlertDialog.Builder(requireActivity());
    builder.setView(binding.getRoot()).setPositiveButton(R.string.common_ok, (dialog, which) -> {
        if (listener != null) {
            if (binding.newCheckbox.isChecked() && binding.existingCheckbox.isChecked()) {
                listener.conflictDecisionMade(Decision.KEEP_BOTH);
            } else if (binding.newCheckbox.isChecked()) {
                listener.conflictDecisionMade(Decision.KEEP_LOCAL);
            } else if (binding.existingCheckbox.isChecked()) {
                listener.conflictDecisionMade(Decision.KEEP_SERVER);
            }
        // else do nothing
        }
    }).setNeutralButton(R.string.common_cancel, (dialog, which) -> {
        if (listener != null) {
            listener.conflictDecisionMade(Decision.CANCEL);
        }
    }).setTitle(String.format(getString(R.string.conflict_file_headline), existingFile.getFileName()));
    File parentFile = new File(existingFile.getRemotePath()).getParentFile();
    if (parentFile != null) {
        binding.in.setText(String.format(getString(R.string.in_folder), parentFile.getAbsolutePath()));
    } else {
        binding.in.setVisibility(View.GONE);
    }
    // set info for new file
    binding.newSize.setText(DisplayUtils.bytesToHumanReadable(newFile.length()));
    binding.newTimestamp.setText(DisplayUtils.getRelativeTimestamp(getContext(), newFile.lastModified()));
    binding.newThumbnail.setTag(newFile.hashCode());
    LocalFileListAdapter.setThumbnail(newFile, binding.newThumbnail, getContext());
    // set info for existing file
    binding.existingSize.setText(DisplayUtils.bytesToHumanReadable(existingFile.getFileLength()));
    binding.existingTimestamp.setText(DisplayUtils.getRelativeTimestamp(getContext(), existingFile.getModificationTimestamp()));
    binding.existingThumbnail.setTag(existingFile.getFileId());
    OCFileListAdapter.setThumbnail(existingFile, binding.existingThumbnail, user, new FileDataStorageManager(user, requireContext().getContentResolver()), asyncTasks, false, getContext());
    View.OnClickListener checkBoxClickListener = v -> {
        positiveButton.setEnabled(binding.newCheckbox.isChecked() || binding.existingCheckbox.isChecked());
    };
    binding.newCheckbox.setOnClickListener(checkBoxClickListener);
    binding.existingCheckbox.setOnClickListener(checkBoxClickListener);
    binding.newFileContainer.setOnClickListener(v -> {
        binding.newCheckbox.setChecked(!binding.newCheckbox.isChecked());
        positiveButton.setEnabled(binding.newCheckbox.isChecked() || binding.existingCheckbox.isChecked());
    });
    binding.existingFileContainer.setOnClickListener(v -> {
        binding.existingCheckbox.setChecked(!binding.existingCheckbox.isChecked());
        positiveButton.setEnabled(binding.newCheckbox.isChecked() || binding.existingCheckbox.isChecked());
    });
    return builder.create();
}
Also used : AlertDialog(androidx.appcompat.app.AlertDialog) Context(android.content.Context) User(com.nextcloud.client.account.User) ThumbnailsCacheManager(com.owncloud.android.datamodel.ThumbnailsCacheManager) Bundle(android.os.Bundle) AlertDialog(androidx.appcompat.app.AlertDialog) NonNull(androidx.annotation.NonNull) OCFile(com.owncloud.android.datamodel.OCFile) Dialog(android.app.Dialog) AppCompatActivity(androidx.appcompat.app.AppCompatActivity) ThemeCheckableUtils(com.owncloud.android.utils.theme.ThemeCheckableUtils) ArrayList(java.util.ArrayList) LocalFileListAdapter(com.owncloud.android.ui.adapter.LocalFileListAdapter) ConflictResolveDialogBinding(com.owncloud.android.databinding.ConflictResolveDialogBinding) Toast(android.widget.Toast) OCFileListAdapter(com.owncloud.android.ui.adapter.OCFileListAdapter) Fragment(androidx.fragment.app.Fragment) View(android.view.View) Button(android.widget.Button) DisplayUtils(com.owncloud.android.utils.DisplayUtils) DialogInterface(android.content.DialogInterface) FragmentTransaction(androidx.fragment.app.FragmentTransaction) File(java.io.File) Log_OC(com.owncloud.android.lib.common.utils.Log_OC) List(java.util.List) ThemeColorUtils(com.owncloud.android.utils.theme.ThemeColorUtils) Nullable(androidx.annotation.Nullable) FileDataStorageManager(com.owncloud.android.datamodel.FileDataStorageManager) R(com.owncloud.android.R) ThemeButtonUtils(com.owncloud.android.utils.theme.ThemeButtonUtils) DialogFragment(androidx.fragment.app.DialogFragment) FileDataStorageManager(com.owncloud.android.datamodel.FileDataStorageManager) OCFile(com.owncloud.android.datamodel.OCFile) File(java.io.File) View(android.view.View) NonNull(androidx.annotation.NonNull)

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