diff --git a/README.md b/README.md index a1df5c1..d1418ba 100644 --- a/README.md +++ b/README.md @@ -17,7 +17,7 @@ Saving a link should not depend on whether your linkding server is reachable at ## How it works -1. Share an HTTP(S) link to ShareDing from a browser or another app, or enter it in the Add Bookmark form. You can save links before configuring the server. +1. Share an HTTP(S) link to ShareDing from a browser or another app, choose ShareDing if the app offers **Open with**, or enter it in the Add Bookmark form. You can save links before configuring the server. 2. ShareDing removes known tracking parameters such as `utm_*`, `fbclid`, and `si` on YouTube and Spotify links, then writes the bookmark to a Room database on the device before attempting a network request. The browser stays visible; a short `Saved to queue` Toast appears only after the local write succeeds. Invalid links and local save errors get a different message. 3. WorkManager runs sync when a network is available. ShareDing checks the configured linkding server itself, so a server reachable through LAN or VPN does not need public internet access. 4. Before sending a link from a known URL shortener such as `t.co`, `bit.ly`, or `vk.cc`, ShareDing asks the shortener where it leads and sends that address instead, noting the short link in the bookmark notes. It never opens the target site, so a blocked destination does not matter; if the shortener cannot be reached, the short link is sent as is. After linkding accepts the bookmark, ShareDing removes it from the queue. Connection and server errors leave it queued for another attempt. Retries use exponential backoff starting at 30 seconds; Android may run them later than the scheduled time. @@ -47,6 +47,8 @@ These screens were captured on an Android 16 emulator with an example link in th If sync hits a problem that retrying cannot fix, such as a rejected API token, ShareDing stops sync and shows a notification. Sync starts again when you save settings, tap **Sync now**, or tap **Retry**. Until then, and while no server is set up, saving a link shows the reason in the confirmation and in a notification, and no background work runs. Links that wait longer than a day also raise a notification. On Android 13 and newer it asks for the notification permission the first time you open the app; to change the answer later, use the system settings of the app. Without notifications, sync works the same and errors stay visible in Queue. +Choosing ShareDing in **Open with** saves the link as a bookmark and returns to the source app without loading the page. Not every app shows a chooser: ordinary link taps can go straight to your default browser. Keep your regular browser as the default and use **Share → ShareDing** when there is no choice. + Settings also lets you set default tags and choose whether bookmarks are marked unread or archived. These defaults are applied when a link is sent, so changing them affects links already in the queue. Enter multiple tags with commas, for example `reading, work notes`, then tap **Save settings**. With a configured connection, existing linkding tags appear as suggestions while you type in Settings or a bookmark form. You can still enter new tags and save while the server is offline. ShareDing connects to linkding and bookmarked pages directly. It has no proxy setting; if your server is reachable only through another route, use a VPN on your device. Versions before 0.2.1 had an optional HTTP proxy. It was removed because proxy credentials were sent without TLS, and updating deletes any saved proxy settings. diff --git a/app/src/androidTest/java/org/evsyukov/shareding/OpenLinkIntentTest.kt b/app/src/androidTest/java/org/evsyukov/shareding/OpenLinkIntentTest.kt new file mode 100644 index 0000000..8217e1f --- /dev/null +++ b/app/src/androidTest/java/org/evsyukov/shareding/OpenLinkIntentTest.kt @@ -0,0 +1,123 @@ +package org.evsyukov.shareding + +import android.content.ComponentName +import android.content.Intent +import android.content.pm.PackageManager +import android.net.Uri +import androidx.test.ext.junit.runners.AndroidJUnit4 +import androidx.test.platform.app.InstrumentationRegistry +import androidx.test.runner.lifecycle.ActivityLifecycleCallback +import androidx.test.runner.lifecycle.ActivityLifecycleMonitorRegistry +import androidx.test.runner.lifecycle.Stage +import kotlinx.coroutines.CompletableDeferred +import kotlinx.coroutines.runBlocking +import kotlinx.coroutines.withTimeout +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNotNull +import org.junit.Assert.assertNull +import org.junit.Rule +import org.junit.Test +import org.junit.runner.RunWith + +@RunWith(AndroidJUnit4::class) +class OpenLinkIntentTest { + @get:Rule val notificationPermission = NotificationPermissionRule() + + private val instrumentation = InstrumentationRegistry.getInstrumentation() + private val context = instrumentation.targetContext + private val container = (context.applicationContext as ShareDingApplication).container + private val dao get() = container.db.bookmarks() + + private fun openIntent(url: String) = Intent(Intent.ACTION_VIEW, Uri.parse(url)) + .addCategory(Intent.CATEGORY_BROWSABLE) + .setPackage(context.packageName) + .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) + + @Suppress("DEPRECATION") + private fun handlerFor(intent: Intent): String { + val handler = context.packageManager.resolveActivity(intent, PackageManager.MATCH_DEFAULT_ONLY) + assertNotNull("ShareDing must handle ${intent.scheme} ACTION_VIEW links", handler) + return requireNotNull(handler).activityInfo.name + } + + private suspend fun launchAndWaitForReturn(intent: Intent, handler: String) { + val returned = CompletableDeferred() + val monitor = ActivityLifecycleMonitorRegistry.getInstance() + val callback = ActivityLifecycleCallback { activity, stage -> + if (activity.javaClass.name == handler && stage == Stage.DESTROYED && activity.isFinishing) { + returned.complete(Unit) + } + } + instrumentation.runOnMainSync { monitor.addLifecycleCallback(callback) } + try { + context.startActivity(intent) + withTimeout(15_000) { returned.await() } + } finally { + instrumentation.runOnMainSync { monitor.removeLifecycleCallback(callback) } + } + } + + @Test fun openHttpsLinkQueuesCleanUrlWithoutServer() = runBlocking { + assertFalse("This test needs an unconfigured queue", container.settings.state.value.configured) + val base = "https://example.com/article-${System.nanoTime()}" + val raw = "$base?id=7&utm_source=test#section" + val clean = "$base?id=7#section" + val intent = openIntent(raw).putExtra(Intent.EXTRA_TITLE, "Do not store this title") + val handler = handlerFor(intent) + try { + launchAndWaitForReturn(intent, handler) + val saved = dao.findByUrl(clean) + assertNotNull("Opening the link should queue the cleaned data URI", saved) + assertEquals("", saved?.title) + assertEquals(false, saved?.sendTitle) + assertNull("The original tracking URL must not be queued", dao.findByUrl(raw)) + } finally { + dao.findByUrl(clean)?.let { dao.delete(it.id) } + dao.findByUrl(raw)?.let { dao.delete(it.id) } + } + } + + @Test fun reopeningHttpLinkKeepsOneBookmark() = runBlocking { + assertFalse("This test needs an unconfigured queue", container.settings.state.value.configured) + val url = "http://example.com/article-${System.nanoTime()}" + val intent = openIntent(url) + val handler = handlerFor(intent) + val before = dao.count() + try { + launchAndWaitForReturn(intent, handler) + val saved = dao.findByUrl(url) + assertNotNull("HTTP links should also be saved", saved) + launchAndWaitForReturn(intent, handler) + assertEquals(saved?.id, dao.findByUrl(url)?.id) + assertEquals(before + 1, dao.count()) + } finally { + dao.findByUrl(url)?.let { dao.delete(it.id) } + } + } + + @Test fun invalidViewLinksDoNotFallBackToShareExtras() = runBlocking { + val fallback = "https://example.com/fallback-${System.nanoTime()}" + val handler = handlerFor(openIntent(fallback)) + val before = dao.count() + val invalid = listOf(null, "ftp://example.com/file", "https:///missing-host") + try { + for (url in invalid) { + // An explicit call can reach the exported activity without a matching filter. + val intent = Intent(Intent.ACTION_VIEW).apply { + component = ComponentName(context.packageName, handler) + data = url?.let(Uri::parse) + addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) + putExtra(Intent.EXTRA_TEXT, fallback) + } + launchAndWaitForReturn(intent, handler) + assertNull("Must not fall back to Share text for $url", dao.findByUrl(fallback)) + assertEquals("Invalid VIEW data: $url", before, dao.count()) + } + } finally { + (invalid.filterNotNull() + fallback).forEach { url -> + dao.findByUrl(url)?.let { dao.delete(it.id) } + } + } + } +} diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml index 73af0a8..0e87e89 100644 --- a/app/src/main/AndroidManifest.xml +++ b/app/src/main/AndroidManifest.xml @@ -33,6 +33,13 @@ + + + + + + + diff --git a/app/src/main/java/org/evsyukov/shareding/ShareActivity.kt b/app/src/main/java/org/evsyukov/shareding/ShareActivity.kt index 1265829..301042a 100644 --- a/app/src/main/java/org/evsyukov/shareding/ShareActivity.kt +++ b/app/src/main/java/org/evsyukov/shareding/ShareActivity.kt @@ -59,27 +59,35 @@ internal object DirectShare { } } -/** A translucent Share target that leaves the sending app visible until the local save completes. */ +/** A translucent link target that leaves the source app visible until the local save completes. */ class ShareActivity : ComponentActivity() { private val container get() = (application as ShareDingApplication).container override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) - val shared = SharedLink.from(intent) - if (shared == null) { + val fromShare = intent.action == Intent.ACTION_SEND + val bookmark = when (intent.action) { + Intent.ACTION_SEND -> SharedLink.from(intent)?.let { Bookmark(url = it.url, title = it.title) } + Intent.ACTION_VIEW -> intent.dataString + ?.let { runCatching { Urls.bookmark(it) }.getOrNull() } + ?.let { Bookmark(url = it) } + else -> null + } + if (bookmark == null) { showResult(SharedLink.INVALID) return } - val (url, title) = shared lifecycleScope.launch { val message = try { - val message = container.queueLink(Bookmark(url = url, title = title)) - withContext(Dispatchers.IO) { - try { - DirectShare.publish(applicationContext) - } catch (error: Exception) { - Log.e("ShareDing", "Could not publish the Direct Share target", error) + val message = container.queueLink(bookmark) + if (fromShare) { + withContext(Dispatchers.IO) { + try { + DirectShare.publish(applicationContext) + } catch (error: Exception) { + Log.e("ShareDing", "Could not publish the Direct Share target", error) + } } } message diff --git a/docs/privacy.md b/docs/privacy.md index a273fe8..99e2e83 100644 --- a/docs/privacy.md +++ b/docs/privacy.md @@ -10,6 +10,8 @@ ShareDing stores queued bookmark URLs, titles, descriptions, notes, tags, and de When sync runs, ShareDing sends the bookmark fields and API token to your configured linkding server. The server URL must use HTTPS. Your linkding server's operator determines how data sent to that server is stored and used; consult that server's policy if you do not operate it yourself. ShareDing has no developer-operated service that receives your bookmarks or token. +If you select ShareDing to open a web link from another app, ShareDing saves the URL as a bookmark without loading the page. The bookmark follows the same sync rules as a shared link. + If you tap **Fetch page details**, ShareDing may request the bookmarked page to read its title and description. Background sync leaves page metadata retrieval to linkding and omits titles received through Share. Titles accepted in the Add Bookmark form are sent to linkding. Page-detail requests do not include your linkding API token. Bookmarked pages may use HTTP or HTTPS. An HTTP page request and its response are unencrypted, and the page operator can receive your IP address and ordinary request information. If a queued link comes from a known URL shortener such as `t.co`, `bit.ly`, or `vk.cc`, the sync worker requests that short link from the shortener to learn its target before sending the bookmark. The request contains the short link but no linkding API token or other bookmark fields. The shortener operator can receive your IP address and ordinary request information. ShareDing does not open the target page; the short link is added to the bookmark notes sent to linkding. diff --git a/docs/specs/share-to-linkding.md b/docs/specs/share-to-linkding.md index 484864a..8b4f5e6 100644 --- a/docs/specs/share-to-linkding.md +++ b/docs/specs/share-to-linkding.md @@ -43,6 +43,7 @@ The app accepts a link from Android's Share menu or its add form, saves it on th - R32. Default tags, unread, and archive are read from the current settings for every POST, so a change applies to all queued links, including links saved before the server was set up or while sync was stopped. A queued entry stores only the tags entered for it in Add Bookmark; they are sent after the default tags without duplicates. - R33. Publish one long-lived sharing shortcut for `text/plain`, so ShareDing appears in the Direct Share row. Publish it on app start and again after each share. Selecting it saves the link exactly as the R1 target does. The shortcut also appears in the launcher menu of the app icon and opens the app there: Android does not keep a shortcut that is excluded from the launcher as a dynamic one. - R34. When Queue comes to the front (app launch or return from another app), read the clipboard once, after the window gets input focus: Android 10+ hides the clipboard from an app without it. Do not read it from Settings, the Add Bookmark form, background work, or while the notification permission request (R28) is open, and skip a clip that has no text type. If the clip holds an HTTP(S) link, extracted and cleaned as in Share, show one dialog with that URL and the actions `Send` and `Not now`. `Send` saves the link as the R1 target does, without a title and without opening the Add Bookmark form, and shows the same confirmation Toast. `Not now`, back, or a tap outside leaves the queue unchanged. Remember the last link sent or dismissed on the device and do not offer it again; a different link is offered. A link already in the queue is not offered. Android 12+ shows its own clipboard-access notice on the read. +- R35. Offer ShareDing as an `ACTION_VIEW` handler for HTTP(S) links where the source app opens an Android chooser. Validate and clean only the intent's data URL, ignoring Share extras. Queue it without a title using the same local-first save and result messages as R1, then return to the source app without loading the page or opening the Add Bookmark form. Do not ask to become the default browser. Ordinary link taps may still go straight to the default browser. An invalid or missing URL leaves the queue unchanged. The single Share target and Direct Share (R1, R33) are unchanged. ## Invariants and compatibility @@ -96,7 +97,8 @@ For R16–R17, Share titles serve as local labels. A persisted flag distinguishe - R32: Queue a shared link and a form link with its own tags, change the defaults, and confirm the POST bodies carry the new tags and flags; repeat for a link stuck on a rejected token. Upgrade version 1 and version 2 databases and confirm the queue is intact and the two columns are gone. Covered by `SyncWorkerTest`, `LinkdingApiTest`, `QueueUiTest`, and `BookmarkMigrationTest`. - R33: After app start the dynamic shortcut carries the share-target category; covered by `ShareIntentTest.appStartPublishesDirectShareTarget`. On an API 36 emulator the system share sheet showed ShareDing in the Direct Share row and selecting it queued the link; this was checked manually. - R34: Copy a tracked link inside text and return to the app: the dialog shows the cleaned URL, `Send` queues it once without the Add Bookmark form, and it is not offered again after it leaves the queue. Dismiss a link and return: no dialog until a different link is copied. A queued link, text without a link, an `ftp://` URL, and a link copied while Settings is shown produce no dialog; switching to Queue then offers the link. Covered by `QueueUiTest.clipboardLinkIsOfferedAndQueuedWithoutAddForm`, `QueueUiTest.dismissedClipboardLinkIsNotOfferedAgainButANewOneIs`, `QueueUiTest.queuedClipboardLinkIsNotOffered`, `QueueUiTest.clipboardWithoutHttpLinkIsNotOffered`, and `QueueUiTest.clipboardIsCheckedOnlyWhileQueueIsShown`. The Toast text comes from `SyncProblem.savedMessage`, covered by `SyncProblemTest`. +- R35: With no server configured, choose ShareDing in a caller's Android chooser for HTTP and HTTPS links. Check that the cleaned URL is queued without a title and the caller returns. Repeat a link and check that there is still one entry and that the Toast reports the duplicate. Try an ordinary tap with another browser set as default: it should open that browser for a generic, unverified link. `OpenLinkIntentTest` covers the package-targeted Android intent handoff, local save, and validation; the system chooser and default routing are separate emulator or device checks. -Automated checks: `./gradlew assembleDebug assembleRelease testDebugUnitTest testReleaseUnitTest lintDebug lintRelease connectedDebugAndroidTest`. URL, metadata, and linkding API cases are covered in `app/src/test/java/org/evsyukov/shareding/network/`; Room queue, Share Intent, worker, scheduler, and UI cases are covered in `app/src/androidTest/java/org/evsyukov/shareding/`. +Automated checks: `./gradlew assembleDebug assembleRelease testDebugUnitTest testReleaseUnitTest lintDebug lintRelease connectedDebugAndroidTest`. URL, metadata, and linkding API cases are covered in `app/src/test/java/org/evsyukov/shareding/network/`; Room queue, Share and Open Link intents, worker, scheduler, and UI cases are covered in `app/src/androidTest/java/org/evsyukov/shareding/`. Manual network checks: Turn off Wi-Fi and mobile data, share a URL, close the app, turn Wi-Fi on, then confirm the POST reaches a test server and the queue empties. To check LAN access without public internet, disable public internet validation in the emulator, confirm that `NET_CAPABILITY_VALIDATED` is absent, and send to a reachable linkding server. To check backoff, make the test server return 503 for the first POST and 201 for the next; the entry must remain queued until the second response.