Files
HackBrowserData/browser/chromium/extract_bookmark.go
T
Roger b04c436a73 refactor: introduce category, record, and export packages (#651)
Later layers speak categories and records, and export needs nothing else.
Ordering rows once in the exporter fixes Firefox history, written least visited first.
2026-10-26 19:55:19 +08:00

79 lines
1.9 KiB
Go

package chromium
import (
"os"
"github.com/tidwall/gjson"
"github.com/moond4rk/hackbrowserdata/internal/record"
"github.com/moond4rk/hackbrowserdata/internal/timeconv"
)
func extractBookmarks(path string) ([]record.Bookmark, error) {
data, err := os.ReadFile(path)
if err != nil {
return nil, err
}
var bookmarks []record.Bookmark
roots := gjson.GetBytes(data, "roots")
roots.ForEach(func(_, value gjson.Result) bool {
walkBookmarks(value, "", &bookmarks)
return true
})
return bookmarks, nil
}
// walkBookmarks recursively traverses the bookmark tree, collecting URL entries.
func walkBookmarks(node gjson.Result, folder string, out *[]record.Bookmark) {
nodeType := node.Get("type").String()
if nodeType == "url" {
*out = append(*out, record.Bookmark{
ID: node.Get("id").Int(),
Name: node.Get("name").String(),
Type: nodeType,
URL: node.Get("url").String(),
Folder: folder,
CreatedAt: timeconv.Chromium(node.Get("date_added").Int()),
})
}
children := node.Get("children")
if !children.Exists() || !children.IsArray() {
return
}
currentFolder := node.Get("name").String()
for _, child := range children.Array() {
walkBookmarks(child, currentFolder, out)
}
}
func countBookmarks(path string) (int, error) {
data, err := os.ReadFile(path)
if err != nil {
return 0, err
}
var count int
roots := gjson.GetBytes(data, "roots")
roots.ForEach(func(_, value gjson.Result) bool {
count += walkCountBookmarks(value)
return true
})
return count, nil
}
// walkCountBookmarks recursively counts URL nodes in the bookmark tree.
func walkCountBookmarks(node gjson.Result) int {
count := 0
if node.Get("type").String() == "url" {
count++
}
children := node.Get("children")
if children.Exists() && children.IsArray() {
for _, child := range children.Array() {
count += walkCountBookmarks(child)
}
}
return count
}