generated from obsidianmd/obsidian-sample-plugin
/
EzImport.js
252 lines (217 loc) · 8.08 KB
/
EzImport.js
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
const READWISE_API_OPTION = "Readwise API key";
const ARTICLE_FORMAT = "Article file name format";
const YOUTUBE_VIDEO_FORMAT = "YouTube video file name format";
const PODCAST_FORMAT = "Podcast episode file name format";
const TWEET_FORMAT = "Tweet file name format";
const BOOK_FORMAT = "Book file name format";
const IGNORE_EMPTY_PROPERTIES = "Ignore empty Properties";
const READWISE_API_URL = "https://readwise.io/api/v2/";
const LogAndThrowError = (error) => {
new Notice("error", 10000);
throw new Error(error);
};
const EzImportType = Object.freeze({
Article: "articles",
YouTube_video: "youtube-video",
Podcast_episode: "podcasts",
Tweet: "tweets",
Book: "books"
});
module.exports = {
entry: () => {
new Notice("Please use one of the specific entry points.", 10000);
},
settings: {
name: "EzImport",
author: "Christian B. B. Houmann",
options: {
[READWISE_API_OPTION]: {
type: "input",
placeholder: "Readwise API key",
},
[IGNORE_EMPTY_PROPERTIES]: {
type: "toggle",
defaultValue: true,
},
[ARTICLE_FORMAT]: {
type: "format",
defaultValue: "",
placeholder: "Article file name format",
},
[YOUTUBE_VIDEO_FORMAT]: {
type: "format",
defaultValue: "",
placeholder: "YouTube video file name format",
},
[PODCAST_FORMAT]: {
type: "format",
defaultValue: "",
placeholder: "Podcast episode file name format",
},
[TWEET_FORMAT]: {
type: "format",
defaultValue: "",
placeholder: "Tweet file name format",
},
[BOOK_FORMAT]: {
type: "format",
defaultValue: "",
placeholder: "Book file name format",
},
}
},
article: (params, settings) => start(params, settings, EzImportType.Article),
podcastEpisode: (params, settings) => start(params, settings, EzImportType.Podcast_episode),
tweet: (params, settings) => start(params, settings, EzImportType.Tweet),
book: (params, settings) => start(params, settings, EzImportType.Book),
};
let QuickAdd;
let Settings;
async function start(params, settings, type) {
QuickAdd = params;
Settings = settings;
if (settings[READWISE_API_OPTION] == null) {
LogAndThrowError("Please provide a valid Readwise API key.");
}
return await getReadwiseHighlights(type);
}
async function getReadwiseHighlights(type) {
const resolve = await getHighlightsByCategory(type);
if (!resolve) {
LogAndThrowError("No highlights found.");
}
const {results} = resolve;
const item = await QuickAdd.quickAddApi.suggester(results.map(item => item.title), results);
if (!item) {
LogAndThrowError("No item selected.");
}
const safeTitle = replaceIllegalFileNameCharactersInString(item.title);
const fileName = await getFileName(type, safeTitle);
QuickAdd.variables = {
...QuickAdd.variables,
safeTitle,
fileName,
title: item.title,
author: `[[${item.author}]]`,
source: item.source_url,
tags: item.tags.map(tag => tag.name).join(", "),
cover: item.cover_image_url,
lastHighlightAt: item.last_highlight_at,
updated: item.updated,
numHighlights: item.num_highlights,
};
if (Settings[IGNORE_EMPTY_PROPERTIES]) {
Object.keys(QuickAdd.variables).forEach(key => {
if (QuickAdd.variables[key] === "") {
QuickAdd.variables[key] = " ";
}
});
}
const file = await QuickAdd.app.vault.getAbstractFileByPath(`${fileName.replace('.md', '')}.md`);
if (file) {
await handleAddToExistingFile(file, item);
} else {
await handleCreateSourceFile(item);
}
return fileName;
}
async function handleAddToExistingFile(file, item) {
const metaEdit = QuickAdd.app.plugins.plugins["metaedit"];
if (!metaEdit) {
LogAndThrowError("MetaEdit not found. Please install it to add highlights to existing files.");
}
const { update } = metaEdit.api;
const lastHighlightAt = QuickAdd.app.metadataCache.getFileCache(file).frontmatter["lastHighlightAt"];
if (!lastHighlightAt) {
LogAndThrowError("File does not have a lastHighlightAt property.");
}
const resolve = await getHighlightsAfterDateForItem(item, lastHighlightAt);
const highlights = resolve.results.reverse();
if (highlights.length > 0) {
QuickAdd.variables.highlights = `\n${formatHighlights(highlights)}`;
await update("lastHighlightAt", item.last_highlight_at, file);
new Notice(`Added ${highlights.length} highlights to '${file.basename}'.`, 10000);
} else {
// Throw so we don't continue the capture flow.
LogAndThrowError(`No highlights found after ${new Date(lastHighlightAt).toISOString()}`);
}
}
async function handleCreateSourceFile(item) {
const resolve = await getHighlightsForItem(item);
if (!resolve) {
LogAndThrowError("No highlights found.");
}
const highlights = resolve.results.reverse();
QuickAdd.variables.highlights = formatHighlights(highlights);
}
async function getFileName(type, safeTitle) {
let fileNameFormat;
switch (type) {
case EzImportType.Article:
fileNameFormat = Settings[ARTICLE_FORMAT];
break;
case EzImportType.YouTube_video:
fileNameFormat = Settings[YOUTUBE_VIDEO_FORMAT];
break;
case EzImportType.Podcast_episode:
fileNameFormat = Settings[PODCAST_FORMAT];
break;
case EzImportType.Tweet:
fileNameFormat = Settings[TWEET_FORMAT];
break;
case EzImportType.Book:
fileNameFormat = Settings[BOOK_FORMAT];
break;
}
fileNameFormat = fileNameFormat.replace(/{{VALUE:safeTitle}}/g, safeTitle);
return await QuickAdd.quickAddApi.format(fileNameFormat);
}
function formatHighlights(highlights) {
return highlights.map(hl => {
if (hl.text == "No title") return;
const {quote, note} = textFormatter(hl.text, hl.note);
return `${quote}${note}`;
}).join("\n\n");
}
function textFormatter(sourceText, sourceNote) {
let quote = sourceText.split("\n").filter(line => line != "").map(line => {
if (sourceNote.includes(".h1"))
return `## ${line}`;
else
return `> ${line}`;
}).join("\n");
let note;
if (sourceNote.includes(".h1") || sourceNote == "" || !sourceNote) {
note = "";
} else {
note = "\n\n" + sourceNote;
}
return {quote, note};
}
async function getHighlightsByCategory(category) {
return apiGet(`${READWISE_API_URL}books`, {category, "page_size": 1000});
}
async function getHighlightsForItem(element) {
return apiGet(`${READWISE_API_URL}highlights`, {book_id: element.id, page_size: 1000});
}
async function getHighlightsAfterDateForItem(element, date) {
return apiGet(`${READWISE_API_URL}highlights`, {book_id: element.id, page_size: 1000, highlighted_at__gt: date});
}
async function apiGet(url, data) {
let finalURL = new URL(url);
if (data)
Object.keys(data).forEach(key => finalURL.searchParams.append(key, data[key]));
return await fetch(finalURL, {
method: 'GET', cache: 'no-cache',
headers: {
'Content-Type': 'application/json',
Authorization: `Token ${Settings[READWISE_API_OPTION]}`
},
}).then(async (res) => await res.json());
}
function replaceIllegalFileNameCharactersInString(string) {
return string
.replace(/[\\,#%&\{\}\/*<>$\'\":@]*/g, '') // Replace illegal file name characters with empty string
.replace(/\n/, ' ') // replace newlines with spaces
.replace(' ', ' '); // replace multiple spaces with single space to make sure we don't have double spaces in the file name
}