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
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ import com.duckduckgo.savedsites.api.models.SavedSite.Bookmark
import com.duckduckgo.savedsites.api.models.SavedSite.Favorite
import com.duckduckgo.savedsites.api.models.SavedSitesNames
import com.duckduckgo.savedsites.api.models.TreeNode
import com.duckduckgo.savedsites.api.service.SavedSitesImporter.ImportFolder
import com.duckduckgo.savedsites.impl.MissingEntitiesRelationReconciler
import com.duckduckgo.savedsites.impl.RealFavoritesDelegate
import com.duckduckgo.savedsites.impl.RealSavedSitesRepository
Expand Down Expand Up @@ -156,7 +157,7 @@ class SavedSitesParserTest {
val inputStream = FileUtilities.loadResource(javaClass.classLoader!!, "bookmarks/bookmarks_invalid.html")
val document = Jsoup.parse(inputStream, Charsets.UTF_8.name(), "duckduckgo.com")

val bookmarks = parser.parseHtml(document, repository)
val bookmarks = parser.parseHtml(document, repository, ImportFolder.Root)

assertTrue(bookmarks.isEmpty())
}
Expand All @@ -166,7 +167,7 @@ class SavedSitesParserTest {
val inputStream = FileUtilities.loadResource(javaClass.classLoader!!, "bookmarks/bookmarks_firefox.html")
val document = Jsoup.parse(inputStream, Charsets.UTF_8.name(), "duckduckgo.com")

val bookmarks = parser.parseHtml(document, repository).filterIsInstance<Bookmark>()
val bookmarks = parser.parseHtml(document, repository, ImportFolder.Root).filterIsInstance<Bookmark>()

assertEquals(17, bookmarks.size)

Expand All @@ -185,7 +186,7 @@ class SavedSitesParserTest {
val inputStream = FileUtilities.loadResource(javaClass.classLoader!!, "bookmarks/bookmarks_brave.html")
val document = Jsoup.parse(inputStream, Charsets.UTF_8.name(), "duckduckgo.com")

val bookmarks = parser.parseHtml(document, repository).filterIsInstance<Bookmark>()
val bookmarks = parser.parseHtml(document, repository, ImportFolder.Root).filterIsInstance<Bookmark>()

assertEquals(12, bookmarks.size)

Expand All @@ -206,7 +207,7 @@ class SavedSitesParserTest {
val inputStream = FileUtilities.loadResource(javaClass.classLoader!!, "bookmarks/bookmarks_chrome.html")
val document = Jsoup.parse(inputStream, Charsets.UTF_8.name(), "duckduckgo.com")

val bookmarks = parser.parseHtml(document, repository).filterIsInstance<Bookmark>()
val bookmarks = parser.parseHtml(document, repository, ImportFolder.Root).filterIsInstance<Bookmark>()

assertEquals(12, bookmarks.size)

Expand All @@ -228,7 +229,7 @@ class SavedSitesParserTest {
val inputStream = FileUtilities.loadResource(javaClass.classLoader!!, "bookmarks/bookmarks_ddg_android.html")
val document = Jsoup.parse(inputStream, Charsets.UTF_8.name(), "duckduckgo.com")

val bookmarks = parser.parseHtml(document, repository).filterNot { it is BookmarkFolder }
val bookmarks = parser.parseHtml(document, repository, ImportFolder.Root).filterNot { it is BookmarkFolder }

assertEquals(13, bookmarks.size)

Expand All @@ -250,7 +251,7 @@ class SavedSitesParserTest {
val inputStream = FileUtilities.loadResource(javaClass.classLoader!!, "bookmarks/bookmarks_ddg_macos.html")
val document = Jsoup.parse(inputStream, Charsets.UTF_8.name(), "duckduckgo.com")

val bookmarks = parser.parseHtml(document, repository).filterIsInstance<Bookmark>()
val bookmarks = parser.parseHtml(document, repository, ImportFolder.Root).filterIsInstance<Bookmark>()

assertEquals(13, bookmarks.size)

Expand All @@ -273,7 +274,7 @@ class SavedSitesParserTest {
val inputStream = FileUtilities.loadResource(javaClass.classLoader!!, "bookmarks/bookmarks_safari.html")
val document = Jsoup.parse(inputStream, Charsets.UTF_8.name(), "duckduckgo.com")

val bookmarks = parser.parseHtml(document, repository).filterIsInstance<Bookmark>()
val bookmarks = parser.parseHtml(document, repository, ImportFolder.Root).filterIsInstance<Bookmark>()

assertEquals(14, bookmarks.size)

Expand All @@ -295,7 +296,7 @@ class SavedSitesParserTest {
val inputStream = FileUtilities.loadResource(javaClass.classLoader!!, "bookmarks/bookmarks_favorites_ddg.html")
val document = Jsoup.parse(inputStream, Charsets.UTF_8.name(), "duckduckgo.com")

val savedSites = parser.parseHtml(document, repository)
val savedSites = parser.parseHtml(document, repository, ImportFolder.Root)

val favorites = savedSites.filterIsInstance<Favorite>()
val bookmarks = savedSites.filterIsInstance<Bookmark>()
Expand Down Expand Up @@ -367,4 +368,29 @@ class SavedSitesParserTest {
assertEquals(3, favoritesLists.size)
assertEquals(9, bookmarks.size)
}

@Test
fun canImportBookmarksWithDestinationFolder() = runTest {
val inputStream = FileUtilities.loadResource(javaClass.classLoader!!, "bookmarks/bookmarks_chrome.html")
val document = Jsoup.parse(inputStream, Charsets.UTF_8.name(), "duckduckgo.com")

val folderName = "Imported Bookmarks"
val savedSites = parser.parseHtml(document, repository, ImportFolder.Folder(folderName))
val bookmarks = savedSites.filterIsInstance<Bookmark>()

// Should import bookmarks successfully
assertTrue("Should import bookmarks with folder destination", bookmarks.isNotEmpty())

// Verify that a destination folder was created in the repository
val createdFolders = repository.getFolderTreeItems(SavedSitesNames.BOOKMARKS_ROOT)
.filter { it.name == folderName && it.url == null }

assertTrue("Should create destination folder in repository", createdFolders.isNotEmpty())

val destinationFolderId = createdFolders.first().id

// Verify that bookmarks reference the destination folder as their parent
val bookmarksInDestinationFolder = bookmarks.filter { it.parentId == destinationFolderId }
assertTrue("Bookmarks should be placed in destination folder", bookmarksInDestinationFolder.isNotEmpty())
}
}
1 change: 1 addition & 0 deletions autofill/autofill-impl/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@ dependencies {
testImplementation project(':feature-toggles-test')
implementation project(path: ':settings-api') // temporary until we release new settings
implementation project(':library-loader-api')
implementation project(':saved-sites-api')

anvil project(path: ':anvil-compiler')
implementation project(path: ':anvil-annotations')
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
/*
* Copyright (c) 2025 DuckDuckGo
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package com.duckduckgo.autofill.impl.importing.takeout.processor

import android.net.Uri
import com.duckduckgo.common.utils.DispatcherProvider
import com.duckduckgo.di.scopes.AppScope
import com.duckduckgo.savedsites.api.service.ImportSavedSitesResult
import com.duckduckgo.savedsites.api.service.SavedSitesImporter
import com.duckduckgo.savedsites.api.service.SavedSitesImporter.ImportFolder
import com.squareup.anvil.annotations.ContributesBinding
import java.io.File
import javax.inject.Inject
import kotlinx.coroutines.withContext

/**
* Interface for importing bookmarks with flexible destination handling.
* Supports both root-level imports and folder-based imports while preserving structure.
*/
interface TakeoutBookmarkImporter {

/**
* Imports bookmarks from HTML content to the specified destination.
* @param htmlContent The HTML bookmark content to import (in Netscape format)
* @param destination Where to import the bookmarks (Root or named Folder within bookmarks root)
* @return ImportSavedSitesResult indicating success with imported items or error
*/
suspend fun importBookmarks(htmlContent: String, destination: ImportFolder): ImportSavedSitesResult
}

@ContributesBinding(AppScope::class)
class RealTakeoutBookmarkImporter @Inject constructor(
private val savedSitesImporter: SavedSitesImporter,
private val dispatchers: DispatcherProvider,
) : TakeoutBookmarkImporter {

override suspend fun importBookmarks(htmlContent: String, destination: ImportFolder): ImportSavedSitesResult {
return withContext(dispatchers.io()) {
import(htmlContent = htmlContent, destination = destination)
}
}

private suspend fun import(htmlContent: String, destination: ImportFolder = ImportFolder.Root): ImportSavedSitesResult {
return try {
// saved sites importer needs a file uri, so we create a temp file here
val tempFile = File.createTempFile("bookmark_import_", ".html")
try {
tempFile.writeText(htmlContent)
return savedSitesImporter.import(Uri.fromFile(tempFile), destination)
} finally {
// delete the temp file after import
tempFile.takeIf { it.exists() }?.delete()
}
} catch (exception: Exception) {
ImportSavedSitesResult.Error(exception)
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,103 @@
/*
* Copyright (c) 2025 DuckDuckGo
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package com.duckduckgo.autofill.impl.importing.takeout.zip

import android.content.Context
import android.net.Uri
import com.duckduckgo.autofill.impl.importing.takeout.zip.TakeoutBookmarkExtractor.ExtractionResult
import com.duckduckgo.autofill.impl.importing.takeout.zip.ZipEntryContentReader.ReadResult
import com.duckduckgo.common.utils.DispatcherProvider
import com.duckduckgo.di.scopes.AppScope
import com.squareup.anvil.annotations.ContributesBinding
import java.util.zip.ZipEntry
import java.util.zip.ZipInputStream
import javax.inject.Inject
import kotlinx.coroutines.withContext
import logcat.LogPriority.WARN
import logcat.logcat

interface TakeoutBookmarkExtractor {

sealed class ExtractionResult {
data class Success(val bookmarkHtmlContent: String) : ExtractionResult() {
override fun toString(): String {
return "ExtractionResult=success"
}
}
data class Error(val exception: Exception) : ExtractionResult()
}

/**
* Extracts the bookmark HTML content from the provided Google Takeout ZIP file URI.
* @param fileUri The URI of the Google Takeout ZIP file containing the bookmarks.
* @return ExtractionResult containing either the bookmark HTML content or an error.
*/
suspend fun extractBookmarksHtml(fileUri: Uri): ExtractionResult
}

@ContributesBinding(AppScope::class)
class TakeoutZipBookmarkExtractor @Inject constructor(
private val context: Context,
private val dispatchers: DispatcherProvider,
private val zipEntryContentReader: ZipEntryContentReader,
) : TakeoutBookmarkExtractor {

override suspend fun extractBookmarksHtml(fileUri: Uri): ExtractionResult {
return withContext(dispatchers.io()) {
runCatching {
context.contentResolver.openInputStream(fileUri)?.use { inputStream ->
ZipInputStream(inputStream).use { zipInputStream ->
processZipEntries(zipInputStream)
}
} ?: ExtractionResult.Error(Exception("Unable to open file: $fileUri"))
}.getOrElse { ExtractionResult.Error(Exception(it)) }
}
}

private fun processZipEntries(zipInputStream: ZipInputStream): ExtractionResult {
var entry = zipInputStream.nextEntry

if (entry == null) {
logcat(WARN) { "No entries found in ZIP stream" }
return ExtractionResult.Error(Exception("Invalid or empty ZIP file"))
}

while (entry != null) {
val entryName = entry.name
logcat { "Processing zip entry '$entryName'" }

if (isBookmarkEntry(entry)) {
return when (val readResult = zipEntryContentReader.readAndValidateContent(zipInputStream, entryName)) {
is ReadResult.Success -> ExtractionResult.Success(readResult.content)
is ReadResult.Error -> ExtractionResult.Error(readResult.exception)
}
}

entry = zipInputStream.nextEntry
}

return ExtractionResult.Error(Exception("Chrome/Bookmarks.html not found in file"))
}

private fun isBookmarkEntry(entry: ZipEntry): Boolean {
return !entry.isDirectory && entry.name.endsWith(EXPECTED_BOOKMARKS_FILENAME, ignoreCase = true)
}

companion object {
private const val EXPECTED_BOOKMARKS_FILENAME = "Chrome/Bookmarks.html"
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
/*
* Copyright (c) 2025 DuckDuckGo
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package com.duckduckgo.autofill.impl.importing.takeout.zip

import com.duckduckgo.di.scopes.AppScope
import com.squareup.anvil.annotations.ContributesBinding
import java.util.zip.ZipInputStream
import javax.inject.Inject
import logcat.logcat

interface ZipEntryContentReader {

sealed class ReadResult {
data class Success(val content: String) : ReadResult()
data class Error(val exception: Exception) : ReadResult()
}

fun readAndValidateContent(
zipInputStream: ZipInputStream,
entryName: String,
): ReadResult
}

@ContributesBinding(AppScope::class)
class BookmarkZipEntryContentReader @Inject constructor() : ZipEntryContentReader {

override fun readAndValidateContent(
zipInputStream: ZipInputStream,
entryName: String,
): ZipEntryContentReader.ReadResult {
logcat { "Reading content from ZIP entry: '$entryName'" }

return try {
val content = readContent(zipInputStream, entryName)

if (isValidBookmarkContent(content)) {
logcat { "Content validation passed for: '$entryName'" }
ZipEntryContentReader.ReadResult.Success(content)
} else {
logcat { "Content validation failed for: '$entryName'" }
ZipEntryContentReader.ReadResult.Error(
Exception("File content is not a valid bookmark file"),
)
}
} catch (e: Exception) {
logcat { "Error reading ZIP entry content: ${e.message}" }
ZipEntryContentReader.ReadResult.Error(e)
}
}

private fun readContent(zipInputStream: ZipInputStream, entryName: String): String {
val content = zipInputStream.bufferedReader(Charsets.UTF_8).use { it.readText() }
logcat { "Read content from '$entryName', length: ${content.length}" }
return content
}

private fun isValidBookmarkContent(content: String): Boolean {
val hasNetscapeHeader = content.contains(NETSCAPE_HEADER, ignoreCase = true)
val hasBookmarkTitle = content.contains(BOOKMARK_TITLE, ignoreCase = true)

logcat { "Content validation: hasNetscapeHeader=$hasNetscapeHeader, hasBookmarkTitle=$hasBookmarkTitle" }

return hasNetscapeHeader || hasBookmarkTitle
}

companion object {
private const val NETSCAPE_HEADER = "<!DOCTYPE NETSCAPE-Bookmark-file"
private const val BOOKMARK_TITLE = "<title>Bookmarks</title>"
}
}
4 changes: 4 additions & 0 deletions autofill/autofill-impl/src/main/res/values/donottranslate.xml
Original file line number Diff line number Diff line change
Expand Up @@ -16,4 +16,8 @@

<resources>

<!-- Import Bookmarks Strings -->
<string name="autofillImportBookmarksChromeFolderName">Imported from Chrome</string>


</resources>
Loading
Loading