Skip to content

Commit

Permalink
feat: add pinned notes using bbolt (#9)
Browse files Browse the repository at this point in the history
  • Loading branch information
JackWilli authored Dec 13, 2024
1 parent 8768fea commit 21229f5
Show file tree
Hide file tree
Showing 8 changed files with 204 additions and 4 deletions.
6 changes: 5 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ Oolong looks for a configuration file at `~/.config/oolong.toml`
| `ignored_directories` | Subdirectories to exclude from reading and linking | `[".git"]` |
| `allowed_extensions` | Whitelist of file extensions to use in linking | `[".md", ".txt", ".mdx", ".tex", ".typ"]` |
| `open_command` | Command to run when clicking a graph node | `["code"]` (See below for more details) |

| `pinning_enabled` | **Optional** boolean indicating if note pinning should be enabled | `false` |

The `open_command` option is used by the graph to allow you to open a clicked note in an editor of your choice.

Expand Down Expand Up @@ -94,6 +94,7 @@ For more situations where you want to run a more complex command, separate conse
| plugin_paths | List of scripts to load | `[]` |



### Example Configuration

```toml
Expand All @@ -118,6 +119,9 @@ allowed_extensions = [
".typ",
]

# Enables note pinning
pinning_enabled = true

# Command to run when open endpoint it called (a note node is clicked on the graph)
# Note: All arguments MUST be separated into separate strings (see config for more details)
open_command = [ "code" ]
Expand Down
1 change: 1 addition & 0 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ require (
require (
github.com/BurntSushi/toml v1.4.0
github.com/oolong-sh/sync v0.0.0-20241128232107-4aff73e779a0
go.etcd.io/bbolt v1.3.11
)

require (
Expand Down
7 changes: 6 additions & 1 deletion go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -21,11 +21,14 @@ github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZN
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw=
github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/stretchr/testify v1.8.0 h1:pSgiaMZlXftHpm5L7V1+rVB+AZJydKsMxsQBIJw4PKk=
github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU=
github.com/stretchr/testify v1.8.1 h1:w7B6lhMri9wdJUVmEZPGGhZzrYTPvgJArz7wNPgYKsk=
github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4=
github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY=
github.com/yuin/gopher-lua v1.1.1 h1:kYKnWBjvbNP4XLT3+bPEwAXJx262OhaHDWDVOPjL46M=
github.com/yuin/gopher-lua v1.1.1/go.mod h1:GBR0iDaNXjAgGg9zfCvksxSRnQx76gclCIb7kdAd1Pw=
go.etcd.io/bbolt v1.3.11 h1:yGEzV1wPz2yVCLsD8ZAiGHhHVlczyC9d1rP43/VCRJ0=
go.etcd.io/bbolt v1.3.11/go.mod h1:dksAq7YMXoljX0xu6VF5DMZGbhYYoLUalEiSySYAS4I=
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc=
golang.org/x/crypto v0.17.0/go.mod h1:gCAAfMLgwOJRpTjQ2zCCt2OcSfYMTeZVSRtQlPC7Nq4=
Expand All @@ -41,6 +44,8 @@ golang.org/x/net v0.10.0/go.mod h1:0qNGK6F8kojg2nk9dLZ2mShWaEBan6FAoqfSigmmuDg=
golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.1.0/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.5.0 h1:60k92dhOjHxJkrqnwsfl8KuaHbn/5dl0lUPUklKo3qE=
golang.org/x/sync v0.5.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk=
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
Expand Down
9 changes: 9 additions & 0 deletions internal/api/endpoints.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@ package api
import (
"log"
"net/http"

"github.com/oolong-sh/oolong/internal/config"
)

// spawn the oolong api server
Expand All @@ -29,6 +31,13 @@ func SpawnServer() {
mux.HandleFunc("DELETE /note", handleDeleteNote)
mux.HandleFunc("GET /open/note", handleOpenNote)

// pinning endpoints
if config.PinningEnabled() {
mux.HandleFunc("GET /pins", handleGetPinnedNotes)
mux.HandleFunc("POST /pins", handleAddPinnedNote)
mux.HandleFunc("DELETE /pins", handleDeletePinnedNote)
}

// search endpoints
mux.HandleFunc("GET /search/keyword", handleSearchKeyword)
mux.HandleFunc("GET /search/note", handleSearchNote)
Expand Down
122 changes: 121 additions & 1 deletion internal/api/note_handlers.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,9 @@ import (
"path/filepath"

"github.com/oolong-sh/oolong/internal/config"
"github.com/oolong-sh/oolong/internal/db"
"github.com/oolong-sh/oolong/internal/state"
"go.etcd.io/bbolt"
)

type createUpdateRequest struct {
Expand Down Expand Up @@ -145,7 +147,7 @@ func handleUpdateNote(w http.ResponseWriter, r *http.Request) {
}
}

// 'Delete /note?path=/path/to/note' endpoint handler deletess a note file based on query input
// 'Delete /note?path=/path/to/note' endpoint handler deletes a note file based on query input
func handleDeleteNote(w http.ResponseWriter, r *http.Request) {
log.Println("Request received:", r.Method, r.URL, r.Host)

Expand Down Expand Up @@ -173,6 +175,124 @@ func handleDeleteNote(w http.ResponseWriter, r *http.Request) {
// - check this case in state, this may require substantial logic missing there
}

func addPinnedNote(path string) error {
return db.Database.Update(func(tx *bbolt.Tx) error {
bucket := tx.Bucket([]byte(db.PinnedBucket))
if bucket == nil {
return fmt.Errorf("bucket %s not found", db.PinnedBucket)
}

if bucket.Get([]byte(path)) != nil {
return fmt.Errorf("note already pinned")
}

return bucket.Put([]byte(path), []byte{})
})
}

func getPinnedNotes() ([]string, error) {
notes := []string{}

err := db.Database.View(func(tx *bbolt.Tx) error {
bucket := tx.Bucket([]byte(db.PinnedBucket))
if bucket == nil {
return fmt.Errorf("bucket %s not found", db.PinnedBucket)
}

return bucket.ForEach(func(k, _ []byte) error {
notes = append(notes, string(k))
return nil
})
})

return notes, err
}

func deletePinnedNote(path string) error {
return db.Database.Update(func(tx *bbolt.Tx) error {
bucket := tx.Bucket([]byte(db.PinnedBucket))
if bucket == nil {
return fmt.Errorf("bucket %s not found", db.PinnedBucket)
}

return bucket.Delete([]byte(path))
})
}

func handleGetPinnedNotes(w http.ResponseWriter, r *http.Request) {
log.Println("Request received:", r.Method, r.URL, r.Host)

// CORS handling
if err := checkOrigin(w, r); err != nil {
log.Println(err)
http.Error(w, fmt.Sprintln(err), 500)
return
}

pinnedNotes, err := getPinnedNotes()
if err != nil {
log.Println(err)
http.Error(w, "Failed to fetch pinned notes", 500)
return
}

w.Header().Set("Content-Type", "application/json")
if err := json.NewEncoder(w).Encode(pinnedNotes); err != nil {
log.Println(err)
http.Error(w, "Failed to encode response", 500)
}
}

func handleAddPinnedNote(w http.ResponseWriter, r *http.Request) {
log.Println("Request received:", r.Method, r.URL, r.Host)

// CORS handling
if err := checkOrigin(w, r); err != nil {
log.Println(err)
http.Error(w, fmt.Sprintln(err), 500)
return
}

path := r.URL.Query().Get("path")
if path == "" {
http.Error(w, "Path parameter not specified", http.StatusBadRequest)
return
}

if err := addPinnedNote(path); err != nil {
log.Println(err)
http.Error(w, err.Error(), 400)
return
}

w.WriteHeader(http.StatusCreated)
}

func handleDeletePinnedNote(w http.ResponseWriter, r *http.Request) {
log.Println("Request received:", r.Method, r.URL, r.Host)

// CORS handling
if err := checkOrigin(w, r); err != nil {
log.Println(err)
http.Error(w, fmt.Sprintln(err), 500)
return
}

path := r.URL.Query().Get("path")
if path == "" {
http.Error(w, "Path parameter not specified", http.StatusBadRequest)
return
}

if err := deletePinnedNote(path); err != nil {
log.Println(err)
http.Error(w, "Failed to delete pinned note", 400)
return
}

w.WriteHeader(http.StatusNoContent)
}

// 'GET /open/note?path=/path/to/note.md' opens the specified not file using the command specified in oolong.toml
func handleOpenNote(w http.ResponseWriter, r *http.Request) {
log.Println("Request received:", r.Method, r.URL, r.Host)
Expand Down
3 changes: 2 additions & 1 deletion internal/config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ type OolongConfig struct {
AllowedExtensions []string `toml:"allowed_extensions"`
IgnoreDirectories []string `toml:"ignored_directories"`
OpenCommand []string `toml:"open_command"`
PinningEnabled bool `toml:"pinning_enabled"`

LinkerConfig OolongLinkerConfig `toml:"linker"`
GraphConfig OolongGraphConfig `toml:"graph"`
Expand All @@ -25,7 +26,6 @@ type OolongConfig struct {
}

type OolongLinkerConfig struct {
// TODO: move these things to a "linker" config section
NGramRange []int `toml:"ngram_range"`
StopWords []string `toml:"stop_words"`
}
Expand Down Expand Up @@ -58,6 +58,7 @@ func StopWords() []string { return cfg.LinkerConfig.StopWords }
func WeightThresholds() OolongGraphConfig { return cfg.GraphConfig }
func GraphMode() string { return cfg.GraphConfig.DefaultMode }
func SyncConfig() OolongSyncConfig { return cfg.SyncConfig }
func PinningEnabled() bool { return cfg.PinningEnabled }

func Setup() error {
configPath, err := findConfigPath()
Expand Down
50 changes: 50 additions & 0 deletions internal/db/db.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
package db

import (
"os"
"path/filepath"
"runtime"

"go.etcd.io/bbolt"
)

var Database *bbolt.DB

const PinnedBucket = "PinnedNotes"

// Initialize the database and ensure the bucket exists
func InitializeDB() error {
homeDir, err := os.UserHomeDir()
if err != nil {
return err
}

var db_path string
if runtime.GOOS == "windows" {
db_path = filepath.Join(homeDir, "AppData", "Local", "oolong", "oolong.db")
} else {
db_path = filepath.Join(homeDir, ".local", "share", "oolong", "oolong.db")
}

err = os.MkdirAll(filepath.Dir(db_path), 0755)
if err != nil {
return err
}

Database, err = bbolt.Open(db_path, 0666, nil)
if err != nil {
return err
}

return Database.Update(func(tx *bbolt.Tx) error {
_, err := tx.CreateBucketIfNotExists([]byte(PinnedBucket))
return err
})
}

// Close the database when the server shuts down
func CloseDB() {
if Database != nil {
Database.Close()
}
}
10 changes: 10 additions & 0 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import (

"github.com/oolong-sh/oolong/internal/config"
"github.com/oolong-sh/oolong/internal/daemon"
"github.com/oolong-sh/oolong/internal/db"
"github.com/oolong-sh/oolong/internal/documents"
"github.com/oolong-sh/oolong/internal/linking/ngrams"
"github.com/oolong-sh/oolong/internal/state"
Expand All @@ -29,6 +30,15 @@ func main() {
panic(err)
}

go func() {
if config.PinningEnabled() {
if err := db.InitializeDB(); err != nil {
panic(err)
}
defer db.CloseDB()
}
}()

// go plugins.InitPlugins()

// run daemon if --no-daemon flag is not passed
Expand Down

0 comments on commit 21229f5

Please sign in to comment.