forked from HeronErin/LibbyRip
-
Notifications
You must be signed in to change notification settings - Fork 0
/
userscript.js
283 lines (245 loc) · 9.51 KB
/
userscript.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
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
// ==UserScript==
// @name LibreGRAB
// @namespace http://tampermonkey.net/
// @version 2024-06-24
// @description Download all the booty!
// @author HeronErin
// @license MIT
// @supportURL https://github.com/HeronErin/LibbyRip/issues
// @match *://*.listen.libbyapp.com/*
// @icon https://www.google.com/s2/favicons?sz=64&domain=libbyapp.com
// @require https://cdnjs.cloudflare.com/ajax/libs/jszip/3.7.1/jszip.min.js
// @grant none
// @downloadURL https://update.greasyfork.org/scripts/498782/LibreGRAB.user.js
// @updateURL https://update.greasyfork.org/scripts/498782/LibreGRAB.meta.js
// ==/UserScript==
(()=>{
const CSS = `
.pNav{
background-color: red;
width: 100%;
display: flex;
justify-content: space-between;
}
.pLink{
color: blue;
text-decoration-line: underline;
padding: .25em;
font-size: 1em;
}
.foldMenu{
position: absolute;
width: 100%;
height: 0%;
z-index: 1000;
background-color: grey;
overflow-x: hidden;
overflow-y: scroll;
transition: height 0.3s
}
.active{
height: 40%;
border: double;
}
.pChapLabel{
font-size: 2em;
}
`;
const newNav = `
<a class="pLink" id="chap"> <h1> View chapters </h1> </a>
<a class="pLink" id="dow"> <h1> Download chapters </h1> </a>
<a class="pLink" id="exp"> <h1> Export audiobook </h1> </a>
`;
const chaptersMenu = `
<h2>This book contains {CHAPTERS} chapters.</h2>
`;
let chapterMenuElem;
let downloadElem;
function buildPirateUi(){
// Create the nav
let nav = document.createElement("div");
nav.innerHTML = newNav;
nav.querySelector("#chap").onclick = viewChapters;
nav.querySelector("#dow").onclick = downloadChapters;
nav.querySelector("#exp").onclick = exportChapters;
nav.classList.add("pNav");
let pbar = document.querySelector(".nav-progress-bar");
pbar.insertBefore(nav, pbar.children[1]);
// Create the chapters menu
chapterMenuElem = document.createElement("div");
chapterMenuElem.classList.add("foldMenu");
chapterMenuElem.setAttribute("tabindex", "-1"); // Don't mess with tab key
const urls = getUrls();
chapterMenuElem.innerHTML = chaptersMenu.replace("{CHAPTERS}", urls.length);
document.body.appendChild(chapterMenuElem);
downloadElem = document.createElement("div");
downloadElem.classList.add("foldMenu");
document.body.appendChild(downloadElem);
}
function repairSplinePath(s, si) {
if (!s || !s.includes("?cmpt=")) {
console.error("Invalid URL structure:", s);
return null; // or handle accordingly, e.g., return an empty string or skip processing this entry
}
s = window.origin + "/" + s;
const spline = btoa(JSON.stringify({ spine: si }));
const ssplit = s.split("?cmpt=");
return ssplit[0] + "?cmpt=" + spline + "--" + ssplit[1].split("--")[1].substring(0, 40);
}
function getUrls(){
let ret = [];
for (let spine of BIF.map.spine){
let data = {
url: repairSplinePath(spine.path, spine["-odread-spine-position"]),
index : spine["-odread-spine-position"],
duration: spine["audio-duration"],
size: spine["-odread-file-bytes"],
type: spine["media-type"]
};
ret.push(data);
}
return ret;
}
function paddy(num, padlen, padchar) {
var pad_char = typeof padchar !== 'undefined' ? padchar : '0';
var pad = new Array(1 + padlen).join(pad_char);
return (pad + num).slice(-pad.length);
}
let firstChapClick = true;
function viewChapters(){
// Populate chapters ONLY after first viewing
if (firstChapClick){
firstChapClick = false;
for (let url of getUrls()){
let span = document.createElement("span");
span.classList.add("pChapLabel")
span.textContent = "#" + (1 + url.index);
let audio = document.createElement("audio");
audio.setAttribute("controls", "");
let source = document.createElement("source");
source.setAttribute("src", url.url);
source.setAttribute("type", url.type);
audio.appendChild(source);
chapterMenuElem.appendChild(span);
chapterMenuElem.appendChild(document.createElement("br"));
chapterMenuElem.appendChild(audio);
chapterMenuElem.appendChild(document.createElement("br"));
}
}
if (chapterMenuElem.classList.contains("active"))
chapterMenuElem.classList.remove("active")
else
chapterMenuElem.classList.add("active")
}
async function createMetadata(zip){
let folder = zip.folder("metadata");
let spineToIndex = BIF.map.spine.map((x)=>x["-odread-original-path"]);
let metadata = {
title: BIF.map.title.main,
description: BIF.map.description,
coverUrl: window.tData.codex.title.cover.imageURL,
creator: BIF.map.creator,
spine: BIF.map.spine.map((x)=>{return {
duration: x["audio-duration"],
type: x["media-type"],
bitrate: x["audio-bitrate"],
}})
};
const response = await fetch(metadata.coverUrl);
const blob = await response.blob();
const csplit = metadata.coverUrl.split(".");
folder.file("cover." + csplit[csplit.length-1], blob, { compression: "STORE" });
if (BIF.map.nav.toc != undefined){
metadata.chapters = BIF.map.nav.toc.map((rChap)=>{
return {
title: rChap.title,
spine: spineToIndex.indexOf(rChap.path.split("#")[0]),
offset: 1*(rChap.path.split("#")[1] | 0)
};
});
}
folder.file("metadata.json", JSON.stringify(metadata, null, 2));
}
let downloadState = -1;
async function createAndDownloadZip(urls, addMeta) {
const zip = new JSZip();
// Fetch all files and add them to the zip
const fetchPromises = urls.map(async (url) => {
const response = await fetch(url.url);
const blob = await response.blob();
const filename = "Chapter " + paddy(url.index + 1, 3) + ".mp3";
let partElem = document.createElement("div");
partElem.textContent = "Download of "+ filename + " complete";
downloadElem.appendChild(partElem);
downloadElem.scrollTo(0, downloadElem.scrollHeight);
downloadState += 1;
zip.file(filename, blob, { compression: "STORE" });
});
if (addMeta)
fetchPromises.push(createMetadata(zip));
// Wait for all files to be fetched and added to the zip
await Promise.all(fetchPromises);
downloadElem.innerHTML += "<br><b>Downloads complete!</b> Now waiting for them to be assembled! (This might take a <b><i>minute</i></b>) <br>";
downloadElem.innerHTML += "Zip progress: <b id='zipProg'>0</b>%";
downloadElem.scrollTo(0, downloadElem.scrollHeight);
// Generate the zip file
const zipBlob = await zip.generateAsync({
type: 'blob',
compression: "STORE",
streamFiles: true,
}, (meta)=>{
if (meta.percent)
downloadElem.querySelector("#zipProg").textContent = meta.percent.toFixed(2);
});
downloadElem.innerHTML += "Generated zip file! <br>"
downloadElem.scrollTo(0, downloadElem.scrollHeight);
// Create a download link for the zip file
const downloadUrl = URL.createObjectURL(zipBlob);
downloadElem.innerHTML += "Generated zip file link! <br>"
downloadElem.scrollTo(0, downloadElem.scrollHeight);
const link = document.createElement('a');
link.href = downloadUrl;
link.download = BIF.map.title.main + '.zip';
document.body.appendChild(link);
link.click();
link.remove();
downloadState = -1;
downloadElem.innerHTML = ""
downloadElem.classList.remove("active");
// Clean up the object URL
setTimeout(() => URL.revokeObjectURL(downloadUrl), 100);
}
function downloadChapters(){
if (downloadState != -1)
return;
downloadState = 0;
downloadElem.classList.add("active");
downloadElem.innerHTML = "<b>Starting download</b><br>";
createAndDownloadZip(getUrls()).then((p)=>{});
}
function exportChapters(){
if (downloadState != -1)
return;
downloadState = 0;
downloadElem.classList.add("active");
downloadElem.innerHTML = "<b>Starting export</b><br>";
createAndDownloadZip(getUrls(), true).then((p)=>{});
}
// Main entry point for audiobooks
function bifFound(){
// New global style info
let s = document.createElement("style");
s.innerHTML = CSS;
document.head.appendChild(s)
buildPirateUi();
}
// The "BIF" contains all the info we need to download
// stuff, so we wait until the page is loaded, and the
// BIF is present, to inject the pirate menu.
let intr = setInterval(()=>{
if (window.BIF != undefined){
clearInterval(intr);
bifFound();
}
}, 25);
})();