UsersAndGroupsSearchProvider.java 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304
  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.accounts.Account;
  22. import android.app.SearchManager;
  23. import android.content.ContentProvider;
  24. import android.content.ContentValues;
  25. import android.content.UriMatcher;
  26. import android.database.Cursor;
  27. import android.database.MatrixCursor;
  28. import android.net.Uri;
  29. import android.os.Handler;
  30. import android.os.Looper;
  31. import android.provider.BaseColumns;
  32. import android.support.annotation.NonNull;
  33. import android.support.annotation.Nullable;
  34. import android.widget.Toast;
  35. import com.owncloud.android.R;
  36. import com.owncloud.android.authentication.AccountUtils;
  37. import com.owncloud.android.datamodel.FileDataStorageManager;
  38. import com.owncloud.android.lib.common.operations.RemoteOperationResult;
  39. import com.owncloud.android.lib.common.utils.Log_OC;
  40. import com.owncloud.android.lib.resources.shares.GetRemoteShareesOperation;
  41. import com.owncloud.android.lib.resources.shares.ShareType;
  42. import com.owncloud.android.utils.ErrorMessageAdapter;
  43. import org.json.JSONException;
  44. import org.json.JSONObject;
  45. import java.util.ArrayList;
  46. import java.util.HashMap;
  47. import java.util.Iterator;
  48. import java.util.List;
  49. import java.util.Locale;
  50. import java.util.Map;
  51. /**
  52. * Content provider for search suggestions, to search for users and groups existing in an ownCloud server.
  53. */
  54. public class UsersAndGroupsSearchProvider extends ContentProvider {
  55. private static final String TAG = UsersAndGroupsSearchProvider.class.getSimpleName();
  56. private static final String[] COLUMNS = {
  57. BaseColumns._ID,
  58. SearchManager.SUGGEST_COLUMN_TEXT_1,
  59. SearchManager.SUGGEST_COLUMN_ICON_1,
  60. SearchManager.SUGGEST_COLUMN_INTENT_DATA
  61. };
  62. private static final int SEARCH = 1;
  63. private static final int RESULTS_PER_PAGE = 50;
  64. private static final int REQUESTED_PAGE = 1;
  65. public static String AUTHORITY;
  66. public static String ACTION_SHARE_WITH;
  67. public static final String CONTENT = "content";
  68. public static String DATA_USER;
  69. public static String DATA_GROUP;
  70. public static String DATA_REMOTE;
  71. private UriMatcher mUriMatcher;
  72. private static Map<String, ShareType> sShareTypes = new HashMap<>();
  73. public static ShareType getShareType(String authority) {
  74. return sShareTypes.get(authority);
  75. }
  76. @Nullable
  77. @Override
  78. public String getType(@NonNull Uri uri) {
  79. // TODO implement
  80. return null;
  81. }
  82. @Override
  83. public boolean onCreate() {
  84. if (getContext() == null) {
  85. return false;
  86. }
  87. AUTHORITY = getContext().getResources().getString(R.string.users_and_groups_search_authority);
  88. ACTION_SHARE_WITH = getContext().getResources().getString(R.string.users_and_groups_share_with);
  89. DATA_USER = AUTHORITY + ".data.user";
  90. DATA_GROUP = AUTHORITY + ".data.group";
  91. DATA_REMOTE = AUTHORITY + ".data.remote";
  92. sShareTypes.put(DATA_USER, ShareType.USER);
  93. sShareTypes.put(DATA_GROUP, ShareType.GROUP);
  94. sShareTypes.put(DATA_GROUP, ShareType.ROOM);
  95. sShareTypes.put(DATA_REMOTE, ShareType.FEDERATED);
  96. sShareTypes.put(DATA_REMOTE, ShareType.EMAIL);
  97. mUriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
  98. mUriMatcher.addURI(AUTHORITY, SearchManager.SUGGEST_URI_PATH_QUERY + "/*", SEARCH);
  99. return true;
  100. }
  101. /**
  102. * returns sharee from server
  103. *
  104. * Reference: http://developer.android.com/guide/topics/search/adding-custom-suggestions.html#CustomContentProvider
  105. *
  106. * @param uri Content {@link Uri}, formatted as
  107. * "content://com.nextcloud.android.providers.UsersAndGroupsSearchProvider/" +
  108. * {@link android.app.SearchManager#SUGGEST_URI_PATH_QUERY} + "/" + 'userQuery'
  109. * @param projection Expected to be NULL.
  110. * @param selection Expected to be NULL.
  111. * @param selectionArgs Expected to be NULL.
  112. * @param sortOrder Expected to be NULL.
  113. * @return Cursor with possible sharees in the server that match 'query'.
  114. */
  115. @Nullable
  116. @Override
  117. public Cursor query(@NonNull Uri uri, String[] projection, String selection, String[] selectionArgs,
  118. String sortOrder) {
  119. Log_OC.d(TAG, "query received in thread " + Thread.currentThread().getName());
  120. int match = mUriMatcher.match(uri);
  121. switch (match) {
  122. case SEARCH:
  123. return searchForUsersOrGroups(uri);
  124. default:
  125. return null;
  126. }
  127. }
  128. private Cursor searchForUsersOrGroups(Uri uri) {
  129. MatrixCursor response = null;
  130. String userQuery = uri.getLastPathSegment().toLowerCase(Locale.ROOT);
  131. // need to trust on the AccountUtils to get the current account since the query in the client side is not
  132. // directly started by our code, but from SearchView implementation
  133. Account account = AccountUtils.getCurrentOwnCloudAccount(getContext());
  134. // request to the OC server about users and groups matching userQuery
  135. GetRemoteShareesOperation searchRequest = new GetRemoteShareesOperation(
  136. userQuery, REQUESTED_PAGE, RESULTS_PER_PAGE
  137. );
  138. RemoteOperationResult result = searchRequest.execute(account, getContext());
  139. List<JSONObject> names = new ArrayList<>();
  140. if (result.isSuccess()) {
  141. for (Object o : result.getData()) {
  142. names.add((JSONObject) o);
  143. }
  144. } else {
  145. showErrorMessage(result);
  146. }
  147. // convert the responses from the OC server to the expected format
  148. if (names.size() > 0) {
  149. response = new MatrixCursor(COLUMNS);
  150. Iterator<JSONObject> namesIt = names.iterator();
  151. JSONObject item;
  152. String displayName;
  153. int icon = 0;
  154. Uri dataUri;
  155. int count = 0;
  156. Uri userBaseUri = new Uri.Builder().scheme(CONTENT).authority(DATA_USER).build();
  157. Uri groupBaseUri = new Uri.Builder().scheme(CONTENT).authority(DATA_GROUP).build();
  158. Uri remoteBaseUri = new Uri.Builder().scheme(CONTENT).authority(DATA_REMOTE).build();
  159. FileDataStorageManager manager = new FileDataStorageManager(account, getContext().getContentResolver());
  160. boolean federatedShareAllowed = manager.getCapability(account.name).getFilesSharingFederationOutgoing()
  161. .isTrue();
  162. try {
  163. while (namesIt.hasNext()) {
  164. item = namesIt.next();
  165. dataUri = null;
  166. displayName = null;
  167. String userName = item.getString(GetRemoteShareesOperation.PROPERTY_LABEL);
  168. JSONObject value = item.getJSONObject(GetRemoteShareesOperation.NODE_VALUE);
  169. ShareType type = ShareType.fromValue(value.getInt(GetRemoteShareesOperation.PROPERTY_SHARE_TYPE));
  170. String shareWith = value.getString(GetRemoteShareesOperation.PROPERTY_SHARE_WITH);
  171. switch (type) {
  172. case GROUP:
  173. displayName = getContext().getString(R.string.share_group_clarification, userName);
  174. icon = R.drawable.ic_group;
  175. dataUri = Uri.withAppendedPath(groupBaseUri, shareWith);
  176. break;
  177. case FEDERATED:
  178. if (federatedShareAllowed) {
  179. icon = R.drawable.ic_user;
  180. dataUri = Uri.withAppendedPath(remoteBaseUri, shareWith);
  181. if (userName.equals(shareWith)) {
  182. displayName = getContext().getString(R.string.share_remote_clarification, userName);
  183. } else {
  184. String[] uriSplitted = shareWith.split("@");
  185. displayName = getContext().getString(R.string.share_known_remote_clarification,
  186. userName, uriSplitted[uriSplitted.length - 1]);
  187. }
  188. }
  189. break;
  190. case USER:
  191. displayName = userName;
  192. icon = R.drawable.ic_user;
  193. dataUri = Uri.withAppendedPath(userBaseUri, shareWith);
  194. break;
  195. case EMAIL:
  196. icon = R.drawable.ic_email;
  197. displayName = getContext().getString(R.string.share_email_clarification, userName);
  198. dataUri = Uri.withAppendedPath(remoteBaseUri, shareWith);
  199. break;
  200. case ROOM:
  201. icon = R.drawable.ic_chat_bubble;
  202. displayName = getContext().getString(R.string.share_room_clarification, userName);
  203. dataUri = Uri.withAppendedPath(groupBaseUri, shareWith);
  204. break;
  205. default:
  206. break;
  207. }
  208. if (displayName != null && dataUri != null) {
  209. response.newRow()
  210. .add(count++) // BaseColumns._ID
  211. .add(displayName) // SearchManager.SUGGEST_COLUMN_TEXT_1
  212. .add(icon) // SearchManager.SUGGEST_COLUMN_ICON_1
  213. .add(dataUri);
  214. }
  215. }
  216. } catch (JSONException e) {
  217. Log_OC.e(TAG, "Exception while parsing data of users/groups", e);
  218. }
  219. }
  220. return response;
  221. }
  222. @Nullable
  223. @Override
  224. public Uri insert(@NonNull Uri uri, ContentValues values) {
  225. return null;
  226. }
  227. @Override
  228. public int delete(@NonNull Uri uri, String selection, String[] selectionArgs) {
  229. return 0;
  230. }
  231. @Override
  232. public int update(@NonNull Uri uri, ContentValues values, String selection, String[] selectionArgs) {
  233. return 0;
  234. }
  235. /**
  236. * Show error message
  237. *
  238. * @param result Result with the failure information.
  239. */
  240. private void showErrorMessage(final RemoteOperationResult result) {
  241. Handler handler = new Handler(Looper.getMainLooper());
  242. handler.post(new Runnable() {
  243. @Override
  244. public void run() {
  245. // The Toast must be shown in the main thread to grant that will be hidden correctly; otherwise
  246. // the thread may die before, an exception will occur, and the message will be left on the screen
  247. // until the app dies
  248. Toast.makeText(getContext().getApplicationContext(),
  249. ErrorMessageAdapter.getErrorCauseMessage(result, null, getContext().getResources()),
  250. Toast.LENGTH_SHORT).show();
  251. }
  252. });
  253. }
  254. }