-
Notifications
You must be signed in to change notification settings - Fork 23
/
main.go
343 lines (306 loc) · 8.92 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
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
package main
import (
"os"
"os/user"
"strings"
"fmt"
"path/filepath"
"database/sql"
"bytes"
"compress/gzip"
"io/ioutil"
"golang.org/x/text/unicode/norm"
_ "github.com/mattn/go-sqlite3"
"github.com/sballin/alfred-search-notes-app/alfred"
)
const (
DbPath = "~/Library/Group Containers/group.com.apple.notes/NoteStore.sqlite"
TitleKey = "title"
SubtitleKey = "subtitle"
ArgKey = "URL"
BodyKey = "noteBodyZipped"
NotesSQLTemplate = `
SELECT
noteTitle as title,
folderTitle as subtitle,
'x-coredata://' || z_uuid || '/ICNote/p' || xcoreDataID as URL,
noteBodyZipped
FROM (
SELECT
c.ztitle1 AS noteTitle,
c.zfolder AS noteFolderID,
c.zmodificationdate1 AS modDate,
c.z_pk AS xcoredataID,
n.zdata AS noteBodyZipped
FROM
ziccloudsyncingobject AS c
INNER JOIN zicnotedata AS n ON c.znotedata = n.z_pk -- note id (int) distinct from xcoredataID
WHERE
noteTitle IS NOT NULL AND
modDate IS NOT NULL AND
xcoredataID IS NOT NULL AND
noteBodyZipped IS NOT NULL AND
c.zmarkedfordeletion != 1
) AS notes
INNER JOIN (
SELECT
z_pk AS folderID,
ztitle2 AS folderTitle,
zfoldertype as isRecentlyDeletedFolder
FROM ziccloudsyncingobject
WHERE
folderTitle IS NOT NULL AND
isRecentlyDeletedFolder != 1 AND
zmarkedfordeletion != 1
) AS folders ON noteFolderID = folderID
LEFT JOIN (
SELECT z_uuid FROM z_metadata
)
%s -- either blank to get all notes or WHERE titles/folders like...
ORDER BY %s
`
FoldersSQLTemplate = `
SELECT
ztitle2 AS title,
'' AS subtitle,
'x-coredata://' || z_uuid || '/ICFolder/p' || z_pk as URL
FROM ziccloudsyncingobject
LEFT JOIN (
SELECT z_uuid FROM z_metadata
)
WHERE
title IS NOT NULL AND
zmarkedfordeletion != 1 AND
lower(title) LIKE lower(?)
ORDER BY title ASC
`)
type LiteDB struct {
db *sql.DB
}
type UserQuery struct {
Tokens []string
WordString string
}
func Escape(s string) string {
return strings.Replace(s, "'", "''", -1)
}
func Expanduser(path string) string {
usr, _ := user.Current()
dir := usr.HomeDir
if path[:2] == "~/" {
path = filepath.Join(dir, path[2:])
}
return path
}
func NewLiteDB(path string) (LiteDB, error) {
db, err := sql.Open("sqlite3", path)
litedb := LiteDB{db}
return litedb, err
}
func NewNotesDB() (LiteDB, error) {
path := Expanduser(DbPath)
litedb, err := NewLiteDB("file:" + path + "?mode=ro&_query_only=true")
return litedb, err
}
func (lite LiteDB) Query(sqlQuery string, sqlArg string) ([]map[string]string, error) {
results := []map[string]string{}
rows, err := lite.db.Query(sqlQuery, sqlArg)
if err != nil {
return results, err
}
defer rows.Close()
cols, err := rows.Columns()
if err != nil {
return results, err
}
for rows.Next() {
m := map[string]string{}
columns := make([]interface{}, len(cols))
columnPointers := make([]interface{}, len(cols))
for i := range columns {
columnPointers[i] = &columns[i]
}
if err := rows.Scan(columnPointers...); err != nil {
return results, err
}
for i, colName := range cols {
val := columnPointers[i].(*interface{})
s, ok := (*val).(string)
if ok {
m[colName] = s
} else {
m[colName] = ""
}
}
results = append(results, m)
}
return results, err
}
func (lite LiteDB) QueryThenSearch(q string, search string) ([]map[string]string, error) {
results := []map[string]string{}
rows, err := lite.db.Query(q)
if err != nil {
return results, err
}
defer rows.Close()
cols, err := rows.Columns()
if err != nil {
return results, err
}
gotReaders := false
var bytesReader *bytes.Reader
var gzipReader *gzip.Reader
for rows.Next() {
m := map[string]string{}
columns := make([]interface{}, len(cols))
columnPointers := make([]interface{}, len(cols))
for i := range columns {
columnPointers[i] = &columns[i]
}
if err := rows.Scan(columnPointers...); err != nil {
return results, err
}
// Skip adding item if note body does not contain search string
val := columnPointers[len(cols)-1].(*interface{})
// Type assertion required by bytesReader
noteBodyZippedBytes, ok := (*val).([]byte)
if !ok {
continue
}
if gotReaders {
bytesReader.Reset(noteBodyZippedBytes)
gzipReader.Reset(bytesReader)
} else {
bytesReader = bytes.NewReader(noteBodyZippedBytes)
gzipReader, err = gzip.NewReader(bytesReader)
if err != nil {
continue
}
gotReaders = true
}
body, err := ioutil.ReadAll(gzipReader)
if err != nil {
continue
}
if !strings.Contains(strings.ToLower(string(body)), strings.ToLower(search)) {
continue
}
for i, colName := range cols {
// Don't add note body data to future alfred row
if colName == BodyKey {
continue
}
val := columnPointers[i].(*interface{})
s, ok := (*val).(string)
if ok {
m[colName] = s
} else {
m[colName] = ""
}
}
results = append(results, m)
}
return results, err
}
func RowToItem(row map[string]string, userQuery UserQuery) alfred.Item {
return alfred.Item{
Title: row[TitleKey],
Subtitle: row[SubtitleKey],
Arg: row[ArgKey] + "?" + Escape(userQuery.WordString),
QuicklookURL: nil,
}
}
func CreateNoteItem(userQuery UserQuery) (*alfred.Item, error) {
title := userQuery.WordString
item := alfred.Item{
Title: title,
Arg: title,
Subtitle: "Create new note",
}
return &item, nil
}
func ParseUserQuery(arg string) UserQuery {
userQuery := UserQuery{}
userQuery.Tokens = strings.Split(norm.NFC.String(arg), " ")
words := []string{}
for _, e := range userQuery.Tokens {
if e != "" {
words = append(words, e)
}
}
userQuery.WordString = strings.Join(words, " ")
return userQuery
}
func GetOrderPreference() string {
if (os.Getenv("sortByDate") != "0") {
return "modDate DESC"
} else {
return "lower(noteTitle) ASC"
}
}
func GetSearchTitleRows(litedb LiteDB, userQuery UserQuery) ([]map[string]string, error) {
likeString := "%%" + userQuery.WordString + "%%"
orderBy := GetOrderPreference()
var where string
if (os.Getenv("searchFolders") != "0") {
where = "WHERE (lower(folderTitle) || ' ' || lower(noteTitle)) LIKE lower(?)"
} else {
where = "WHERE lower(noteTitle) LIKE lower(?)"
}
rows, err := litedb.Query(fmt.Sprintf(NotesSQLTemplate, where, orderBy), likeString)
if err != nil {
return nil, err
}
return rows, nil
}
func GetSearchBodyRows(litedb LiteDB, userQuery UserQuery) ([]map[string]string, error) {
orderBy := GetOrderPreference()
where := ""
rows, err := litedb.QueryThenSearch(fmt.Sprintf(NotesSQLTemplate, where, orderBy), userQuery.WordString)
if err != nil {
return nil, err
}
return rows, nil
}
func GetSearchFolderRows(litedb LiteDB, userQuery UserQuery) ([]map[string]string, error) {
likeString := "%%" + userQuery.WordString + "%%"
rows, err := litedb.Query(FoldersSQLTemplate, likeString)
if err != nil {
return nil, err
}
return rows, nil
}
func PanicOnErr(err error) {
if err != nil {
panic(err)
}
}
func main() {
if len(os.Args) >= 3 {
litedb, err := NewNotesDB()
PanicOnErr(err)
userQuery := ParseUserQuery(os.Args[2])
searchRows := []map[string]string{}
if os.Args[1] == "title" {
searchRows, err = GetSearchTitleRows(litedb, userQuery)
PanicOnErr(err)
if len(searchRows) == 0 {
createItem, err := CreateNoteItem(userQuery)
PanicOnErr(err)
alfred.Add(*createItem)
}
} else if os.Args[1] == "body" {
searchRows, err = GetSearchBodyRows(litedb, userQuery)
PanicOnErr(err)
} else if os.Args[1] == "folder" {
searchRows, err = GetSearchFolderRows(litedb, userQuery)
PanicOnErr(err)
}
if len(searchRows) > 0 {
for _, row := range searchRows {
alfred.Add(RowToItem(row, userQuery))
}
}
alfred.Run()
}
}