NativeShareActivityIntegrationTest.java 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340
  1. package cn.fmode.app;
  2. import static org.junit.Assert.assertEquals;
  3. import static org.junit.Assert.assertFalse;
  4. import static org.junit.Assert.assertNotNull;
  5. import static org.junit.Assert.assertSame;
  6. import static org.junit.Assert.assertTrue;
  7. import static org.junit.Assert.fail;
  8. import android.app.Activity;
  9. import android.app.Instrumentation;
  10. import android.content.ClipData;
  11. import android.content.ComponentName;
  12. import android.content.Context;
  13. import android.content.Intent;
  14. import android.net.Uri;
  15. import android.os.SystemClock;
  16. import androidx.core.content.FileProvider;
  17. import androidx.test.ext.junit.runners.AndroidJUnit4;
  18. import androidx.test.platform.app.InstrumentationRegistry;
  19. import androidx.test.runner.lifecycle.ActivityLifecycleMonitorRegistry;
  20. import androidx.test.runner.lifecycle.Stage;
  21. import com.getcapacitor.JSObject;
  22. import com.getcapacitor.PluginCall;
  23. import java.io.File;
  24. import java.io.FileOutputStream;
  25. import java.io.IOException;
  26. import java.nio.charset.StandardCharsets;
  27. import java.util.ArrayList;
  28. import java.util.Arrays;
  29. import java.util.HashSet;
  30. import java.util.Set;
  31. import java.util.UUID;
  32. import java.util.concurrent.CountDownLatch;
  33. import java.util.concurrent.LinkedBlockingQueue;
  34. import java.util.concurrent.TimeUnit;
  35. import java.util.concurrent.atomic.AtomicReference;
  36. import org.json.JSONArray;
  37. import org.json.JSONObject;
  38. import org.junit.After;
  39. import org.junit.Before;
  40. import org.junit.Test;
  41. import org.junit.runner.RunWith;
  42. @RunWith(AndroidJUnit4.class)
  43. public class NativeShareActivityIntegrationTest {
  44. private Instrumentation instrumentation;
  45. private Context target;
  46. private Context sender;
  47. private File sources;
  48. private final Set<String> ownedShares = new HashSet<>();
  49. @Before
  50. public void setUp() throws Exception {
  51. instrumentation = InstrumentationRegistry.getInstrumentation();
  52. target = instrumentation.getTargetContext();
  53. sender = instrumentation.getContext();
  54. assertFalse(target.getPackageName().equals(sender.getPackageName()));
  55. sources = new File(target.getCacheDir(), "native-share-integration-" + UUID.randomUUID());
  56. assertTrue(sources.mkdirs());
  57. finishActivities();
  58. }
  59. @After
  60. public void tearDown() throws Exception {
  61. MainActivity activity = foreground();
  62. if (activity != null) {
  63. NativeSharePlugin plugin = plugin(activity);
  64. for (String id : ownedShares) acknowledge(plugin, id);
  65. }
  66. finishActivities();
  67. File[] files = sources.listFiles();
  68. if (files != null) for (File file : files) assertTrue(file.delete());
  69. assertTrue(sources.delete());
  70. }
  71. @Test
  72. public void coldSendCopiesRealFileProviderTextAndReplaysLateListener() throws Exception {
  73. String title = uniqueTitle();
  74. Uri source = textUri("cold.txt", "cold payload 中文");
  75. Intent intent = shareIntent(Intent.ACTION_SEND, title).putExtra(Intent.EXTRA_STREAM, source)
  76. .putExtra(Intent.EXTRA_TEXT, "cold accompanying text");
  77. sender.startActivity(intent);
  78. MainActivity activity = awaitActivity();
  79. NativeSharePlugin plugin = plugin(activity);
  80. JSONObject share = awaitShare(plugin, title);
  81. String id = own(share);
  82. assertEquals("cold accompanying text", share.getString("text"));
  83. assertFile(share, 0, "cold.txt", "cold payload 中文");
  84. assertFalse(share.has("errors"));
  85. CaptureCall listener = new CaptureCall("addListener", new JSObject().put("eventName", "shareReceived"));
  86. plugin.addListener(listener);
  87. JSONObject replay = awaitEvent(listener, id);
  88. assertEquals(share.getJSONArray("files").toString(), replay.getJSONArray("files").toString());
  89. File cached = file(share.getJSONArray("files").getJSONObject(0));
  90. acknowledge(plugin, id);
  91. assertFalse(cached.exists());
  92. instrumentation.runOnMainSync(() -> NativeSharePlugin.receiveIntent(activity, activity.getIntent()));
  93. assertAbsent(plugin, id);
  94. CaptureCall removed = new CaptureCall("removeAllListeners", new JSObject());
  95. plugin.removeAllListeners(removed);
  96. removed.await();
  97. CaptureCall later = new CaptureCall("addListener", new JSObject().put("eventName", "shareReceived"));
  98. plugin.addListener(later);
  99. CaptureCall barrier = new CaptureCall("getPendingShares", new JSObject());
  100. plugin.getPendingShares(barrier);
  101. barrier.await();
  102. for (JSObject event : later.events) assertFalse(id.equals(event.getJSONObject("share").getString("id")));
  103. acknowledge(plugin, id);
  104. }
  105. @Test
  106. public void hotSendMultipleDeduplicatesStreamsAndClipData() throws Exception {
  107. MainActivity before = launchNormally();
  108. NativeSharePlugin plugin = plugin(before);
  109. String title = uniqueTitle();
  110. Uri first = textUri("first.txt", "first");
  111. Uri second = textUri("second.txt", "second");
  112. Intent intent = shareIntent(Intent.ACTION_SEND_MULTIPLE, title)
  113. .putParcelableArrayListExtra(Intent.EXTRA_STREAM, new ArrayList<>(Arrays.asList(first, second)));
  114. ClipData clip = ClipData.newUri(target.getContentResolver(), "first", first);
  115. clip.addItem(new ClipData.Item(second));
  116. clip.addItem(new ClipData.Item(first));
  117. intent.setClipData(clip);
  118. sender.startActivity(intent);
  119. JSONObject share = awaitShare(plugin, title);
  120. own(share);
  121. assertSame(before, awaitActivity());
  122. assertEquals(2, share.getJSONArray("files").length());
  123. assertFile(share, 0, "first.txt", "first");
  124. assertFile(share, 1, "second.txt", "second");
  125. acknowledge(plugin, share.getString("id"));
  126. assertAbsent(plugin, share.getString("id"));
  127. }
  128. @Test
  129. public void clipDataOnlyAndInvalidUrisTravelThroughSystemDelivery() throws Exception {
  130. MainActivity activity = launchNormally();
  131. NativeSharePlugin plugin = plugin(activity);
  132. String title = uniqueTitle();
  133. Intent clipOnly = shareIntent(Intent.ACTION_SEND, title);
  134. clipOnly.setClipData(ClipData.newUri(target.getContentResolver(), "clip", textUri("clip.txt", "clip only")));
  135. sender.startActivity(clipOnly);
  136. JSONObject valid = awaitShare(plugin, title);
  137. own(valid);
  138. assertFile(valid, 0, "clip.txt", "clip only");
  139. String invalidTitle = uniqueTitle();
  140. Intent invalid = shareIntent(Intent.ACTION_SEND, invalidTitle)
  141. .putExtra(Intent.EXTRA_STREAM, Uri.parse("https://not-content.invalid/private.txt"))
  142. .putExtra(Intent.EXTRA_TEXT, "text must survive invalid attachment");
  143. sender.startActivity(invalid);
  144. JSONObject rejected = awaitShare(plugin, invalidTitle);
  145. own(rejected);
  146. assertEquals(0, rejected.getJSONArray("files").length());
  147. assertTrue(rejected.getJSONArray("errors").toString().contains("E_URI_SCHEME"));
  148. assertEquals("text must survive invalid attachment", rejected.getString("text"));
  149. acknowledge(plugin, valid.getString("id"));
  150. acknowledge(plugin, rejected.getString("id"));
  151. assertAbsent(plugin, rejected.getString("id"));
  152. }
  153. @Test
  154. public void unacknowledgedQueueSurvivesActivityFinishAndRestart() throws Exception {
  155. String title = uniqueTitle();
  156. sender.startActivity(shareIntent(Intent.ACTION_SEND, title)
  157. .putExtra(Intent.EXTRA_STREAM, textUri("persist.txt", "persist across Activity")));
  158. MainActivity firstActivity = awaitActivity();
  159. JSONObject original = awaitShare(plugin(firstActivity), title);
  160. String id = own(original);
  161. finishActivities();
  162. assertNotNull(new NativeSharePlugin.ShareStore(target).share(id));
  163. MainActivity restarted = launchNormally();
  164. assertFalse(firstActivity == restarted);
  165. NativeSharePlugin plugin = plugin(restarted);
  166. JSONObject recovered = awaitShare(plugin, title);
  167. assertEquals(id, recovered.getString("id"));
  168. assertFile(recovered, 0, "persist.txt", "persist across Activity");
  169. assertEquals(1, countTitle(pending(plugin), title));
  170. acknowledge(plugin, id);
  171. finishActivities();
  172. MainActivity afterAck = launchNormally();
  173. assertAbsent(plugin(afterAck), id);
  174. assertEquals(0, countTitle(new NativeSharePlugin.ShareStore(target).pending(), title));
  175. }
  176. private MainActivity launchNormally() throws Exception {
  177. Intent intent = new Intent(Intent.ACTION_MAIN).addCategory(Intent.CATEGORY_LAUNCHER)
  178. .setComponent(new ComponentName(target, MainActivity.class)).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
  179. sender.startActivity(intent);
  180. return awaitActivity();
  181. }
  182. private Intent shareIntent(String action, String title) {
  183. return new Intent(action).setType("text/plain").addCategory(Intent.CATEGORY_DEFAULT)
  184. .setComponent(new ComponentName(target, MainActivity.class)).putExtra(Intent.EXTRA_SUBJECT, title)
  185. .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_GRANT_READ_URI_PERMISSION);
  186. }
  187. private Uri textUri(String name, String text) throws Exception {
  188. File file = new File(sources, name);
  189. try (FileOutputStream output = new FileOutputStream(file)) { output.write(text.getBytes(StandardCharsets.UTF_8)); }
  190. Uri uri = FileProvider.getUriForFile(target, target.getPackageName() + ".fileprovider", file);
  191. assertEquals("content", uri.getScheme());
  192. return uri;
  193. }
  194. private NativeSharePlugin plugin(MainActivity activity) throws Exception {
  195. long deadline = SystemClock.elapsedRealtime() + 15000;
  196. while (SystemClock.elapsedRealtime() < deadline) {
  197. if (activity.getBridge() != null && activity.getBridge().getPlugin("NativeShare") != null) {
  198. return (NativeSharePlugin) activity.getBridge().getPlugin("NativeShare").getInstance();
  199. }
  200. SystemClock.sleep(50);
  201. }
  202. throw new AssertionError("NativeShare was not registered by MainActivity");
  203. }
  204. private JSONObject awaitShare(NativeSharePlugin plugin, String title) throws Exception {
  205. long deadline = SystemClock.elapsedRealtime() + 20000;
  206. while (SystemClock.elapsedRealtime() < deadline) {
  207. JSONArray shares = pending(plugin);
  208. for (int index = 0; index < shares.length(); index++) {
  209. JSONObject share = shares.getJSONObject(index);
  210. if (title.equals(share.optString("title"))) return share;
  211. }
  212. SystemClock.sleep(50);
  213. }
  214. throw new AssertionError("System share did not reach NativeShare queue: " + title);
  215. }
  216. private static JSONArray pending(NativeSharePlugin plugin) throws Exception {
  217. CaptureCall call = new CaptureCall("getPendingShares", new JSObject());
  218. plugin.getPendingShares(call);
  219. return call.await().getJSONArray("shares");
  220. }
  221. private static void acknowledge(NativeSharePlugin plugin, String id) throws Exception {
  222. CaptureCall call = new CaptureCall("acknowledgeShare", new JSObject().put("id", id));
  223. plugin.acknowledgeShare(call);
  224. call.await();
  225. }
  226. private static void assertAbsent(NativeSharePlugin plugin, String id) throws Exception {
  227. JSONArray shares = pending(plugin);
  228. for (int index = 0; index < shares.length(); index++) assertFalse(id.equals(shares.getJSONObject(index).getString("id")));
  229. }
  230. private JSONObject awaitEvent(CaptureCall listener, String id) throws Exception {
  231. long deadline = SystemClock.elapsedRealtime() + 10000;
  232. while (SystemClock.elapsedRealtime() < deadline) {
  233. JSObject event = listener.events.poll(200, TimeUnit.MILLISECONDS);
  234. if (event != null && id.equals(event.getJSONObject("share").getString("id"))) return event.getJSONObject("share");
  235. }
  236. throw new AssertionError("Late shareReceived listener did not receive durable share");
  237. }
  238. private void assertFile(JSONObject share, int index, String name, String content) throws Exception {
  239. JSONObject metadata = share.getJSONArray("files").getJSONObject(index);
  240. assertEquals(name, metadata.getString("name"));
  241. assertEquals("text/plain", metadata.getString("mimeType"));
  242. assertEquals(content.getBytes(StandardCharsets.UTF_8).length, metadata.getLong("size"));
  243. File file = file(metadata);
  244. assertTrue(file.getCanonicalPath().startsWith(new File(target.getCacheDir(), "shared-incoming").getCanonicalPath() + "/"));
  245. assertEquals(content, new String(java.nio.file.Files.readAllBytes(file.toPath()), StandardCharsets.UTF_8));
  246. }
  247. private static File file(JSONObject metadata) throws Exception {
  248. Uri uri = Uri.parse(metadata.getString("path"));
  249. assertEquals("file", uri.getScheme());
  250. return new File(uri.getPath());
  251. }
  252. private String own(JSONObject share) throws Exception {
  253. String id = share.getString("id");
  254. ownedShares.add(id);
  255. return id;
  256. }
  257. private static String uniqueTitle() { return "native-share-system-" + UUID.randomUUID(); }
  258. private static int countTitle(JSONArray shares, String title) throws Exception {
  259. int matches = 0;
  260. for (int index = 0; index < shares.length(); index++) if (title.equals(shares.getJSONObject(index).optString("title"))) matches++;
  261. return matches;
  262. }
  263. private MainActivity foreground() {
  264. AtomicReference<MainActivity> result = new AtomicReference<>();
  265. instrumentation.runOnMainSync(() -> {
  266. for (Activity activity : ActivityLifecycleMonitorRegistry.getInstance().getActivitiesInStage(Stage.RESUMED)) {
  267. if (activity instanceof MainActivity) result.set((MainActivity) activity);
  268. }
  269. });
  270. return result.get();
  271. }
  272. private MainActivity awaitActivity() {
  273. long deadline = SystemClock.elapsedRealtime() + 20000;
  274. while (SystemClock.elapsedRealtime() < deadline) {
  275. MainActivity activity = foreground();
  276. if (activity != null) return activity;
  277. SystemClock.sleep(50);
  278. }
  279. throw new AssertionError("MainActivity did not resume");
  280. }
  281. private void finishActivities() {
  282. instrumentation.runOnMainSync(() -> {
  283. Set<Activity> activities = new HashSet<>();
  284. for (Stage stage : new Stage[] {Stage.CREATED, Stage.STARTED, Stage.RESUMED, Stage.PAUSED, Stage.STOPPED}) {
  285. activities.addAll(ActivityLifecycleMonitorRegistry.getInstance().getActivitiesInStage(stage));
  286. }
  287. for (Activity activity : activities) if (activity instanceof MainActivity) activity.finish();
  288. });
  289. instrumentation.waitForIdleSync();
  290. long deadline = SystemClock.elapsedRealtime() + 10000;
  291. while (foreground() != null && SystemClock.elapsedRealtime() < deadline) SystemClock.sleep(50);
  292. }
  293. private static final class CaptureCall extends PluginCall {
  294. final LinkedBlockingQueue<JSObject> events = new LinkedBlockingQueue<>();
  295. private final CountDownLatch finished = new CountDownLatch(1);
  296. private JSObject result;
  297. private String failure;
  298. CaptureCall(String method, JSObject data) { super(null, "NativeShare", UUID.randomUUID().toString(), method, data); }
  299. @Override public void resolve(JSObject data) {
  300. result = data;
  301. events.add(data);
  302. finished.countDown();
  303. }
  304. @Override public void resolve() { result = new JSObject(); finished.countDown(); }
  305. @Override public void reject(String message, String code) { failure = code + ": " + message; finished.countDown(); }
  306. JSObject await() throws Exception {
  307. assertTrue("NativeShare callback timed out", finished.await(20, TimeUnit.SECONDS));
  308. if (failure != null) fail(failure);
  309. return result;
  310. }
  311. }
  312. }