Add bookmark import export packages

This commit is contained in:
2026-05-09 02:07:37 -04:00
parent 8d4d951ab8
commit 1eb8e271f5
10 changed files with 714 additions and 31 deletions
+3
View File
@@ -21,6 +21,9 @@ pub enum CoreError {
#[error("invalid .elyspace package: {reason}")]
InvalidSpacePackage { reason: String },
#[error("invalid .elybookmarks package: {reason}")]
InvalidBookmarkPackage { reason: String },
#[error("trashed space not found: {id}")]
TrashedSpaceNotFound { id: SpaceId },
+4 -3
View File
@@ -4,7 +4,8 @@ mod state;
pub use error::CoreError;
pub use state::{
BrowserCore, BrowserSnapshot, ELYSPACE_FILE_EXTENSION, ELYSPACE_SCHEMA_VERSION,
ElySpacePackage, InitialBrowserConfig, InstalledPlugin, PluginAuditAction, PluginAuditEvent,
SiteDataClearance, SpaceImportProfileMapping, TrashedSpace,
BookmarkImportSummary, BrowserCore, BrowserSnapshot, ELYBOOKMARKS_FILE_EXTENSION,
ELYBOOKMARKS_SCHEMA_VERSION, ELYSPACE_FILE_EXTENSION, ELYSPACE_SCHEMA_VERSION,
ElyBookmarksPackage, ElySpacePackage, InitialBrowserConfig, InstalledPlugin, PluginAuditAction,
PluginAuditEvent, SiteDataClearance, SpaceImportProfileMapping, TrashedSpace,
};
+4
View File
@@ -32,6 +32,10 @@ mod tab_order;
mod tab_selection;
mod tabs;
pub use bookmarks::{
BookmarkImportSummary, ELYBOOKMARKS_FILE_EXTENSION, ELYBOOKMARKS_SCHEMA_VERSION,
ElyBookmarksPackage,
};
pub use plugins::{InstalledPlugin, PluginAuditAction, PluginAuditEvent};
pub use site_data::SiteDataClearance;
pub use space_exports::{
+188 -2
View File
@@ -1,11 +1,69 @@
use std::time::SystemTime;
use std::{collections::BTreeSet, time::SystemTime};
use ely_domain::{BookmarkEntry, BookmarkId, UrlText};
use ely_domain::{BookmarkEntry, BookmarkId, SpaceId, UrlText};
use serde::{Deserialize, Serialize};
use crate::CoreError;
use super::BrowserCore;
pub const ELYBOOKMARKS_SCHEMA_VERSION: u16 = 1;
pub const ELYBOOKMARKS_FILE_EXTENSION: &str = "elybookmarks";
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
pub struct ElyBookmarksPackage {
version: u16,
bookmarks: Vec<ElyBookmarkRecord>,
}
impl ElyBookmarksPackage {
#[must_use]
pub fn version(&self) -> u16 {
self.version
}
#[must_use]
pub fn bookmark_count(&self) -> usize {
self.bookmarks.len()
}
}
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(deny_unknown_fields)]
struct ElyBookmarkRecord {
title: String,
url: String,
collection_name: String,
space_name: String,
tags: Vec<String>,
note: Option<String>,
thumbnail_key: Option<String>,
}
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
pub struct BookmarkImportSummary {
imported: usize,
skipped: usize,
}
impl BookmarkImportSummary {
#[must_use]
pub fn imported(self) -> usize {
self.imported
}
#[must_use]
pub fn skipped(self) -> usize {
self.skipped
}
#[must_use]
pub fn label(self) -> String {
format!("Imported {} bookmarks, skipped {}", self.imported, self.skipped)
}
}
impl BrowserCore {
pub fn bookmark_active_tab(&mut self) -> Result<BookmarkId, CoreError> {
let active_tab = self.active_tab()?.clone();
@@ -102,6 +160,66 @@ impl BrowserCore {
Ok(())
}
pub fn export_bookmarks_package_json(&self) -> Result<String, CoreError> {
serde_json::to_string_pretty(&self.export_bookmarks_package()?)
.map_err(invalid_bookmark_package)
}
pub fn export_bookmarks_package(&self) -> Result<ElyBookmarksPackage, CoreError> {
let bookmarks = self
.bookmarks
.iter()
.filter(|bookmark| bookmark.profile_id() == &self.active_profile_id)
.map(|bookmark| {
self.bookmark_space_name(bookmark.space_id())
.map(|space_name| ElyBookmarkRecord::from_bookmark(bookmark, space_name))
})
.collect::<Result<Vec<_>, _>>()?;
Ok(ElyBookmarksPackage { version: ELYBOOKMARKS_SCHEMA_VERSION, bookmarks })
}
pub fn import_bookmarks_package_json(
&mut self,
package_json: &str,
) -> Result<BookmarkImportSummary, CoreError> {
let package = serde_json::from_str(package_json).map_err(invalid_bookmark_package)?;
self.import_bookmarks_package(package)
}
pub fn import_bookmarks_package(
&mut self,
package: ElyBookmarksPackage,
) -> Result<BookmarkImportSummary, CoreError> {
validate_bookmark_package_version(package.version)?;
let active_profile_id = self.active_profile_id.clone();
let mut seen = self
.bookmarks
.iter()
.filter(|bookmark| bookmark.profile_id() == &active_profile_id)
.map(|bookmark| bookmark_identity(bookmark.space_id(), bookmark.url()))
.collect::<BTreeSet<_>>();
let mut imported_bookmarks = Vec::new();
let mut skipped = 0;
for record in package.bookmarks {
let space_id = self.import_bookmark_space_id(&record.space_name);
let url = UrlText::parse(&record.url)?;
let identity = bookmark_identity(&space_id, &url);
if !seen.insert(identity) {
skipped += 1;
continue;
}
imported_bookmarks.push(record.into_bookmark(active_profile_id.clone(), space_id)?);
}
let imported = imported_bookmarks.len();
self.bookmarks.extend(imported_bookmarks);
Ok(BookmarkImportSummary { imported, skipped })
}
pub(super) fn find_bookmark_match(&self, query: &str) -> Option<UrlText> {
let normalized_query = query.trim().to_lowercase();
if normalized_query.is_empty() {
@@ -130,6 +248,21 @@ impl BrowserCore {
.find(|bookmark| bookmark.id() == bookmark_id)
.ok_or_else(|| CoreError::BookmarkNotFound { id: bookmark_id.clone() })
}
fn bookmark_space_name(&self, space_id: &SpaceId) -> Result<String, CoreError> {
self.spaces
.iter()
.find(|space| space.id() == space_id)
.map(|space| space.name().to_string())
.ok_or_else(|| CoreError::SpaceNotFound { id: space_id.clone() })
}
fn import_bookmark_space_id(&self, space_name: &str) -> SpaceId {
self.spaces
.iter()
.find(|space| space.name().eq_ignore_ascii_case(space_name.trim()))
.map_or_else(|| self.active_space_id.clone(), |space| space.id().clone())
}
}
fn bookmark_matches_query(bookmark: &BookmarkEntry, normalized_query: &str) -> bool {
@@ -140,3 +273,56 @@ fn bookmark_matches_query(bookmark: &BookmarkEntry, normalized_query: &str) -> b
|| bookmark.tags().iter().any(|tag| tag.to_lowercase().contains(normalized_query))
|| bookmark.note().is_some_and(|note| note.to_lowercase().contains(normalized_query))
}
impl ElyBookmarkRecord {
fn from_bookmark(bookmark: &BookmarkEntry, space_name: String) -> Self {
Self {
title: bookmark.title().to_string(),
url: bookmark.url().as_str().to_string(),
collection_name: bookmark.collection_name().to_string(),
space_name,
tags: bookmark.tags().to_vec(),
note: bookmark.note().map(str::to_string),
thumbnail_key: bookmark.thumbnail_key().map(str::to_string),
}
}
fn into_bookmark(
self,
profile_id: ely_domain::ProfileId,
space_id: SpaceId,
) -> Result<BookmarkEntry, CoreError> {
let mut bookmark = BookmarkEntry::new(
profile_id,
space_id,
self.collection_name,
self.title,
UrlText::parse(self.url)?,
SystemTime::now(),
)?;
bookmark.set_tags(self.tags)?;
if let Some(note) = self.note {
bookmark.set_note(note)?;
}
if let Some(thumbnail_key) = self.thumbnail_key {
bookmark.set_thumbnail_key(thumbnail_key)?;
}
Ok(bookmark)
}
}
fn bookmark_identity(space_id: &SpaceId, url: &UrlText) -> (SpaceId, String) {
(space_id.clone(), url.as_str().to_string())
}
fn validate_bookmark_package_version(version: u16) -> Result<(), CoreError> {
if version == ELYBOOKMARKS_SCHEMA_VERSION {
Ok(())
} else {
Err(CoreError::InvalidBookmarkPackage { reason: format!("unsupported version {version}") })
}
}
fn invalid_bookmark_package(error: impl ToString) -> CoreError {
CoreError::InvalidBookmarkPackage { reason: error.to_string() }
}
@@ -247,6 +247,10 @@ impl BrowserCore {
self.open_tab(bookmarks_url()?);
Ok(true)
}
"export-bookmarks" | "export bookmarks" | "import-bookmarks" | "import bookmarks" => {
self.open_tab(bookmarks_url()?);
Ok(true)
}
"reading-list" | "open-reading-list" | "open reading list" => {
self.open_tab(reading_list_url()?);
Ok(true)
+116 -1
View File
@@ -1,7 +1,8 @@
use std::error::Error;
use ely_browser_core::{BrowserCore, CoreError, InitialBrowserConfig};
use ely_browser_core::{BrowserCore, CoreError, ELYBOOKMARKS_SCHEMA_VERSION, InitialBrowserConfig};
use ely_domain::{BookmarkId, CommandIntent, CommandScope, DomainError, ProfileKind, UrlText};
use serde_json::Value;
#[test]
fn bookmark_active_tab_records_current_context() -> Result<(), Box<dyn Error>> {
@@ -240,3 +241,117 @@ fn open_bookmarks_command_opens_bookmarks_page() -> Result<(), Box<dyn Error>> {
assert_eq!(core.snapshot()?.command_query, "");
Ok(())
}
#[test]
fn export_bookmarks_package_json_contains_active_profile_bookmarks() -> Result<(), Box<dyn Error>> {
let mut core = BrowserCore::new(InitialBrowserConfig::ely_defaults()?)?;
let default_profile_id = core.snapshot()?.active_profile_id;
core.open_tab(UrlText::parse("https://example.com/research")?);
let bookmark_id = core.bookmark_active_tab()?;
core.set_bookmark_collection_name(&bookmark_id, "Research")?;
core.set_bookmark_tags(&bookmark_id, vec!["rust".to_string(), "gpui".to_string()])?;
core.set_bookmark_note(&bookmark_id, "Servo reference")?;
core.set_bookmark_thumbnail_key(&bookmark_id, "screenshots/example.avif")?;
core.create_profile("Personal", 0xf54e00, ProfileKind::Standard)?;
core.open_tab(UrlText::parse("https://example.com/personal")?);
core.bookmark_active_tab()?;
core.select_profile(&default_profile_id)?;
let package = core.export_bookmarks_package()?;
let package_json = core.export_bookmarks_package_json()?;
let value: Value = serde_json::from_str(&package_json)?;
let bookmarks = value["bookmarks"].as_array().ok_or("missing bookmarks array")?;
assert_eq!(package.version(), ELYBOOKMARKS_SCHEMA_VERSION);
assert_eq!(package.bookmark_count(), 1);
assert_eq!(bookmarks.len(), 1);
assert_eq!(bookmarks[0]["title"], "example.com");
assert_eq!(bookmarks[0]["url"], "https://example.com/research");
assert_eq!(bookmarks[0]["collection_name"], "Research");
assert_eq!(bookmarks[0]["space_name"], "Work");
assert_eq!(bookmarks[0]["tags"], serde_json::json!(["rust", "gpui"]));
assert_eq!(bookmarks[0]["note"], "Servo reference");
assert_eq!(bookmarks[0]["thumbnail_key"], "screenshots/example.avif");
Ok(())
}
#[test]
fn import_bookmarks_package_json_creates_active_profile_bookmarks() -> Result<(), Box<dyn Error>> {
let mut source = BrowserCore::new(InitialBrowserConfig::ely_defaults()?)?;
source.open_tab(UrlText::parse("https://example.com/research")?);
let bookmark_id = source.bookmark_active_tab()?;
source.set_bookmark_collection_name(&bookmark_id, "Research")?;
source.set_bookmark_tags(&bookmark_id, vec!["rust".to_string()])?;
source.set_bookmark_note(&bookmark_id, "Read later")?;
let package_json = source.export_bookmarks_package_json()?;
let mut target = BrowserCore::new(InitialBrowserConfig::ely_defaults()?)?;
let active_profile_id = target.snapshot()?.active_profile_id;
let active_space_id = target.snapshot()?.active_space_id;
let summary = target.import_bookmarks_package_json(&package_json)?;
let snapshot = target.snapshot()?;
assert_eq!(summary.imported(), 1);
assert_eq!(summary.skipped(), 0);
assert_eq!(summary.label(), "Imported 1 bookmarks, skipped 0");
assert_eq!(snapshot.bookmarks.len(), 1);
assert_eq!(snapshot.bookmarks[0].profile_id(), &active_profile_id);
assert_eq!(snapshot.bookmarks[0].space_id(), &active_space_id);
assert_eq!(snapshot.bookmarks[0].collection_name(), "Research");
assert_eq!(snapshot.bookmarks[0].tags(), &["rust".to_string()]);
assert_eq!(snapshot.bookmarks[0].note(), Some("Read later"));
Ok(())
}
#[test]
fn import_bookmarks_package_skips_duplicate_active_profile_urls() -> Result<(), Box<dyn Error>> {
let mut source = BrowserCore::new(InitialBrowserConfig::ely_defaults()?)?;
source.open_tab(UrlText::parse("https://example.com/research")?);
source.bookmark_active_tab()?;
let package_json = source.export_bookmarks_package_json()?;
let mut target = BrowserCore::new(InitialBrowserConfig::ely_defaults()?)?;
target.open_tab(UrlText::parse("https://example.com/research")?);
target.bookmark_active_tab()?;
let summary = target.import_bookmarks_package_json(&package_json)?;
assert_eq!(summary.imported(), 0);
assert_eq!(summary.skipped(), 1);
assert_eq!(target.snapshot()?.bookmarks.len(), 1);
Ok(())
}
#[test]
fn import_bookmarks_package_rejects_unknown_fields() -> Result<(), Box<dyn Error>> {
let mut core = BrowserCore::new(InitialBrowserConfig::ely_defaults()?)?;
let package_json = r#"{
"version": 1,
"unexpected": true,
"bookmarks": []
}"#;
let Err(error) = core.import_bookmarks_package_json(package_json) else {
return Err("expected invalid bookmark package".into());
};
assert!(matches!(error, CoreError::InvalidBookmarkPackage { .. }));
Ok(())
}
#[test]
fn bookmark_file_commands_open_bookmarks_page() -> Result<(), Box<dyn Error>> {
let mut core = BrowserCore::new(InitialBrowserConfig::ely_defaults()?)?;
core.set_command_query(">export-bookmarks");
let export_intent = core.submit_command()?;
assert_eq!(export_intent, Some(CommandIntent::Command("export-bookmarks".to_string())));
assert_eq!(core.active_tab()?.url().as_str(), "ely://bookmarks");
core.set_command_query(">import-bookmarks");
let import_intent = core.submit_command()?;
assert_eq!(import_intent, Some(CommandIntent::Command("import-bookmarks".to_string())));
assert_eq!(core.active_tab()?.title(), "Bookmarks");
assert_eq!(core.snapshot()?.command_query, "");
Ok(())
}