Search in sources :

Example 11 with OwnCloudClient

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

the class FileActivity method requestCredentialsUpdate.

/**
 * Invalidates the credentials stored for the given OC account and requests new credentials to the user,
 * navigating to {@link AuthenticatorActivity}
 *
 * @param context   Android Context needed to access the {@link AccountManager}. Received as a parameter
 *                  to make the method accessible to {@link android.content.BroadcastReceiver}s.
 * @param account   Stored OC account to request credentials update for. If null, current account will
 *                  be used.
 */
protected void requestCredentialsUpdate(Context context, Account account) {
    try {
        // / step 1 - invalidate credentials of current account
        if (account == null) {
            account = getAccount();
        }
        OwnCloudClient client;
        OwnCloudAccount ocAccount = new OwnCloudAccount(account, context);
        client = (OwnCloudClientManagerFactory.getDefaultSingleton().removeClientFor(ocAccount));
        if (client != null) {
            OwnCloudCredentials cred = client.getCredentials();
            if (cred != null) {
                AccountManager am = AccountManager.get(context);
                if (cred.authTokenExpires()) {
                    am.invalidateAuthToken(account.type, cred.getAuthToken());
                } else {
                    am.clearPassword(account);
                }
            }
        }
        // / step 2 - request credentials to user
        Intent updateAccountCredentials = new Intent(this, AuthenticatorActivity.class);
        updateAccountCredentials.putExtra(AuthenticatorActivity.EXTRA_ACCOUNT, account);
        updateAccountCredentials.putExtra(AuthenticatorActivity.EXTRA_ACTION, AuthenticatorActivity.ACTION_UPDATE_EXPIRED_TOKEN);
        updateAccountCredentials.addFlags(Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
        startActivityForResult(updateAccountCredentials, REQUEST_CODE__UPDATE_CREDENTIALS);
    } catch (com.owncloud.android.lib.common.accounts.AccountUtils.AccountNotFoundException e) {
        DisplayUtils.showSnackMessage(this, R.string.auth_account_does_not_exist);
    }
}
Also used : AccountManager(android.accounts.AccountManager) Intent(android.content.Intent) OwnCloudClient(com.owncloud.android.lib.common.OwnCloudClient) OwnCloudAccount(com.owncloud.android.lib.common.OwnCloudAccount) OwnCloudCredentials(com.owncloud.android.lib.common.OwnCloudCredentials)

Example 12 with OwnCloudClient

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

the class ConnectivityUtils method isInternetWalled.

public static boolean isInternetWalled(Context context) {
    if (isOnlineWithWifi(context)) {
        try {
            Account account = AccountUtils.getCurrentOwnCloudAccount(context);
            if (account != null) {
                OwnCloudAccount ocAccount = new OwnCloudAccount(account, context);
                OwnCloudVersion serverVersion = AccountUtils.getServerVersion(account);
                String url;
                if (serverVersion.compareTo(OwnCloudVersion.nextcloud_13) > 0) {
                    url = ocAccount.getBaseUri() + "/index.php/204";
                } else {
                    url = ocAccount.getBaseUri() + "/status.php";
                }
                GetMethod get = new GetMethod(url);
                OwnCloudClient client = OwnCloudClientFactory.createOwnCloudClient(account, context);
                int status = client.executeMethod(get);
                if (serverVersion.compareTo(OwnCloudVersion.nextcloud_13) > 0) {
                    return !(status == 204 && (get.getResponseContentLength() == -1 || get.getResponseContentLength() == 0));
                } else {
                    if (status == 200) {
                        try {
                            // try parsing json to verify response
                            // check if json contains maintenance and it should be false
                            String json = get.getResponseBodyAsString();
                            return new JSONObject(json).getBoolean("maintenance");
                        } catch (Exception e) {
                            return true;
                        }
                    } else {
                        return true;
                    }
                }
            }
        } catch (IOException e) {
            Log_OC.e(TAG, "Error checking internet connection", e);
        } catch (com.owncloud.android.lib.common.accounts.AccountUtils.AccountNotFoundException e) {
            Log_OC.e(TAG, "Account not found", e);
        } catch (OperationCanceledException e) {
            Log_OC.e(TAG, e.getMessage());
        } catch (AuthenticatorException e) {
            Log_OC.e(TAG, e.getMessage());
        }
    } else if (!Device.getNetworkType(context).equals(JobRequest.NetworkType.ANY)) {
        return false;
    }
    return true;
}
Also used : Account(android.accounts.Account) OwnCloudAccount(com.owncloud.android.lib.common.OwnCloudAccount) OperationCanceledException(android.accounts.OperationCanceledException) AccountUtils(com.owncloud.android.authentication.AccountUtils) AuthenticatorException(android.accounts.AuthenticatorException) OwnCloudAccount(com.owncloud.android.lib.common.OwnCloudAccount) IOException(java.io.IOException) OperationCanceledException(android.accounts.OperationCanceledException) IOException(java.io.IOException) AuthenticatorException(android.accounts.AuthenticatorException) JSONObject(org.json.JSONObject) GetMethod(org.apache.commons.httpclient.methods.GetMethod) OwnCloudClient(com.owncloud.android.lib.common.OwnCloudClient) OwnCloudVersion(com.owncloud.android.lib.resources.status.OwnCloudVersion)

Example 13 with OwnCloudClient

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

the class HttpStreamFetcher method loadData.

@Override
public InputStream loadData(Priority priority) throws Exception {
    Account mAccount = AccountUtils.getCurrentOwnCloudAccount(MainApp.getAppContext());
    OwnCloudAccount ocAccount = new OwnCloudAccount(mAccount, MainApp.getAppContext());
    OwnCloudClient mClient = OwnCloudClientManagerFactory.getDefaultSingleton().getClientFor(ocAccount, MainApp.getAppContext());
    if (mClient != null) {
        if (AccountUtils.getServerVersion(mAccount).supportsRemoteThumbnails()) {
            GetMethod get = null;
            try {
                get = new GetMethod(mURL);
                get.setRequestHeader("Cookie", "nc_sameSiteCookielax=true;nc_sameSiteCookiestrict=true");
                get.setRequestHeader(RemoteOperation.OCS_API_HEADER, RemoteOperation.OCS_API_HEADER_VALUE);
                int status = mClient.executeMethod(get);
                if (status == HttpStatus.SC_OK) {
                    return get.getResponseBodyAsStream();
                } else {
                    mClient.exhaustResponse(get.getResponseBodyAsStream());
                }
            } catch (Exception e) {
                Log_OC.d(TAG, e.getMessage(), e);
            }
        } else {
            Log_OC.d(TAG, "Server too old");
        }
    }
    return null;
}
Also used : Account(android.accounts.Account) OwnCloudAccount(com.owncloud.android.lib.common.OwnCloudAccount) GetMethod(org.apache.commons.httpclient.methods.GetMethod) OwnCloudAccount(com.owncloud.android.lib.common.OwnCloudAccount) OwnCloudClient(com.owncloud.android.lib.common.OwnCloudClient)

Example 14 with OwnCloudClient

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

the class PushUtils method pushRegistrationToServer.

public static void pushRegistrationToServer() {
    String token = PreferenceManager.getPushToken(MainApp.getAppContext());
    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 = null;
            Gson gson = new Gson();
            for (Account account : AccountUtils.getAccounts(context)) {
                providerValue = arbitraryDataProvider.getValue(account, 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 mClient = OwnCloudClientManagerFactory.getDefaultSingleton().getClientFor(ocAccount, context);
                        RemoteOperation registerAccountDeviceForNotificationsOperation = new RegisterAccountDeviceForNotificationsOperation(pushTokenHash, publicKey, context.getResources().getString(R.string.push_server_url));
                        RemoteOperationResult remoteOperationResult = registerAccountDeviceForNotificationsOperation.execute(mClient);
                        if (remoteOperationResult.isSuccess()) {
                            PushResponse pushResponse = remoteOperationResult.getPushResponseData();
                            RemoteOperation registerAccountDeviceForProxyOperation = new RegisterAccountDeviceForProxyOperation(context.getResources().getString(R.string.push_server_url), token, pushResponse.getDeviceIdentifier(), pushResponse.getSignature(), pushResponse.getPublicKey());
                            remoteOperationResult = registerAccountDeviceForProxyOperation.execute(mClient);
                            if (remoteOperationResult.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, AccountUtils.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) RemoteOperation(com.owncloud.android.lib.common.operations.RemoteOperation) PublicKey(java.security.PublicKey) RemoteOperationResult(com.owncloud.android.lib.common.operations.RemoteOperationResult) OperationCanceledException(android.accounts.OperationCanceledException) RegisterAccountDeviceForNotificationsOperation(com.owncloud.android.lib.resources.notifications.RegisterAccountDeviceForNotificationsOperation) AccountUtils(com.owncloud.android.authentication.AccountUtils) 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 15 with OwnCloudClient

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

the class OwnCloudClientManagerTest method testUserId.

/**
 * Like on files app we create & store an account in Android's account manager.
 */
@Test
public void testUserId() throws OperationCanceledException, AuthenticatorException, IOException, AccountUtils.AccountNotFoundException {
    Bundle arguments = InstrumentationRegistry.getArguments();
    Uri url = Uri.parse(arguments.getString("TEST_SERVER_URL"));
    String loginName = arguments.getString("TEST_SERVER_USERNAME");
    String password = arguments.getString("TEST_SERVER_PASSWORD");
    AccountManager accountManager = AccountManager.get(targetContext);
    String accountName = AccountUtils.buildAccountName(url, loginName);
    Account newAccount = new Account(accountName, "nextcloud");
    accountManager.addAccountExplicitly(newAccount, password, null);
    accountManager.setUserData(newAccount, AccountUtils.Constants.KEY_OC_BASE_URL, url.toString());
    accountManager.setUserData(newAccount, AccountUtils.Constants.KEY_USER_ID, loginName);
    OwnCloudClientManager manager = new OwnCloudClientManager();
    OwnCloudAccount account = new OwnCloudAccount(newAccount, targetContext);
    OwnCloudClient client = manager.getClientFor(account, targetContext);
    assertEquals(loginName, client.getUserId());
    accountManager.removeAccountExplicitly(newAccount);
    assertEquals(1, accountManager.getAccounts().length);
}
Also used : Account(android.accounts.Account) OwnCloudAccount(com.owncloud.android.lib.common.OwnCloudAccount) Bundle(android.os.Bundle) OwnCloudClientManager(com.owncloud.android.lib.common.OwnCloudClientManager) AccountManager(android.accounts.AccountManager) OwnCloudAccount(com.owncloud.android.lib.common.OwnCloudAccount) OwnCloudClient(com.owncloud.android.lib.common.OwnCloudClient) Uri(android.net.Uri) Test(org.junit.Test)

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