-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcontent.js
158 lines (133 loc) · 4.68 KB
/
content.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
'use strict';
const CACHE_NAME = 'BOOKS_CACHE';
const domParser = new DOMParser();
const wordsByPage = 254.5;
const wpmSpeed = 300;
const escapedBookTitle = escapeText(document.querySelector('.pvi-product-title').innerText);
const providers = {
amazon: function(q) {
const getUrl = (q) => (
`https://www.amazon.fr/gp/search?ie=UTF8&camp=1642&creative=6746&index=books&keywords=${q}`
);
const parseResults = (dom) => {
const firstResult = dom.querySelectorAll('.s-access-detail-page')[0];
if (!firstResult) {
insertMessage('Not found on Amazon');
return;
}
return Promise.resolve(firstResults.href);
};
const parsePageCount = (dom) => {
const details = [...dom.querySelectorAll('#detail_bullets_id .bucket .content')].map(b => b.innerText)[0];
const matchedPagesStr = details.match(/[0-9]{2,4}(?= pages)/g);
if (!matchedPagesStr || matchedPagesStr.length === 0) {
insertMessage('Page count not found');
return;
}
const pages = parseInt(matchedPagesStr[0]);
const readingMinutes = matchedPages * wordsByPage / wpmSpeed;
return Promise.resolve({ pages, readingMinutes });
};
return fetchPage(getUrl(q)).then(parseResults).then(fetchPage).then(parsePageCount);
},
fnac: function(q) {
const getUrl = (q) => (
`http://www.fnac.com//r/${q}?SCat=2!1`
);
const parseResults = (dom) => {
const firstResult = [...dom.querySelectorAll('.Article-item .Article-desc a')].map(x => x.href)[0];
if (!firstResult) {
insertMessage('Not found on Fnac');
return;
}
return Promise.resolve(firstResult);
};
const parsePageCount = (dom) => {
const pageCountStr = [...dom.querySelectorAll('.whiteContent .Feature-item')]
.filter(x => {
const a = x.querySelector('.Feature-label');
return a && a.innerText.trim() === 'Nombre de pages';
})
.map(x => x.querySelector('.Feature-desc').innerText.trim())[0];
if (!pageCountStr) {
insertMessage('Page count not found');
return;
}
const pages = parseInt(pageCountStr);
const readingMinutes = matchedPages * wordsByPage / wpmSpeed;
return Promise.resolve({ pages, readingMinutes });
};
fetchPage(getUrl(q)).then(parseResults).then(fetchPage).then(parsePageCount);
}
};
const getBookStatsLi = (matchedPages, readingMinutes) => {
const titleSpan = document.createElement('span');
titleSpan.title = 'Pour une vitesse moyenne de 300 mots/minute';
titleSpan.innerText = `${matchedPages} pages (${prettifyMinutes(readingMinutes)})`;
return getAdditionalStatsLi(titleSpan);
};
const insertMessage = (text = '') => {
const span = document.createElement('span');
span.innerText = text;
const messageLi = getAdditionalStatsLi(span);
insertAdditionalStats(messageLi);
};
const getAdditionalStatsLi = (child) => {
const additionalDetailsLi = document.createElement("li");
additionalDetailsLi.className = 'pvi-productDetails-item';
additionalDetailsLi.appendChild(child);
additionalDetailsLi.id = 'book-stats';
return additionalDetailsLi;
};
const insertAdditionalStats = (additionalDetailsLi) => {
const previousLi = document.querySelector('#book-stats');
if (previousLi) {
previousLi.replaceWith(additionalDetailsLi);
} else {
const bookDetailsUl = document.querySelector('.pvi-productDetails ul');
bookDetailsUl.appendChild(additionalDetailsLi);
}
};
const cache = JSON.parse(localStorage.getItem(CACHE_NAME) || null);
if (cache && escapedBookTitle in cache) {
const {
matchedPages,
readingMinutes,
lexileScore
} = cache[escapedBookTitle];
const additionalDetailsLi = getBookStatsLi(matchedPages, readingMinutes);
insertAdditionalStats(additionalDetailsLi);
} else {
insertMessage('...');
const provider = providers['amazon'];
provider(escapedBookTitle).then(({ pages, readingMinutes }) => {
const additionalDetailsLi = getBookStatsLi(pages, readingMinutes);
insertAdditionalStats(additionalDetailsLi);
updateCache(q, { matchedPages, readingMinutes });
});
}
/**
* Tools
*/
function fetchPage(url) {
return fetch(url)
.then(res => res.text())
.then(content => Promise.resolve(domParser.parseFromString(content, 'text/html')));
}
function updateCache(bookTitle, values) {
const newCache = cache || {};
newCache[bookTitle] = values;
localStorage.setItem(CACHE_NAME, JSON.stringify(newCache));
}
function prettifyMinutes(minutes) {
return Math.floor(minutes / 60) + 'h' + (90 % 60) + 'm';
}
function escapeText(text = '') {
return escape(text.trim());
}
/**
* Lexile fetcher
*/
function fetchLexileScore(bookName) {
return Promise.resolve(0);
}