-
Notifications
You must be signed in to change notification settings - Fork 2
/
crossref.js
261 lines (237 loc) · 6.86 KB
/
crossref.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
253
254
255
256
257
258
259
260
261
const notice = (msg) => new Notice(msg, 5000);
const log = (msg) => console.log(msg);
const API_URL = "https://api.crossref.org/v1/works";
const TEMPLATE = "Template file:";
const DESTINATION_DIR = "Destination folder:";
const FILENAME_FORMAT = "Filename format:";
const FILENAME_FORMAT_DEFAULT = "{{~title~}}";
const ILLEGAL_OBSIDIAN_FILE_NAME_PATTERN = /[\\,#%&\{\}\/*<>?$\'\":@]*/g;
module.exports = {
entry: start,
settings: {
name: "Crossref",
// author: "",
options: {
[FILENAME_FORMAT]: {
type: "text",
defaultValue: FILENAME_FORMAT_DEFAULT,
},
[TEMPLATE]: {
type: "select",
options: app.vault.getAbstractFileByPath('templates').children.map((t) => t.path),
},
[DESTINATION_DIR]: {
type: "select",
options: Object.keys(app.vault.fileMap).filter(function (filemapentry){return Object.keys(app.vault.fileMap[filemapentry]).includes('children')}),
},
},
},
};
let QuickAdd;
let Settings;
function init(params, settings) {
QuickAdd = params;
Settings = settings;
}
async function start(params, settings) {
QuickAdd = params;
Settings = settings;
var query = activeDocument.getSelection().toString();
if (typeof query != "string"){
query = null;
}
if (!query){
query = getFrontmatterDoi();
if (query){
if (!await QuickAdd.quickAddApi.yesNoPrompt('Use DOI from frontmatter?')){
query = null;
}
}
}
if (!query){
query = await getQuery();
query = query.searchTerms;
}
if (!query) {
notice("No query entered.");
throw new Error("No query entered.");
}
var selectedRef;
if (isDoi(query)){
selectedRef = await fetchReference(API_URL, query);
}
else{
let possibleRefs = await getRefsByQueryParams(query);
selectedRef = await promptUserForSelectingSuggestions(possibleRefs);
}
if (selectedRef){
console.log(selectedRef);
// Read in template as defined in settings:
let template_file = app.vault.getAbstractFileByPath(Settings[TEMPLATE]);
let template = await app.vault.read(template_file);
// Apply template to coll object:
let rendered = params.app.plugins.getPlugin('obsidian-handlebar-helper-plugin').compileAndRender(template,selectedRef);
// Build filename and create file:
filename_template = Settings[FILENAME_FORMAT];
fileName = params.app.plugins.getPlugin('obsidian-handlebar-helper-plugin').compileAndRender(filename_template,selectedRef);
fileName = Settings[DESTINATION_DIR] + '/' + fileName.replace(ILLEGAL_OBSIDIAN_FILE_NAME_PATTERN, "") + '.md';
console.log(fileName);
try{
createdFile = await params.app.vault.create(fileName, rendered);
if (createdFile){
// Open it:
leaf = params.app.workspace.getUnpinnedLeaf();
await leaf.openFile(createdFile)
}
}
catch(Error){
notice('Could not create file / already exists');
}
}
else{
notice("No reference selected");
throw new Error("No reference selected.");
}
}
function formatTitleForSuggestionList(resultItem) {
var suggestion = `${resultItem.title}`;
// if (resultItem.description){
// suggestion = suggestion + ` Description: ${resultItem.description}`
// }
// if (resultItem.geography){
// suggestion = suggestion + ` Geography: ${resultItem.geography}`
// }
// if (resultItem.taxonomicCoverage){
// suggestion = suggestion + ` Taxonomic coverage: ${resultItem.taxonomicCoverage}`
// }
return decodeEntity(suggestion);
}
function decodeEntity(inputStr) {
var textarea = document.createElement("textarea");
textarea.innerHTML = inputStr;
return textarea.value;
}
function getFrontmatterDoi(){
var doi;
leaf = app.workspace.getUnpinnedLeaf();
var filemeta = app.metadataCache.getFileCache(leaf.view.file);
if (Object.keys(filemeta).includes("frontmatter")){
if (Object.keys(filemeta.frontmatter).includes("doi")){
doi = filemeta.frontmatter.doi;
}
}
return doi;
}
async function getQuery(){
return Promise.all([promptUserForSearchTerms()]).then(
([searchTerms]) =>
new Promise((resolve, reject) => {
if (!searchTerms) {
notice("No query entered.");
reject(new Error("No query entered."));
}
resolve({ searchTerms });
})
);
}
function promptUserForSearchTerms(){
return QuickAdd.quickAddApi.inputPrompt("Crossref search terms:");
}
function promptUserForSelectingSuggestions(suggestions) {
return new Promise((resolve, reject) => {
QuickAdd.quickAddApi
.suggester(suggestions.map(formatTitleForSuggestionList), suggestions)
.then(async (selectedRef) => {
if (!selectedRef) {
notice("No choice selected.");
reject(new Error("No choice selected."));
}
resolve(selectedRef);
});
});
}
/**
*
* @param {object} reference The reference data searching CrossRef
* @returns {Reference}
*/
function buildReferencesData(reference) {
return reference;
}
/**
*
* @param {object} queryParams
* @throws Will throw Error if no collections are found
* @returns {Reference[]} The reference results from searching for a reference
*/
async function getRefsByQueryParams(queryParams) {
const searchResults = await fetchReferences(
API_URL,
queryParams
);
console.log(searchResults);
if (!searchResults || !searchResults.length) {
notice("No results found.");
throw new Error("No results found.");
}
return searchResults.map(buildReferencesData);
}
/**
*
* @param {object} queryParams
* @returns {string} The query string for requests to crossref API
*/
function buildQueryString(queryParam) {
return queryParam;
}
function isDoi(str){
var possibleDoi = str
if (/^doi:[^\s]+$/i.test(str)){
possibleDoi = str.replace(/^doi:/i,'')
}
return /^10.[^\s]+$/i.test(possibleDoi);
}
function cleanDoiPrefix(str){
var cleaned = str;
if (/^doi:[^\s]+$/i.test(str)){
cleaned = str.replace(/^doi:/i,'')
}
return cleaned;
}
/**
*
* @param {string} url
* @param {object} queryParams
* @returns {object[]}
*/
async function fetchReferences(url, queryParam) {
let finalURL = new URL(url);
finalURL.searchParams.append("query", buildQueryString(queryParam));
console.log(finalURL);
return JSON.parse(
await request({
url: finalURL.href,
method: "GET",
cache: "no-cache",
headers: {
"Content-Type": "application/json",
"User-Agent": "ObsidianQuickAddMacro ( [email protected] )",
},
})
)['message']['items'];
}
async function fetchReference(url, doi) {
let finalURL = new URL(url + '/' + cleanDoiPrefix(doi));
console.log(finalURL);
return JSON.parse(
await request({
url: finalURL.href,
method: "GET",
cache: "no-cache",
headers: {
"Content-Type": "application/json",
"User-Agent": "ObsidianQuickAddMacro ( [email protected] )",
},
})
)['message'];
}