bookmark 0.1.4

Interactive bookmark manager with knowledge graph generation from browser bookmarks and history
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
# Architecture Documentation

## System Overview

Bookmark Exporter is a modular, cross-platform CLI application built with Rust that extracts browser data from multiple web browsers and converts it to structured YAML format.

## High-Level Architecture

```
┌─────────────────┐    ┌─────────────────┐    ┌─────────────────┐    ┌─────────────────┐
│   CLI Layer     │────│  Detection      │────│  Extraction     │────│   Output Layer  │
│ main.rs + cli.rs│    │  browser.rs     │    │  exporter/      │    │  graph/formats  │
└─────────────────┘    └─────────────────┘    └─────────────────┘    └─────────────────┘
         │                       │                       │                       │
         ▼                       ▼                       ▼                       ▼
┌─────────────────┐    ┌─────────────────┐    ┌─────────────────┐    ┌─────────────────┐
│  Command Parse  │    │  Browser Enum   │    │  chrome.rs      │    │  DOT/JSON/GEXF  │
│  Dispatch       │    │  Path Resolver  │    │  firefox.rs     │    │  HTML (D3.js)   │
│  (clap)         │    │  Profile Finder │    │  safari.rs      │    │  Serialization  │
└─────────────────┘    └─────────────────┘    └─────────────────┘    └─────────────────┘
```

## Module Architecture

### 1. CLI Layer (`main.rs` + `cli.rs`)

**Purpose**: Command-line interface and application entry point

**Module Structure**:

- `main.rs`: CLI definitions (clap Parser/Subcommand) and dispatch (~220 lines)
- `cli.rs`: Handler functions for each command (~350 lines)

**Components**:

- `Cli`: Main argument parser using clap
- `Commands`: Enum for subcommands (Export, List, Search, Open, Process, Graph, Config)
- Handler functions: `export_all_browsers`, `process_bookmarks`, `generate_graph`, `handle_config`, `list_all_browsers`, `list_browser_profiles`

### 2. Browser Detection (`browser.rs`)

**Purpose**: Discover and enumerate browser installations and profiles

**Components**:

- `Browser` enum: Supported browser types
- `get_default_data_dir()`: Platform-specific path resolution
- `find_profiles()`: Profile discovery logic
- `list_all_browsers()`: Browser enumeration

**Responsibilities**:

- Cross-platform browser detection
- Profile directory discovery
- Path resolution for browser data files
- Browser availability validation

**Platform-Specific Logic**:

```rust
match platform {
    MacOS => ~/Library/Application Support/{Browser}
    Windows => %APPDATA%/{Browser}/User Data
    Linux => ~/.config/{browser}
}
```

### 3. Data Extraction (`exporter/`)

**Purpose**: Extract and parse browser-specific data formats

**Module Structure**:

- `exporter/mod.rs`: Types (Bookmark, UrlEntry, BrowserData), public API (`load_browser_data`, `export_data`), browser dispatch
- `exporter/chrome.rs`: Chrome/Edge bookmark JSON + History SQLite parsing
- `exporter/firefox.rs`: Firefox places.sqlite bookmark + history parsing (with lock-safe copy)
- `exporter/safari.rs`: Safari Bookmarks.plist parsing

**Key API**: `load_browser_data(browser, data_type)` — reads live from browser databases in-memory, no temp files

**Data Flow**:

```
Browser DB/JSON/plist → Browser-specific parser → Unified Bookmark/UrlEntry model
```

### 4. Knowledge Graph Engine (`graph/`)

**Purpose**: Generate rich knowledge graphs from bookmark/history data

**Module Structure**:

- `graph/mod.rs`: Types (NodeType, EdgeType, GraphNode, GraphEdge, KnowledgeGraph, GraphConfig)
- `graph/builder.rs`: GraphBuilder with unified `ingest_items()` pipeline (DRY)
- `graph/analyzer.rs`: Tag extraction, categorization, similarity (Jaccard), domain extraction
- `graph/formats.rs`: Export formats (DOT, JSON, GEXF, HTML with D3.js)
- `graph/tests.rs`: 18 unit tests

**Data Loading**: Reads live from browser databases via `exporter::load_browser_data()` — no intermediate file I/O

**Components**:

- `GraphBuilder`: Stateful builder with unified `ingest_items()` method
- `GraphConfig`: Configuration for edge types, thresholds, detail levels, similarity
- `KnowledgeGraph`: Output structure with nodes, edges, metadata

**Node Types**: Bookmark, Domain, Folder, Tag, Category

**Edge Types**: BelongsToDomain, InFolder, SameDomain, HasTag, InCategory, SimilarContent

**Processing Pipeline**:

```
Bookmarks → Tag Extraction → Category Assignment → Node/Edge Creation → Similarity Detection → Graph Output
```

**Tag Extraction**: Splits titles/URLs into tokens, filters stop words, extracts URL path segments

**Auto-Categorization**: Keyword-based classification into 10 categories (Development, AI & ML, Cloud & DevOps, News, Social, Shopping, Finance, Education, Design, Reference)

**Similarity Detection**: Jaccard similarity on extracted tag sets between bookmark pairs

**Export Formats**:

- HTML: Interactive D3.js force-directed graph with dark/light theme, filters, zoom/pan
- DOT: Graphviz format with color-coded node/edge types
- JSON: Structured data for web visualization
- GEXF: Gephi network analysis format

### 5. Data Models

**Core Structures**:

```rust
pub struct BrowserData {
    pub browser: String,
    pub profile: String,
    pub export_date: DateTime<Utc>,
    pub bookmarks: Option<Vec<Bookmark>>,
    pub history: Option<HistoryEntry>,
    pub passwords: Option<Vec<Password>>,
}

pub struct Bookmark {
    pub id: String,
    pub title: String,
    pub url: Option<String>,
    pub folder: Option<String>,
    pub date_added: Option<DateTime<Utc>>,
    pub children: Option<Vec<Bookmark>>,
}
```

## Cross-Platform Architecture

### Abstraction Layers

1. **File System Layer**
   - Uses `dirs` crate for standard directories
   - Platform-specific path templates
   - Custom path override support

2. **Database Access Layer**
   - SQLite with `rusqlite`
   - Connection pooling (future enhancement)
   - Lock handling and recovery

3. **Security Layer**
   - Platform-specific keychain access
   - Permission handling
   - Secure memory management

### Browser-Specific Implementations

#### Chrome/Chromium

```
Profile/Bookmarks (JSON) → parse_chrome_bookmarks()
Profile/History (SQLite) → extract_chrome_history()
Profile/Login Data (SQLite) → extract_chrome_passwords()
```

#### Firefox

```
Profile/places.sqlite (SQLite) → extract_firefox_bookmarks()
Profile/places.sqlite (SQLite) → extract_firefox_history()
Profile/logins.json (JSON) → extract_firefox_passwords()
```

#### Safari

```
~/Library/Safari/Bookmarks.plist (Property List) → extract_safari_bookmarks()
~/Library/Safari/History.db (SQLite) → extract_safari_history()
System Keychain → extract_safari_passwords()
```

## Error Handling Architecture

### Error Types

1. **Recoverable Errors**
   - Browser not installed
   - Database locked
   - Permission denied
   - Corrupted data

2. **Configuration Errors**
   - Invalid arguments
   - Missing dependencies
   - Path not found

3. **System Errors**
   - Out of memory
   - Disk full
   - Network errors (future)

### Error Handling Strategy

```rust
match operation {
    Ok(result) => proceed_with(result),
    Err(error) => {
        match error.kind() {
            PermissionDenied => offer_manual_workaround(),
            DatabaseLocked => suggest_close_browser(),
            NotFound => continue_with_next_browser(),
            _ => log_and_continue(),
        }
    }
}
```

## Performance Architecture

### Memory Management

1. **Streaming for Large Datasets**
   - Iterator-based database access
   - Lazy loading of bookmark trees
   - Chunked file processing

2. **Efficient Data Structures**
   - String interning for repeated URLs
   - Compact timestamp representation
   - Minimal temporary allocations

### I/O Optimization

1. **Database Access**
   - Prepared statements for repeated queries
   - Batch operations where possible
   - Connection reuse

2. **File Operations**
   - Buffered I/O for large files
   - Atomic file writes
   - Temporary file cleanup

## Security Architecture

### Data Protection

1. **Access Control**
   - Read-only access to browser data
   - No modification of original files
   - Permission validation

2. **Sensitive Data Handling**
   - No plaintext passwords in logs
   - Secure memory for password extraction
   - Temporary file encryption (future)

### Platform Security Integration

```rust
match platform {
    MacOS => Keychain Services API,
    Windows => Credential Manager API,
    Linux => Secret Service API,
}
```

## Extensibility Architecture

### Adding New Browsers

1. **Enum Extension**

```rust
pub enum Browser {
    Chrome,
    Firefox,
    Safari,
    Edge,
    Brave,  // New browser
}
```

2. **Implementation Pattern**
   - Add path resolution logic
   - Implement extraction functions
   - Add platform-specific handling
   - Update tests

### Adding New Export Formats

1. **Trait-Based Design** (future enhancement)

```rust
trait Exporter {
    fn export(data: &BrowserData, output: &Path) -> Result<()>;
}
```

2. **Plugin Architecture** (future)
   - Dynamic format loading
   - Custom serializer registration
   - Format validation

## Dependency Management

### Core Dependencies

```
clap: CLI argument parsing
serde: Serialization framework
serde_yaml: YAML output
rusqlite: SQLite database access
dirs: Cross-platform directories
anyhow: Error handling
chrono: Date/time handling
plist: Safari property list parsing
```

### Dependency Graph

```
main.rs
├── clap
├── browser.rs
│   ├── dirs
│   └── std::fs
└── exporter.rs
    ├── serde_yaml
    ├── rusqlite
    ├── plist
    ├── chrono
    └── serde
```

## Testing Architecture

### Test Organization

1. **Unit Tests**
   - Browser detection logic
   - Data parsing functions
   - Error handling paths

2. **Integration Tests**
   - End-to-end export workflows
   - Cross-platform behavior
   - Database handling

3. **Mock Tests**
   - Browser simulation
   - File system mocking
   - Error scenario testing

### Test Data

1. **Sample Browser Data**
   - Chrome bookmark JSON
   - Firefox SQLite databases
   - Safari plist files

2. **Test Scenarios**
   - Empty databases
   - Corrupted files
   - Large datasets
   - Permission issues

## Future Architectural Enhancements

### Planned Improvements

1. **Async/Await Migration**
   - Parallel browser processing
   - Non-blocking I/O operations
   - Better resource utilization

2. **Plugin System**
   - Dynamic browser support
   - Custom export formats
   - Third-party extensions

3. **Web Interface**
   - REST API layer
   - Web-based UI
   - Remote operation capability

4. **Performance Optimizations**
   - Database connection pooling
   - Memory-mapped files
   - Compression for large exports

### Scalability Considerations

1. **Large Dataset Handling**
   - Streaming processing
   - Progress indicators
   - Resume capability

2. **Multi-User Support**
   - Profile isolation
   - Concurrent access
   - Resource limits