yuque-dl 1.0.2 → 1.0.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +2 -2
- package/dist/cjs/cli.js +0 -44
- package/dist/cjs/index-984ebe84.js +0 -402
- package/dist/cjs/index.js +0 -15
- package/dist/es/cli.js +0 -42
- package/dist/es/index-ec82d116.js +0 -398
- package/dist/es/index.js +0 -8
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "yuque-dl",
|
|
3
|
-
"version": "1.0.
|
|
3
|
+
"version": "1.0.3",
|
|
4
4
|
"description": "yuque 知识库下载",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"bin": {
|
|
@@ -50,7 +50,7 @@
|
|
|
50
50
|
"axios": "^1.4.0",
|
|
51
51
|
"log4js": "^6.9.1",
|
|
52
52
|
"progress": "^2.0.3",
|
|
53
|
-
"pull-md-img": "^0.0.
|
|
53
|
+
"pull-md-img": "^0.0.19",
|
|
54
54
|
"rand-user-agent": "1.0.109",
|
|
55
55
|
"cac": "^6.7.14"
|
|
56
56
|
},
|
package/dist/cjs/cli.js
DELETED
|
@@ -1,44 +0,0 @@
|
|
|
1
|
-
'use strict';
|
|
2
|
-
|
|
3
|
-
var cac = require('cac');
|
|
4
|
-
var index = require('./index-984ebe84.js');
|
|
5
|
-
require('node:fs/promises');
|
|
6
|
-
require('node:path');
|
|
7
|
-
require('axios');
|
|
8
|
-
require('log4js');
|
|
9
|
-
require('progress');
|
|
10
|
-
require('rand-user-agent');
|
|
11
|
-
require('pull-md-img');
|
|
12
|
-
|
|
13
|
-
var version = "1.0.1";
|
|
14
|
-
|
|
15
|
-
const cli = cac.cac('yuque-dl');
|
|
16
|
-
cli
|
|
17
|
-
.command('<url>', 'request url')
|
|
18
|
-
.option('-d, --distDir <dir>', '下载的目录 eg: -d download', {
|
|
19
|
-
default: 'download',
|
|
20
|
-
})
|
|
21
|
-
.action(async (url, options) => {
|
|
22
|
-
try {
|
|
23
|
-
await index.main(url, options);
|
|
24
|
-
}
|
|
25
|
-
catch (err) {
|
|
26
|
-
index.logger.error(err.message || 'unknown exception');
|
|
27
|
-
}
|
|
28
|
-
});
|
|
29
|
-
cli.help();
|
|
30
|
-
cli.version(version);
|
|
31
|
-
try {
|
|
32
|
-
cli.parse();
|
|
33
|
-
}
|
|
34
|
-
catch (err) {
|
|
35
|
-
index.logger.error(err.message || 'unknown exception');
|
|
36
|
-
process.exit(1);
|
|
37
|
-
}
|
|
38
|
-
// try {
|
|
39
|
-
// cli.parse(process.argv, { run: false })
|
|
40
|
-
// await cli.runMatchedCommand()
|
|
41
|
-
// } catch (error) {
|
|
42
|
-
// logger.error(error.message || 'unknown exception')
|
|
43
|
-
// process.exit(1)
|
|
44
|
-
// }
|
|
@@ -1,402 +0,0 @@
|
|
|
1
|
-
'use strict';
|
|
2
|
-
|
|
3
|
-
var fs = require('node:fs/promises');
|
|
4
|
-
var path = require('node:path');
|
|
5
|
-
var axios = require('axios');
|
|
6
|
-
var log4js = require('log4js');
|
|
7
|
-
var progress = require('progress');
|
|
8
|
-
var randUserAgentLib = require('rand-user-agent');
|
|
9
|
-
var mdImg = require('pull-md-img');
|
|
10
|
-
|
|
11
|
-
var config = {
|
|
12
|
-
knowledgeBaseReg: /decodeURIComponent\(\"(.+)\"\)\);/m,
|
|
13
|
-
dist: './download'
|
|
14
|
-
};
|
|
15
|
-
// data = re.findall(r"decodeURIComponent\(\"(.+)\"\)\);", docsdata.content.decode('utf-8'))
|
|
16
|
-
// const config = {
|
|
17
|
-
// path: '',
|
|
18
|
-
// suffix: '',
|
|
19
|
-
// dist: './res/',
|
|
20
|
-
// imgDir:`./img/${Date.now()}`,
|
|
21
|
-
// // markdown img 正则 注意多行匹配
|
|
22
|
-
// mdImgReg: /!\[(.*?)\]\((.*?)\)/gm,
|
|
23
|
-
// isIgnoreConsole: false
|
|
24
|
-
// }
|
|
25
|
-
|
|
26
|
-
/**
|
|
27
|
-
* log 初始化
|
|
28
|
-
*/
|
|
29
|
-
const getLogger = () => {
|
|
30
|
-
log4js.configure({
|
|
31
|
-
appenders: {
|
|
32
|
-
// cheeseLog: { type: 'file', filename: 'cheese.log' },
|
|
33
|
-
cheese: {
|
|
34
|
-
type: 'console',
|
|
35
|
-
layout: {
|
|
36
|
-
// type: 'messagePassThrough',
|
|
37
|
-
type: 'pattern',
|
|
38
|
-
// pattern: '%[%d{yyyy-MM-dd hh:mm:ss} [%p] %c -%] %m%n'
|
|
39
|
-
pattern: '%[%c [%p]:%] %m%n'
|
|
40
|
-
}
|
|
41
|
-
}
|
|
42
|
-
},
|
|
43
|
-
categories: { default: { appenders: ['cheese'], level: 'trace' } }
|
|
44
|
-
});
|
|
45
|
-
return log4js.getLogger('yuque-dl');
|
|
46
|
-
};
|
|
47
|
-
var logger = getLogger();
|
|
48
|
-
|
|
49
|
-
class Progress {
|
|
50
|
-
constructor(bookPath, total) {
|
|
51
|
-
this.bookPath = '';
|
|
52
|
-
this.processFilePath = '';
|
|
53
|
-
this.processInfo = [];
|
|
54
|
-
this.curr = 0;
|
|
55
|
-
this.total = 0;
|
|
56
|
-
this.isDownloadInterrupted = false;
|
|
57
|
-
this.bar = null;
|
|
58
|
-
this.completePromise = null;
|
|
59
|
-
this.bookPath = bookPath;
|
|
60
|
-
this.processFilePath = `${bookPath}/process.json`;
|
|
61
|
-
this.total = total;
|
|
62
|
-
}
|
|
63
|
-
async init() {
|
|
64
|
-
this.processInfo = await this.getProgress();
|
|
65
|
-
this.curr = this.processInfo.length;
|
|
66
|
-
let completeResolve;
|
|
67
|
-
this.completePromise = new Promise(resolve => {
|
|
68
|
-
completeResolve = resolve;
|
|
69
|
-
});
|
|
70
|
-
if (this.curr > 0 && this.curr !== this.total) {
|
|
71
|
-
this.isDownloadInterrupted = true;
|
|
72
|
-
logger.info('断点下载');
|
|
73
|
-
}
|
|
74
|
-
this.bar = new progress('[:bar] :rate/bps :percent :etas', {
|
|
75
|
-
// width: 20,
|
|
76
|
-
total: this.total,
|
|
77
|
-
curr: this.curr,
|
|
78
|
-
callback() {
|
|
79
|
-
completeResolve();
|
|
80
|
-
}
|
|
81
|
-
});
|
|
82
|
-
}
|
|
83
|
-
async getProgress() {
|
|
84
|
-
let processInfo = [];
|
|
85
|
-
try {
|
|
86
|
-
const processInfoStr = await fs.readFile(this.processFilePath, { encoding: 'utf8' });
|
|
87
|
-
processInfo = JSON.parse(processInfoStr);
|
|
88
|
-
}
|
|
89
|
-
catch (err) {
|
|
90
|
-
if (err && err.code === 'ENOENT') {
|
|
91
|
-
await fs.writeFile(this.processFilePath, JSON.stringify(processInfo), { encoding: 'utf8' });
|
|
92
|
-
}
|
|
93
|
-
}
|
|
94
|
-
return processInfo;
|
|
95
|
-
}
|
|
96
|
-
async updateProgress(progressItem) {
|
|
97
|
-
this.processInfo.push(progressItem);
|
|
98
|
-
await fs.writeFile(this.processFilePath, JSON.stringify(this.processInfo), { encoding: 'utf8' });
|
|
99
|
-
this.curr = this.curr + 1;
|
|
100
|
-
if (this.bar) {
|
|
101
|
-
this.bar?.tick();
|
|
102
|
-
}
|
|
103
|
-
}
|
|
104
|
-
}
|
|
105
|
-
|
|
106
|
-
function randUserAgent({ browser = 'chrome', os = 'mac os', device = 'desktop' }) {
|
|
107
|
-
device = device.toLowerCase();
|
|
108
|
-
browser = browser.toLowerCase();
|
|
109
|
-
os = os.toLowerCase();
|
|
110
|
-
let UA = randUserAgentLib(device, browser, os);
|
|
111
|
-
if (browser === 'chrome') {
|
|
112
|
-
while (UA.includes('Chrome-Lighthouse')
|
|
113
|
-
|| UA.includes('Gener8')
|
|
114
|
-
|| UA.includes('HeadlessChrome')
|
|
115
|
-
|| UA.includes('SMTBot')) {
|
|
116
|
-
UA = randUserAgentLib(device, browser, os);
|
|
117
|
-
}
|
|
118
|
-
}
|
|
119
|
-
if (browser === 'safari') {
|
|
120
|
-
while (UA.includes('Applebot')) {
|
|
121
|
-
UA = randUserAgentLib(device, browser, os);
|
|
122
|
-
}
|
|
123
|
-
}
|
|
124
|
-
return UA;
|
|
125
|
-
}
|
|
126
|
-
|
|
127
|
-
// SUMMARY.md
|
|
128
|
-
function getKnowledgeBaseInfo(url) {
|
|
129
|
-
return axios.get(url, {
|
|
130
|
-
headers: {
|
|
131
|
-
"user-agent": randUserAgent({ browser: 'chrome', device: "desktop" })
|
|
132
|
-
}
|
|
133
|
-
}).then(({ data = '', status }) => {
|
|
134
|
-
if (status === 200)
|
|
135
|
-
return data;
|
|
136
|
-
return '';
|
|
137
|
-
}).then(html => {
|
|
138
|
-
const data = html.match(config.knowledgeBaseReg) || '';
|
|
139
|
-
if (!data[1])
|
|
140
|
-
return {};
|
|
141
|
-
const jsonData = JSON.parse(decodeURIComponent(data[1]));
|
|
142
|
-
const info = {
|
|
143
|
-
bookId: jsonData.book.id,
|
|
144
|
-
tocList: jsonData.book.toc || [],
|
|
145
|
-
bookName: jsonData.book.name || '',
|
|
146
|
-
bookDesc: jsonData.book.description || '',
|
|
147
|
-
};
|
|
148
|
-
return info;
|
|
149
|
-
});
|
|
150
|
-
}
|
|
151
|
-
async function main(url, options) {
|
|
152
|
-
const { bookId, tocList, bookName, bookDesc } = await getKnowledgeBaseInfo(url);
|
|
153
|
-
if (!bookId)
|
|
154
|
-
throw new Error('No found book id');
|
|
155
|
-
if (!tocList || tocList.length === 0)
|
|
156
|
-
throw new Error('No found toc list');
|
|
157
|
-
const bookPath = `${options.distDir}/${bookId}`;
|
|
158
|
-
await fs.mkdir(bookPath, { recursive: true });
|
|
159
|
-
const total = tocList.length;
|
|
160
|
-
const progress = new Progress(bookPath, total);
|
|
161
|
-
await progress.init();
|
|
162
|
-
if (progress.curr === total) {
|
|
163
|
-
logger.info('√ 已完成');
|
|
164
|
-
return;
|
|
165
|
-
}
|
|
166
|
-
const uuidMap = new Map();
|
|
167
|
-
// 下载中断 重新获取下载进度数据
|
|
168
|
-
if (progress.isDownloadInterrupted) {
|
|
169
|
-
progress.processInfo.forEach(item => {
|
|
170
|
-
uuidMap.set(item.toc.uuid, item);
|
|
171
|
-
});
|
|
172
|
-
}
|
|
173
|
-
const articleUrlPrefix = path.parse(url).dir;
|
|
174
|
-
for (let i = 0; i < total; i++) {
|
|
175
|
-
const item = tocList[i];
|
|
176
|
-
if (typeof item.type !== 'string')
|
|
177
|
-
continue;
|
|
178
|
-
if (uuidMap.get(item.uuid))
|
|
179
|
-
continue;
|
|
180
|
-
const itemType = item.type.toLocaleLowerCase();
|
|
181
|
-
const dirNameReg = /[\\\/:\*\?"<>\|\n\r]/g;
|
|
182
|
-
// 目录
|
|
183
|
-
if (itemType === 'title' || item['child_uuid'] !== '') {
|
|
184
|
-
let tempItem = item;
|
|
185
|
-
let pathTitleList = [];
|
|
186
|
-
let pathIdList = [];
|
|
187
|
-
while (tempItem) {
|
|
188
|
-
pathTitleList.unshift(tempItem.title.replace(dirNameReg, '_'));
|
|
189
|
-
pathIdList.unshift(tempItem.uuid);
|
|
190
|
-
if (uuidMap.get(tempItem['parent_uuid'])) {
|
|
191
|
-
tempItem = uuidMap.get(tempItem['parent_uuid']).toc;
|
|
192
|
-
}
|
|
193
|
-
else {
|
|
194
|
-
tempItem = undefined;
|
|
195
|
-
}
|
|
196
|
-
}
|
|
197
|
-
const progressItem = {
|
|
198
|
-
path: pathTitleList.join('/'),
|
|
199
|
-
pathTitleList,
|
|
200
|
-
pathIdList,
|
|
201
|
-
toc: item
|
|
202
|
-
};
|
|
203
|
-
await fs.mkdir(`${bookPath}/${pathTitleList.join('/')}`, { recursive: true });
|
|
204
|
-
uuidMap.set(item.uuid, progressItem);
|
|
205
|
-
progress.updateProgress(progressItem);
|
|
206
|
-
}
|
|
207
|
-
else if (item.url) {
|
|
208
|
-
let preItem = {
|
|
209
|
-
path: '',
|
|
210
|
-
pathTitleList: [],
|
|
211
|
-
pathIdList: []
|
|
212
|
-
};
|
|
213
|
-
if (uuidMap.get(item['parent_uuid'])) {
|
|
214
|
-
preItem = uuidMap.get(item['parent_uuid']);
|
|
215
|
-
}
|
|
216
|
-
const fileName = item.title.replace(dirNameReg, '_');
|
|
217
|
-
const pathTitleList = [...preItem.pathTitleList, `${fileName}.md`];
|
|
218
|
-
const pathIdList = [...preItem.pathIdList, item.uuid];
|
|
219
|
-
const progressItem = {
|
|
220
|
-
path: pathTitleList.join('/'),
|
|
221
|
-
pathTitleList,
|
|
222
|
-
pathIdList,
|
|
223
|
-
toc: item
|
|
224
|
-
};
|
|
225
|
-
const isSuccess = await downloadArticle({
|
|
226
|
-
bookId,
|
|
227
|
-
itemUrl: item.url,
|
|
228
|
-
savePath: `${bookPath}/${preItem.path}`,
|
|
229
|
-
saveFilePath: `${bookPath}/${progressItem.path}`,
|
|
230
|
-
uuid: item.uuid,
|
|
231
|
-
articleUrl: `${articleUrlPrefix}/${item.url}`,
|
|
232
|
-
articleTitle: item.title
|
|
233
|
-
});
|
|
234
|
-
if (isSuccess) {
|
|
235
|
-
uuidMap.set(item.uuid, progressItem);
|
|
236
|
-
progress.updateProgress(progressItem);
|
|
237
|
-
}
|
|
238
|
-
}
|
|
239
|
-
}
|
|
240
|
-
await progress.completePromise;
|
|
241
|
-
logger.info('生成目录 SUMMARY.md');
|
|
242
|
-
await genSummaryFile({
|
|
243
|
-
bookPath,
|
|
244
|
-
bookName,
|
|
245
|
-
bookDesc,
|
|
246
|
-
uuidMap
|
|
247
|
-
});
|
|
248
|
-
if (progress.curr === total) {
|
|
249
|
-
logger.info('√ 已完成');
|
|
250
|
-
return;
|
|
251
|
-
}
|
|
252
|
-
}
|
|
253
|
-
async function downloadArticle(params) {
|
|
254
|
-
const { bookId, itemUrl, savePath, saveFilePath, uuid, articleUrl, articleTitle } = params;
|
|
255
|
-
const apiUrl = `https://www.yuque.com/api/docs/${itemUrl}`;
|
|
256
|
-
const response = await axios.get(apiUrl, {
|
|
257
|
-
headers: {
|
|
258
|
-
"user-agent": randUserAgent({ browser: 'chrome', device: "desktop" })
|
|
259
|
-
},
|
|
260
|
-
params: {
|
|
261
|
-
'book_id': bookId,
|
|
262
|
-
'merge_dynamic_data': false,
|
|
263
|
-
mode: 'markdown'
|
|
264
|
-
}
|
|
265
|
-
}).then(({ data, status }) => {
|
|
266
|
-
if (status === 200)
|
|
267
|
-
return data;
|
|
268
|
-
logger.error(`download article error: ${apiUrl} http status ${status}`);
|
|
269
|
-
return null;
|
|
270
|
-
});
|
|
271
|
-
if (!response || !response.data || !response.data.sourcecode)
|
|
272
|
-
return false;
|
|
273
|
-
let mdData = response.data.sourcecode;
|
|
274
|
-
try {
|
|
275
|
-
mdData = await mdImg.run(mdData, {
|
|
276
|
-
dist: savePath,
|
|
277
|
-
imgDir: `img/${uuid}`,
|
|
278
|
-
isIgnoreConsole: true
|
|
279
|
-
});
|
|
280
|
-
}
|
|
281
|
-
catch (err) {
|
|
282
|
-
logger.error(`download article img Error (api: ${apiUrl})`);
|
|
283
|
-
return false;
|
|
284
|
-
}
|
|
285
|
-
mdData = mdData.replace(/<br(\s?)\/>/gm, '\n');
|
|
286
|
-
if (articleTitle) {
|
|
287
|
-
mdData = `# ${articleTitle}\n<!--page header-->\n\n${mdData}\n\n`;
|
|
288
|
-
}
|
|
289
|
-
if (articleUrl) {
|
|
290
|
-
mdData += `<!--page footer-->\n- 原文: <${articleUrl}>`;
|
|
291
|
-
}
|
|
292
|
-
try {
|
|
293
|
-
await fs.writeFile(saveFilePath, mdData);
|
|
294
|
-
return true;
|
|
295
|
-
}
|
|
296
|
-
catch (e) {
|
|
297
|
-
logger.error(`download article write file Error (api: ${apiUrl})`);
|
|
298
|
-
return false;
|
|
299
|
-
}
|
|
300
|
-
}
|
|
301
|
-
async function genSummaryFile(params) {
|
|
302
|
-
const { bookName, bookDesc, bookPath, uuidMap } = params;
|
|
303
|
-
const header = `# ${bookName}\n\n > ${bookDesc}\n\n`;
|
|
304
|
-
let mdContent = header;
|
|
305
|
-
const summary = [];
|
|
306
|
-
uuidMap.forEach(processItem => {
|
|
307
|
-
const toc = processItem.toc;
|
|
308
|
-
const parentId = toc['parent_uuid'];
|
|
309
|
-
const findRes = findTree(summary, parentId);
|
|
310
|
-
if (toc.type.toLocaleLowerCase() === 'title' || toc['child_uuid'] !== '') {
|
|
311
|
-
if (typeof findRes !== 'boolean') {
|
|
312
|
-
if (!Array.isArray(findRes.children))
|
|
313
|
-
findRes.children = [];
|
|
314
|
-
findRes.children.push({
|
|
315
|
-
id: toc.uuid,
|
|
316
|
-
type: 'title',
|
|
317
|
-
level: findRes.level + 1,
|
|
318
|
-
text: toc.title
|
|
319
|
-
});
|
|
320
|
-
}
|
|
321
|
-
else {
|
|
322
|
-
summary.push({
|
|
323
|
-
id: toc.uuid,
|
|
324
|
-
type: 'title',
|
|
325
|
-
text: toc.title,
|
|
326
|
-
level: 1
|
|
327
|
-
});
|
|
328
|
-
}
|
|
329
|
-
}
|
|
330
|
-
else {
|
|
331
|
-
if (typeof findRes !== 'boolean') {
|
|
332
|
-
if (!Array.isArray(findRes.children))
|
|
333
|
-
findRes.children = [];
|
|
334
|
-
findRes.children.push({
|
|
335
|
-
id: toc.uuid,
|
|
336
|
-
type: 'link',
|
|
337
|
-
level: findRes.level + 1,
|
|
338
|
-
link: processItem.path,
|
|
339
|
-
text: toc.title
|
|
340
|
-
});
|
|
341
|
-
}
|
|
342
|
-
else {
|
|
343
|
-
summary.push({
|
|
344
|
-
id: toc.uuid,
|
|
345
|
-
type: 'link',
|
|
346
|
-
text: toc.title,
|
|
347
|
-
link: processItem.path,
|
|
348
|
-
level: 1
|
|
349
|
-
});
|
|
350
|
-
}
|
|
351
|
-
}
|
|
352
|
-
});
|
|
353
|
-
let summaryContent = genSummaryContent(summary, '');
|
|
354
|
-
mdContent += summaryContent;
|
|
355
|
-
try {
|
|
356
|
-
await fs.writeFile(`${bookPath}/SUMMARY.md`, mdContent);
|
|
357
|
-
}
|
|
358
|
-
catch (err) {
|
|
359
|
-
logger.error('Generate Summary Error');
|
|
360
|
-
}
|
|
361
|
-
}
|
|
362
|
-
function genSummaryContent(summary, summaryContent) {
|
|
363
|
-
for (let i = 0; i < summary.length; i++) {
|
|
364
|
-
const item = summary[i];
|
|
365
|
-
if (item.type === 'title') {
|
|
366
|
-
summaryContent += `\n${''.padStart(item.level + 1, '#')} ${item.text}\n\n`;
|
|
367
|
-
}
|
|
368
|
-
else if (item.type === 'link') {
|
|
369
|
-
const link = item.link ? item.link.replace(/\s/g, '%20') : item.link;
|
|
370
|
-
summaryContent += `- [${item.text}](${link})\n`;
|
|
371
|
-
}
|
|
372
|
-
if (Array.isArray(item.children)) {
|
|
373
|
-
summaryContent += genSummaryContent(item.children, '');
|
|
374
|
-
}
|
|
375
|
-
}
|
|
376
|
-
return summaryContent;
|
|
377
|
-
}
|
|
378
|
-
function findIdItem(node, id) {
|
|
379
|
-
if (node.id === id) {
|
|
380
|
-
return node;
|
|
381
|
-
}
|
|
382
|
-
else if (node.children) {
|
|
383
|
-
const findRes = findTree(node.children, id);
|
|
384
|
-
if (findRes)
|
|
385
|
-
return findRes;
|
|
386
|
-
}
|
|
387
|
-
return false;
|
|
388
|
-
}
|
|
389
|
-
function findTree(tree, id) {
|
|
390
|
-
if (!id)
|
|
391
|
-
return false;
|
|
392
|
-
for (let i = 0; i < tree.length; i++) {
|
|
393
|
-
const findRes = findIdItem(tree[i], id);
|
|
394
|
-
if (findRes)
|
|
395
|
-
return findRes;
|
|
396
|
-
}
|
|
397
|
-
return false;
|
|
398
|
-
}
|
|
399
|
-
|
|
400
|
-
exports.getKnowledgeBaseInfo = getKnowledgeBaseInfo;
|
|
401
|
-
exports.logger = logger;
|
|
402
|
-
exports.main = main;
|
package/dist/cjs/index.js
DELETED
|
@@ -1,15 +0,0 @@
|
|
|
1
|
-
'use strict';
|
|
2
|
-
|
|
3
|
-
require('node:fs/promises');
|
|
4
|
-
require('node:path');
|
|
5
|
-
require('axios');
|
|
6
|
-
var index = require('./index-984ebe84.js');
|
|
7
|
-
require('pull-md-img');
|
|
8
|
-
require('log4js');
|
|
9
|
-
require('progress');
|
|
10
|
-
require('rand-user-agent');
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
exports.getKnowledgeBaseInfo = index.getKnowledgeBaseInfo;
|
|
15
|
-
exports.main = index.main;
|
package/dist/es/cli.js
DELETED
|
@@ -1,42 +0,0 @@
|
|
|
1
|
-
import { cac } from 'cac';
|
|
2
|
-
import { m as main, l as logger } from './index-ec82d116.js';
|
|
3
|
-
import 'node:fs/promises';
|
|
4
|
-
import 'node:path';
|
|
5
|
-
import 'axios';
|
|
6
|
-
import 'log4js';
|
|
7
|
-
import 'progress';
|
|
8
|
-
import 'rand-user-agent';
|
|
9
|
-
import 'pull-md-img';
|
|
10
|
-
|
|
11
|
-
var version = "1.0.1";
|
|
12
|
-
|
|
13
|
-
const cli = cac('yuque-dl');
|
|
14
|
-
cli
|
|
15
|
-
.command('<url>', 'request url')
|
|
16
|
-
.option('-d, --distDir <dir>', '下载的目录 eg: -d download', {
|
|
17
|
-
default: 'download',
|
|
18
|
-
})
|
|
19
|
-
.action(async (url, options) => {
|
|
20
|
-
try {
|
|
21
|
-
await main(url, options);
|
|
22
|
-
}
|
|
23
|
-
catch (err) {
|
|
24
|
-
logger.error(err.message || 'unknown exception');
|
|
25
|
-
}
|
|
26
|
-
});
|
|
27
|
-
cli.help();
|
|
28
|
-
cli.version(version);
|
|
29
|
-
try {
|
|
30
|
-
cli.parse();
|
|
31
|
-
}
|
|
32
|
-
catch (err) {
|
|
33
|
-
logger.error(err.message || 'unknown exception');
|
|
34
|
-
process.exit(1);
|
|
35
|
-
}
|
|
36
|
-
// try {
|
|
37
|
-
// cli.parse(process.argv, { run: false })
|
|
38
|
-
// await cli.runMatchedCommand()
|
|
39
|
-
// } catch (error) {
|
|
40
|
-
// logger.error(error.message || 'unknown exception')
|
|
41
|
-
// process.exit(1)
|
|
42
|
-
// }
|
|
@@ -1,398 +0,0 @@
|
|
|
1
|
-
import fs from 'node:fs/promises';
|
|
2
|
-
import path from 'node:path';
|
|
3
|
-
import axios from 'axios';
|
|
4
|
-
import log4js from 'log4js';
|
|
5
|
-
import progress from 'progress';
|
|
6
|
-
import randUserAgentLib from 'rand-user-agent';
|
|
7
|
-
import mdImg from 'pull-md-img';
|
|
8
|
-
|
|
9
|
-
var config = {
|
|
10
|
-
knowledgeBaseReg: /decodeURIComponent\(\"(.+)\"\)\);/m,
|
|
11
|
-
dist: './download'
|
|
12
|
-
};
|
|
13
|
-
// data = re.findall(r"decodeURIComponent\(\"(.+)\"\)\);", docsdata.content.decode('utf-8'))
|
|
14
|
-
// const config = {
|
|
15
|
-
// path: '',
|
|
16
|
-
// suffix: '',
|
|
17
|
-
// dist: './res/',
|
|
18
|
-
// imgDir:`./img/${Date.now()}`,
|
|
19
|
-
// // markdown img 正则 注意多行匹配
|
|
20
|
-
// mdImgReg: /!\[(.*?)\]\((.*?)\)/gm,
|
|
21
|
-
// isIgnoreConsole: false
|
|
22
|
-
// }
|
|
23
|
-
|
|
24
|
-
/**
|
|
25
|
-
* log 初始化
|
|
26
|
-
*/
|
|
27
|
-
const getLogger = () => {
|
|
28
|
-
log4js.configure({
|
|
29
|
-
appenders: {
|
|
30
|
-
// cheeseLog: { type: 'file', filename: 'cheese.log' },
|
|
31
|
-
cheese: {
|
|
32
|
-
type: 'console',
|
|
33
|
-
layout: {
|
|
34
|
-
// type: 'messagePassThrough',
|
|
35
|
-
type: 'pattern',
|
|
36
|
-
// pattern: '%[%d{yyyy-MM-dd hh:mm:ss} [%p] %c -%] %m%n'
|
|
37
|
-
pattern: '%[%c [%p]:%] %m%n'
|
|
38
|
-
}
|
|
39
|
-
}
|
|
40
|
-
},
|
|
41
|
-
categories: { default: { appenders: ['cheese'], level: 'trace' } }
|
|
42
|
-
});
|
|
43
|
-
return log4js.getLogger('yuque-dl');
|
|
44
|
-
};
|
|
45
|
-
var logger = getLogger();
|
|
46
|
-
|
|
47
|
-
class Progress {
|
|
48
|
-
constructor(bookPath, total) {
|
|
49
|
-
this.bookPath = '';
|
|
50
|
-
this.processFilePath = '';
|
|
51
|
-
this.processInfo = [];
|
|
52
|
-
this.curr = 0;
|
|
53
|
-
this.total = 0;
|
|
54
|
-
this.isDownloadInterrupted = false;
|
|
55
|
-
this.bar = null;
|
|
56
|
-
this.completePromise = null;
|
|
57
|
-
this.bookPath = bookPath;
|
|
58
|
-
this.processFilePath = `${bookPath}/process.json`;
|
|
59
|
-
this.total = total;
|
|
60
|
-
}
|
|
61
|
-
async init() {
|
|
62
|
-
this.processInfo = await this.getProgress();
|
|
63
|
-
this.curr = this.processInfo.length;
|
|
64
|
-
let completeResolve;
|
|
65
|
-
this.completePromise = new Promise(resolve => {
|
|
66
|
-
completeResolve = resolve;
|
|
67
|
-
});
|
|
68
|
-
if (this.curr > 0 && this.curr !== this.total) {
|
|
69
|
-
this.isDownloadInterrupted = true;
|
|
70
|
-
logger.info('断点下载');
|
|
71
|
-
}
|
|
72
|
-
this.bar = new progress('[:bar] :rate/bps :percent :etas', {
|
|
73
|
-
// width: 20,
|
|
74
|
-
total: this.total,
|
|
75
|
-
curr: this.curr,
|
|
76
|
-
callback() {
|
|
77
|
-
completeResolve();
|
|
78
|
-
}
|
|
79
|
-
});
|
|
80
|
-
}
|
|
81
|
-
async getProgress() {
|
|
82
|
-
let processInfo = [];
|
|
83
|
-
try {
|
|
84
|
-
const processInfoStr = await fs.readFile(this.processFilePath, { encoding: 'utf8' });
|
|
85
|
-
processInfo = JSON.parse(processInfoStr);
|
|
86
|
-
}
|
|
87
|
-
catch (err) {
|
|
88
|
-
if (err && err.code === 'ENOENT') {
|
|
89
|
-
await fs.writeFile(this.processFilePath, JSON.stringify(processInfo), { encoding: 'utf8' });
|
|
90
|
-
}
|
|
91
|
-
}
|
|
92
|
-
return processInfo;
|
|
93
|
-
}
|
|
94
|
-
async updateProgress(progressItem) {
|
|
95
|
-
this.processInfo.push(progressItem);
|
|
96
|
-
await fs.writeFile(this.processFilePath, JSON.stringify(this.processInfo), { encoding: 'utf8' });
|
|
97
|
-
this.curr = this.curr + 1;
|
|
98
|
-
if (this.bar) {
|
|
99
|
-
this.bar?.tick();
|
|
100
|
-
}
|
|
101
|
-
}
|
|
102
|
-
}
|
|
103
|
-
|
|
104
|
-
function randUserAgent({ browser = 'chrome', os = 'mac os', device = 'desktop' }) {
|
|
105
|
-
device = device.toLowerCase();
|
|
106
|
-
browser = browser.toLowerCase();
|
|
107
|
-
os = os.toLowerCase();
|
|
108
|
-
let UA = randUserAgentLib(device, browser, os);
|
|
109
|
-
if (browser === 'chrome') {
|
|
110
|
-
while (UA.includes('Chrome-Lighthouse')
|
|
111
|
-
|| UA.includes('Gener8')
|
|
112
|
-
|| UA.includes('HeadlessChrome')
|
|
113
|
-
|| UA.includes('SMTBot')) {
|
|
114
|
-
UA = randUserAgentLib(device, browser, os);
|
|
115
|
-
}
|
|
116
|
-
}
|
|
117
|
-
if (browser === 'safari') {
|
|
118
|
-
while (UA.includes('Applebot')) {
|
|
119
|
-
UA = randUserAgentLib(device, browser, os);
|
|
120
|
-
}
|
|
121
|
-
}
|
|
122
|
-
return UA;
|
|
123
|
-
}
|
|
124
|
-
|
|
125
|
-
// SUMMARY.md
|
|
126
|
-
function getKnowledgeBaseInfo(url) {
|
|
127
|
-
return axios.get(url, {
|
|
128
|
-
headers: {
|
|
129
|
-
"user-agent": randUserAgent({ browser: 'chrome', device: "desktop" })
|
|
130
|
-
}
|
|
131
|
-
}).then(({ data = '', status }) => {
|
|
132
|
-
if (status === 200)
|
|
133
|
-
return data;
|
|
134
|
-
return '';
|
|
135
|
-
}).then(html => {
|
|
136
|
-
const data = html.match(config.knowledgeBaseReg) || '';
|
|
137
|
-
if (!data[1])
|
|
138
|
-
return {};
|
|
139
|
-
const jsonData = JSON.parse(decodeURIComponent(data[1]));
|
|
140
|
-
const info = {
|
|
141
|
-
bookId: jsonData.book.id,
|
|
142
|
-
tocList: jsonData.book.toc || [],
|
|
143
|
-
bookName: jsonData.book.name || '',
|
|
144
|
-
bookDesc: jsonData.book.description || '',
|
|
145
|
-
};
|
|
146
|
-
return info;
|
|
147
|
-
});
|
|
148
|
-
}
|
|
149
|
-
async function main(url, options) {
|
|
150
|
-
const { bookId, tocList, bookName, bookDesc } = await getKnowledgeBaseInfo(url);
|
|
151
|
-
if (!bookId)
|
|
152
|
-
throw new Error('No found book id');
|
|
153
|
-
if (!tocList || tocList.length === 0)
|
|
154
|
-
throw new Error('No found toc list');
|
|
155
|
-
const bookPath = `${options.distDir}/${bookId}`;
|
|
156
|
-
await fs.mkdir(bookPath, { recursive: true });
|
|
157
|
-
const total = tocList.length;
|
|
158
|
-
const progress = new Progress(bookPath, total);
|
|
159
|
-
await progress.init();
|
|
160
|
-
if (progress.curr === total) {
|
|
161
|
-
logger.info('√ 已完成');
|
|
162
|
-
return;
|
|
163
|
-
}
|
|
164
|
-
const uuidMap = new Map();
|
|
165
|
-
// 下载中断 重新获取下载进度数据
|
|
166
|
-
if (progress.isDownloadInterrupted) {
|
|
167
|
-
progress.processInfo.forEach(item => {
|
|
168
|
-
uuidMap.set(item.toc.uuid, item);
|
|
169
|
-
});
|
|
170
|
-
}
|
|
171
|
-
const articleUrlPrefix = path.parse(url).dir;
|
|
172
|
-
for (let i = 0; i < total; i++) {
|
|
173
|
-
const item = tocList[i];
|
|
174
|
-
if (typeof item.type !== 'string')
|
|
175
|
-
continue;
|
|
176
|
-
if (uuidMap.get(item.uuid))
|
|
177
|
-
continue;
|
|
178
|
-
const itemType = item.type.toLocaleLowerCase();
|
|
179
|
-
const dirNameReg = /[\\\/:\*\?"<>\|\n\r]/g;
|
|
180
|
-
// 目录
|
|
181
|
-
if (itemType === 'title' || item['child_uuid'] !== '') {
|
|
182
|
-
let tempItem = item;
|
|
183
|
-
let pathTitleList = [];
|
|
184
|
-
let pathIdList = [];
|
|
185
|
-
while (tempItem) {
|
|
186
|
-
pathTitleList.unshift(tempItem.title.replace(dirNameReg, '_'));
|
|
187
|
-
pathIdList.unshift(tempItem.uuid);
|
|
188
|
-
if (uuidMap.get(tempItem['parent_uuid'])) {
|
|
189
|
-
tempItem = uuidMap.get(tempItem['parent_uuid']).toc;
|
|
190
|
-
}
|
|
191
|
-
else {
|
|
192
|
-
tempItem = undefined;
|
|
193
|
-
}
|
|
194
|
-
}
|
|
195
|
-
const progressItem = {
|
|
196
|
-
path: pathTitleList.join('/'),
|
|
197
|
-
pathTitleList,
|
|
198
|
-
pathIdList,
|
|
199
|
-
toc: item
|
|
200
|
-
};
|
|
201
|
-
await fs.mkdir(`${bookPath}/${pathTitleList.join('/')}`, { recursive: true });
|
|
202
|
-
uuidMap.set(item.uuid, progressItem);
|
|
203
|
-
progress.updateProgress(progressItem);
|
|
204
|
-
}
|
|
205
|
-
else if (item.url) {
|
|
206
|
-
let preItem = {
|
|
207
|
-
path: '',
|
|
208
|
-
pathTitleList: [],
|
|
209
|
-
pathIdList: []
|
|
210
|
-
};
|
|
211
|
-
if (uuidMap.get(item['parent_uuid'])) {
|
|
212
|
-
preItem = uuidMap.get(item['parent_uuid']);
|
|
213
|
-
}
|
|
214
|
-
const fileName = item.title.replace(dirNameReg, '_');
|
|
215
|
-
const pathTitleList = [...preItem.pathTitleList, `${fileName}.md`];
|
|
216
|
-
const pathIdList = [...preItem.pathIdList, item.uuid];
|
|
217
|
-
const progressItem = {
|
|
218
|
-
path: pathTitleList.join('/'),
|
|
219
|
-
pathTitleList,
|
|
220
|
-
pathIdList,
|
|
221
|
-
toc: item
|
|
222
|
-
};
|
|
223
|
-
const isSuccess = await downloadArticle({
|
|
224
|
-
bookId,
|
|
225
|
-
itemUrl: item.url,
|
|
226
|
-
savePath: `${bookPath}/${preItem.path}`,
|
|
227
|
-
saveFilePath: `${bookPath}/${progressItem.path}`,
|
|
228
|
-
uuid: item.uuid,
|
|
229
|
-
articleUrl: `${articleUrlPrefix}/${item.url}`,
|
|
230
|
-
articleTitle: item.title
|
|
231
|
-
});
|
|
232
|
-
if (isSuccess) {
|
|
233
|
-
uuidMap.set(item.uuid, progressItem);
|
|
234
|
-
progress.updateProgress(progressItem);
|
|
235
|
-
}
|
|
236
|
-
}
|
|
237
|
-
}
|
|
238
|
-
await progress.completePromise;
|
|
239
|
-
logger.info('生成目录 SUMMARY.md');
|
|
240
|
-
await genSummaryFile({
|
|
241
|
-
bookPath,
|
|
242
|
-
bookName,
|
|
243
|
-
bookDesc,
|
|
244
|
-
uuidMap
|
|
245
|
-
});
|
|
246
|
-
if (progress.curr === total) {
|
|
247
|
-
logger.info('√ 已完成');
|
|
248
|
-
return;
|
|
249
|
-
}
|
|
250
|
-
}
|
|
251
|
-
async function downloadArticle(params) {
|
|
252
|
-
const { bookId, itemUrl, savePath, saveFilePath, uuid, articleUrl, articleTitle } = params;
|
|
253
|
-
const apiUrl = `https://www.yuque.com/api/docs/${itemUrl}`;
|
|
254
|
-
const response = await axios.get(apiUrl, {
|
|
255
|
-
headers: {
|
|
256
|
-
"user-agent": randUserAgent({ browser: 'chrome', device: "desktop" })
|
|
257
|
-
},
|
|
258
|
-
params: {
|
|
259
|
-
'book_id': bookId,
|
|
260
|
-
'merge_dynamic_data': false,
|
|
261
|
-
mode: 'markdown'
|
|
262
|
-
}
|
|
263
|
-
}).then(({ data, status }) => {
|
|
264
|
-
if (status === 200)
|
|
265
|
-
return data;
|
|
266
|
-
logger.error(`download article error: ${apiUrl} http status ${status}`);
|
|
267
|
-
return null;
|
|
268
|
-
});
|
|
269
|
-
if (!response || !response.data || !response.data.sourcecode)
|
|
270
|
-
return false;
|
|
271
|
-
let mdData = response.data.sourcecode;
|
|
272
|
-
try {
|
|
273
|
-
mdData = await mdImg.run(mdData, {
|
|
274
|
-
dist: savePath,
|
|
275
|
-
imgDir: `img/${uuid}`,
|
|
276
|
-
isIgnoreConsole: true
|
|
277
|
-
});
|
|
278
|
-
}
|
|
279
|
-
catch (err) {
|
|
280
|
-
logger.error(`download article img Error (api: ${apiUrl})`);
|
|
281
|
-
return false;
|
|
282
|
-
}
|
|
283
|
-
mdData = mdData.replace(/<br(\s?)\/>/gm, '\n');
|
|
284
|
-
if (articleTitle) {
|
|
285
|
-
mdData = `# ${articleTitle}\n<!--page header-->\n\n${mdData}\n\n`;
|
|
286
|
-
}
|
|
287
|
-
if (articleUrl) {
|
|
288
|
-
mdData += `<!--page footer-->\n- 原文: <${articleUrl}>`;
|
|
289
|
-
}
|
|
290
|
-
try {
|
|
291
|
-
await fs.writeFile(saveFilePath, mdData);
|
|
292
|
-
return true;
|
|
293
|
-
}
|
|
294
|
-
catch (e) {
|
|
295
|
-
logger.error(`download article write file Error (api: ${apiUrl})`);
|
|
296
|
-
return false;
|
|
297
|
-
}
|
|
298
|
-
}
|
|
299
|
-
async function genSummaryFile(params) {
|
|
300
|
-
const { bookName, bookDesc, bookPath, uuidMap } = params;
|
|
301
|
-
const header = `# ${bookName}\n\n > ${bookDesc}\n\n`;
|
|
302
|
-
let mdContent = header;
|
|
303
|
-
const summary = [];
|
|
304
|
-
uuidMap.forEach(processItem => {
|
|
305
|
-
const toc = processItem.toc;
|
|
306
|
-
const parentId = toc['parent_uuid'];
|
|
307
|
-
const findRes = findTree(summary, parentId);
|
|
308
|
-
if (toc.type.toLocaleLowerCase() === 'title' || toc['child_uuid'] !== '') {
|
|
309
|
-
if (typeof findRes !== 'boolean') {
|
|
310
|
-
if (!Array.isArray(findRes.children))
|
|
311
|
-
findRes.children = [];
|
|
312
|
-
findRes.children.push({
|
|
313
|
-
id: toc.uuid,
|
|
314
|
-
type: 'title',
|
|
315
|
-
level: findRes.level + 1,
|
|
316
|
-
text: toc.title
|
|
317
|
-
});
|
|
318
|
-
}
|
|
319
|
-
else {
|
|
320
|
-
summary.push({
|
|
321
|
-
id: toc.uuid,
|
|
322
|
-
type: 'title',
|
|
323
|
-
text: toc.title,
|
|
324
|
-
level: 1
|
|
325
|
-
});
|
|
326
|
-
}
|
|
327
|
-
}
|
|
328
|
-
else {
|
|
329
|
-
if (typeof findRes !== 'boolean') {
|
|
330
|
-
if (!Array.isArray(findRes.children))
|
|
331
|
-
findRes.children = [];
|
|
332
|
-
findRes.children.push({
|
|
333
|
-
id: toc.uuid,
|
|
334
|
-
type: 'link',
|
|
335
|
-
level: findRes.level + 1,
|
|
336
|
-
link: processItem.path,
|
|
337
|
-
text: toc.title
|
|
338
|
-
});
|
|
339
|
-
}
|
|
340
|
-
else {
|
|
341
|
-
summary.push({
|
|
342
|
-
id: toc.uuid,
|
|
343
|
-
type: 'link',
|
|
344
|
-
text: toc.title,
|
|
345
|
-
link: processItem.path,
|
|
346
|
-
level: 1
|
|
347
|
-
});
|
|
348
|
-
}
|
|
349
|
-
}
|
|
350
|
-
});
|
|
351
|
-
let summaryContent = genSummaryContent(summary, '');
|
|
352
|
-
mdContent += summaryContent;
|
|
353
|
-
try {
|
|
354
|
-
await fs.writeFile(`${bookPath}/SUMMARY.md`, mdContent);
|
|
355
|
-
}
|
|
356
|
-
catch (err) {
|
|
357
|
-
logger.error('Generate Summary Error');
|
|
358
|
-
}
|
|
359
|
-
}
|
|
360
|
-
function genSummaryContent(summary, summaryContent) {
|
|
361
|
-
for (let i = 0; i < summary.length; i++) {
|
|
362
|
-
const item = summary[i];
|
|
363
|
-
if (item.type === 'title') {
|
|
364
|
-
summaryContent += `\n${''.padStart(item.level + 1, '#')} ${item.text}\n\n`;
|
|
365
|
-
}
|
|
366
|
-
else if (item.type === 'link') {
|
|
367
|
-
const link = item.link ? item.link.replace(/\s/g, '%20') : item.link;
|
|
368
|
-
summaryContent += `- [${item.text}](${link})\n`;
|
|
369
|
-
}
|
|
370
|
-
if (Array.isArray(item.children)) {
|
|
371
|
-
summaryContent += genSummaryContent(item.children, '');
|
|
372
|
-
}
|
|
373
|
-
}
|
|
374
|
-
return summaryContent;
|
|
375
|
-
}
|
|
376
|
-
function findIdItem(node, id) {
|
|
377
|
-
if (node.id === id) {
|
|
378
|
-
return node;
|
|
379
|
-
}
|
|
380
|
-
else if (node.children) {
|
|
381
|
-
const findRes = findTree(node.children, id);
|
|
382
|
-
if (findRes)
|
|
383
|
-
return findRes;
|
|
384
|
-
}
|
|
385
|
-
return false;
|
|
386
|
-
}
|
|
387
|
-
function findTree(tree, id) {
|
|
388
|
-
if (!id)
|
|
389
|
-
return false;
|
|
390
|
-
for (let i = 0; i < tree.length; i++) {
|
|
391
|
-
const findRes = findIdItem(tree[i], id);
|
|
392
|
-
if (findRes)
|
|
393
|
-
return findRes;
|
|
394
|
-
}
|
|
395
|
-
return false;
|
|
396
|
-
}
|
|
397
|
-
|
|
398
|
-
export { getKnowledgeBaseInfo as g, logger as l, main as m };
|
package/dist/es/index.js
DELETED