CircleToSearch with multi search engine support for all android
Kotlin
fix: removed catbox.moe and added imagedb as image host
AKS Labsf46382189ec7
diff --git a/app/src/main/java/com/akslabs/circletosearch/OverlayActivity.kt b/app/src/main/java/com/akslabs/circletosearch/OverlayActivity.ktindex 6ecca8f..c3797e8 100644--- a/app/src/main/java/com/akslabs/circletosearch/OverlayActivity.kt+++ b/app/src/main/java/com/akslabs/circletosearch/OverlayActivity.kt@@ -44,6 +44,24 @@ class OverlayActivity : ComponentActivity() {super.onCreate(savedInstanceState)android.util.Log.d("CircleToSearch", "OverlayActivity onCreate")+ // Allow chrome://inspect attachment for diagnosing engine tabs (debug builds only)+ if (applicationInfo.flags and android.content.pm.ApplicationInfo.FLAG_DEBUGGABLE != 0) {+ android.webkit.WebView.setWebContentsDebuggingEnabled(true)+ }++ // Fresh cookie jar each session (Incognito-equivalent): Google cookies+ // accumulated across challenged/failed sessions may be trust-flagged,+ // which breaks Lens ("image not associated with your account") while a+ // clean Incognito profile loads the same URL fine.+ try {+ val cm = android.webkit.CookieManager.getInstance()+ cm.removeAllCookies { cm.flush() }+ cm.flush()+ android.util.Log.d("LensDiag", "COOKIES_CLEARED")+ } catch (e: Exception) {+ android.util.Log.e("LensDiag", "cookie clear failed: $e")+ }+// Ensure the activity can receive touches and focus properlywindow.addFlags(android.view.WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL)window.addFlags(android.view.WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN)diff --git a/app/src/main/java/com/akslabs/circletosearch/ui/CircleToSearchScreen.kt b/app/src/main/java/com/akslabs/circletosearch/ui/CircleToSearchScreen.ktindex b1289d7..c57b964 100644--- a/app/src/main/java/com/akslabs/circletosearch/ui/CircleToSearchScreen.kt+++ b/app/src/main/java/com/akslabs/circletosearch/ui/CircleToSearchScreen.kt@@ -189,6 +189,7 @@ import kotlinx.coroutines.launchimport kotlinx.coroutines.withContextimport java.io.ByteArrayOutputStreamimport androidx.webkit.WebViewFeature+import androidx.webkit.UserAgentMetadataimport com.akslabs.circletosearch.data.isDirectUploadimport kotlin.math.maximport kotlin.math.min@@ -478,9 +479,9 @@ fun CircleToSearchScreen(val newUserAgent = if (isDesktop) {"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36"} else {- WebSettings.getDefaultUserAgent(wv.context)+ "Mozilla/5.0 (Linux; Android 10; K) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Mobile Safari/537.36"}-+if (wv.settings.userAgentString != newUserAgent) {wv.settings.userAgentString = newUserAgentwv.reload()@@ -499,7 +500,7 @@ fun CircleToSearchScreen(override fun onPageFinished(view: android.webkit.WebView?, url: String?) {super.onPageFinished(view, url)val darkModeCSS = """- javascript:(function() {+ (function() {var style = document.createElement('style');style.innerHTML = `html { filter: invert(1) hue-rotate(180deg) !important; background: #000 !important; }@@ -508,7 +509,7 @@ fun CircleToSearchScreen(document.head.appendChild(style);})()""".trimIndent()- view?.loadUrl(darkModeCSS)+ view?.evaluateJavascript(darkModeCSS, null)}}} else {@@ -761,40 +762,180 @@ fun CircleToSearchScreen(userAgentString = if (isDesktop(engine)) {"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36"} else {- // Use the real, always-current WebView UA. A hardcoded stale UA- // makes Google serve degraded variants (app-promo/homepage pages).- WebSettings.getDefaultUserAgent(ctx)+ "Mozilla/5.0 (Linux; Android 10; K) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Mobile Safari/537.36"}-+// Dark Mode - Use CSS injection for universal compatibility// Algorithmic darkening alone doesn't work on many websitesandroid.util.Log.d("CircleToSearch", "Dark mode enabled: $isDarkMode")}-+// UI TweaksisVerticalScrollBarEnabled = falseisHorizontalScrollBarEnabled = false// Enable Third-Party Cookies- val cookieManager = android.webkit.CookieManager.getInstance()- cookieManager.setAcceptThirdPartyCookies(this, true)- // Pre-seed Google's consent cookie (only if the user has no choice yet) so- // region consent walls don't redirect image searches to a homepage/promo page.- val googleConsentUrl = "https://www.google.com"- if (cookieManager.getCookie(googleConsentUrl)?.contains("SOCS=") != true) {- cookieManager.setCookie(googleConsentUrl, "SOCS=CAESHAgBEhIaAB")- cookieManager.setCookie("https://lens.google.com", "SOCS=CAESHAgBEhIaAB")- cookieManager.flush()+ android.webkit.CookieManager.getInstance().setAcceptThirdPartyCookies(this, true)++ // Instrument fetch/XHR so the Lens results RPC (and its status) is+ // visible even when it fails silently. Injected at page start AND+ // finish (start can race the document commit); per-document guard.+ fun installNetDiag(view: WebView) {+ val netJs = """+ (function() {+ if (window.__netDiag) return 'already';+ window.__netDiag = 1;+ try {+ var of = window.fetch;+ window.fetch = function(u, init) {+ var m = (init && init.method) || 'GET';+ var url = (typeof u === 'string') ? u : ((u && u.url) || '');+ console.warn('NET fetch ' + m + ' ' + url.slice(0, 200));+ return of.apply(this, arguments).then(function(r) {+ console.warn('NET fetchdone ' + r.status + ' ' + m + ' ' + url.slice(0, 200));+ if (/Validate|qfmetadata|sgasync|httpservice|batchexecute|folsrch|bgasy|\/search\?/.test(url)) {+ try {+ console.warn('NETBODY_CLONE ' + url.split('?')[0].slice(-70));+ r.clone().text().then(function(t) {+ var i = t.search(/not associated with your account|No image at the URL|Image not found|Something went wrong/);+ if (i >= 0) {+ console.warn('NETBODY_HIT @' + i + '/' + t.length + ' >> ' + t.slice(Math.max(0, i - 150), i + 250));+ } else {+ console.warn('NETBODY ' + url.split('?')[0].slice(-70) + ' len=' + t.length + ' head=' + t.slice(0, 200));+ }+ }).catch(function(e) { console.warn('NETBODY_ERR ' + e); });+ } catch (e) { console.warn('NETBODY_ERR ' + e); }+ }+ return r;+ }, function(e) {+ console.warn('NET fetcherr ' + m + ' ' + url.slice(0, 200) + ' ' + e);+ throw e;+ });+ };+ var ox = XMLHttpRequest.prototype.open;+ var os = XMLHttpRequest.prototype.send;+ XMLHttpRequest.prototype.open = function(m, u) { this.__dm = m; this.__du = u; return ox.apply(this, arguments); };+ XMLHttpRequest.prototype.send = function() {+ var s = this, m = this.__dm, u = this.__du;+ console.warn('NET xhr ' + m + ' ' + String(u).slice(0, 200));+ s.addEventListener('loadend', function() {+ console.warn('NET xhrdone ' + s.status + ' ' + m + ' ' + String(u).slice(0, 200));+ try {+ if (/Validate|qfmetadata|sgasync|httpservice|batchexecute|folsrch|bgasy/.test(String(u)) && s.responseText) {+ console.warn('NETBODY_XHR ' + String(u).split('?')[0].slice(-70) + ' >> ' + String(s.responseText).slice(0, 400));+ }+ } catch (e) {}+ });+ return os.apply(this, arguments);+ };+ return 'installed';+ } catch (e) { return 'NETDIAG_ERR ' + e; }+ })()+ """.trimIndent()+ view.evaluateJavascript(netJs) { r ->+ if (r != null && r != "\"already\"") {+ android.util.Log.d("LensDiag", "NETDIAG $r")+ }+ }}-+webViewClient = object : WebViewClient() {+ override fun onPageStarted(view: WebView?, url: String?, favicon: android.graphics.Bitmap?) {+ super.onPageStarted(view, url, favicon)+ if (url != null && url.contains("google.") && view != null) {+ android.util.Log.d("LensDiag", "NAV $url")+ installNetDiag(view)+ }+ }++ override fun onReceivedHttpError(+ view: WebView?,+ request: android.webkit.WebResourceRequest?,+ response: android.webkit.WebResourceResponse?+ ) {+ val host = request?.url?.host ?: ""+ if (response != null && response.statusCode in 400..599 &&+ (host.contains("google") || host.contains("imgdb") || host.contains("catbox"))+ ) {+ android.util.Log.e("LensDiag", "HTTP ${response.statusCode} ${response.reasonPhrase} ${request?.url}")+ }+ }+override fun onPageFinished(view: WebView?, url: String?) {super.onPageFinished(view, url)+ // Lens loads its result tabs via async RPCs after page finish.+ // Snapshot the network + DOM state so silent failures are visible.+ if (url != null && url.contains("google.") && view != null) {+ val v = view+ installNetDiag(v)+ v.postDelayed({+ try {+ val resJs = """+ (function() {+ try {+ var noise = ['xjs', '/log', 'gen_204', 'client_204', 'folsrch', 'sprites', '.css', '.woff', '.ttf'];+ var r = performance.getEntriesByType('resource')+ .filter(function(e) {+ var n = e.name;+ var host = n.indexOf('google') >= 0 || n.indexOf('gstatic') >= 0;+ var bad = noise.some(function(s) { return n.indexOf(s) >= 0; });+ return host && !bad;+ })+ .slice(-40)+ .map(function(e) { return (e.responseStatus || '?') + ' ' + e.name.split('?')[0].slice(0, 110); })+ .join(String.fromCharCode(10));+ return r || 'NO_GOOGLE_RESOURCES';+ } catch (err) { return 'SNAP_ERR ' + err; }+ })()+ """.trimIndent()+ v.evaluateJavascript(resJs) { r ->+ android.util.Log.d("LensDiag", "GOOGLE_RES $r")+ }+ val envJs = """+ (function() {+ try {+ var d = {+ ua: (navigator.userAgent || '').slice(0, 110),+ brands: navigator.userAgentData ? navigator.userAgentData.brands : 'NO_UADATA',+ mobile: navigator.userAgentData ? navigator.userAgentData.mobile : '?',+ platform: navigator.userAgentData ? navigator.userAgentData.platform : '?',+ chrome: typeof window.chrome === 'undefined' ? 'UNDEFINED' : Object.keys(window.chrome).join(','),+ webdriver: navigator.webdriver,+ cookies: (document.cookie || '').slice(0, 300)+ };+ return JSON.stringify(d);+ } catch (err) { return 'ENV_ERR ' + err; }+ })()+ """.trimIndent()+ v.evaluateJavascript(envJs) { r ->+ android.util.Log.d("LensDiag", "GOOGLE_ENV $r")+ }+ val bodyJs = """+ (function() {+ try {+ var txt = (document.body.innerText || '').replace(/\s+/g, ' ').slice(0, 450);+ return location.href.slice(0, 250) + ' >> ' + document.title + ' >> ' + txt;+ } catch (err) { return 'SNAP_ERR ' + err; }+ })()+ """.trimIndent()+ v.postDelayed({+ try {+ v.evaluateJavascript(bodyJs) { r ->+ android.util.Log.d("LensDiag", "GOOGLE_BODY $r")+ }+ android.util.Log.d("LensDiag", "GOOGLE_COOKIES ${android.webkit.CookieManager.getInstance().getCookie("https://lens.google.com")}")+ } catch (e: Exception) { android.util.Log.e("LensDiag", "snap failed", e) }+ }, 3000)+ } catch (e: Exception) {+ android.util.Log.e("LensDiag", "snapshot failed", e)+ }+ }, 4000)+ }// Inject dark mode CSS if enabledif (isDarkMode) {val darkModeCSS = """- javascript:(function() {+ (function() {var style = document.createElement('style');style.innerHTML = `html { filter: invert(1) hue-rotate(180deg) !important; background: #000 !important; }@@ -803,11 +944,25 @@ fun CircleToSearchScreen(document.head.appendChild(style);})()""".trimIndent()- view?.loadUrl(darkModeCSS)+ view?.evaluateJavascript(darkModeCSS, null)android.util.Log.d("CircleToSearch", "Dark mode CSS injected for: $url")}}}+ webChromeClient = object : android.webkit.WebChromeClient() {+ override fun onConsoleMessage(consoleMessage: android.webkit.ConsoleMessage?): Boolean {+ val msg = consoleMessage?.message() ?: return super.onConsoleMessage(consoleMessage)+ val isNet = msg.contains("NET ") || msg.contains("NETBODY")+ val isGoogleSrc = consoleMessage.sourceId()?.contains("google") == true+ when {+ consoleMessage.messageLevel() == android.webkit.ConsoleMessage.MessageLevel.ERROR ->+ android.util.Log.e("LensDiag", "JS $msg @${consoleMessage.sourceId()}:${consoleMessage.lineNumber()}")+ consoleMessage.messageLevel() == android.webkit.ConsoleMessage.MessageLevel.WARNING && (isNet || isGoogleSrc) ->+ android.util.Log.w("LensDiag", "JSW $msg")+ }+ return super.onConsoleMessage(consoleMessage)+ }+ }isNestedScrollingEnabled = truesetOnTouchListener { v, event ->when (event.action) {diff --git a/app/src/main/java/com/akslabs/circletosearch/utils/ImageSearchUploader.kt b/app/src/main/java/com/akslabs/circletosearch/utils/ImageSearchUploader.ktindex 81ffa14..76ae869 100644--- a/app/src/main/java/com/akslabs/circletosearch/utils/ImageSearchUploader.kt+++ b/app/src/main/java/com/akslabs/circletosearch/utils/ImageSearchUploader.kt@@ -36,37 +36,58 @@ object ImageSearchUploader {private const val TIMEOUT = 30000/**- * Uploads the bitmap to Litterbox (1-hour temporary storage) with Catbox as fallback.- * Litterbox is used for privacy as images auto-delete after 1 hour.+ * Uploads the bitmap to imgdb.io (1-hour TTL) with Litterbox (1h) as+ * fallback. No permanent host is used: every upload must expire within+ * 1 hour. Returns a valid https URL, or null if both hosts fail.*/suspend fun uploadToImageHost(bitmap: Bitmap): String? = withContext(Dispatchers.IO) {- // Try Litterbox first (temporary, privacy-focused)+ // Try imgdb.io first (explicit 1h TTL, verified below)+ val imgdbUrl = uploadToImgdb(bitmap)+ if (imgdbUrl != null) {+ Log.d(TAG, "Successfully uploaded to imgdb.io (1h expiration)")+ return@withContext imgdbUrl+ }++ // Fallback to Litterbox (1h expiration)+ Log.w(TAG, "imgdb.io failed, falling back to Litterbox")val litterboxUrl = uploadToLitterbox(bitmap)if (litterboxUrl != null) {Log.d(TAG, "Successfully uploaded to Litterbox (1h expiration)")return@withContext litterboxUrl}-- // Fallback to Catbox if Litterbox fails- Log.w(TAG, "Litterbox failed, falling back to Catbox")- val catboxUrl = uploadToCatbox(bitmap)- if (catboxUrl != null) {- Log.d(TAG, "Successfully uploaded to Catbox (fallback)")- return@withContext catboxUrl- }-- Log.e(TAG, "Both Litterbox and Catbox uploads failed")++ Log.e(TAG, "Both imgdb.io and Litterbox uploads failed")null}-++ private fun compressForUpload(bitmap: Bitmap): ByteArray {+ val resized = ImageUtils.resizeBitmap(bitmap, 1280)+ val outputStream = ByteArrayOutputStream()+ resized.compress(Bitmap.CompressFormat.JPEG, 90, outputStream)+ return outputStream.toByteArray()+ }++ private fun validHttpsUrl(candidate: String?): String? {+ val url = candidate?.trim()+ return if (url != null && url.startsWith("https://") && !url.contains(Regex("\\s"))) {+ url+ } else {+ Log.e(TAG, "Host returned invalid URL: $candidate")+ null+ }+ }+/**- * Uploads to Litterbox.catbox.moe with 1-hour expiration for privacy+ * Uploads to imgdb.io with an explicit 1-hour TTL (ttl=3600). The+ * response's `expires` field is verified to be at most ~1 hour ahead —+ * if the server ever ignored the TTL, the link is rejected rather than+ * used beyond the promised lifetime.*/- private suspend fun uploadToLitterbox(bitmap: Bitmap): String? = withContext(Dispatchers.IO) {+ private suspend fun uploadToImgdb(bitmap: Bitmap): String? = withContext(Dispatchers.IO) {try {val boundary = "----WebKitFormBoundary" + UUID.randomUUID().toString().replace("-", "")- val url = URL("https://litterbox.catbox.moe/resources/internals/api.php")-+ val url = URL("https://imgdb.io/api/v1/upload?ttl=3600")+val connection = (url.openConnection() as HttpURLConnection).apply {requestMethod = "POST"doOutput = true@@ -77,60 +98,55 @@ object ImageSearchUploader {setRequestProperty("User-Agent", USER_AGENT)setRequestProperty("Content-Type", "multipart/form-data; boundary=$boundary")}-- // Resize and compress image- val resized = ImageUtils.resizeBitmap(bitmap, 1280)- val outputStream = ByteArrayOutputStream()- resized.compress(Bitmap.CompressFormat.JPEG, 90, outputStream)- val imageBytes = outputStream.toByteArray()-- Log.d(TAG, "Uploading to Litterbox: ${imageBytes.size} bytes")-++ val imageBytes = compressForUpload(bitmap)+ Log.d(TAG, "Uploading to imgdb.io: ${imageBytes.size} bytes (ttl=3600s)")+DataOutputStream(connection.outputStream).use { dos ->- // reqtype=fileupload- dos.writeBytes("--$boundary\r\n")- dos.writeBytes("Content-Disposition: form-data; name=\"reqtype\"\r\n\r\n")- dos.writeBytes("fileupload\r\n")-- // time=1h (1 hour expiration)dos.writeBytes("--$boundary\r\n")- dos.writeBytes("Content-Disposition: form-data; name=\"time\"\r\n\r\n")- dos.writeBytes("1h\r\n")-- // fileToUpload- dos.writeBytes("--$boundary\r\n")- dos.writeBytes("Content-Disposition: form-data; name=\"fileToUpload\"; filename=\"image.jpg\"\r\n")+ dos.writeBytes("Content-Disposition: form-data; name=\"file\"; filename=\"image.jpg\"\r\n")dos.writeBytes("Content-Type: image/jpeg\r\n\r\n")dos.write(imageBytes)dos.writeBytes("\r\n")-dos.writeBytes("--$boundary--\r\n")dos.flush()}-+val responseCode = connection.responseCode- if (responseCode == 200) {- val imageUrl = connection.inputStream.bufferedReader().use { it.readText() }- Log.d(TAG, "Litterbox URL: $imageUrl (expires in 1h)")- imageUrl- } else {- Log.e(TAG, "Litterbox upload failed: $responseCode")- null+ val body = (if (responseCode in 200..299) connection.inputStream else connection.errorStream)+ ?.bufferedReader()?.use { it.readText() }+ if (responseCode !in 200..299) {+ Log.e(TAG, "imgdb.io upload failed: $responseCode $body")+ return@withContext null+ }++ val json = org.json.JSONObject(body ?: "")+ val imageUrl = validHttpsUrl(json.optString("url").ifEmpty { null })+ ?: return@withContext null++ // Enforce the 1-hour lifetime: reject anything expiring later.+ val expires = json.optLong("expires", -1L)+ val now = System.currentTimeMillis() / 1000+ if (expires <= 0 || expires - now > 3600 + 60) {+ Log.e(TAG, "imgdb.io link exceeds 1h lifetime (expires=$expires), rejecting")+ return@withContext null}+ Log.d(TAG, "imgdb.io URL: $imageUrl (expires in ${expires - now}s)")+ imageUrl} catch (e: Exception) {- Log.e(TAG, "Litterbox upload error", e)+ Log.e(TAG, "imgdb.io upload error", e)null}}-+/**- * Fallback: Uploads to Catbox.moe (permanent storage)+ * Uploads to Litterbox.catbox.moe with 1-hour expiration for privacy*/- private suspend fun uploadToCatbox(bitmap: Bitmap): String? = withContext(Dispatchers.IO) {+ private suspend fun uploadToLitterbox(bitmap: Bitmap): String? = withContext(Dispatchers.IO) {try {val boundary = "----WebKitFormBoundary" + UUID.randomUUID().toString().replace("-", "")- val url = URL("https://catbox.moe/user/api.php")-+ val url = URL("https://litterbox.catbox.moe/resources/internals/api.php")+val connection = (url.openConnection() as HttpURLConnection).apply {requestMethod = "POST"doOutput = true@@ -141,43 +157,44 @@ object ImageSearchUploader {setRequestProperty("User-Agent", USER_AGENT)setRequestProperty("Content-Type", "multipart/form-data; boundary=$boundary")}-- // Resize and compress image- val resized = ImageUtils.resizeBitmap(bitmap, 1280)- val outputStream = ByteArrayOutputStream()- resized.compress(Bitmap.CompressFormat.JPEG, 90, outputStream)- val imageBytes = outputStream.toByteArray()-- Log.d(TAG, "Uploading to Catbox: ${imageBytes.size} bytes")-++ val imageBytes = compressForUpload(bitmap)+ Log.d(TAG, "Uploading to Litterbox: ${imageBytes.size} bytes")+DataOutputStream(connection.outputStream).use { dos ->// reqtype=fileuploaddos.writeBytes("--$boundary\r\n")dos.writeBytes("Content-Disposition: form-data; name=\"reqtype\"\r\n\r\n")dos.writeBytes("fileupload\r\n")-++ // time=1h (1 hour expiration)+ dos.writeBytes("--$boundary\r\n")+ dos.writeBytes("Content-Disposition: form-data; name=\"time\"\r\n\r\n")+ dos.writeBytes("1h\r\n")+// fileToUploaddos.writeBytes("--$boundary\r\n")dos.writeBytes("Content-Disposition: form-data; name=\"fileToUpload\"; filename=\"image.jpg\"\r\n")dos.writeBytes("Content-Type: image/jpeg\r\n\r\n")dos.write(imageBytes)dos.writeBytes("\r\n")-+dos.writeBytes("--$boundary--\r\n")dos.flush()}-+val responseCode = connection.responseCode- if (responseCode == 200) {- val imageUrl = connection.inputStream.bufferedReader().use { it.readText() }- Log.d(TAG, "Catbox URL: $imageUrl")+ if (responseCode in 200..299) {+ val raw = connection.inputStream.bufferedReader().use { it.readText() }+ val imageUrl = validHttpsUrl(raw)+ if (imageUrl != null) Log.d(TAG, "Litterbox URL: $imageUrl (expires in 1h)")imageUrl} else {- Log.e(TAG, "Catbox upload failed: $responseCode")+ Log.e(TAG, "Litterbox upload failed: $responseCode")null}} catch (e: Exception) {- Log.e(TAG, "Catbox upload error", e)+ Log.e(TAG, "Litterbox upload error", e)null}}@@ -186,10 +203,7 @@ object ImageSearchUploader {fun getGoogleLensUrl(imageUrl: String): String {val encodedUrl = URLEncoder.encode(imageUrl, "UTF-8")- // Pin the results locale to the device language so Google serves a stable,- // region-consistent experience instead of redirecting to a localized homepage.- val hl = URLEncoder.encode(java.util.Locale.getDefault().toLanguageTag(), "UTF-8")- return "https://lens.google.com/uploadbyurl?url=$encodedUrl&hl=$hl"+ return "https://lens.google.com/uploadbyurl?url=$encodedUrl"}fun getGoogleImagesUrl(imageUrl: String): String {