Search in sources :

Example 16 with OwnCloudClient

use of com.owncloud.android.lib.common.OwnCloudClient in project android by nextcloud.

the class PushUtils method pushRegistrationToServer.

public static void pushRegistrationToServer(final UserAccountManager accountManager, final String token) {
    arbitraryDataProvider = new ArbitraryDataProvider(MainApp.getAppContext().getContentResolver());
    if (!TextUtils.isEmpty(MainApp.getAppContext().getResources().getString(R.string.push_server_url)) && !TextUtils.isEmpty(token)) {
        PushUtils.generateRsa2048KeyPair();
        String pushTokenHash = PushUtils.generateSHA512Hash(token).toLowerCase(Locale.ROOT);
        PublicKey devicePublicKey = (PublicKey) PushUtils.readKeyFromFile(true);
        if (devicePublicKey != null) {
            byte[] publicKeyBytes = Base64.encode(devicePublicKey.getEncoded(), Base64.NO_WRAP);
            String publicKey = new String(publicKeyBytes);
            publicKey = publicKey.replaceAll("(.{64})", "$1\n");
            publicKey = "-----BEGIN PUBLIC KEY-----\n" + publicKey + "\n-----END PUBLIC KEY-----\n";
            Context context = MainApp.getAppContext();
            String providerValue;
            PushConfigurationState accountPushData;
            Gson gson = new Gson();
            for (Account account : accountManager.getAccounts()) {
                providerValue = arbitraryDataProvider.getValue(account.name, KEY_PUSH);
                if (!TextUtils.isEmpty(providerValue)) {
                    accountPushData = gson.fromJson(providerValue, PushConfigurationState.class);
                } else {
                    accountPushData = null;
                }
                if (accountPushData != null && !accountPushData.getPushToken().equals(token) && !accountPushData.isShouldBeDeleted() || TextUtils.isEmpty(providerValue)) {
                    try {
                        OwnCloudAccount ocAccount = new OwnCloudAccount(account, context);
                        OwnCloudClient client = OwnCloudClientManagerFactory.getDefaultSingleton().getClientFor(ocAccount, context);
                        RemoteOperationResult remoteOperationResult = new RegisterAccountDeviceForNotificationsOperation(pushTokenHash, publicKey, context.getResources().getString(R.string.push_server_url)).execute(client);
                        if (remoteOperationResult.isSuccess()) {
                            PushResponse pushResponse = remoteOperationResult.getPushResponseData();
                            RemoteOperationResult resultProxy = new RegisterAccountDeviceForProxyOperation(context.getResources().getString(R.string.push_server_url), token, pushResponse.getDeviceIdentifier(), pushResponse.getSignature(), pushResponse.getPublicKey(), MainApp.getUserAgent()).run();
                            if (resultProxy.isSuccess()) {
                                PushConfigurationState pushArbitraryData = new PushConfigurationState(token, pushResponse.getDeviceIdentifier(), pushResponse.getSignature(), pushResponse.getPublicKey(), false);
                                arbitraryDataProvider.storeOrUpdateKeyValue(account.name, KEY_PUSH, gson.toJson(pushArbitraryData));
                            }
                        } else if (remoteOperationResult.getCode() == RemoteOperationResult.ResultCode.ACCOUNT_USES_STANDARD_PASSWORD) {
                            arbitraryDataProvider.storeOrUpdateKeyValue(account.name, UserAccountManager.ACCOUNT_USES_STANDARD_PASSWORD, "true");
                        }
                    } catch (com.owncloud.android.lib.common.accounts.AccountUtils.AccountNotFoundException e) {
                        Log_OC.d(TAG, "Failed to find an account");
                    } catch (AuthenticatorException e) {
                        Log_OC.d(TAG, "Failed via AuthenticatorException");
                    } catch (IOException e) {
                        Log_OC.d(TAG, "Failed via IOException");
                    } catch (OperationCanceledException e) {
                        Log_OC.d(TAG, "Failed via OperationCanceledException");
                    }
                } else if (accountPushData != null && accountPushData.isShouldBeDeleted()) {
                    deleteRegistrationForAccount(account);
                }
            }
        }
    }
}
Also used : Context(android.content.Context) Account(android.accounts.Account) OwnCloudAccount(com.owncloud.android.lib.common.OwnCloudAccount) PublicKey(java.security.PublicKey) RemoteOperationResult(com.owncloud.android.lib.common.operations.RemoteOperationResult) OperationCanceledException(android.accounts.OperationCanceledException) RegisterAccountDeviceForNotificationsOperation(com.owncloud.android.lib.resources.notifications.RegisterAccountDeviceForNotificationsOperation) ArbitraryDataProvider(com.owncloud.android.datamodel.ArbitraryDataProvider) Gson(com.google.gson.Gson) AuthenticatorException(android.accounts.AuthenticatorException) OwnCloudAccount(com.owncloud.android.lib.common.OwnCloudAccount) IOException(java.io.IOException) RegisterAccountDeviceForProxyOperation(com.owncloud.android.lib.resources.notifications.RegisterAccountDeviceForProxyOperation) PushConfigurationState(com.owncloud.android.datamodel.PushConfigurationState) OwnCloudClient(com.owncloud.android.lib.common.OwnCloudClient) PushResponse(com.owncloud.android.lib.resources.notifications.models.PushResponse)

Example 17 with OwnCloudClient

use of com.owncloud.android.lib.common.OwnCloudClient in project android by nextcloud.

the class InputStreamBinder method processRequest.

private HttpMethodBase processRequest(final NextcloudRequest request, final InputStream requestBodyInputStream) throws UnsupportedOperationException, com.owncloud.android.lib.common.accounts.AccountUtils.AccountNotFoundException, OperationCanceledException, AuthenticatorException, IOException {
    Account account = accountManager.getAccountByName(request.getAccountName());
    if (account == null) {
        throw new IllegalStateException(EXCEPTION_ACCOUNT_NOT_FOUND);
    }
    // Validate token
    if (!isValid(request)) {
        throw new IllegalStateException(EXCEPTION_INVALID_TOKEN);
    }
    // Validate URL
    if (request.getUrl().length() == 0 || request.getUrl().charAt(0) != PATH_SEPARATOR) {
        throw new IllegalStateException(EXCEPTION_INVALID_REQUEST_URL, new IllegalStateException("URL need to start with a /"));
    }
    OwnCloudClientManager ownCloudClientManager = OwnCloudClientManagerFactory.getDefaultSingleton();
    OwnCloudAccount ocAccount = new OwnCloudAccount(account, context);
    OwnCloudClient client = ownCloudClientManager.getClientFor(ocAccount, context);
    HttpMethodBase method = buildMethod(request, client.getBaseUri(), requestBodyInputStream);
    if (request.getParameterV2() != null && !request.getParameterV2().isEmpty()) {
        method.setQueryString(convertListToNVP(request.getParameterV2()));
    } else {
        method.setQueryString(convertMapToNVP(request.getParameter()));
    }
    method.addRequestHeader("OCS-APIREQUEST", "true");
    for (Map.Entry<String, List<String>> header : request.getHeader().entrySet()) {
        // https://stackoverflow.com/a/3097052
        method.addRequestHeader(header.getKey(), TextUtils.join(",", header.getValue()));
        if ("OCS-APIREQUEST".equalsIgnoreCase(header.getKey())) {
            throw new IllegalStateException("The 'OCS-APIREQUEST' header will be automatically added by the Nextcloud SSO Library. " + "Please remove the header before making a request");
        }
    }
    client.setFollowRedirects(request.isFollowRedirects());
    int status = client.executeMethod(method);
    // Check if status code is 2xx --> https://en.wikipedia.org/wiki/List_of_HTTP_status_codes#2xx_Success
    if (status >= HTTP_STATUS_CODE_OK && status < HTTP_STATUS_CODE_MULTIPLE_CHOICES) {
        return method;
    } else {
        InputStream inputStream = method.getResponseBodyAsStream();
        String total = "No response body";
        // If response body is available
        if (inputStream != null) {
            total = inputStreamToString(inputStream);
            Log_OC.e(TAG, total);
        }
        method.releaseConnection();
        throw new IllegalStateException(EXCEPTION_HTTP_REQUEST_FAILED, new IllegalStateException(String.valueOf(status), new IllegalStateException(total)));
    }
}
Also used : Account(android.accounts.Account) OwnCloudAccount(com.owncloud.android.lib.common.OwnCloudAccount) HttpMethodBase(org.apache.commons.httpclient.HttpMethodBase) ObjectInputStream(java.io.ObjectInputStream) ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) OwnCloudClientManager(com.owncloud.android.lib.common.OwnCloudClientManager) List(java.util.List) OwnCloudAccount(com.owncloud.android.lib.common.OwnCloudAccount) OwnCloudClient(com.owncloud.android.lib.common.OwnCloudClient) Map(java.util.Map)

Example 18 with OwnCloudClient

use of com.owncloud.android.lib.common.OwnCloudClient in project android by nextcloud.

the class ThumbnailsCacheManager method generateThumbnailFromOCFile.

public static void generateThumbnailFromOCFile(OCFile file, User user, Context context) {
    int pxW;
    int pxH;
    pxW = pxH = getThumbnailDimension();
    String imageKey = PREFIX_THUMBNAIL + file.getRemoteId();
    GetMethod getMethod = null;
    try {
        Bitmap thumbnail = null;
        OwnCloudClient client = mClient;
        if (client == null) {
            OwnCloudAccount ocAccount = user.toOwnCloudAccount();
            client = OwnCloudClientManagerFactory.getDefaultSingleton().getClientFor(ocAccount, context);
        }
        String uri = client.getBaseUri() + "/index.php/apps/files/api/v1/thumbnail/" + pxW + "/" + pxH + Uri.encode(file.getRemotePath(), "/");
        Log_OC.d(TAG, "generate thumbnail: " + file.getFileName() + " URI: " + uri);
        getMethod = new GetMethod(uri);
        getMethod.setRequestHeader("Cookie", "nc_sameSiteCookielax=true;nc_sameSiteCookiestrict=true");
        getMethod.setRequestHeader(RemoteOperation.OCS_API_HEADER, RemoteOperation.OCS_API_HEADER_VALUE);
        int status = client.executeMethod(getMethod);
        if (status == HttpStatus.SC_OK) {
            InputStream inputStream = getMethod.getResponseBodyAsStream();
            Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
            thumbnail = ThumbnailUtils.extractThumbnail(bitmap, pxW, pxH);
        } else {
            client.exhaustResponse(getMethod.getResponseBodyAsStream());
        }
        // Add thumbnail to cache
        if (thumbnail != null) {
            // Handle PNG
            if (PNG_MIMETYPE.equalsIgnoreCase(file.getMimeType())) {
                thumbnail = handlePNG(thumbnail, pxW, pxH);
            }
            Log_OC.d(TAG, "add thumbnail to cache: " + file.getFileName());
            addBitmapToCache(imageKey, thumbnail);
        }
    } catch (Exception e) {
        Log_OC.d(TAG, e.getMessage(), e);
    } finally {
        if (getMethod != null) {
            getMethod.releaseConnection();
        }
    }
}
Also used : Bitmap(android.graphics.Bitmap) InputStream(java.io.InputStream) GetMethod(org.apache.commons.httpclient.methods.GetMethod) OwnCloudClient(com.owncloud.android.lib.common.OwnCloudClient) OwnCloudAccount(com.owncloud.android.lib.common.OwnCloudAccount) Paint(android.graphics.Paint) Point(android.graphics.Point) FileNotFoundException(java.io.FileNotFoundException)

Example 19 with OwnCloudClient

use of com.owncloud.android.lib.common.OwnCloudClient in project android by nextcloud.

the class SyncFolderHandler method doOperation.

/**
 * Performs the next operation in the queue
 */
private void doOperation(Account account, String remotePath) {
    mCurrentSyncOperation = mPendingOperations.get(account.name, remotePath);
    if (mCurrentSyncOperation != null) {
        RemoteOperationResult result;
        try {
            if (mCurrentAccount == null || !mCurrentAccount.equals(account)) {
                mCurrentAccount = account;
            }
            // always get client from client manager, to get fresh credentials in case of update
            OwnCloudAccount ocAccount = new OwnCloudAccount(account, mService);
            OwnCloudClient mOwnCloudClient = OwnCloudClientManagerFactory.getDefaultSingleton().getClientFor(ocAccount, mService);
            result = mCurrentSyncOperation.execute(mOwnCloudClient);
            sendBroadcastFinishedSyncFolder(account, remotePath, result.isSuccess());
            mService.dispatchResultToOperationListeners(mCurrentSyncOperation, result);
        } catch (AccountsException | IOException e) {
            sendBroadcastFinishedSyncFolder(account, remotePath, false);
            mService.dispatchResultToOperationListeners(mCurrentSyncOperation, new RemoteOperationResult(e));
            Log_OC.e(TAG, "Error while trying to get authorization", e);
        } finally {
            mPendingOperations.removePayload(account.name, remotePath);
        }
    }
}
Also used : RemoteOperationResult(com.owncloud.android.lib.common.operations.RemoteOperationResult) OwnCloudAccount(com.owncloud.android.lib.common.OwnCloudAccount) OwnCloudClient(com.owncloud.android.lib.common.OwnCloudClient) IOException(java.io.IOException) AccountsException(android.accounts.AccountsException)

Example 20 with OwnCloudClient

use of com.owncloud.android.lib.common.OwnCloudClient in project android by nextcloud.

the class DocumentsStorageProvider method createFile.

private String createFile(Document targetFolder, String displayName, String mimeType) throws FileNotFoundException {
    User user = targetFolder.getUser();
    // create dummy file
    File tempDir = new File(FileStorageUtils.getTemporalPath(user.getAccountName()));
    if (!tempDir.exists() && !tempDir.mkdirs()) {
        throw new FileNotFoundException("Temp folder could not be created: " + tempDir.getAbsolutePath());
    }
    File emptyFile = new File(tempDir, displayName);
    if (emptyFile.exists() && !emptyFile.delete()) {
        throw new FileNotFoundException("Previous file could not be deleted");
    }
    try {
        if (!emptyFile.createNewFile()) {
            throw new FileNotFoundException("File could not be created");
        }
    } catch (IOException e) {
        throw getFileNotFoundExceptionWithCause("File could not be created", e);
    }
    String newFilePath = targetFolder.getRemotePath() + displayName;
    // FIXME we need to update the mimeType somewhere else as well
    // perform the upload, no need for chunked operation as we have a empty file
    OwnCloudClient client = targetFolder.getClient();
    RemoteOperationResult result = new UploadFileRemoteOperation(emptyFile.getAbsolutePath(), newFilePath, mimeType, "", String.valueOf(System.currentTimeMillis() / 1000), FileUtil.getCreationTimestamp(emptyFile), false).execute(client);
    if (!result.isSuccess()) {
        Log_OC.e(TAG, result.toString());
        throw new FileNotFoundException("Failed to upload document with path " + newFilePath);
    }
    Context context = getNonNullContext();
    RemoteOperationResult updateParent = new RefreshFolderOperation(targetFolder.getFile(), System.currentTimeMillis(), false, false, true, targetFolder.getStorageManager(), user, context).execute(client);
    if (!updateParent.isSuccess()) {
        Log_OC.e(TAG, updateParent.toString());
        throw new FileNotFoundException("Failed to create document with documentId " + targetFolder.getDocumentId());
    }
    Document newFile = new Document(targetFolder.getStorageManager(), newFilePath);
    context.getContentResolver().notifyChange(toNotifyUri(targetFolder), null, false);
    return newFile.getDocumentId();
}
Also used : Context(android.content.Context) User(com.nextcloud.client.account.User) UploadFileRemoteOperation(com.owncloud.android.lib.resources.files.UploadFileRemoteOperation) RemoteOperationResult(com.owncloud.android.lib.common.operations.RemoteOperationResult) RefreshFolderOperation(com.owncloud.android.operations.RefreshFolderOperation) FileNotFoundException(java.io.FileNotFoundException) IOException(java.io.IOException) OwnCloudClient(com.owncloud.android.lib.common.OwnCloudClient) OCFile(com.owncloud.android.datamodel.OCFile) File(java.io.File)

Aggregations

OwnCloudClient (com.owncloud.android.lib.common.OwnCloudClient)21 OwnCloudAccount (com.owncloud.android.lib.common.OwnCloudAccount)15 RemoteOperationResult (com.owncloud.android.lib.common.operations.RemoteOperationResult)12 Account (android.accounts.Account)9 IOException (java.io.IOException)6 Context (android.content.Context)5 OwnCloudCredentials (com.owncloud.android.lib.common.OwnCloudCredentials)5 AccountManager (android.accounts.AccountManager)4 AuthenticatorException (android.accounts.AuthenticatorException)4 OperationCanceledException (android.accounts.OperationCanceledException)4 User (com.nextcloud.client.account.User)4 ArbitraryDataProvider (com.owncloud.android.datamodel.ArbitraryDataProvider)4 OCFile (com.owncloud.android.datamodel.OCFile)4 Intent (android.content.Intent)3 Uri (android.net.Uri)3 Gson (com.google.gson.Gson)3 ClientFactory (com.nextcloud.client.network.ClientFactory)3 AccountUtils (com.owncloud.android.authentication.AccountUtils)3 FileDataStorageManager (com.owncloud.android.datamodel.FileDataStorageManager)3 PushConfigurationState (com.owncloud.android.datamodel.PushConfigurationState)3