summaryrefslogtreecommitdiff
path: root/Settings/src/com/android/tv/settings/accounts/AccountsFragment.java
blob: e3c0c11eb1ad21010cfd98880217ff40f3e69402 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
/*
 * Copyright (C) 2018 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.android.tv.settings.accounts;

import static com.android.tv.settings.util.InstrumentationUtils.logEntrySelected;

import android.accounts.Account;
import android.accounts.AccountManager;
import android.accounts.AuthenticatorDescription;
import android.app.tvsettings.TvSettingsEnums;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.res.Resources;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.UserHandle;
import android.os.UserManager;
import android.provider.Settings;
import android.text.TextUtils;
import android.util.ArraySet;
import android.util.Log;

import androidx.annotation.Keep;
import androidx.preference.Preference;
import androidx.preference.PreferenceScreen;

import com.android.settingslib.accounts.AuthenticatorHelper;
import com.android.settingslib.widget.FooterPreference;
import com.android.tv.settings.R;
import com.android.tv.settings.SettingsPreferenceFragment;
import com.android.tv.settings.overlay.FlavorUtils;
import com.android.tv.settings.system.SecurityFragment;

import java.util.ArrayList;
import java.util.Set;

/**
 * The "Accounts and Sign in" screen in TV settings.
 */
@Keep
public class AccountsFragment extends SettingsPreferenceFragment {
    private static final String TAG = "AccountsFragment";
    private static final String KEY_ADD_ACCOUNT = "add_account";
    private static final String KEY_DEVICE_OWNER_FOOTER = "do_org_footer";
    private static final int ORDER_ADD_ACCOUNT = Integer.MAX_VALUE - 2;
    private static final int ORDER_FOOTER = Integer.MAX_VALUE - 1;
    private AuthenticatorHelper mAuthenticatorHelper;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        mAuthenticatorHelper = new AuthenticatorHelper(getContext(),
                new UserHandle(UserHandle.myUserId()), userHandle -> updateAccounts());
        super.onCreate(savedInstanceState);
    }

    @Override
    public void onCreatePreferences(Bundle savedInstanceState, String rootKey) {
        setPreferencesFromResource(R.xml.accounts, null);
        refreshAllPreferences();
    }

    private void refreshAllPreferences() {
        final PreferenceScreen prefScreen = getPreferenceScreen();
        for (int i = 0; i < prefScreen.getPreferenceCount();) {
            final Preference preference = prefScreen.getPreference(i);
            final String key = preference.getKey();
            if (TextUtils.equals(KEY_ADD_ACCOUNT, key)
                    || TextUtils.equals(KEY_DEVICE_OWNER_FOOTER, key)) {
                i++;
            } else {
                prefScreen.removePreference(preference);
            }
        }
    }

    @Override
    public void onStart() {
        super.onStart();
        mAuthenticatorHelper.listenToAccountUpdates();
    }

    @Override
    public void onStop() {
        super.onStop();
        mAuthenticatorHelper.stopListeningToAccountUpdates();
    }

    @Override
    public void onResume() {
        super.onResume();
        updateAccounts();
    }

    private void updateAccounts() {
        PreferenceScreen prefScreen = getPreferenceScreen();
        final Set<String> touchedAccounts = new ArraySet<>(prefScreen.getPreferenceCount());

        final AccountManager am = AccountManager.get(getContext());
        final AuthenticatorDescription[] authTypes = am.getAuthenticatorTypes();
        final ArrayList<String> allowableAccountTypes = new ArrayList<>(authTypes.length);
        final Context themedContext = getPreferenceManager().getContext();

        for (AuthenticatorDescription authDesc : authTypes) {
            Context targetContext = getTargetContext(getContext(), authDesc);
            if (targetContext == null) {
                continue;
            }

            String authTitle = getAuthTitle(targetContext, authDesc);


            Account[] accounts = am.getAccountsByType(authDesc.type);
            if (accounts == null || accounts.length == 0) {
                continue;  // No point in continuing; there aren't any accounts to show.
            }

            Drawable authImage = getAuthImage(targetContext, authDesc);

            // Display an entry for each installed account we have.
            for (final Account account : accounts) {
                final String key = "account_pref:" + account.type + ":" + account.name;
                Preference preference = findPreference(key);
                if (preference == null) {
                    preference = new Preference(themedContext);
                }
                preference.setTitle(authTitle != null ? authTitle : account.name);
                preference.setIcon(authImage);
                preference.setSummary(authTitle != null ? account.name : null);
                preference.setFragment(AccountSyncFragment.class.getName());
                AccountSyncFragment.prepareArgs(preference.getExtras(), account);

                touchedAccounts.add(key);
                preference.setKey(key);

                prefScreen.addPreference(preference);
            }
        }

        for (int i = 0; i < prefScreen.getPreferenceCount();) {
            final Preference preference = prefScreen.getPreference(i);
            final String key = preference.getKey();
            if (touchedAccounts.contains(key) || TextUtils.equals(KEY_ADD_ACCOUNT, key)
                    || TextUtils.equals(KEY_DEVICE_OWNER_FOOTER, key)) {
                i++;
            } else {
                prefScreen.removePreference(preference);
            }
        }

        // Never allow restricted profile to add accounts.
        final Preference addAccountPref = findPreference(KEY_ADD_ACCOUNT);
        if (addAccountPref != null) {
            addAccountPref.setOrder(ORDER_ADD_ACCOUNT);
            if (!AccountsUtil.isAdminRestricted(getContext())) {
                if (isRestricted()) {
                    addAccountPref.setVisible(false);
                } else {
                    setUpAddAccountPrefIntent(addAccountPref, getContext());
                }
            }
        }

        // Show device managed footer information if DO active
        final FooterPreference footerPref = findPreference(KEY_DEVICE_OWNER_FOOTER);
        if (footerPref != null) {
            final CharSequence deviceOwnerDisclosure = FlavorUtils.getFeatureFactory(
                    getContext()).getEnterprisePrivacyFeatureProvider(
                    getContext()).getDeviceOwnerDisclosure();
            footerPref.setTitle(deviceOwnerDisclosure);
            footerPref.setOrder(ORDER_FOOTER);
            final Context context = getContext();
            footerPref.setLearnMoreAction(view ->
                context.startActivity(new Intent(Settings.ACTION_ENTERPRISE_PRIVACY_SETTINGS))
            );
            final String learnMoreText = context.getString(R.string.learn_more);
            footerPref.setLearnMoreText(learnMoreText);
            footerPref.setVisible(deviceOwnerDisclosure != null);
        }
    }

    private boolean isRestricted() {
        return SecurityFragment.isRestrictedProfileInEffect(getContext()) || UserManager.get(
                getContext()).hasUserRestriction(UserManager.DISALLOW_MODIFY_ACCOUNTS);
    }

    /**
     * Set up the intent and visibility for the given preference based on the information from
     * AccountManager.
     */
    public static void setUpAddAccountPrefIntent(Preference preference, Context context) {
        final AccountManager am = AccountManager.get(context);
        final AuthenticatorDescription[] authTypes = am.getAuthenticatorTypes();
        final ArrayList<String> allowableAccountTypes = new ArrayList<>(authTypes.length);
        for (AuthenticatorDescription authDesc : authTypes) {
            final Context targetContext = getTargetContext(context, authDesc);
            if (targetContext == null) {
                continue;
            }
            String authTitle = getAuthTitle(targetContext, authDesc);
            if (authTitle != null || authDesc.iconId != 0) {
                allowableAccountTypes.add(authDesc.type);
            }
        }

        Intent i = new Intent().setComponent(new ComponentName("com.android.tv.settings",
                "com.android.tv.settings.accounts.AddAccountWithTypeActivity"));
        i.putExtra(AddAccountWithTypeActivity.EXTRA_ALLOWABLE_ACCOUNT_TYPES_STRING_ARRAY,
                allowableAccountTypes.toArray(new String[allowableAccountTypes.size()]));

                // If there are available account types, show the "add account" button.
        preference.setVisible(!allowableAccountTypes.isEmpty());
        preference.setIntent(i);
        preference.setOnPreferenceClickListener(
                preference1 -> {
                    logEntrySelected(TvSettingsEnums.ACCOUNT_CLASSIC_ADD_ACCOUNT);
                    return false;
                });
    }

    private static Context getTargetContext(Context context, AuthenticatorDescription authDesc) {
        Context targetContext = null;
        try {
            targetContext = context.createPackageContext(authDesc.packageName, 0);
        } catch (PackageManager.NameNotFoundException e) {
            Log.e(TAG, "Authenticator description with bad package name", e);
        } catch (SecurityException e) {
            Log.e(TAG, "Security exception loading package resources", e);
        }
        return targetContext;
    }

    private static String getAuthTitle(Context targetContext, AuthenticatorDescription authDesc) {
        // Main title text comes from the authenticator description (e.g. "Google").
        String authTitle = null;
        try {
            authTitle = targetContext.getString(authDesc.labelId);
            if (TextUtils.isEmpty(authTitle)) {
                authTitle = null;  // Handled later when we add the row.
            }
        } catch (Resources.NotFoundException e) {
            Log.e(TAG, "Authenticator description with bad label id", e);
        }
        return authTitle;
    }

    private static Drawable getAuthImage(Context targetContext, AuthenticatorDescription authDesc) {
        // Icon URI to be displayed for each account is based on the type of authenticator.
        Drawable authImage = null;
        try {
            authImage = targetContext.getDrawable(authDesc.iconId);
        } catch (Resources.NotFoundException e) {
            Log.e(TAG, "Authenticator has bad resources", e);
        }
        return authImage;
    }

}