forked from Elaws/script_googleBooks_quickAdd
-
Notifications
You must be signed in to change notification settings - Fork 0
/
script_googleBooks_quickAdd.js
210 lines (169 loc) · 5.61 KB
/
script_googleBooks_quickAdd.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
const notice = (msg) => new Notice(msg, 5000);
const log = (msg) => console.log(msg);
// Do NOT edit this.
// API KEY should be entered in the script settings in QuickAdd plugin options.
const API_URL = "https://www.googleapis.com/books/v1/volumes";
const API_KEY = "Google Books API Key"
const GOODREADS_URL = "https://www.goodreads.com/search?qid=&q="
module.exports = {
entry: start,
settings: {
name: "Books script",
author: "Elaws",
options: {
[API_KEY]: {
type: "text",
defaultValue: "",
placeholder: "Google Books API Key",
}
},
},
};
let QuickAdd;
let Settings;
async function start(params, settings) {
QuickAdd = params;
Settings = settings;
var author;
// Possible to enter a book title or ISBN.
var query = await QuickAdd.quickAddApi.inputPrompt(
"Book title or ISBN: "
);
// If no ISBN is entered, a prompt asks author name.
// Possible to enter only author name, and no book title at previous step.
if(!isISBN(query)){
author = await QuickAdd.quickAddApi.inputPrompt(
"Author: "
);
}
if(author) {
if(!query){
query = `inauthor:${author}`;
} else {
query = query.concat(" inauthor:", author);
}
}
if (!query) {
notice("No query entered.");
throw new Error("No query entered.");
}
log(query);
const searchResults = await getByQuery(query);
const selection = await QuickAdd.quickAddApi.suggester(
searchResults.map(formatTitleForSuggestion),
searchResults
);
if (!selection) {
notice("No choice selected.");
throw new Error("No choice selected.");
}
const selectedBook = selection.volumeInfo;
const ISBN = getISBN(selectedBook);
const isRead = await QuickAdd.quickAddApi.yesNoPrompt("Read ?");
let myRating = "/10";
let myRecommender = " ";
let comment = " ";
// If book already read, add a rating to it.
if(isRead){
myRating = await QuickAdd.quickAddApi.inputPrompt("Rating", null, "/10");
}
myRecommender = await QuickAdd.quickAddApi.inputPrompt("Recommender", null, " ");
comment = await QuickAdd.quickAddApi.inputPrompt("Comment", null, " ");
QuickAdd.variables = {
...selectedBook,
fileName: replaceIllegalFileNameCharactersInString(selectedBook.title),
authors: formatList(selectedBook.authors),
isbn10: `${ISBN.ISBN10 ? ISBN.ISBN10 : " "}`,
isbn13: `${ISBN.ISBN13 ? ISBN.ISBN13 : " "}`,
// An URL to the GoodReads page of the book using its ISBN.
// May fail if ISBN returned by Google Books is not in Goodreads database.
goodreadsURL: `${ISBN.ISBN13 ? GOODREADS_URL + ISBN.ISBN13 : (ISBN.ISBN10 ? GOODREADS_URL + ISBN.ISBN10 : " ")}`,
thumbnail: `${selectedBook.imageLinks ? selectedBook.imageLinks.thumbnail : " "}`.replace("http:", "https:"),
// Publication date
release: `${selectedBook.publishedDate ? (new Date((selectedBook.publishedDate))).getFullYear() : " "}`,
// Squares of different color to tag Obsidian's note, depending if book has already been read or not.
tag: `${isRead ? "\u{0001F7E7}" : "\u{0001F7E5}"}`,
// Main Category reported for the book
genre: `${selectedBook.categories ? selectedBook.categories : "N/A"}`,
// A rating for the read book, /10.
rating: myRating,
// The global average review * 2 to get /10
avRating: `${selectedBook.averageRating ? selectedBook.averageRating * 2 : 0 }`,
// For mature audiences or not?
mature: `${selectedBook.maturityRating ? selectedBook.maturityRating : "NA" }`,
// Pages reported in book
pageCount: `${selectedBook.pageCount ? selectedBook.pageCount : 0 }`,
// blurb
bookDesc: `${selectedBook.description ? selectedBook.description : "No Description Reported" }`,
// Is the book already read ? 1 if yes, 0 otherwise.
read: `${isRead ? "1" : "0"}`,
// Who recommended the book to me?
recommender: myRecommender,
// A short personal comment on the book.
comment
};
}
function getISBN(item){
var ISBN10 = " ";
var ISBN13 = " ";
var isbn10_data, isbn13_data;
if(item.industryIdentifiers)
{
isbn10_data = (item.industryIdentifiers).find(element => element.type == "ISBN_10");
isbn13_data = (item.industryIdentifiers).find(element => element.type == "ISBN_13");
}
if(isbn10_data) ISBN10 = isbn10_data.identifier;
if(isbn13_data) ISBN13 = isbn13_data.identifier;
return {ISBN10, ISBN13};
}
function isISBN(str){
return /^(97(8|9))?\d{9}(\d|X)$/.test(str);
}
// Suggestion prompt will include :
// (i) prefix if a book cover is available (i for "image")
// Book's title
// Book's author
// Publication year
function formatTitleForSuggestion(resultItem){
return `${
resultItem.volumeInfo.imageLinks ? "(i)" : ""
} ${
resultItem.volumeInfo.title} - ${
resultItem.volumeInfo.authors ? resultItem.volumeInfo.authors[0] : ""
} (${
(new Date(resultItem.volumeInfo.publishedDate)).getFullYear()
})`;
}
async function getByQuery(query) {
const searchResults = await apiGet(query);
if(searchResults.error)
{
notice("Request failed");
throw new Error("Request failed");
}
if (searchResults.totalItems == 0) {
notice("No results found.");
throw new Error("No results found.");
}
return searchResults.items;
}
function formatList(list) {
if (list.length === 0 || list[0] == "N/A") return " ";
if (list.length === 1) return `${list[0]}`;
return list.map((item) => `\"${item.trim()}\"`).join(", ");
}
function replaceIllegalFileNameCharactersInString(string) {
return string.replace(/[\\,#%&\{\}\/*<>$\":@.]*/g, "");
}
async function apiGet(query) {
let finalURL = new URL(API_URL);
finalURL.searchParams.append("q", query);
finalURL.searchParams.append("key", Settings[API_KEY]);
log(finalURL.href);
const res = await request({
url: finalURL.href,
method: 'GET',
cache: 'no-cache',
})
return JSON.parse(res);
}