UsersAndGroupsSearchProvider.java 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461
  1. /*
  2. * ownCloud Android client application
  3. *
  4. * @author David A. Velasco
  5. * @author Juan Carlos González Cabrero
  6. * Copyright (C) 2015 ownCloud Inc.
  7. *
  8. * This program is free software: you can redistribute it and/or modify
  9. * it under the terms of the GNU General Public License version 2,
  10. * as published by the Free Software Foundation.
  11. *
  12. * This program is distributed in the hope that it will be useful,
  13. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  15. * GNU General Public License for more details.
  16. *
  17. * You should have received a copy of the GNU General Public License
  18. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  19. */
  20. package com.owncloud.android.providers;
  21. import android.app.SearchManager;
  22. import android.content.ContentProvider;
  23. import android.content.ContentValues;
  24. import android.content.Context;
  25. import android.content.UriMatcher;
  26. import android.database.Cursor;
  27. import android.database.MatrixCursor;
  28. import android.graphics.Bitmap;
  29. import android.net.Uri;
  30. import android.os.Handler;
  31. import android.os.Looper;
  32. import android.os.ParcelFileDescriptor;
  33. import android.provider.BaseColumns;
  34. import android.text.TextUtils;
  35. import android.widget.Toast;
  36. import com.nextcloud.client.account.User;
  37. import com.nextcloud.client.account.UserAccountManager;
  38. import com.owncloud.android.R;
  39. import com.owncloud.android.datamodel.ArbitraryDataProvider;
  40. import com.owncloud.android.datamodel.FileDataStorageManager;
  41. import com.owncloud.android.datamodel.ThumbnailsCacheManager;
  42. import com.owncloud.android.lib.common.operations.RemoteOperationResult;
  43. import com.owncloud.android.lib.common.utils.Log_OC;
  44. import com.owncloud.android.lib.resources.shares.GetShareesRemoteOperation;
  45. import com.owncloud.android.lib.resources.shares.ShareType;
  46. import com.owncloud.android.lib.resources.users.Status;
  47. import com.owncloud.android.lib.resources.users.StatusType;
  48. import com.owncloud.android.ui.TextDrawable;
  49. import com.owncloud.android.utils.BitmapUtils;
  50. import com.owncloud.android.utils.ErrorMessageAdapter;
  51. import org.json.JSONException;
  52. import org.json.JSONObject;
  53. import java.io.ByteArrayOutputStream;
  54. import java.io.File;
  55. import java.io.FileNotFoundException;
  56. import java.io.FileOutputStream;
  57. import java.util.ArrayList;
  58. import java.util.HashMap;
  59. import java.util.Iterator;
  60. import java.util.List;
  61. import java.util.Locale;
  62. import java.util.Map;
  63. import javax.inject.Inject;
  64. import androidx.annotation.NonNull;
  65. import androidx.annotation.Nullable;
  66. import dagger.android.AndroidInjection;
  67. import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
  68. import static com.owncloud.android.lib.resources.shares.GetShareesRemoteOperation.PROPERTY_CLEAR_AT;
  69. import static com.owncloud.android.lib.resources.shares.GetShareesRemoteOperation.PROPERTY_ICON;
  70. import static com.owncloud.android.lib.resources.shares.GetShareesRemoteOperation.PROPERTY_MESSAGE;
  71. import static com.owncloud.android.lib.resources.shares.GetShareesRemoteOperation.PROPERTY_STATUS;
  72. /**
  73. * Content provider for search suggestions, to search for users and groups existing in an ownCloud server.
  74. */
  75. public class UsersAndGroupsSearchProvider extends ContentProvider {
  76. private static final String TAG = UsersAndGroupsSearchProvider.class.getSimpleName();
  77. private static final String[] COLUMNS = {
  78. BaseColumns._ID,
  79. SearchManager.SUGGEST_COLUMN_TEXT_1,
  80. SearchManager.SUGGEST_COLUMN_TEXT_2,
  81. SearchManager.SUGGEST_COLUMN_ICON_1,
  82. SearchManager.SUGGEST_COLUMN_INTENT_DATA
  83. };
  84. private static final int SEARCH = 1;
  85. private static final int RESULTS_PER_PAGE = 50;
  86. private static final int REQUESTED_PAGE = 1;
  87. @SuppressFBWarnings("MS_CANNOT_BE_FINAL")
  88. public static String ACTION_SHARE_WITH;
  89. public static final String CONTENT = "content";
  90. private String DATA_USER;
  91. private String DATA_GROUP;
  92. private String DATA_ROOM;
  93. private String DATA_REMOTE;
  94. private String DATA_EMAIL;
  95. private String DATA_CIRCLE;
  96. private UriMatcher mUriMatcher;
  97. @Inject
  98. protected UserAccountManager accountManager;
  99. private static final Map<String, ShareType> sShareTypes = new HashMap<>();
  100. public static ShareType getShareType(String authority) {
  101. return sShareTypes.get(authority);
  102. }
  103. private static void setActionShareWith(@NonNull Context context) {
  104. ACTION_SHARE_WITH = context.getResources().getString(R.string.users_and_groups_share_with);
  105. }
  106. @Nullable
  107. @Override
  108. public String getType(@NonNull Uri uri) {
  109. // TODO implement
  110. return null;
  111. }
  112. @Override
  113. public boolean onCreate() {
  114. AndroidInjection.inject(this);
  115. if (getContext() == null) {
  116. return false;
  117. }
  118. String AUTHORITY = getContext().getResources().getString(R.string.users_and_groups_search_authority);
  119. setActionShareWith(getContext());
  120. DATA_USER = AUTHORITY + ".data.user";
  121. DATA_GROUP = AUTHORITY + ".data.group";
  122. DATA_ROOM = AUTHORITY + ".data.room";
  123. DATA_REMOTE = AUTHORITY + ".data.remote";
  124. DATA_EMAIL = AUTHORITY + ".data.email";
  125. DATA_CIRCLE = AUTHORITY + ".data.circle";
  126. sShareTypes.put(DATA_USER, ShareType.USER);
  127. sShareTypes.put(DATA_GROUP, ShareType.GROUP);
  128. sShareTypes.put(DATA_ROOM, ShareType.ROOM);
  129. sShareTypes.put(DATA_REMOTE, ShareType.FEDERATED);
  130. sShareTypes.put(DATA_EMAIL, ShareType.EMAIL);
  131. sShareTypes.put(DATA_CIRCLE, ShareType.CIRCLE);
  132. mUriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
  133. mUriMatcher.addURI(AUTHORITY, SearchManager.SUGGEST_URI_PATH_QUERY + "/*", SEARCH);
  134. return true;
  135. }
  136. /**
  137. * returns sharee from server
  138. *
  139. * Reference: http://developer.android.com/guide/topics/search/adding-custom-suggestions.html#CustomContentProvider
  140. *
  141. * @param uri Content {@link Uri}, formatted as "content://com.nextcloud.android.providers.UsersAndGroupsSearchProvider/"
  142. * + {@link android.app.SearchManager#SUGGEST_URI_PATH_QUERY} + "/" +
  143. * 'userQuery'
  144. * @param projection Expected to be NULL.
  145. * @param selection Expected to be NULL.
  146. * @param selectionArgs Expected to be NULL.
  147. * @param sortOrder Expected to be NULL.
  148. * @return Cursor with possible sharees in the server that match 'query'.
  149. */
  150. @Nullable
  151. @Override
  152. public Cursor query(@NonNull Uri uri, String[] projection, String selection, String[] selectionArgs,
  153. String sortOrder) {
  154. Log_OC.d(TAG, "query received in thread " + Thread.currentThread().getName());
  155. int match = mUriMatcher.match(uri);
  156. if (match == SEARCH) {
  157. return searchForUsersOrGroups(uri);
  158. }
  159. return null;
  160. }
  161. private Cursor searchForUsersOrGroups(Uri uri) {
  162. String lastPathSegment = uri.getLastPathSegment();
  163. if (lastPathSegment == null) {
  164. throw new IllegalArgumentException("Wrong URI passed!");
  165. }
  166. // need to trust on the AccountUtils to get the current account since the query in the client side is not
  167. // directly started by our code, but from SearchView implementation
  168. User user = accountManager.getUser();
  169. String userQuery = lastPathSegment.toLowerCase(Locale.ROOT);
  170. // request to the OC server about users and groups matching userQuery
  171. GetShareesRemoteOperation searchRequest = new GetShareesRemoteOperation(userQuery, REQUESTED_PAGE,
  172. RESULTS_PER_PAGE);
  173. RemoteOperationResult result = searchRequest.execute(user.toPlatformAccount(), getContext());
  174. List<JSONObject> names = new ArrayList<>();
  175. if (result.isSuccess()) {
  176. for (Object o : result.getData()) {
  177. names.add((JSONObject) o);
  178. }
  179. } else {
  180. showErrorMessage(result);
  181. }
  182. MatrixCursor response = null;
  183. // convert the responses from the OC server to the expected format
  184. if (names.size() > 0) {
  185. if (getContext() == null) {
  186. throw new IllegalArgumentException("Context may not be null!");
  187. }
  188. response = new MatrixCursor(COLUMNS);
  189. Uri userBaseUri = new Uri.Builder().scheme(CONTENT).authority(DATA_USER).build();
  190. Uri groupBaseUri = new Uri.Builder().scheme(CONTENT).authority(DATA_GROUP).build();
  191. Uri roomBaseUri = new Uri.Builder().scheme(CONTENT).authority(DATA_ROOM).build();
  192. Uri remoteBaseUri = new Uri.Builder().scheme(CONTENT).authority(DATA_REMOTE).build();
  193. Uri emailBaseUri = new Uri.Builder().scheme(CONTENT).authority(DATA_EMAIL).build();
  194. Uri circleBaseUri = new Uri.Builder().scheme(CONTENT).authority(DATA_CIRCLE).build();
  195. FileDataStorageManager manager = new FileDataStorageManager(user,
  196. getContext().getContentResolver());
  197. boolean federatedShareAllowed = manager.getCapability(user.getAccountName())
  198. .getFilesSharingFederationOutgoing()
  199. .isTrue();
  200. try {
  201. Iterator<JSONObject> namesIt = names.iterator();
  202. JSONObject item;
  203. String displayName;
  204. String subline = null;
  205. Object icon = 0;
  206. Uri dataUri;
  207. int count = 0;
  208. while (namesIt.hasNext()) {
  209. item = namesIt.next();
  210. dataUri = null;
  211. displayName = null;
  212. String userName = item.getString(GetShareesRemoteOperation.PROPERTY_LABEL);
  213. String name = item.isNull("name") ? "" : item.getString("name");
  214. JSONObject value = item.getJSONObject(GetShareesRemoteOperation.NODE_VALUE);
  215. ShareType type = ShareType.fromValue(value.getInt(GetShareesRemoteOperation.PROPERTY_SHARE_TYPE));
  216. String shareWith = value.getString(GetShareesRemoteOperation.PROPERTY_SHARE_WITH);
  217. Status status;
  218. JSONObject statusObject = item.optJSONObject(PROPERTY_STATUS);
  219. if (statusObject != null) {
  220. status = new Status(
  221. StatusType.valueOf(statusObject.getString(PROPERTY_STATUS).toUpperCase(Locale.US)),
  222. statusObject.isNull(PROPERTY_MESSAGE) ? "" : statusObject.getString(PROPERTY_MESSAGE),
  223. statusObject.isNull(PROPERTY_ICON) ? "" : statusObject.getString(PROPERTY_ICON),
  224. statusObject.isNull(PROPERTY_CLEAR_AT) ? -1 : statusObject.getLong(PROPERTY_CLEAR_AT));
  225. } else {
  226. status = new Status(StatusType.OFFLINE, "", "", -1);
  227. }
  228. switch (type) {
  229. case GROUP:
  230. displayName = userName;
  231. icon = R.drawable.ic_group;
  232. dataUri = Uri.withAppendedPath(groupBaseUri, shareWith);
  233. break;
  234. case FEDERATED:
  235. if (federatedShareAllowed) {
  236. icon = R.drawable.ic_user;
  237. dataUri = Uri.withAppendedPath(remoteBaseUri, shareWith);
  238. if (userName.equals(shareWith)) {
  239. displayName = name;
  240. subline = getContext().getString(R.string.remote);
  241. } else {
  242. String[] uriSplitted = shareWith.split("@");
  243. displayName = name;
  244. subline = getContext().getString(R.string.share_known_remote_on_clarification,
  245. uriSplitted[uriSplitted.length - 1]);
  246. }
  247. }
  248. break;
  249. case USER:
  250. displayName = userName;
  251. subline = (status.getMessage() == null || status.getMessage().isEmpty()) ? null :
  252. status.getMessage();
  253. Uri.Builder builder =
  254. Uri.parse("content://com.nextcloud.android.providers.UsersAndGroupsSearchProvider/icon")
  255. .buildUpon();
  256. builder.appendQueryParameter("shareWith", shareWith);
  257. builder.appendQueryParameter("displayName", displayName);
  258. builder.appendQueryParameter("status", status.getStatus().toString());
  259. if (!TextUtils.isEmpty(status.getIcon()) && !"null".equals(status.getIcon())) {
  260. builder.appendQueryParameter("icon", status.getIcon());
  261. }
  262. icon = builder.build();
  263. dataUri = Uri.withAppendedPath(userBaseUri, shareWith);
  264. break;
  265. case EMAIL:
  266. icon = R.drawable.ic_email;
  267. displayName = name;
  268. subline = shareWith;
  269. dataUri = Uri.withAppendedPath(emailBaseUri, shareWith);
  270. break;
  271. case ROOM:
  272. icon = R.drawable.ic_talk;
  273. displayName = userName;
  274. dataUri = Uri.withAppendedPath(roomBaseUri, shareWith);
  275. break;
  276. case CIRCLE:
  277. icon = R.drawable.ic_circles;
  278. displayName = userName;
  279. dataUri = Uri.withAppendedPath(circleBaseUri, shareWith);
  280. break;
  281. default:
  282. break;
  283. }
  284. if (displayName != null && dataUri != null) {
  285. response.newRow()
  286. .add(count++) // BaseColumns._ID
  287. .add(displayName) // SearchManager.SUGGEST_COLUMN_TEXT_1
  288. .add(subline) // SearchManager.SUGGEST_COLUMN_TEXT_2
  289. .add(icon) // SearchManager.SUGGEST_COLUMN_ICON_1
  290. .add(dataUri);
  291. }
  292. }
  293. } catch (JSONException e) {
  294. Log_OC.e(TAG, "Exception while parsing data of users/groups", e);
  295. }
  296. }
  297. return response;
  298. }
  299. @Nullable
  300. @Override
  301. public Uri insert(@NonNull Uri uri, ContentValues values) {
  302. return null;
  303. }
  304. @Override
  305. public int delete(@NonNull Uri uri, String selection, String[] selectionArgs) {
  306. return 0;
  307. }
  308. @Override
  309. public int update(@NonNull Uri uri, ContentValues values, String selection, String[] selectionArgs) {
  310. return 0;
  311. }
  312. @Nullable
  313. @Override
  314. @SuppressFBWarnings("IOI_USE_OF_FILE_STREAM_CONSTRUCTORS") // TODO remove with API26
  315. public ParcelFileDescriptor openFile(@NonNull Uri uri, @NonNull String mode) throws FileNotFoundException {
  316. ArbitraryDataProvider arbitraryDataProvider = new ArbitraryDataProvider(getContext().getContentResolver());
  317. String userId = uri.getQueryParameter("shareWith");
  318. String displayName = uri.getQueryParameter("displayName");
  319. String accountName = accountManager.getUser().getAccountName();
  320. String serverName = accountName.substring(accountName.lastIndexOf('@') + 1);
  321. String eTag = arbitraryDataProvider.getValue(userId + "@" + serverName, ThumbnailsCacheManager.AVATAR);
  322. String avatarKey = "a_" + userId + "_" + serverName + "_" + eTag;
  323. StatusType status = StatusType.valueOf(uri.getQueryParameter("status"));
  324. String icon = uri.getQueryParameter("icon");
  325. if (icon == null) {
  326. icon = "";
  327. }
  328. Bitmap avatarBitmap = ThumbnailsCacheManager.getBitmapFromDiskCache(avatarKey);
  329. if (avatarBitmap == null) {
  330. float avatarRadius = getContext().getResources().getDimension(R.dimen.list_item_avatar_icon_radius);
  331. avatarBitmap = BitmapUtils.drawableToBitmap(TextDrawable.createNamedAvatar(displayName, avatarRadius));
  332. }
  333. Bitmap avatar = BitmapUtils.createAvatarWithStatus(avatarBitmap, status, icon, getContext());
  334. // create a file to write bitmap data
  335. File f = new File(getContext().getCacheDir(), "test");
  336. try {
  337. if (f.exists()) {
  338. if (!f.delete()) {
  339. throw new IllegalStateException("Existing file could not be deleted!");
  340. }
  341. }
  342. if (!f.createNewFile()) {
  343. throw new IllegalStateException("File could not be created!");
  344. }
  345. //Convert bitmap to byte array
  346. ByteArrayOutputStream bos = new ByteArrayOutputStream();
  347. avatar.compress(Bitmap.CompressFormat.PNG, 90, bos);
  348. byte[] bitmapData = bos.toByteArray();
  349. //write the bytes in file
  350. try (FileOutputStream fos = new FileOutputStream(f)) {
  351. fos.write(bitmapData);
  352. } catch (FileNotFoundException e) {
  353. Log_OC.e(TAG, "File not found: " + e.getMessage());
  354. }
  355. } catch (Exception e) {
  356. Log_OC.e(TAG, "Error opening file: " + e.getMessage());
  357. }
  358. return ParcelFileDescriptor.open(f, ParcelFileDescriptor.MODE_READ_ONLY);
  359. }
  360. /**
  361. * Show error message
  362. *
  363. * @param result Result with the failure information.
  364. */
  365. private void showErrorMessage(final RemoteOperationResult result) {
  366. Handler handler = new Handler(Looper.getMainLooper());
  367. handler.post(() -> {
  368. // The Toast must be shown in the main thread to grant that will be hidden correctly; otherwise
  369. // the thread may die before, an exception will occur, and the message will be left on the screen
  370. // until the app dies
  371. Context context = getContext();
  372. if (context == null) {
  373. throw new IllegalArgumentException("Context may not be null!");
  374. }
  375. Toast.makeText(getContext().getApplicationContext(),
  376. ErrorMessageAdapter.getErrorCauseMessage(result, null, getContext().getResources()),
  377. Toast.LENGTH_SHORT).show();
  378. });
  379. }
  380. }