-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhoarder.py
279 lines (244 loc) · 10.2 KB
/
hoarder.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
273
274
275
276
277
278
279
import requests
import json
import sys
import os
import hashlib
from pathlib import Path
from urllib.parse import urlparse, quote
# cache at current directory
CACHE_DIR = Path(__file__).parent / "cache"
HOARDER_SERVER_ADDR = os.getenv("HOARDER_SERVER_ADDR")
HORADER_API_URL = f"{HOARDER_SERVER_ADDR}/api/v1/bookmarks"
HOARDER_SEARCH_API_URL = f"{HOARDER_SERVER_ADDR}/api/trpc/bookmarks.searchBookmarks"
HOARDER_API_KEY = os.getenv("HOARDER_API_KEY")
HEADERS = {
"Accept": "application/json",
"Authorization": f"Bearer {HOARDER_API_KEY}"
}
TAGS_SHOWN_COUNT = int(os.getenv("TAGS_SHOWN_COUNT", "0"))
def ensure_cache_dir():
CACHE_DIR.mkdir(parents=True, exist_ok=True)
def get_favicon_path(favicon_url):
"""Download favicon and return local path"""
if not favicon_url:
return "icon.png"
# use md5 as file name
favicon_hash = hashlib.md5(favicon_url.encode()).hexdigest()
file_extension = Path(urlparse(favicon_url).path).suffix or '.ico'
cache_path = CACHE_DIR / f"{favicon_hash}{file_extension}"
# if cache exists and is not empty, return it
if cache_path.exists() and cache_path.stat().st_size > 0:
return str(cache_path)
return "icon.png"
# download favicon
#try:
# response = requests.get(favicon_url, timeout=5)
# response.raise_for_status()
# with open(cache_path, 'wb') as f:
# f.write(response.content)
# return str(cache_path)
#except Exception as e:
# print(f"Error downloading favicon: {e}", file=sys.stderr)
# return "icon.png"
def get_thumbnail_path(asset_id):
"""Download and cache thumbnail for image assets"""
if not asset_id:
return "icon.png"
cache_path = CACHE_DIR / f"thumb_{asset_id}.png"
if cache_path.exists() and cache_path.stat().st_size > 0:
return str(cache_path)
return "icon.png"
#try:
# thumbnail_url = f"{HOARDER_SERVER_ADDR}/api/assets/{asset_id}"
# response = requests.get(thumbnail_url, headers=HEADERS, timeout=5)
# response.raise_for_status()
# with open(cache_path, 'wb') as f:
# f.write(response.content)
# return str(cache_path)
#except Exception as e:
# print(f"Error downloading thumbnail: {e}", file=sys.stderr)
# return "icon.png"
def format_title_with_tags(bookmark):
"""Format title with tags based on TAGS_SHOWN_COUNT"""
content = bookmark.get("content", {})
content_type = content.get("type")
if content_type == "asset" and content.get("assetType") == "image":
title = content.get("fileName", "Untitled Image")
else:
title = (bookmark.get("content", {}).get("title") or
bookmark.get("title") or
"Untitled")
if TAGS_SHOWN_COUNT > 0:
tags = bookmark.get("tags", [])
if tags:
shown_tags = tags[:TAGS_SHOWN_COUNT]
tags_string = " " + ", ".join(f"#{tag.get('name', '')}" for tag in shown_tags if tag.get('name'))
title = f"{title}{tags_string}"
return title
def format_title_without_tags(bookmark):
content = bookmark.get("content", {})
content_type = content.get("type")
if content_type == "asset" and content.get("assetType") == "image":
title = content.get("fileName", "Untitled Image")
else:
title = (bookmark.get("content", {}).get("title") or
bookmark.get("title") or
"Untitled")
return title
def get_arg_and_icon(bookmark):
"""Get appropriate arg and icon path based on content type"""
content = bookmark.get("content", {})
content_type = content.get("type")
if content_type == "text" or content_type == "asset":
#arg = bookmark.get("id", "")
arg = HOARDER_SERVER_ADDR + "/dashboard/preview/" + bookmark.get("id", "")
icon_path = ("icon.png" if content_type == "text" else
get_thumbnail_path(content.get("assetId")))
else:
arg = content.get("url", "")
icon_path = get_favicon_path(content.get("favicon"))
return arg, icon_path
def fetch_bookmarks():
try:
# add pagination params
params = {
'limit': 20, # or larger number
'page': 1 # or use offset: 0
}
ensure_cache_dir()
response = requests.get(HORADER_API_URL, headers=HEADERS, params=params)
response.raise_for_status()
data = response.json()
# print actual data structure
#print("DEBUG: API Response:", json.dumps(data, indent=2), file=sys.stderr)
# print response headers
#print("DEBUG Headers:", dict(response.headers), file=sys.stderr)
#print("DEBUG Total bookmarks:", len(data.get("bookmarks", [])), file=sys.stderr)
# DEBUG; get data directly, not use .get("bookmarks")
#bookmarks = data if isinstance(data, list) else data.get("bookmarks", [])
bookmarks = data.get("bookmarks", [])
# Format bookmarks for Alfred feedback
alfred_feedback = {
"items": [
{
"title": format_title_with_tags(bookmark),
"subtitle": (bookmark.get("content", {}).get("url", "") or
bookmark.get("content", {}).get("text", "") or
bookmark.get("content", {}).get("fileName", "")),
"arg": get_arg_and_icon(bookmark)[0],
"mods": {
"ctrl": {
"arg": bookmark.get("id", "")
},
"cmd": {
"arg": get_arg_and_icon(bookmark)[0],
},
"option": {
"arg": f"{HOARDER_SERVER_ADDR}/dashboard/preview/{bookmark.get('id', '')}"
},
"shift": {
"arg": f"[{format_title_without_tags(bookmark)}]({get_arg_and_icon(bookmark)[0]})"
}
},
"icon": {
"path": get_arg_and_icon(bookmark)[1]
},
"quicklookurl": bookmark.get("content", {}).get("url"),
# create match text, include title, url, description and html content and tags
#"match": " ".join(filter(None, [
# bookmark.get("content", {}).get("title", ""),
# bookmark.get("content", {}).get("url", ""),
# bookmark.get("content", {}).get("description", ""),
# bookmark.get("content", {}).get("htmlContent", ""),
# bookmark.get("note", ""),
# bookmark.get("summary", ""),
# # join tags with space
# " ".join(tag.get("name", "") for tag in bookmark.get("tags", []))
#])).replace('/', ' ').replace('-', ' ').replace('_', ' ')
} for bookmark in bookmarks
]
}
print(json.dumps(alfred_feedback))
except requests.exceptions.RequestException as e:
print(json.dumps({
"items": [
{
"title": "Error fetching bookmarks",
"subtitle": str(e),
"icon": {
"path": "icon.png"
}
}
]
}))
sys.exit(1)
def search_bookmarks(query=""):
try:
ensure_cache_dir()
# Construct the search payload
search_input = {
"0": {
"json": {
"text": query
}
}
}
encoded_input = quote(json.dumps(search_input))
search_url = f"{HOARDER_SEARCH_API_URL}?batch=1&input={encoded_input}"
response = requests.get(search_url, headers=HEADERS)
response.raise_for_status()
data = response.json()
# Extract bookmarks from the search response
bookmarks = data[0]["result"]["data"]["json"]["bookmarks"] if data else []
# Use the same format as fetch_bookmarks
alfred_feedback = {
"items": [
{
"title": format_title_with_tags(bookmark),
"subtitle": (bookmark.get("content", {}).get("url", "") or
bookmark.get("content", {}).get("text", "") or
bookmark.get("content", {}).get("fileName", "")),
"arg": get_arg_and_icon(bookmark)[0],
"mods": {
"ctrl": {
"arg": bookmark.get("id", "")
},
"option": {
"arg": f"{HOARDER_SERVER_ADDR}/dashboard/preview/{bookmark.get('id', '')}"
},
"cmd": {
"arg": get_arg_and_icon(bookmark)[0],
},
"shift": {
"arg": f"[{format_title_without_tags(bookmark)}]({get_arg_and_icon(bookmark)[0]})"
}
},
"icon": {
"path": get_arg_and_icon(bookmark)[1]
},
"quicklookurl": bookmark.get("content", {}).get("url")
} for bookmark in bookmarks
]
}
print(json.dumps(alfred_feedback))
except requests.exceptions.RequestException as e:
print(json.dumps({
"items": [
{
"title": "Error searching bookmarks",
"subtitle": str(e),
"icon": {
"path": "icon.png"
}
}
]
}))
sys.exit(1)
if __name__ == "__main__":
# Get search query from command line argument if provided
#fetch_bookmarks()
query = sys.argv[1] if len(sys.argv) > 1 else ""
if not query:
fetch_bookmarks()
sys.exit(0)
search_bookmarks(query)