1 /*
2  * Copyright (C) 2020 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 package com.android.documentsui.base;
18 
19 import static androidx.core.util.Preconditions.checkNotNull;
20 
21 import android.content.ContentResolver;
22 import android.content.Context;
23 import android.content.Intent;
24 import android.content.pm.PackageManager;
25 import android.graphics.drawable.Drawable;
26 import android.net.Uri;
27 import android.os.Process;
28 import android.os.UserHandle;
29 import android.os.UserManager;
30 import android.provider.DocumentsContract;
31 
32 import androidx.annotation.VisibleForTesting;
33 import androidx.loader.content.CursorLoader;
34 
35 import java.io.DataInputStream;
36 import java.io.DataOutputStream;
37 import java.io.IOException;
38 import java.net.ProtocolException;
39 import java.util.Objects;
40 /**
41  * Representation of a {@link UserHandle}.
42  */
43 public final class UserId {
44 
45     // A unspecified user is used as when the user's value is uninitialized. e.g. rootInfo.reset()
46     public static final UserId UNSPECIFIED_USER = UserId.of(UserHandle.of(-1000));
47     // A current user represents the user of the app's process. It is mainly used for comparison.
48     public static final UserId CURRENT_USER = UserId.of(Process.myUserHandle());
49     // A default user represents the user of the app's process. It is mainly used for operation
50     // which supports only the current user only.
51     public static final UserId DEFAULT_USER = CURRENT_USER;
52 
53     private static final int VERSION_INIT = 1;
54 
55     private final UserHandle mUserHandle;
56 
UserId(UserHandle userHandle)57     private UserId(UserHandle userHandle) {
58         checkNotNull(userHandle);
59         mUserHandle = userHandle;
60     }
61 
62     /**
63      * Returns a {@link UserId} for a given {@link UserHandle}.
64      */
of(UserHandle userHandle)65     public static UserId of(UserHandle userHandle) {
66         return new UserId(userHandle);
67     }
68 
69     /**
70      * Returns a {@link UserId} for the given user id identifier.
71      *
72      * @see UserHandle#getIdentifier
73      */
of(int userIdentifier)74     public static UserId of(int userIdentifier) {
75         return of(UserHandle.of(userIdentifier));
76     }
77 
78     /**
79      * Returns the given context if the user is the current user or unspecified. Otherwise, returns
80      * an "android" package context as the user.
81      *
82      * @throws IllegalStateException if android package of the other user does not exist
83      */
84     @VisibleForTesting
asContext(Context context)85     Context asContext(Context context) {
86         if (CURRENT_USER.equals(this) || isUnspecified()) {
87             return context;
88         }
89         try {
90             return context.createPackageContextAsUser("android", /* flags= */ 0, mUserHandle);
91         } catch (PackageManager.NameNotFoundException e) {
92             throw new IllegalStateException("android package not found.");
93         }
94 
95     }
96 
97     /**
98      * Return a package manager instance of this user.
99      */
getPackageManager(Context context)100     public PackageManager getPackageManager(Context context) {
101         return asContext(context).getPackageManager();
102     }
103 
104     /**
105      * Return a content resolver instance of this user.
106      */
getContentResolver(Context context)107     public ContentResolver getContentResolver(Context context) {
108         return asContext(context).getContentResolver();
109     }
110 
111     /**
112      * Returns a drawable object associated with a particular resource ID in this user.
113      */
getDrawable(Context context, int resId)114     public Drawable getDrawable(Context context, int resId) {
115         return asContext(context).getDrawable(resId);
116     }
117 
118     /**
119      * If this target user is a managed profile, then this returns a badged copy of the given icon
120      * to be able to distinguish it from the original icon.
121      */
getUserBadgedIcon(Context context, Drawable drawable)122     public Drawable getUserBadgedIcon(Context context, Drawable drawable) {
123         return getPackageManager(context).getUserBadgedIcon(drawable, mUserHandle);
124     }
125 
126     /**
127      * Returns the value of {@link PackageManager#getUserBadgedLabel(CharSequence, UserHandle)} for
128      * the user and given label.
129      */
getUserBadgedLabel(Context context, CharSequence label)130     public CharSequence getUserBadgedLabel(Context context, CharSequence label) {
131         return getPackageManager(context).getUserBadgedLabel(label, mUserHandle);
132     }
133 
134     /**
135      * Returns true if this user refers to the system user; false otherwise.
136      */
isSystem()137     public boolean isSystem() {
138         return mUserHandle.isSystem();
139     }
140 
141     /**
142      * Returns true if the this user is a managed profile.
143      */
isManagedProfile(UserManager userManager)144     public boolean isManagedProfile(UserManager userManager) {
145         return userManager.isManagedProfile(mUserHandle.getIdentifier());
146     }
147 
148     /**
149      * Returns true if the this user is in quiet mode.
150      */
isQuietModeEnabled(Context context)151     public boolean isQuietModeEnabled(Context context) {
152         final UserManager userManager =
153                 (UserManager) context.getSystemService(Context.USER_SERVICE);
154         return userManager.isQuietModeEnabled(mUserHandle);
155     }
156 
157     /**
158      * Disables quiet mode for a managed profile. The caller should check {@code
159      * MODIFY_QUIET_MODE} permission first.
160      *
161      * @return {@code false} if user's credential is needed in order to turn off quiet mode,
162      * {@code true} otherwise
163      */
requestQuietModeDisabled(Context context)164     public boolean requestQuietModeDisabled(Context context) {
165         final UserManager userManager =
166                 (UserManager) context.getSystemService(Context.USER_SERVICE);
167         return userManager.requestQuietModeEnabled(false, mUserHandle);
168     }
169 
170     /**
171      * Returns a document uri representing this user.
172      */
buildDocumentUriAsUser(String authority, String documentId)173     public Uri buildDocumentUriAsUser(String authority, String documentId) {
174         return DocumentsContract.buildDocumentUriAsUser(authority, documentId, mUserHandle);
175     }
176 
177     /**
178      * Returns a tree document uri representing this user.
179      */
buildTreeDocumentUriAsUser(String authority, String documentId)180     public Uri buildTreeDocumentUriAsUser(String authority, String documentId) {
181         String authorityWithUserInfo = buildDocumentUriAsUser(authority, documentId).getAuthority();
182         Uri treeUri = DocumentsContract.buildTreeDocumentUri(authority, documentId);
183 
184         return treeUri.buildUpon()
185                 .encodedAuthority(authorityWithUserInfo)
186                 .build();
187     }
188 
189     /**
190      * Starts activity for this user
191      */
startActivityAsUser(Context context, Intent intent)192     public void startActivityAsUser(Context context, Intent intent) {
193         context.startActivityAsUser(intent, mUserHandle);
194     }
195 
196     /**
197      * Returns an identifier stored in this user id. This can be used to recreate the {@link UserId}
198      * by {@link UserId#of(int)}.
199      */
getIdentifier()200     public int getIdentifier() {
201         return mUserHandle.getIdentifier();
202     }
203 
isUnspecified()204     private boolean isUnspecified() {
205         return UNSPECIFIED_USER.equals(this);
206     }
207 
208     @Override
toString()209     public String toString() {
210         return isUnspecified() ? "UNSPECIFIED" : String.valueOf(mUserHandle.getIdentifier());
211     }
212 
213     @Override
equals(Object o)214     public boolean equals(Object o) {
215         if (o == null) {
216             return false;
217         }
218 
219         if (this == o) {
220             return true;
221         }
222 
223         if (o instanceof UserId) {
224             UserId other = (UserId) o;
225             return Objects.equals(mUserHandle, other.mUserHandle);
226         }
227 
228         return false;
229     }
230 
231     @Override
hashCode()232     public int hashCode() {
233         return Objects.hash(mUserHandle);
234     }
235 
236     /**
237      * Reads a {@link UserId} from an input stream.
238      */
read(DataInputStream in)239     public static UserId read(DataInputStream in) throws IOException {
240         final int version = in.readInt();
241         switch (version) {
242             case VERSION_INIT:
243                 int userId = in.readInt();
244                 return UserId.of(UserHandle.of(userId));
245             default:
246                 throw new ProtocolException("Unknown version " + version);
247         }
248     }
249 
250     /**
251      * Writes a {@link UserId} to an output stream.
252      */
write(DataOutputStream out, UserId userId)253     public static void write(DataOutputStream out, UserId userId) throws IOException {
254         out.writeInt(VERSION_INIT);
255         out.writeInt(userId.mUserHandle.getIdentifier());
256     }
257 
258     /**
259      * Create a cursor loader of the user for the given uri.
260      */
createCursorLoader(Context context, Uri uri, UserId userId)261     public static CursorLoader createCursorLoader(Context context, Uri uri, UserId userId) {
262         return new CursorLoader(userId.asContext(context), uri, null, null, null, null);
263     }
264 }
265