-
Notifications
You must be signed in to change notification settings - Fork 0
/
__init__.py
272 lines (235 loc) · 8.38 KB
/
__init__.py
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
"""
Obsidian plugin for Albert launcher.
Searches notes in an Obsidian vault. Allows for creation of new notes in the selected vault.
"""
from pathlib import Path
from threading import Event, Thread
from time import perf_counter_ns
from urllib import parse
import frontmatter
from albert import *
from watchfiles import Change, DefaultFilter, watch
from yaml.constructor import ConstructorError
md_iid = "2.3"
md_version = "1.6"
md_name = "Obsidian"
md_description = "Search/add notes in a Obsidian vault."
md_url = "https://github.com/Pete-Hamlin/albert-obsidian.git"
md_license = "MIT"
md_authors = ["@Pete-Hamlin"]
md_lib_dependencies = ["python-frontmatter", "watchfiles"]
class Note:
def __init__(self, path: Path, body) -> None:
self.path = path
self.body = body
class CDFilter(DefaultFilter):
"""
When it comes to indexing, we don't care about updates to the file, so this filter
allows us to just watch for create/delete events and re-index accordingly when they happen
"""
allowed_changes = [Change.added, Change.deleted]
def __call__(self, change: Change, path: str) -> bool:
return change in self.allowed_changes and super().__call__(change, path)
class FileWatcherThread(Thread):
def __init__(self, callback, path, *args, **kwargs) -> None:
super().__init__(*args, **kwargs)
self.__stop_event = Event()
self.__callback = callback
self.__path = path
def run(self):
# Watch for file changes and re-index
for _ in watch(
self.__path, watch_filter=CDFilter(), stop_event=self.__stop_event
):
self.__callback()
def stop(self):
self.__stop_event.set()
class Plugin(PluginInstance, IndexQueryHandler):
iconUrls = [
f"file:{Path(__file__).parent}/obsidian.png",
"xdg:folder-documents",
]
def __init__(self):
PluginInstance.__init__(self)
IndexQueryHandler.__init__(
self,
id=self.id,
name=self.name,
description=self.description,
defaultTrigger="obs ",
synopsis="<note>",
)
self._root_dir = self.readConfig("root_dir", str) or ""
self._open_override = self.readConfig("open_override", str) or "xdg-open"
self._config_dir = self.readConfig("config_dir", str) or ""
self._filter_by_tags = self.readConfig("filter_by_tags", bool) or True
self._filter_by_body = self.readConfig("filter_by_body", bool) or False
self.root_path = Path(self._root_dir)
self.thread = FileWatcherThread(self.updateIndexItems, self._root_dir)
self.thread.start()
def __del__(self):
self.thread.stop()
self.thread.join()
@property
def root_dir(self):
return self._root_dir
@root_dir.setter
def root_dir(self, value):
self._root_dir = value
self.writeConfig("root_dir", value)
self.root_path = Path(value)
self.thread.stop()
self.thread.join()
self.thread = FileWatcherThread(self.updateIndexItems, self._root_dir)
self.thread.start()
@property
def open_override(self):
return self._open_override
@open_override.setter
def open_override(self, value):
self._open_override = value
self.writeConfig("open_override", value)
@property
def filter_by_tags(self):
return self._filter_by_tags
@filter_by_tags.setter
def filter_by_tags(self, value):
self._filter_by_tags = value
self.writeConfig("filter_by_tags", value)
@property
def filter_by_body(self):
return self._filter_by_body
@filter_by_body.setter
def filter_by_body(self, value):
self._filter_by_body = value
self.writeConfig("filter_by_body", value)
def configWidget(self):
return [
{
"type": "lineedit",
"property": "root_dir",
"label": "Path to notes vault",
},
{
"type": "lineedit",
"property": "open_override",
"label": "Open command to run Obsidian URI",
},
{
"type": "checkbox",
"property": "filter_by_tags",
"label": "Filter by note tags",
},
{
"type": "checkbox",
"property": "filter_by_body",
"label": "Filter by note body",
},
]
def updateIndexItems(self):
start = perf_counter_ns()
notes = self.parse_notes()
index_items = []
for note in notes:
filter = self.create_filters(note)
item = self.gen_item(note)
index_items.append(IndexItem(item=item, string=filter))
self.setIndexItems(index_items)
info(
"Indexed {} notes [{:d} ms]".format(
len(index_items), (int(perf_counter_ns() - start) // 1000000)
)
)
def handleTriggerQuery(self, query):
# Trigger query will ignore the index and always check against the latest vault state
stripped = query.string.strip()
if stripped:
if not query.isValid:
return
data = self.parse_notes()
notes = (
item
for item in data
if all(
filter in self.create_filters(item)
for filter in query.string.split()
)
)
items = [self.gen_item(item) for item in notes]
text = parse.urlencode(
{"vault": self.root_path.name, "name": stripped}, quote_via=parse.quote
)
run_args = self._open_override.split() + [f"obsidian://new?{text}"]
query.add(items)
query.add(
StandardItem(
id=self.id,
text="Create new Note",
subtext=f"{str(self.root_path)}/{stripped}",
iconUrls=["xdg:accessories-text-editor"],
actions=[
Action(
"create",
"Create note",
lambda args=run_args: runDetachedProcess(args),
)
],
)
)
else:
query.add(
StandardItem(
id=self.id,
text=self.name,
subtext="Search for a note in Obsidian",
iconUrls=self.iconUrls,
)
)
def parse_notes(self):
for item in self.root_path.rglob("*.md"):
try:
body = frontmatter.load(item)
except ConstructorError:
# If the frontmatter is unparsable (e.g. template, just skip it)
warning(f"Unable to parse {item.name} - skipping")
continue
yield Note(item, body)
def create_filters(self, note: Note) -> str:
filters, tags = note.path.name, note.body.get("tags")
if self._filter_by_tags and tags:
if isinstance(tags, list):
tags = [tag or "" for tag in tags]
filters += ",".join(tags)
else:
filters += str(tags)
if self._filter_by_body:
filters += note.body.content
return filters.lower()
def gen_item(self, note: Note):
tags = note.body.get("tags")
if tags:
tags = (tag or "" for tag in tags)
subtext = " - ".join([str(note.path), ",".join(tags)])
else:
subtext = str(note.path)
note_uri = "obsidian://open?{}".format(
parse.urlencode(
{"vault": self.root_path.name, "file": note.path.name},
quote_via=parse.quote,
)
)
run_args = self._open_override.split() + [note_uri]
return StandardItem(
id=self.id,
text=note.path.name.replace(".md", ""),
subtext=subtext,
iconUrls=self.iconUrls,
actions=[
Action(
"open",
"Open",
lambda args=run_args: runDetachedProcess(args),
),
Action("copy", "Copy URI", lambda uri=note_uri: setClipboardText(uri)),
],
)