~adnano/astronaut

astronaut/bookmarks.go -rw-r--r-- 1.2 KiB
947cfac7Adnan Maolood Update default bindings 12 days ago
                                                                                
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
package main

import (
	"errors"
	"fmt"
	"os"

	"git.sr.ht/~adnano/go-gemini"
)

type Bookmarks struct {
	file  *os.File
	links map[string]string // map of link URLs to names
}

// Load loads bookmarks from path.
func (b *Bookmarks) Load(path string) error {
	b.links = map[string]string{}
	f, err := os.OpenFile(path, os.O_RDONLY, 0644)
	if err != nil {
		if !errors.Is(err, os.ErrNotExist) {
			return err
		}

		// Create the file
		b, _ := static.ReadFile("about/bookmarks.gmi")
		b = []byte(fmt.Sprintf(string(b), path))
		if err := os.WriteFile(path, b, 0644); err != nil {
			return err
		}
		return nil
	}
	defer f.Close()
	return gemini.ParseLines(f, func(line gemini.Line) {
		if link, ok := line.(gemini.LineLink); ok {
			b.links[link.URL] = link.Name
		}
	})
}

func (b *Bookmarks) Open(path string) error {
	if err := b.Load(path); err != nil {
		return err
	}
	f, err := os.OpenFile(path, os.O_APPEND|os.O_WRONLY, 0644)
	if err != nil {
		return err
	}
	b.file = f
	return nil
}

func (b *Bookmarks) Add(link gemini.LineLink) bool {
	if _, ok := b.links[link.URL]; ok {
		return false
	}

	b.links[link.URL] = link.Name
	if b.file != nil {
		fmt.Fprintf(b.file, "%s\n", link)
	}
	return true
}