UsersAndGroupsSearchProvider.java 18 KB

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