package bookmarks import "os" import "fmt" import "bufio" import "strings" import "net/url" import "path/filepath" import "git.tebibyte.media/sashakoshka/stone/config" var bookmarksFile string var dataDirectory string type Bookmark struct { Title string Location *url.URL } var bookmarks []Bookmark func Gemtext () (page string) { page += "# Bookmarks\n" for _, bookmark := range bookmarks { page += "=> " + bookmark.Location.String() + " " + bookmark.Title + "\n" } return } func New (title, location string) (bookmark Bookmark) { bookmark.Title = title bookmark.Location, _ = url.Parse(location) bookmark.Location.RawQuery = url.PathEscape(bookmark.Location.RawQuery) return } func Add (bookmark Bookmark) { bookmarks = append(bookmarks, bookmark) save() } func init () { dataDirectory = config.DataHome("skipper") bookmarksFile = filepath.Join(dataDirectory, "bookmarks") load() } func load () { defer func () { if len(bookmarks) > 0 { return } bookmarks = []Bookmark { New("Project Gemini", "gemini://gemini.circumlunar.space:1965/"), New("Search", "gemini://geminispace.info:1965/search/"), } } () file, err := os.Open(bookmarksFile) if err != nil { return } scanner := bufio.NewScanner(file) for scanner.Scan() { line := strings.TrimSpace(scanner.Text()) if len(line) == 0 { continue } if line[0] == '#' { continue } title, location, found := strings.Cut(scanner.Text(), ":") if !found { continue } title = strings.TrimSpace(title) location = strings.TrimSpace(location) bookmarks = append(bookmarks, New(title, location)) } } func save () (err error) { err = os.MkdirAll(dataDirectory, 0755) if err != nil { return } file, err := os.OpenFile ( bookmarksFile, os.O_WRONLY | os.O_CREATE | os.O_TRUNC, 0744) if err != nil { return } defer file.Close() for _, bookmark := range bookmarks { fmt.Fprintf ( file, "%s: %s\n", bookmark.Title, bookmark.Location.String()) } return }