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.
@@ -0,0 +1,405 @@
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
+ let errArticleCount = 0;
173
+ let totalArticleCount = 0;
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
+ totalArticleCount += 1;
209
+ let preItem = {
210
+ path: '',
211
+ pathTitleList: [],
212
+ pathIdList: []
213
+ };
214
+ if (uuidMap.get(item['parent_uuid'])) {
215
+ preItem = uuidMap.get(item['parent_uuid']);
216
+ }
217
+ const fileName = item.title.replace(dirNameReg, '_');
218
+ const pathTitleList = [...preItem.pathTitleList, `${fileName}.md`];
219
+ const pathIdList = [...preItem.pathIdList, item.uuid];
220
+ const progressItem = {
221
+ path: pathTitleList.join('/'),
222
+ pathTitleList,
223
+ pathIdList,
224
+ toc: item
225
+ };
226
+ const isSuccess = await downloadArticle({
227
+ bookId,
228
+ itemUrl: item.url,
229
+ savePath: `${bookPath}/${preItem.path}`,
230
+ saveFilePath: `${bookPath}/${progressItem.path}`,
231
+ uuid: item.uuid,
232
+ articleUrl: `${articleUrlPrefix}/${item.url}`,
233
+ articleTitle: item.title
234
+ });
235
+ if (isSuccess) {
236
+ uuidMap.set(item.uuid, progressItem);
237
+ progress.updateProgress(progressItem);
238
+ }
239
+ else {
240
+ errArticleCount += 1;
241
+ }
242
+ }
243
+ }
244
+ await progress.completePromise;
245
+ logger.info(`总数${totalArticleCount}篇,✕ 失败${errArticleCount}篇`);
246
+ logger.info('生成目录 SUMMARY.md');
247
+ await genSummaryFile({
248
+ bookPath,
249
+ bookName,
250
+ bookDesc,
251
+ uuidMap
252
+ });
253
+ if (progress.curr === total) {
254
+ logger.info('√ 已完成');
255
+ return;
256
+ }
257
+ }
258
+ async function downloadArticle(params) {
259
+ const { bookId, itemUrl, savePath, saveFilePath, uuid, articleUrl, articleTitle } = params;
260
+ const apiUrl = `https://www.yuque.com/api/docs/${itemUrl}`;
261
+ const response = await axios.get(apiUrl, {
262
+ headers: {
263
+ "user-agent": randUserAgent({ browser: 'chrome', device: "desktop" })
264
+ },
265
+ params: {
266
+ 'book_id': bookId,
267
+ 'merge_dynamic_data': false,
268
+ mode: 'markdown'
269
+ }
270
+ }).then(({ data, status }) => {
271
+ if (status === 200)
272
+ return data;
273
+ logger.error(`download article error: ${apiUrl} http status ${status}`);
274
+ return null;
275
+ });
276
+ if (!response || !response.data || !response.data.sourcecode)
277
+ return false;
278
+ let mdData = response.data.sourcecode;
279
+ try {
280
+ mdData = await mdImg.run(mdData, {
281
+ dist: savePath,
282
+ imgDir: `img/${uuid}`,
283
+ isIgnoreConsole: true
284
+ });
285
+ }
286
+ catch (err) {
287
+ logger.error(`download article img Error (api: ${apiUrl})`);
288
+ return false;
289
+ }
290
+ mdData = mdData.replace(/<br(\s?)\/>/gm, '\n');
291
+ if (articleTitle) {
292
+ mdData = `# ${articleTitle}\n<!--page header-->\n\n${mdData}\n\n`;
293
+ }
294
+ if (articleUrl) {
295
+ mdData += `<!--page footer-->\n- 原文: <${articleUrl}>`;
296
+ }
297
+ try {
298
+ await fs.writeFile(saveFilePath, mdData);
299
+ return true;
300
+ }
301
+ catch (e) {
302
+ logger.error(`download article write file Error (api: ${apiUrl})`);
303
+ return false;
304
+ }
305
+ }
306
+ async function genSummaryFile(params) {
307
+ const { bookName, bookDesc, bookPath, uuidMap } = params;
308
+ const header = `# ${bookName}\n\n > ${bookDesc}\n\n`;
309
+ let mdContent = header;
310
+ const summary = [];
311
+ uuidMap.forEach(processItem => {
312
+ const toc = processItem.toc;
313
+ const parentId = toc['parent_uuid'];
314
+ const findRes = findTree(summary, parentId);
315
+ if (toc.type.toLocaleLowerCase() === 'title' || toc['child_uuid'] !== '') {
316
+ if (typeof findRes !== 'boolean') {
317
+ if (!Array.isArray(findRes.children))
318
+ findRes.children = [];
319
+ findRes.children.push({
320
+ id: toc.uuid,
321
+ type: 'title',
322
+ level: findRes.level + 1,
323
+ text: toc.title
324
+ });
325
+ }
326
+ else {
327
+ summary.push({
328
+ id: toc.uuid,
329
+ type: 'title',
330
+ text: toc.title,
331
+ level: 1
332
+ });
333
+ }
334
+ }
335
+ else {
336
+ if (typeof findRes !== 'boolean') {
337
+ if (!Array.isArray(findRes.children))
338
+ findRes.children = [];
339
+ findRes.children.push({
340
+ id: toc.uuid,
341
+ type: 'link',
342
+ level: findRes.level + 1,
343
+ link: processItem.path,
344
+ text: toc.title
345
+ });
346
+ }
347
+ else {
348
+ summary.push({
349
+ id: toc.uuid,
350
+ type: 'link',
351
+ text: toc.title,
352
+ link: processItem.path,
353
+ level: 1
354
+ });
355
+ }
356
+ }
357
+ });
358
+ let summaryContent = genSummaryContent(summary, '');
359
+ mdContent += summaryContent;
360
+ try {
361
+ await fs.writeFile(`${bookPath}/SUMMARY.md`, mdContent);
362
+ }
363
+ catch (err) {
364
+ logger.error('Generate Summary Error');
365
+ }
366
+ }
367
+ function genSummaryContent(summary, summaryContent) {
368
+ for (let i = 0; i < summary.length; i++) {
369
+ const item = summary[i];
370
+ if (item.type === 'title') {
371
+ summaryContent += `\n${''.padStart(item.level + 1, '#')} ${item.text}\n\n`;
372
+ }
373
+ else if (item.type === 'link') {
374
+ const link = item.link ? item.link.replace(/\s/g, '%20') : item.link;
375
+ summaryContent += `- [${item.text}](${link})\n`;
376
+ }
377
+ if (Array.isArray(item.children)) {
378
+ summaryContent += genSummaryContent(item.children, '');
379
+ }
380
+ }
381
+ return summaryContent;
382
+ }
383
+ function findIdItem(node, id) {
384
+ if (node.id === id) {
385
+ return node;
386
+ }
387
+ else if (node.children) {
388
+ const findRes = findTree(node.children, id);
389
+ if (findRes)
390
+ return findRes;
391
+ }
392
+ return false;
393
+ }
394
+ function findTree(tree, id) {
395
+ if (!id)
396
+ return false;
397
+ for (let i = 0; i < tree.length; i++) {
398
+ const findRes = findIdItem(tree[i], id);
399
+ if (findRes)
400
+ return findRes;
401
+ }
402
+ return false;
403
+ }
404
+
405
+ export { getKnowledgeBaseInfo as g, logger as l, main as m };
@@ -0,0 +1,8 @@
1
+ import 'node:fs/promises';
2
+ import 'node:path';
3
+ import 'axios';
4
+ export { g as getKnowledgeBaseInfo, m as main } from './index-5cda90ca.js';
5
+ import 'pull-md-img';
6
+ import 'log4js';
7
+ import 'progress';
8
+ import 'rand-user-agent';
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "yuque-dl",
3
- "version": "1.0.3",
3
+ "version": "1.0.5",
4
4
  "description": "yuque 知识库下载",
5
5
  "type": "module",
6
6
  "bin": {
@@ -12,7 +12,7 @@
12
12
  "build:bundle": "rollup -c rollup.config.ts --configPlugin typescript",
13
13
  "build:types": "tsc --emitDeclarationOnly --outDir types -p tsconfig.base.json",
14
14
  "clean": "rm -rf dist types",
15
- "test": "echo \"Error: no test specified\" && exit 1"
15
+ "publish": "np"
16
16
  },
17
17
  "repository": {
18
18
  "type": "git",
@@ -33,6 +33,7 @@
33
33
  "@typescript-eslint/eslint-plugin": "^6.3.0",
34
34
  "@typescript-eslint/parser": "^6.3.0",
35
35
  "jest": "^29.6.2",
36
+ "np": "^8.0.4",
36
37
  "npm-run-all": "^4.1.5",
37
38
  "rollup": "^3.28.0",
38
39
  "tslib": "^2.6.1"
@@ -48,11 +49,11 @@
48
49
  },
49
50
  "dependencies": {
50
51
  "axios": "^1.4.0",
52
+ "cac": "^6.7.14",
51
53
  "log4js": "^6.9.1",
52
54
  "progress": "^2.0.3",
53
- "pull-md-img": "^0.0.19",
54
- "rand-user-agent": "1.0.109",
55
- "cac": "^6.7.14"
55
+ "pull-md-img": "^0.0.20",
56
+ "rand-user-agent": "1.0.109"
56
57
  },
57
58
  "engines": {
58
59
  "node": "^14.18.0 || >=16.0.0"
@@ -10,8 +10,12 @@
10
10
  "esModuleInterop": true,
11
11
  "useUnknownInCatchVariables": false,
12
12
  "resolveJsonModule": true,
13
+ "paths": {
14
+ "@/*": ["./*"],
15
+ }
13
16
  },
14
17
  "include": [
15
- "src/**/*"
16
- ]
18
+ "./src/**/*"
19
+ ],
20
+
17
21
  }
@@ -0,0 +1,23 @@
1
+ import progress from 'progress';
2
+ import type { KnowledgeBase } from './types/KnowledgeBaseResponse';
3
+ export interface IProcessItem {
4
+ path: string;
5
+ toc: KnowledgeBase.Toc;
6
+ pathIdList: string[];
7
+ pathTitleList: string[];
8
+ }
9
+ export declare type IProcess = IProcessItem[];
10
+ export default class Progress {
11
+ bookPath: string;
12
+ processFilePath: string;
13
+ processInfo: IProcess;
14
+ curr: number;
15
+ total: number;
16
+ isDownloadInterrupted: boolean;
17
+ bar: progress | null;
18
+ completePromise: Promise<void> | null;
19
+ constructor(bookPath: string, total: number);
20
+ init(): Promise<void>;
21
+ getProgress(): Promise<IProcess>;
22
+ updateProgress(progressItem: IProcessItem): Promise<void>;
23
+ }
package/types/cli.d.ts ADDED
@@ -0,0 +1,3 @@
1
+ export interface IOptions {
2
+ distDir: string;
3
+ }
@@ -0,0 +1,5 @@
1
+ declare const _default: {
2
+ knowledgeBaseReg: RegExp;
3
+ dist: string;
4
+ };
5
+ export default _default;
@@ -0,0 +1,11 @@
1
+ import type { IOptions } from './cli';
2
+ import type { KnowledgeBase } from './types/KnowledgeBaseResponse';
3
+ interface IKnowledgeBaseInfo {
4
+ bookId?: number;
5
+ tocList?: KnowledgeBase.Toc[];
6
+ bookName?: string;
7
+ bookDesc?: string;
8
+ }
9
+ declare function getKnowledgeBaseInfo(url: string): Promise<IKnowledgeBaseInfo>;
10
+ declare function main(url: string, options: IOptions): Promise<void>;
11
+ export { getKnowledgeBaseInfo, main };
package/types/log.d.ts ADDED
@@ -0,0 +1,3 @@
1
+ import log4js from 'log4js';
2
+ declare const _default: log4js.Logger;
3
+ export default _default;
@@ -0,0 +1,42 @@
1
+ export declare namespace ArticleResponse {
2
+ interface RootObject {
3
+ meta: Meta;
4
+ data: Data;
5
+ }
6
+ interface Data {
7
+ id: number;
8
+ space_id: number;
9
+ type: string;
10
+ sub_type?: any;
11
+ format: string;
12
+ title: string;
13
+ slug: string;
14
+ public: number;
15
+ status: number;
16
+ read_status: number;
17
+ created_at: string;
18
+ content_updated_at: string;
19
+ published_at: string;
20
+ first_published_at: string;
21
+ sourcecode: string;
22
+ last_editor?: any;
23
+ _serializer: string;
24
+ }
25
+ interface Meta {
26
+ abilities: Abilities;
27
+ latestReviewStatus: number;
28
+ }
29
+ interface Abilities {
30
+ create: boolean;
31
+ destroy: boolean;
32
+ update: boolean;
33
+ read: boolean;
34
+ export: boolean;
35
+ manage: boolean;
36
+ join: boolean;
37
+ share: boolean;
38
+ force_delete: boolean;
39
+ create_collaborator: boolean;
40
+ destroy_comment: boolean;
41
+ }
42
+ }