-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
322 lines (279 loc) · 8.48 KB
/
main.go
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
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
package main
import (
"database/sql"
"flag"
"fmt"
"log"
"os/exec"
"path/filepath"
"strings"
"unicode/utf8"
_ "github.com/mattn/go-sqlite3"
)
// Config holds application-wide configuration
type Config struct {
DBPath string
StoragePath string
Version string
}
// Item represents a Zotero library item with its metadata
type Item struct {
StableID string
Title string
Tags sql.NullString
Attachments sql.NullString
}
// Repository handles database operations
type Repository struct {
db *sql.DB
cfg Config
}
// NewRepository creates a new Repository instance
func NewRepository(db *sql.DB, cfg Config) *Repository {
return &Repository{db: db, cfg: cfg}
}
const baseQuery = `
SELECT
i.key,
idv.value as title,
GROUP_CONCAT(DISTINCT t.name) as tags,
GROUP_CONCAT(DISTINCT child.key || ':' || COALESCE(ia.path, '')) as attachments
FROM items i
LEFT JOIN itemData id ON i.itemID = id.itemID
LEFT JOIN itemDataValues idv ON id.valueID = idv.valueID
LEFT JOIN itemTypes it ON i.itemTypeID = it.itemTypeID
LEFT JOIN itemTags itag ON i.itemID = itag.itemID
LEFT JOIN tags t ON itag.tagID = t.tagID
LEFT JOIN itemAttachments ia ON (ia.parentItemID = i.itemID OR ia.itemID = i.itemID)
LEFT JOIN items child ON ia.itemID = child.itemID
WHERE it.display = 1
AND id.fieldID = (SELECT fieldID FROM fields WHERE fieldName = 'title')
AND NOT EXISTS (
SELECT 1 FROM itemAttachments
WHERE itemAttachments.itemID = i.itemID
AND itemAttachments.parentItemID IS NOT NULL)`
// GetByStableID retrieves a single item by its stable ID
func (r *Repository) GetByStableID(stableID string) (*Item, error) {
query := fmt.Sprintf("%s AND i.key = ? GROUP BY i.itemID", baseQuery)
var item Item
err := r.db.QueryRow(query, stableID).Scan(
&item.StableID,
&item.Title,
&item.Tags,
&item.Attachments,
)
if err != nil {
return nil, fmt.Errorf("fetching item: %w", err)
}
return &item, nil
}
// ListItems retrieves items matching the given filters
func (r *Repository) ListItems(titleFilter, tagFilter string) ([]*Item, error) {
queryBuilder := strings.Builder{}
queryBuilder.WriteString(baseQuery)
var args []interface{}
if titleFilter != "" || tagFilter != "" {
conditions := make([]string, 0, 2)
if titleFilter != "" {
conditions = append(conditions, "idv.value LIKE ?")
args = append(args, "%"+titleFilter+"%")
}
if tagFilter != "" {
conditions = append(conditions, "t.name LIKE ?")
args = append(args, "%"+tagFilter+"%")
}
if len(conditions) > 0 {
queryBuilder.WriteString(" AND " + strings.Join(conditions, " AND "))
}
}
queryBuilder.WriteString(" GROUP BY i.itemID")
rows, err := r.db.Query(queryBuilder.String(), args...)
if err != nil {
return nil, fmt.Errorf("executing query: %w", err)
}
defer rows.Close()
var items []*Item
for rows.Next() {
var item Item
if err := rows.Scan(
&item.StableID,
&item.Title,
&item.Tags,
&item.Attachments,
); err != nil {
return nil, fmt.Errorf("scanning row: %w", err)
}
items = append(items, &item)
}
if err = rows.Err(); err != nil {
return nil, fmt.Errorf("iterating rows: %w", err)
}
return items, nil
}
// CLI handles command-line operations
type CLI struct {
repo *Repository
cfg Config
}
// NewCLI creates a new CLI instance
func NewCLI(repo *Repository, cfg Config) *CLI {
return &CLI{repo: repo, cfg: cfg}
}
// getStoragePath returns the full storage path for an item's attachment
func (c *CLI) getStoragePath(item *Item) string {
if !item.Attachments.Valid || item.Attachments.String == "" {
return ""
}
attachments := strings.Split(item.Attachments.String, ",")
if len(attachments) == 0 {
return ""
}
parts := strings.SplitN(attachments[0], ":", 2)
if len(parts) != 2 {
return ""
}
return filepath.Join(
c.cfg.StoragePath,
parts[0],
strings.TrimPrefix(parts[1], "storage:"),
)
}
func truncateString(s string, n int) string {
if utf8.RuneCountInString(s) <= n {
return s
}
runes := []rune(s)
return string(runes[:n-3]) + "..."
}
// printItem formats and prints item information
func (c *CLI) printItem(item *Item, verbose bool) {
if !verbose {
fmt.Println(item.StableID)
return
}
title := truncateString(item.Title, 25)
tags := ""
if item.Tags.Valid {
tags = truncateString(item.Tags.String, 15)
}
if item.Attachments.Valid && item.Attachments.String != "" {
attachments := strings.Split(item.Attachments.String, ",")
for _, att := range attachments {
parts := strings.SplitN(att, ":", 2)
if len(parts) == 2 {
storagePath := filepath.Join(
c.cfg.StoragePath,
parts[0],
strings.TrimPrefix(parts[1], "storage:"),
)
fmt.Printf("%-8s\t%-25s\t%-15s\t%s\n",
item.StableID,
title,
tags,
storagePath)
}
}
} else {
fmt.Printf("%-8s\t%-25s\t%-15s\t\n",
item.StableID,
title,
tags)
}
}
// List displays items matching the given filters
func (c *CLI) List(titleFilter, tagFilter string, verbose bool) error {
items, err := c.repo.ListItems(titleFilter, tagFilter)
if err != nil {
return fmt.Errorf("listing items: %w", err)
}
for _, item := range items {
c.printItem(item, verbose)
}
return nil
}
// Open launches the default application for the item's attachment
func (c *CLI) Open(stableID string) error {
item, err := c.repo.GetByStableID(stableID)
if err != nil {
return fmt.Errorf("getting item: %w", err)
}
path := c.getStoragePath(item)
if path == "" {
return fmt.Errorf("no attachment found for item: %s", stableID)
}
cmd := exec.Command("open", path)
if err := cmd.Run(); err != nil {
return fmt.Errorf("opening file: %w", err)
}
return nil
}
// Reference generates a reference link for the item
func (c *CLI) Reference(stableID string) error {
item, err := c.repo.GetByStableID(stableID)
if err != nil {
return fmt.Errorf("getting item: %w", err)
}
path := c.getStoragePath(item)
if path == "" {
return fmt.Errorf("no attachment found for item: %s", stableID)
}
tags := ""
if item.Tags.Valid {
tags = item.Tags.String
}
tags = "{" + tags + "}"
if tags == "{}" {
tags = "{}"
}
fmt.Printf("[zotero: %s, stableid: %s, tags: %s, version: %s](%s)\n",
item.Title,
item.StableID,
tags,
c.cfg.Version,
path)
return nil
}
func main() {
cfg := Config{
DBPath: "/Users/username/data/zotero/zotero.sqlite",
StoragePath: "/Users/username/data/zotero/storage/",
Version: "1.0",
}
titleFlag := flag.String("f", "", "Find items by title")
tagFlag := flag.String("t", "", "Find items by tag")
verboseFlag := flag.Bool("v", false, "Verbose output")
flag.Parse()
db, err := sql.Open("sqlite3", cfg.DBPath)
if err != nil {
log.Fatalf("Error opening database: %v", err)
}
defer db.Close()
repo := NewRepository(db, cfg)
cli := NewCLI(repo, cfg)
args := flag.Args()
if len(args) == 0 {
if err := cli.List(*titleFlag, *tagFlag, *verboseFlag); err != nil {
log.Fatalf("Error listing items: %v", err)
}
return
}
command := args[0]
switch command {
case "open":
if len(args) != 2 {
log.Fatal("Usage: store-zotero open <stableid>")
}
if err := cli.Open(args[1]); err != nil {
log.Fatalf("Error opening item: %v", err)
}
case "reference":
if len(args) != 2 {
log.Fatal("Usage: store-zotero reference <stableid>")
}
if err := cli.Reference(args[1]); err != nil {
log.Fatalf("Error generating reference: %v", err)
}
default:
log.Fatalf("Unknown command: %s", command)
}
}