prevent duplicates in cache and display

This commit is contained in:
2025-08-18 14:56:01 -07:00
parent 2aa18e77e3
commit 56ca9d0cb8

62
main.go
View File

@@ -20,6 +20,7 @@ import (
"os"
"os/exec"
"os/signal"
"slices"
"strings"
"syscall"
@@ -49,7 +50,10 @@ type Note struct {
func check(err error, format string, a ...any) bool {
if err != nil {
log.Fatalf("\033[31m"+format+"\033[0m: ", a, err)
if writeErr := os.WriteFile("error.log", []byte(fmt.Sprintf(format+": %s", a, err)), 0600); writeErr != nil {
log.Fatalf("Error writing error '%s' to error.log: %s\n", err, writeErr)
}
log.Fatalf("\033[31m"+format+"\033[0m: %s\n", a, err)
return false
}
return true
@@ -145,18 +149,38 @@ CREATE TABLE notes (
check(err, "Error unmarshalling user data")
serverAddress, username, password = userData[0], userData[1], userData[2]
jsonBody := load(db)
// jsonBody := fetch()
// cache(db, jsonBody)
fmt.Println(jsonBody)
list(jsonBody)
fzf := exec.Command("fzf")
stdin, err := fzf.StdinPipe()
check(err, "Error getting stdin pipe for fzf")
check(fzf.Start(), "Error starting fzf")
cacheJsonBody := load(db)
listAll(cacheJsonBody, stdin)
fetchJsonBody := fetch()
for i := range fetchJsonBody {
if !slices.Contains(cacheJsonBody, fetchJsonBody[i]) {
go list(fetchJsonBody[i][1], stdin, Note{})
}
}
cache(db, fetchJsonBody)
fzf.Wait()
default:
login()
}
}
func cache(db *sql.DB, jsonData [][2]string) {
for i := range len(jsonData) {
for i := range jsonData {
var id string
err := db.QueryRow("SELECT id FROM notes WHERE id = ?", jsonData[i][0]).Scan(&id)
if err != sql.ErrNoRows {
check(err, "Error scanning cache database at %s for duplicates", cachePath)
continue
}
stmt, err := db.Prepare("INSERT INTO notes VALUES(?, ?)")
check(err, "Error preparing to insert note into cache database at %s", cachePath)
defer stmt.Close()
@@ -268,21 +292,19 @@ func load(db *sql.DB) [][2]string {
return notes
}
func list(jsonBody [][2]string) {
fzf := exec.Command("fzf")
stdin, err := fzf.StdinPipe()
check(err, "Error executing fzf")
check(fzf.Start(), "Error starting fzf")
func listAll(jsonBody [][2]string, fzfStdin io.WriteCloser) {
decryptedBody := make([]Note, len(jsonBody))
for i := range len(jsonBody) {
err := json.Unmarshal([]byte(decrypt(jsonBody[i][1], password)), &decryptedBody[i])
for i := range jsonBody {
go list(jsonBody[i][1], fzfStdin, decryptedBody[i])
}
}
func list(jsonBody string, fzfStdin io.WriteCloser, decryptedBody Note) {
err := json.Unmarshal([]byte(decrypt(jsonBody, password)), &decryptedBody)
if err != nil {
continue
return
}
if len(decryptedBody[i].Title) > 0 && len(decryptedBody[i].Body) > 0 {
fmt.Fprintf(stdin, "%s | %s\n", decryptedBody[i].Title, strings.ReplaceAll(decryptedBody[i].Body, "\n", " "))
if len(decryptedBody.Title) > 0 && len(decryptedBody.Body) > 0 {
fmt.Fprintf(fzfStdin, "%s | %s\n", decryptedBody.Title, strings.ReplaceAll(decryptedBody.Body, "\n", " "))
}
}
fzf.Wait()
}