summaryrefslogtreecommitdiff
path: root/internal/api/obsidian.go
blob: a8ba80ddc1f6abc7c8e0a242f9fc2c0331c3f29c (plain)
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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
package api

import (
	"bufio"
	"context"
	"fmt"
	"os"
	"path/filepath"
	"regexp"
	"sort"
	"strings"
	"time"

	"task-dashboard/internal/models"
)

// ObsidianClient handles reading notes from an Obsidian vault
type ObsidianClient struct {
	vaultPath string
}

// NewObsidianClient creates a new Obsidian vault reader
func NewObsidianClient(vaultPath string) *ObsidianClient {
	return &ObsidianClient{
		vaultPath: vaultPath,
	}
}

// fileInfo holds file metadata for sorting
type fileInfo struct {
	path    string
	modTime time.Time
}

// GetNotes reads and returns the most recently modified notes from the vault
func (c *ObsidianClient) GetNotes(ctx context.Context, limit int) ([]models.Note, error) {
	if c.vaultPath == "" {
		return nil, fmt.Errorf("obsidian vault path not configured")
	}

	// Check if vault path exists
	if _, err := os.Stat(c.vaultPath); os.IsNotExist(err) {
		return nil, fmt.Errorf("vault path does not exist: %s", c.vaultPath)
	}

	// Collect all markdown files with their modification times
	var files []fileInfo

	err := filepath.Walk(c.vaultPath, func(path string, info os.FileInfo, err error) error {
		if err != nil {
			return nil // Skip files we can't access
		}

		// Skip directories and non-markdown files
		if info.IsDir() || !strings.HasSuffix(info.Name(), ".md") {
			return nil
		}

		// Skip hidden files and directories
		if strings.HasPrefix(info.Name(), ".") {
			return nil
		}

		files = append(files, fileInfo{
			path:    path,
			modTime: info.ModTime(),
		})

		return nil
	})

	if err != nil {
		return nil, fmt.Errorf("failed to walk vault directory: %w", err)
	}

	// Sort by modification time (most recent first)
	sort.Slice(files, func(i, j int) bool {
		return files[i].modTime.After(files[j].modTime)
	})

	// Limit the number of files to process
	if limit > 0 && len(files) > limit {
		files = files[:limit]
	}

	// Parse each file
	notes := make([]models.Note, 0, len(files))
	for _, file := range files {
		note, err := c.parseMarkdownFile(file.path, file.modTime)
		if err != nil {
			// Skip files that fail to parse
			continue
		}
		notes = append(notes, *note)
	}

	return notes, nil
}

// parseMarkdownFile reads and parses a markdown file
func (c *ObsidianClient) parseMarkdownFile(path string, modTime time.Time) (*models.Note, error) {
	file, err := os.Open(path)
	if err != nil {
		return nil, err
	}
	defer file.Close()

	scanner := bufio.NewScanner(file)

	var content strings.Builder
	var tags []string
	inFrontmatter := false
	lineCount := 0

	// Parse file
	for scanner.Scan() {
		line := scanner.Text()
		lineCount++

		// Check for YAML frontmatter
		if lineCount == 1 && line == "---" {
			inFrontmatter = true
			continue
		}

		if inFrontmatter {
			if line == "---" {
				inFrontmatter = false
				continue
			}
			// Extract tags from frontmatter
			if strings.HasPrefix(line, "tags:") {
				tagsStr := strings.TrimPrefix(line, "tags:")
				tagsStr = strings.Trim(tagsStr, " []")
				if tagsStr != "" {
					tags = strings.Split(tagsStr, ",")
					for i, tag := range tags {
						tags[i] = strings.TrimSpace(tag)
					}
				}
			}
			continue
		}

		// Add to content (limit to preview)
		if content.Len() < 500 { // Limit to ~500 chars
			content.WriteString(line)
			content.WriteString("\n")
		}
	}

	if err := scanner.Err(); err != nil {
		return nil, err
	}

	// Extract inline tags (e.g., #tag)
	inlineTags := extractInlineTags(content.String())
	tags = append(tags, inlineTags...)
	tags = uniqueStrings(tags)

	// Get filename and title
	filename := filepath.Base(path)
	title := strings.TrimSuffix(filename, ".md")

	// Try to extract title from first H1 heading
	contentStr := content.String()
	h1Regex := regexp.MustCompile(`^#\s+(.+)$`)
	lines := strings.Split(contentStr, "\n")
	for _, line := range lines {
		if matches := h1Regex.FindStringSubmatch(line); len(matches) > 1 {
			title = matches[1]
			break
		}
	}

	note := &models.Note{
		Filename: filename,
		Title:    title,
		Content:  strings.TrimSpace(contentStr),
		Modified: modTime,
		Path:     path,
		Tags:     tags,
	}

	return note, nil
}

// extractInlineTags finds all #tags in the content
func extractInlineTags(content string) []string {
	tagRegex := regexp.MustCompile(`#([a-zA-Z0-9_-]+)`)
	matches := tagRegex.FindAllStringSubmatch(content, -1)

	tags := make([]string, 0, len(matches))
	for _, match := range matches {
		if len(match) > 1 {
			tags = append(tags, match[1])
		}
	}

	return tags
}

// uniqueStrings returns a slice with duplicate strings removed
func uniqueStrings(slice []string) []string {
	seen := make(map[string]bool)
	result := make([]string, 0, len(slice))

	for _, item := range slice {
		if !seen[item] && item != "" {
			seen[item] = true
			result = append(result, item)
		}
	}

	return result
}