yuque-dl 1.0.3 → 1.0.5

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/.np-config.js ADDED
@@ -0,0 +1,3 @@
1
+ export default {
2
+ tests: false
3
+ }
@@ -0,0 +1,46 @@
1
+ 'use strict';
2
+
3
+ var node_fs = require('node:fs');
4
+ var cac = require('cac');
5
+ var index = require('./index-4969d150.js');
6
+ require('node:fs/promises');
7
+ require('node:path');
8
+ require('axios');
9
+ require('log4js');
10
+ require('progress');
11
+ require('rand-user-agent');
12
+ require('pull-md-img');
13
+
14
+ const cli = cac.cac('yuque-dl');
15
+ // 不能直接使用 import {version} from '../package.json'
16
+ // 否则declaration 生成的d.ts 会多一层src目录
17
+ const { version } = JSON.parse(node_fs.readFileSync(new URL('../../package.json', (typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (document.currentScript && document.currentScript.src || new URL('cli.js', document.baseURI).href)))).toString());
18
+ cli
19
+ .command('<url>', 'request url')
20
+ .option('-d, --distDir <dir>', '下载的目录 eg: -d download', {
21
+ default: 'download',
22
+ })
23
+ .action(async (url, options) => {
24
+ try {
25
+ await index.main(url, options);
26
+ }
27
+ catch (err) {
28
+ index.logger.error(err.message || 'unknown exception');
29
+ }
30
+ });
31
+ cli.help();
32
+ cli.version(version);
33
+ try {
34
+ cli.parse();
35
+ }
36
+ catch (err) {
37
+ index.logger.error(err.message || 'unknown exception');
38
+ process.exit(1);
39
+ }
40
+ // try {
41
+ // cli.parse(process.argv, { run: false })
42
+ // await cli.runMatchedCommand()
43
+ // } catch (error) {
44
+ // logger.error(error.message || 'unknown exception')
45
+ // process.exit(1)
46
+ // }
@@ -0,0 +1,409 @@
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
+ let errArticleCount = 0;
175
+ let totalArticleCount = 0;
176
+ for (let i = 0; i < total; i++) {
177
+ const item = tocList[i];
178
+ if (typeof item.type !== 'string')
179
+ continue;
180
+ if (uuidMap.get(item.uuid))
181
+ continue;
182
+ const itemType = item.type.toLocaleLowerCase();
183
+ const dirNameReg = /[\\\/:\*\?"<>\|\n\r]/g;
184
+ // 目录
185
+ if (itemType === 'title' || item['child_uuid'] !== '') {
186
+ let tempItem = item;
187
+ let pathTitleList = [];
188
+ let pathIdList = [];
189
+ while (tempItem) {
190
+ pathTitleList.unshift(tempItem.title.replace(dirNameReg, '_'));
191
+ pathIdList.unshift(tempItem.uuid);
192
+ if (uuidMap.get(tempItem['parent_uuid'])) {
193
+ tempItem = uuidMap.get(tempItem['parent_uuid']).toc;
194
+ }
195
+ else {
196
+ tempItem = undefined;
197
+ }
198
+ }
199
+ const progressItem = {
200
+ path: pathTitleList.join('/'),
201
+ pathTitleList,
202
+ pathIdList,
203
+ toc: item
204
+ };
205
+ await fs.mkdir(`${bookPath}/${pathTitleList.join('/')}`, { recursive: true });
206
+ uuidMap.set(item.uuid, progressItem);
207
+ progress.updateProgress(progressItem);
208
+ }
209
+ else if (item.url) {
210
+ totalArticleCount += 1;
211
+ let preItem = {
212
+ path: '',
213
+ pathTitleList: [],
214
+ pathIdList: []
215
+ };
216
+ if (uuidMap.get(item['parent_uuid'])) {
217
+ preItem = uuidMap.get(item['parent_uuid']);
218
+ }
219
+ const fileName = item.title.replace(dirNameReg, '_');
220
+ const pathTitleList = [...preItem.pathTitleList, `${fileName}.md`];
221
+ const pathIdList = [...preItem.pathIdList, item.uuid];
222
+ const progressItem = {
223
+ path: pathTitleList.join('/'),
224
+ pathTitleList,
225
+ pathIdList,
226
+ toc: item
227
+ };
228
+ const isSuccess = await downloadArticle({
229
+ bookId,
230
+ itemUrl: item.url,
231
+ savePath: `${bookPath}/${preItem.path}`,
232
+ saveFilePath: `${bookPath}/${progressItem.path}`,
233
+ uuid: item.uuid,
234
+ articleUrl: `${articleUrlPrefix}/${item.url}`,
235
+ articleTitle: item.title
236
+ });
237
+ if (isSuccess) {
238
+ uuidMap.set(item.uuid, progressItem);
239
+ progress.updateProgress(progressItem);
240
+ }
241
+ else {
242
+ errArticleCount += 1;
243
+ }
244
+ }
245
+ }
246
+ await progress.completePromise;
247
+ logger.info(`总数${totalArticleCount}篇,✕ 失败${errArticleCount}篇`);
248
+ logger.info('生成目录 SUMMARY.md');
249
+ await genSummaryFile({
250
+ bookPath,
251
+ bookName,
252
+ bookDesc,
253
+ uuidMap
254
+ });
255
+ if (progress.curr === total) {
256
+ logger.info('√ 已完成');
257
+ return;
258
+ }
259
+ }
260
+ async function downloadArticle(params) {
261
+ const { bookId, itemUrl, savePath, saveFilePath, uuid, articleUrl, articleTitle } = params;
262
+ const apiUrl = `https://www.yuque.com/api/docs/${itemUrl}`;
263
+ const response = await axios.get(apiUrl, {
264
+ headers: {
265
+ "user-agent": randUserAgent({ browser: 'chrome', device: "desktop" })
266
+ },
267
+ params: {
268
+ 'book_id': bookId,
269
+ 'merge_dynamic_data': false,
270
+ mode: 'markdown'
271
+ }
272
+ }).then(({ data, status }) => {
273
+ if (status === 200)
274
+ return data;
275
+ logger.error(`download article error: ${apiUrl} http status ${status}`);
276
+ return null;
277
+ });
278
+ if (!response || !response.data || !response.data.sourcecode)
279
+ return false;
280
+ let mdData = response.data.sourcecode;
281
+ try {
282
+ mdData = await mdImg.run(mdData, {
283
+ dist: savePath,
284
+ imgDir: `img/${uuid}`,
285
+ isIgnoreConsole: true
286
+ });
287
+ }
288
+ catch (err) {
289
+ logger.error(`download article img Error (api: ${apiUrl})`);
290
+ return false;
291
+ }
292
+ mdData = mdData.replace(/<br(\s?)\/>/gm, '\n');
293
+ if (articleTitle) {
294
+ mdData = `# ${articleTitle}\n<!--page header-->\n\n${mdData}\n\n`;
295
+ }
296
+ if (articleUrl) {
297
+ mdData += `<!--page footer-->\n- 原文: <${articleUrl}>`;
298
+ }
299
+ try {
300
+ await fs.writeFile(saveFilePath, mdData);
301
+ return true;
302
+ }
303
+ catch (e) {
304
+ logger.error(`download article write file Error (api: ${apiUrl})`);
305
+ return false;
306
+ }
307
+ }
308
+ async function genSummaryFile(params) {
309
+ const { bookName, bookDesc, bookPath, uuidMap } = params;
310
+ const header = `# ${bookName}\n\n > ${bookDesc}\n\n`;
311
+ let mdContent = header;
312
+ const summary = [];
313
+ uuidMap.forEach(processItem => {
314
+ const toc = processItem.toc;
315
+ const parentId = toc['parent_uuid'];
316
+ const findRes = findTree(summary, parentId);
317
+ if (toc.type.toLocaleLowerCase() === 'title' || toc['child_uuid'] !== '') {
318
+ if (typeof findRes !== 'boolean') {
319
+ if (!Array.isArray(findRes.children))
320
+ findRes.children = [];
321
+ findRes.children.push({
322
+ id: toc.uuid,
323
+ type: 'title',
324
+ level: findRes.level + 1,
325
+ text: toc.title
326
+ });
327
+ }
328
+ else {
329
+ summary.push({
330
+ id: toc.uuid,
331
+ type: 'title',
332
+ text: toc.title,
333
+ level: 1
334
+ });
335
+ }
336
+ }
337
+ else {
338
+ if (typeof findRes !== 'boolean') {
339
+ if (!Array.isArray(findRes.children))
340
+ findRes.children = [];
341
+ findRes.children.push({
342
+ id: toc.uuid,
343
+ type: 'link',
344
+ level: findRes.level + 1,
345
+ link: processItem.path,
346
+ text: toc.title
347
+ });
348
+ }
349
+ else {
350
+ summary.push({
351
+ id: toc.uuid,
352
+ type: 'link',
353
+ text: toc.title,
354
+ link: processItem.path,
355
+ level: 1
356
+ });
357
+ }
358
+ }
359
+ });
360
+ let summaryContent = genSummaryContent(summary, '');
361
+ mdContent += summaryContent;
362
+ try {
363
+ await fs.writeFile(`${bookPath}/SUMMARY.md`, mdContent);
364
+ }
365
+ catch (err) {
366
+ logger.error('Generate Summary Error');
367
+ }
368
+ }
369
+ function genSummaryContent(summary, summaryContent) {
370
+ for (let i = 0; i < summary.length; i++) {
371
+ const item = summary[i];
372
+ if (item.type === 'title') {
373
+ summaryContent += `\n${''.padStart(item.level + 1, '#')} ${item.text}\n\n`;
374
+ }
375
+ else if (item.type === 'link') {
376
+ const link = item.link ? item.link.replace(/\s/g, '%20') : item.link;
377
+ summaryContent += `- [${item.text}](${link})\n`;
378
+ }
379
+ if (Array.isArray(item.children)) {
380
+ summaryContent += genSummaryContent(item.children, '');
381
+ }
382
+ }
383
+ return summaryContent;
384
+ }
385
+ function findIdItem(node, id) {
386
+ if (node.id === id) {
387
+ return node;
388
+ }
389
+ else if (node.children) {
390
+ const findRes = findTree(node.children, id);
391
+ if (findRes)
392
+ return findRes;
393
+ }
394
+ return false;
395
+ }
396
+ function findTree(tree, id) {
397
+ if (!id)
398
+ return false;
399
+ for (let i = 0; i < tree.length; i++) {
400
+ const findRes = findIdItem(tree[i], id);
401
+ if (findRes)
402
+ return findRes;
403
+ }
404
+ return false;
405
+ }
406
+
407
+ exports.getKnowledgeBaseInfo = getKnowledgeBaseInfo;
408
+ exports.logger = logger;
409
+ exports.main = main;
@@ -0,0 +1,15 @@
1
+ 'use strict';
2
+
3
+ require('node:fs/promises');
4
+ require('node:path');
5
+ require('axios');
6
+ var index = require('./index-4969d150.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 ADDED
@@ -0,0 +1,44 @@
1
+ import { readFileSync } from 'node:fs';
2
+ import { cac } from 'cac';
3
+ import { m as main, l as logger } from './index-5cda90ca.js';
4
+ import 'node:fs/promises';
5
+ import 'node:path';
6
+ import 'axios';
7
+ import 'log4js';
8
+ import 'progress';
9
+ import 'rand-user-agent';
10
+ import 'pull-md-img';
11
+
12
+ const cli = cac('yuque-dl');
13
+ // 不能直接使用 import {version} from '../package.json'
14
+ // 否则declaration 生成的d.ts 会多一层src目录
15
+ const { version } = JSON.parse(readFileSync(new URL('../../package.json', import.meta.url)).toString());
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 main(url, options);
24
+ }
25
+ catch (err) {
26
+ 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
+ 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
+ // }