Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ Android intents support incoming shared text and app links. Long-press the launc

Verified connections are remembered on this device with encrypted API keys. Select a remembered connection in Connection Settings, or use the server dropdown on the main menu when more than one connection has an API key. Switching the server you browse preserves your default share destination. Use **Forget** to remove a saved connection from this device.

Search directly from the main menu. The search icon opens a mode menu with the server default, metadata, and full-text options; available modes refresh from the server. Results open in an authenticated embedded server page.
Tap **Search archive** on the main menu to open your server’s search field. Operators, suggestions and results come from the authenticated server. When you tap **Search** while browsing a filtered library view, the app focuses that view’s search field and keeps the current folder, tag, domain, and filters. Older servers open their existing Snapshot search.

For Tailscale, connect your Android device to your tailnet first and enter a server’s MagicDNS name or `100.x.y.z` address as a discovery hint, or paste the output of `tailscale status --json` from a computer on your tailnet. Only reachable candidates can be discovered, and a firewall or VPN policy can block access. You can always enter a server address directly, including a different port.

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -169,18 +169,12 @@ class ArchiveBoxJourneyTest {
compose.onAllNodesWithTag("home.progress").assertCountEquals(0)
shot("library")
click("tab.Archive")
node("sidebar.searchField").assertIsDisplayed().performTextReplacement("cowpig.github.io")
androidx.test.espresso.Espresso.closeSoftKeyboard()
click("sidebar.searchMode")
compose.onNodeWithText("Metadata").performClick()
click("sidebar.searchSubmit")
click("sidebar.searchField")
await("browser.ready")
enterServerSearch("cowpig.github.io")
submitServerSearch()
await("browser.ready")
val snapshotId = snapshots("cowpig.github.io").first { it.getString("url") == "https://cowpig.github.io/about/" }.getString("id")
val inputValue = Atoms.script("function(element) { return element.value; }", Atoms.castOrDie(String::class.java))
onWebView().withElement(findElement(Locator.CSS_SELECTOR, "input[name=q]"))
.check(webMatches(inputValue, equalTo("cowpig.github.io")))
onWebView().withElement(findElement(Locator.CSS_SELECTOR, "select[name=search_mode]"))
.check(webMatches(inputValue, equalTo("meta")))
val resultRow = "//input[@name='_selected_action' and @value='$snapshotId']/ancestor::tr"
onWebView().withElement(findElement(Locator.XPATH, resultRow))
.check(webMatches(getText(), containsString("cowpig.github.io")))
Expand Down
22 changes: 13 additions & 9 deletions app/src/androidTest/java/io/archivebox/app/ClientParityTest.kt
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,11 @@ class ClientParityTest {
}
click("setup.skip")
fill("connection.hints", first)
// An already-granted LAN permission starts discovery on entry. Wait for
// its sweep to finish so this second sweep actually receives the typed hint.
compose.waitUntil(30_000) {
compose.onAllNodes(hasTestTag("connection.discover") and isEnabled()).fetchSemanticsNodes().isNotEmpty()
}
click("connection.discover", scroll = true)
val device = UiDevice.getInstance(instrumentation)
device.wait(Until.findObject(By.res("com.android.permissioncontroller", "permission_allow_button")), 5_000)?.click()
Expand All @@ -76,20 +81,19 @@ class ClientParityTest {
click("sidebar.serverSwitcher"); click("sidebar.switchServer.${firstSaved.id}")
compose.waitUntil(10_000) { ArchiveRepository(context).registry.value.active_server_id == firstSaved.id }
assertEquals(registry.default_server_ids, ArchiveRepository(context).registry.value.default_server_ids)
node("sidebar.searchField").assertIsDisplayed()
fill("sidebar.searchField", "a & b/日本語")
click("sidebar.searchMode"); compose.onNodeWithText("Metadata").performClick()
click("sidebar.searchField"); await("browser.ready")
val query = "title:\"a & b/日本語\""
enterServerSearch(query)
shot("menu-search")
click("sidebar.searchSubmit"); await("browser.ready")
val expression = Atoms.script("return new URL(location.href).searchParams.get('q') + '|' + new URL(location.href).searchParams.get('search_mode');", Atoms.castOrDie(String::class.java))
onWebView().check(webMatches(expression, equalTo("a & b/日本語|meta")))
submitServerSearch(); await("browser.ready")
val expression = Atoms.script("return new URL(location.href).searchParams.get('q');", Atoms.castOrDie(String::class.java))
onWebView().check(webMatches(expression, equalTo(query)))
shot("embedded-search")
click("tab.Archive")
node("sidebar.serverSwitcher").assertIsDisplayed()
click("sidebar.serverSwitcher"); click("sidebar.switchServer.${secondSaved.id}")
node("sidebar.searchField").assertIsDisplayed()
assertEquals("", node("sidebar.searchField").fetchSemanticsNode().config[androidx.compose.ui.semantics.SemanticsProperties.EditableText].text)
click("sidebar.searchSubmit"); await("browser.ready")
click("sidebar.searchField"); await("browser.ready")
onWebView().check(webMatches(Atoms.script("return document.querySelector('form[role=search] input[name=q]').value;", Atoms.castOrDie(String::class.java)), equalTo("")))
onWebView().check(webMatches(Atoms.script("return location.origin;", Atoms.castOrDie(String::class.java)), equalTo(second.trimEnd('/'))))
click("tab.Settings")
click("history.server.${firstSaved.id}", scroll = true)
Expand Down
53 changes: 53 additions & 0 deletions app/src/androidTest/java/io/archivebox/app/ServerSearch.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
package io.archivebox.app

import android.content.ClipData
import android.content.ClipboardManager
import android.view.KeyEvent
import android.webkit.WebView
import androidx.test.espresso.Espresso.onView
import androidx.test.espresso.matcher.ViewMatchers.isAssignableFrom
import androidx.test.espresso.web.assertion.WebViewAssertions.webMatches
import androidx.test.espresso.web.model.Atoms
import androidx.test.espresso.web.sugar.Web.onWebView
import androidx.test.espresso.web.webdriver.DriverAtoms.findElement
import androidx.test.espresso.web.webdriver.DriverAtoms.webClick
import androidx.test.espresso.web.webdriver.Locator
import androidx.test.platform.app.InstrumentationRegistry
import androidx.test.uiautomator.UiDevice
import kotlin.math.roundToInt
import org.hamcrest.Matchers.equalTo
import org.json.JSONArray

/** Use the real WebView input and keyboard so non-ASCII and URL punctuation survive submission. */
internal fun enterServerSearch(query: String) {
// Older supported servers fall back to their ordinary Snapshot search form.
val editor = "form[role=search] [role=combobox], form[role=search] input[name=q]:not(.abx-search-field input)"
val instrumentation = InstrumentationRegistry.getInstrumentation()
val device = UiDevice.getInstance(instrumentation)
// Espresso's webClick synthesizes a DOM click, so Android's actual IME may still
// target a native view. Tap the rendered field, accounting for WebView density.
val center = Atoms.script(
"""function(e) {
const r = e.getBoundingClientRect();
return JSON.stringify([(r.left + r.width/2) * devicePixelRatio, (r.top + r.height/2) * devicePixelRatio]);
}""", Atoms.castOrDie(String::class.java))
val point = JSONArray(onWebView().withElement(findElement(Locator.CSS_SELECTOR, editor)).perform(center).get())
val offset = IntArray(2)
onView(isAssignableFrom(WebView::class.java)).check { view, _ -> view.getLocationOnScreen(offset) }
device.click(offset[0] + point.getDouble(0).roundToInt(), offset[1] + point.getDouble(1).roundToInt())
device.waitForIdle()
instrumentation.runOnMainSync {
instrumentation.targetContext.getSystemService(ClipboardManager::class.java)
.setPrimaryClip(ClipData.newPlainText("Search", query))
}
device.pressKeyCode(KeyEvent.KEYCODE_V, KeyEvent.META_CTRL_ON)
Comment thread
pirate marked this conversation as resolved.
Resolved
device.waitForIdle()
val value = Atoms.script("function(element) { return element.value; }", Atoms.castOrDie(String::class.java))
onWebView().withElement(findElement(Locator.CSS_SELECTOR, "form[role=search] input[name=q]"))
.check(webMatches(value, equalTo(query)))
}

internal fun submitServerSearch() {
onWebView().withElement(findElement(Locator.CSS_SELECTOR, "form[role=search] :is(button,input)[type=submit]"))
.perform(webClick())
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,116 @@
package io.archivebox.app

import android.content.Intent
import android.net.Uri
import androidx.compose.ui.test.*
import androidx.compose.ui.test.junit4.v2.createEmptyComposeRule
import androidx.test.espresso.web.assertion.WebViewAssertions.webMatches
import androidx.test.espresso.web.model.Atoms
import androidx.test.espresso.web.sugar.Web.onWebView
import androidx.test.espresso.web.webdriver.DriverAtoms.findElement
import androidx.test.espresso.web.webdriver.DriverAtoms.webClick
import androidx.test.espresso.web.webdriver.Locator
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 org.hamcrest.Matchers.equalTo
import org.junit.Assert.assertEquals
import org.junit.Assert.assertNotNull
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith

/** Exercises search against a connected server independently of LAN discovery or gallery fixtures. */
@RunWith(AndroidJUnit4::class)
class ServerSearchIntegrationTest {
Comment thread
pirate marked this conversation as resolved.
Resolved
@get:Rule val compose = createEmptyComposeRule()

private fun await(tag: String) = compose.waitUntil(30_000) {
compose.onAllNodesWithTag(tag).fetchSemanticsNodes().isNotEmpty()
}

private fun connect() {
val args = InstrumentationRegistry.getArguments()
val context = InstrumentationRegistry.getInstrumentation().targetContext
val uri = Uri.parse("archivebox://connect").buildUpon()
.appendQueryParameter("server", requireNotNull(args.getString("serverUrl")))
.appendQueryParameter("api_key", requireNotNull(args.getString("apiToken")))
.build()
context.startActivity(Intent(Intent.ACTION_VIEW, uri, context, MainActivity::class.java)
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK))
await("connection.save")
compose.onNodeWithTag("connection.save").performScrollTo().performClick()
await("connection.status")
}

private fun recreateActivity() {
val instrumentation = InstrumentationRegistry.getInstrumentation()
instrumentation.runOnMainSync {
ActivityLifecycleMonitorRegistry.getInstance().getActivitiesInStage(Stage.RESUMED).single().recreate()
}
await("browser.ready")
}

private val currentUrl = Atoms.script("return location.href;", Atoms.castOrDie(String::class.java))

private fun waitForSubmittedQuery(query: String): Uri {
// The admin updates history when streamed results arrive; the document
// remains ready throughout, so wait for the actual submitted URL.
compose.waitUntil(30_000) {
Uri.parse(onWebView().perform(currentUrl).get()).getQueryParameter("q") == query
}
return Uri.parse(onWebView().perform(currentUrl).get())
}

@Test fun submitAndReopenQuotedQuery() {
connect()
compose.onNodeWithTag("tab.Search").performClick()
await("browser.ready")
val query = "title:\"a & b/日本語\""
enterServerSearch(query)
submitServerSearch()
await("browser.ready")
val submitted = waitForSubmittedQuery(query)
// A recreated Activity must restore results, including the encoded expression.
recreateActivity()
onWebView().check(webMatches(currentUrl, equalTo(submitted.toString())))
compose.onNodeWithTag("tab.Archive").performClick()
compose.onNodeWithTag("sidebar.searchField").performClick()
await("browser.ready")
val input = Atoms.script("return document.querySelector('form[role=search] input[name=q]').value;", Atoms.castOrDie(String::class.java))
onWebView().check(webMatches(input, equalTo(query)))
}

@Test fun nativeSearchStaysInSelectedTag() {
connect()
compose.onNodeWithTag("tab.Archive").performClick()
compose.onNodeWithTag("home").performScrollToNode(hasTestTag("route.Tags"))
compose.onNodeWithTag("route.Tags").performClick()
await("browser.ready")
onWebView().withElement(findElement(Locator.CSS_SELECTOR, "a[href*='tags__id__exact=']"))
.perform(webClick())
await("browser.ready")
val filtered = Uri.parse(onWebView().perform(currentUrl).get())
val tag = filtered.getQueryParameter("tags__id__exact")
assertNotNull("The tag count link must open a tag-filtered Snapshot view", tag)

compose.onNodeWithTag("tab.Search").performClick()
Comment thread
pirate marked this conversation as resolved.
Resolved
// The native Search tab must focus the filter's existing form. Opening a
// standalone editor here would appear functional while silently losing the tag.
val fieldFocused = Atoms.script(
"return document.activeElement.matches('[role=search] [role=combobox], [role=search] input[name=q]');",
Atoms.castOrDie(Boolean::class.javaObjectType))
compose.waitUntil(30_000) { onWebView().perform(fieldFocused).get() }
onWebView().check(webMatches(currentUrl, equalTo(filtered.toString())))
enterServerSearch("https")
submitServerSearch()
await("browser.ready")
val submitted = waitForSubmittedQuery("https")
assertEquals(filtered.path, submitted.path)
assertEquals(tag, submitted.getQueryParameter("tags__id__exact"))
assertEquals("https", submitted.getQueryParameter("q"))
recreateActivity()
onWebView().check(webMatches(currentUrl, equalTo(submitted.toString())))
}
}
10 changes: 0 additions & 10 deletions app/src/main/java/io/archivebox/app/data/ArchiveApi.kt
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,6 @@ import java.util.concurrent.TimeUnit
import kotlin.coroutines.resume
import kotlin.coroutines.resumeWithException

data class ArchiveSnapshot(val id: String, val title: String, val url: String, val tags: List<String>)
data class SubmissionReceipt(val server_id: String, val crawl_id: String, val queued_urls: List<String>)
data class ServerPersona(val id: String, val name: String)
data class BrowserSession(val admin_url: String, val cookie: Cookie) {
Expand Down Expand Up @@ -178,15 +177,6 @@ class ArchiveApi(timeoutSeconds: Long = 20) {
validateTokenResponse(result)
}

suspend fun snapshots(connection: ServerConfiguration, query: String = "", offset: Int = 0): List<ArchiveSnapshot> {
require(offset >= 0)
val result = request(connection.server, "api/v1/core/snapshots", connection.token,
query = mapOf("search" to query, "search_mode" to "meta", "limit" to "50", "offset" to offset.toString()))
return result.getJSONArray("items").objects().map {
ArchiveSnapshot(it.getString("id"), it.optString("title").takeUnless { value -> value == "null" }.orEmpty(), it.getString("url"), it.optJSONArray("tags")?.strings().orEmpty())
}
}

suspend fun tagSuggestions(connection: ServerConfiguration, query: String): List<String> {
val result = request(connection.server, "api/v1/core/tags/autocomplete/", connection.token, query = mapOf("q" to query))
return normalizeTags(result.getJSONArray("tags").objects().map { it.getString("name") })
Expand Down
Loading
Loading