| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340 |
- package cn.fmode.app;
- import static org.junit.Assert.assertEquals;
- import static org.junit.Assert.assertFalse;
- import static org.junit.Assert.assertNotNull;
- import static org.junit.Assert.assertSame;
- import static org.junit.Assert.assertTrue;
- import static org.junit.Assert.fail;
- import android.app.Activity;
- import android.app.Instrumentation;
- import android.content.ClipData;
- import android.content.ComponentName;
- import android.content.Context;
- import android.content.Intent;
- import android.net.Uri;
- import android.os.SystemClock;
- import androidx.core.content.FileProvider;
- import androidx.test.ext.junit.runners.AndroidJUnit4;
- import androidx.test.platform.app.InstrumentationRegistry;
- import androidx.test.runner.lifecycle.ActivityLifecycleMonitorRegistry;
- import androidx.test.runner.lifecycle.Stage;
- import com.getcapacitor.JSObject;
- import com.getcapacitor.PluginCall;
- import java.io.File;
- import java.io.FileOutputStream;
- import java.io.IOException;
- import java.nio.charset.StandardCharsets;
- import java.util.ArrayList;
- import java.util.Arrays;
- import java.util.HashSet;
- import java.util.Set;
- import java.util.UUID;
- import java.util.concurrent.CountDownLatch;
- import java.util.concurrent.LinkedBlockingQueue;
- import java.util.concurrent.TimeUnit;
- import java.util.concurrent.atomic.AtomicReference;
- import org.json.JSONArray;
- import org.json.JSONObject;
- import org.junit.After;
- import org.junit.Before;
- import org.junit.Test;
- import org.junit.runner.RunWith;
- @RunWith(AndroidJUnit4.class)
- public class NativeShareActivityIntegrationTest {
- private Instrumentation instrumentation;
- private Context target;
- private Context sender;
- private File sources;
- private final Set<String> ownedShares = new HashSet<>();
- @Before
- public void setUp() throws Exception {
- instrumentation = InstrumentationRegistry.getInstrumentation();
- target = instrumentation.getTargetContext();
- sender = instrumentation.getContext();
- assertFalse(target.getPackageName().equals(sender.getPackageName()));
- sources = new File(target.getCacheDir(), "native-share-integration-" + UUID.randomUUID());
- assertTrue(sources.mkdirs());
- finishActivities();
- }
- @After
- public void tearDown() throws Exception {
- MainActivity activity = foreground();
- if (activity != null) {
- NativeSharePlugin plugin = plugin(activity);
- for (String id : ownedShares) acknowledge(plugin, id);
- }
- finishActivities();
- File[] files = sources.listFiles();
- if (files != null) for (File file : files) assertTrue(file.delete());
- assertTrue(sources.delete());
- }
- @Test
- public void coldSendCopiesRealFileProviderTextAndReplaysLateListener() throws Exception {
- String title = uniqueTitle();
- Uri source = textUri("cold.txt", "cold payload 中文");
- Intent intent = shareIntent(Intent.ACTION_SEND, title).putExtra(Intent.EXTRA_STREAM, source)
- .putExtra(Intent.EXTRA_TEXT, "cold accompanying text");
- sender.startActivity(intent);
- MainActivity activity = awaitActivity();
- NativeSharePlugin plugin = plugin(activity);
- JSONObject share = awaitShare(plugin, title);
- String id = own(share);
- assertEquals("cold accompanying text", share.getString("text"));
- assertFile(share, 0, "cold.txt", "cold payload 中文");
- assertFalse(share.has("errors"));
- CaptureCall listener = new CaptureCall("addListener", new JSObject().put("eventName", "shareReceived"));
- plugin.addListener(listener);
- JSONObject replay = awaitEvent(listener, id);
- assertEquals(share.getJSONArray("files").toString(), replay.getJSONArray("files").toString());
- File cached = file(share.getJSONArray("files").getJSONObject(0));
- acknowledge(plugin, id);
- assertFalse(cached.exists());
- instrumentation.runOnMainSync(() -> NativeSharePlugin.receiveIntent(activity, activity.getIntent()));
- assertAbsent(plugin, id);
- CaptureCall removed = new CaptureCall("removeAllListeners", new JSObject());
- plugin.removeAllListeners(removed);
- removed.await();
- CaptureCall later = new CaptureCall("addListener", new JSObject().put("eventName", "shareReceived"));
- plugin.addListener(later);
- CaptureCall barrier = new CaptureCall("getPendingShares", new JSObject());
- plugin.getPendingShares(barrier);
- barrier.await();
- for (JSObject event : later.events) assertFalse(id.equals(event.getJSONObject("share").getString("id")));
- acknowledge(plugin, id);
- }
- @Test
- public void hotSendMultipleDeduplicatesStreamsAndClipData() throws Exception {
- MainActivity before = launchNormally();
- NativeSharePlugin plugin = plugin(before);
- String title = uniqueTitle();
- Uri first = textUri("first.txt", "first");
- Uri second = textUri("second.txt", "second");
- Intent intent = shareIntent(Intent.ACTION_SEND_MULTIPLE, title)
- .putParcelableArrayListExtra(Intent.EXTRA_STREAM, new ArrayList<>(Arrays.asList(first, second)));
- ClipData clip = ClipData.newUri(target.getContentResolver(), "first", first);
- clip.addItem(new ClipData.Item(second));
- clip.addItem(new ClipData.Item(first));
- intent.setClipData(clip);
- sender.startActivity(intent);
- JSONObject share = awaitShare(plugin, title);
- own(share);
- assertSame(before, awaitActivity());
- assertEquals(2, share.getJSONArray("files").length());
- assertFile(share, 0, "first.txt", "first");
- assertFile(share, 1, "second.txt", "second");
- acknowledge(plugin, share.getString("id"));
- assertAbsent(plugin, share.getString("id"));
- }
- @Test
- public void clipDataOnlyAndInvalidUrisTravelThroughSystemDelivery() throws Exception {
- MainActivity activity = launchNormally();
- NativeSharePlugin plugin = plugin(activity);
- String title = uniqueTitle();
- Intent clipOnly = shareIntent(Intent.ACTION_SEND, title);
- clipOnly.setClipData(ClipData.newUri(target.getContentResolver(), "clip", textUri("clip.txt", "clip only")));
- sender.startActivity(clipOnly);
- JSONObject valid = awaitShare(plugin, title);
- own(valid);
- assertFile(valid, 0, "clip.txt", "clip only");
- String invalidTitle = uniqueTitle();
- Intent invalid = shareIntent(Intent.ACTION_SEND, invalidTitle)
- .putExtra(Intent.EXTRA_STREAM, Uri.parse("https://not-content.invalid/private.txt"))
- .putExtra(Intent.EXTRA_TEXT, "text must survive invalid attachment");
- sender.startActivity(invalid);
- JSONObject rejected = awaitShare(plugin, invalidTitle);
- own(rejected);
- assertEquals(0, rejected.getJSONArray("files").length());
- assertTrue(rejected.getJSONArray("errors").toString().contains("E_URI_SCHEME"));
- assertEquals("text must survive invalid attachment", rejected.getString("text"));
- acknowledge(plugin, valid.getString("id"));
- acknowledge(plugin, rejected.getString("id"));
- assertAbsent(plugin, rejected.getString("id"));
- }
- @Test
- public void unacknowledgedQueueSurvivesActivityFinishAndRestart() throws Exception {
- String title = uniqueTitle();
- sender.startActivity(shareIntent(Intent.ACTION_SEND, title)
- .putExtra(Intent.EXTRA_STREAM, textUri("persist.txt", "persist across Activity")));
- MainActivity firstActivity = awaitActivity();
- JSONObject original = awaitShare(plugin(firstActivity), title);
- String id = own(original);
- finishActivities();
- assertNotNull(new NativeSharePlugin.ShareStore(target).share(id));
- MainActivity restarted = launchNormally();
- assertFalse(firstActivity == restarted);
- NativeSharePlugin plugin = plugin(restarted);
- JSONObject recovered = awaitShare(plugin, title);
- assertEquals(id, recovered.getString("id"));
- assertFile(recovered, 0, "persist.txt", "persist across Activity");
- assertEquals(1, countTitle(pending(plugin), title));
- acknowledge(plugin, id);
- finishActivities();
- MainActivity afterAck = launchNormally();
- assertAbsent(plugin(afterAck), id);
- assertEquals(0, countTitle(new NativeSharePlugin.ShareStore(target).pending(), title));
- }
- private MainActivity launchNormally() throws Exception {
- Intent intent = new Intent(Intent.ACTION_MAIN).addCategory(Intent.CATEGORY_LAUNCHER)
- .setComponent(new ComponentName(target, MainActivity.class)).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
- sender.startActivity(intent);
- return awaitActivity();
- }
- private Intent shareIntent(String action, String title) {
- return new Intent(action).setType("text/plain").addCategory(Intent.CATEGORY_DEFAULT)
- .setComponent(new ComponentName(target, MainActivity.class)).putExtra(Intent.EXTRA_SUBJECT, title)
- .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_GRANT_READ_URI_PERMISSION);
- }
- private Uri textUri(String name, String text) throws Exception {
- File file = new File(sources, name);
- try (FileOutputStream output = new FileOutputStream(file)) { output.write(text.getBytes(StandardCharsets.UTF_8)); }
- Uri uri = FileProvider.getUriForFile(target, target.getPackageName() + ".fileprovider", file);
- assertEquals("content", uri.getScheme());
- return uri;
- }
- private NativeSharePlugin plugin(MainActivity activity) throws Exception {
- long deadline = SystemClock.elapsedRealtime() + 15000;
- while (SystemClock.elapsedRealtime() < deadline) {
- if (activity.getBridge() != null && activity.getBridge().getPlugin("NativeShare") != null) {
- return (NativeSharePlugin) activity.getBridge().getPlugin("NativeShare").getInstance();
- }
- SystemClock.sleep(50);
- }
- throw new AssertionError("NativeShare was not registered by MainActivity");
- }
- private JSONObject awaitShare(NativeSharePlugin plugin, String title) throws Exception {
- long deadline = SystemClock.elapsedRealtime() + 20000;
- while (SystemClock.elapsedRealtime() < deadline) {
- JSONArray shares = pending(plugin);
- for (int index = 0; index < shares.length(); index++) {
- JSONObject share = shares.getJSONObject(index);
- if (title.equals(share.optString("title"))) return share;
- }
- SystemClock.sleep(50);
- }
- throw new AssertionError("System share did not reach NativeShare queue: " + title);
- }
- private static JSONArray pending(NativeSharePlugin plugin) throws Exception {
- CaptureCall call = new CaptureCall("getPendingShares", new JSObject());
- plugin.getPendingShares(call);
- return call.await().getJSONArray("shares");
- }
- private static void acknowledge(NativeSharePlugin plugin, String id) throws Exception {
- CaptureCall call = new CaptureCall("acknowledgeShare", new JSObject().put("id", id));
- plugin.acknowledgeShare(call);
- call.await();
- }
- private static void assertAbsent(NativeSharePlugin plugin, String id) throws Exception {
- JSONArray shares = pending(plugin);
- for (int index = 0; index < shares.length(); index++) assertFalse(id.equals(shares.getJSONObject(index).getString("id")));
- }
- private JSONObject awaitEvent(CaptureCall listener, String id) throws Exception {
- long deadline = SystemClock.elapsedRealtime() + 10000;
- while (SystemClock.elapsedRealtime() < deadline) {
- JSObject event = listener.events.poll(200, TimeUnit.MILLISECONDS);
- if (event != null && id.equals(event.getJSONObject("share").getString("id"))) return event.getJSONObject("share");
- }
- throw new AssertionError("Late shareReceived listener did not receive durable share");
- }
- private void assertFile(JSONObject share, int index, String name, String content) throws Exception {
- JSONObject metadata = share.getJSONArray("files").getJSONObject(index);
- assertEquals(name, metadata.getString("name"));
- assertEquals("text/plain", metadata.getString("mimeType"));
- assertEquals(content.getBytes(StandardCharsets.UTF_8).length, metadata.getLong("size"));
- File file = file(metadata);
- assertTrue(file.getCanonicalPath().startsWith(new File(target.getCacheDir(), "shared-incoming").getCanonicalPath() + "/"));
- assertEquals(content, new String(java.nio.file.Files.readAllBytes(file.toPath()), StandardCharsets.UTF_8));
- }
- private static File file(JSONObject metadata) throws Exception {
- Uri uri = Uri.parse(metadata.getString("path"));
- assertEquals("file", uri.getScheme());
- return new File(uri.getPath());
- }
- private String own(JSONObject share) throws Exception {
- String id = share.getString("id");
- ownedShares.add(id);
- return id;
- }
- private static String uniqueTitle() { return "native-share-system-" + UUID.randomUUID(); }
- private static int countTitle(JSONArray shares, String title) throws Exception {
- int matches = 0;
- for (int index = 0; index < shares.length(); index++) if (title.equals(shares.getJSONObject(index).optString("title"))) matches++;
- return matches;
- }
- private MainActivity foreground() {
- AtomicReference<MainActivity> result = new AtomicReference<>();
- instrumentation.runOnMainSync(() -> {
- for (Activity activity : ActivityLifecycleMonitorRegistry.getInstance().getActivitiesInStage(Stage.RESUMED)) {
- if (activity instanceof MainActivity) result.set((MainActivity) activity);
- }
- });
- return result.get();
- }
- private MainActivity awaitActivity() {
- long deadline = SystemClock.elapsedRealtime() + 20000;
- while (SystemClock.elapsedRealtime() < deadline) {
- MainActivity activity = foreground();
- if (activity != null) return activity;
- SystemClock.sleep(50);
- }
- throw new AssertionError("MainActivity did not resume");
- }
- private void finishActivities() {
- instrumentation.runOnMainSync(() -> {
- Set<Activity> activities = new HashSet<>();
- for (Stage stage : new Stage[] {Stage.CREATED, Stage.STARTED, Stage.RESUMED, Stage.PAUSED, Stage.STOPPED}) {
- activities.addAll(ActivityLifecycleMonitorRegistry.getInstance().getActivitiesInStage(stage));
- }
- for (Activity activity : activities) if (activity instanceof MainActivity) activity.finish();
- });
- instrumentation.waitForIdleSync();
- long deadline = SystemClock.elapsedRealtime() + 10000;
- while (foreground() != null && SystemClock.elapsedRealtime() < deadline) SystemClock.sleep(50);
- }
- private static final class CaptureCall extends PluginCall {
- final LinkedBlockingQueue<JSObject> events = new LinkedBlockingQueue<>();
- private final CountDownLatch finished = new CountDownLatch(1);
- private JSObject result;
- private String failure;
- CaptureCall(String method, JSObject data) { super(null, "NativeShare", UUID.randomUUID().toString(), method, data); }
- @Override public void resolve(JSObject data) {
- result = data;
- events.add(data);
- finished.countDown();
- }
- @Override public void resolve() { result = new JSObject(); finished.countDown(); }
- @Override public void reject(String message, String code) { failure = code + ": " + message; finished.countDown(); }
- JSObject await() throws Exception {
- assertTrue("NativeShare callback timed out", finished.await(20, TimeUnit.SECONDS));
- if (failure != null) fail(failure);
- return result;
- }
- }
- }
|