Skip to content

Commit 838779b

Browse files
authored
fix(export-pdf): fix invalid links of tag and category (#73)
1 parent 2b8ef2a commit 838779b

File tree

5 files changed

+58
-22
lines changed

5 files changed

+58
-22
lines changed

.vscode/launch.json

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,8 @@
1313
"outFiles": ["${workspaceFolder}/dist/**/*.js"],
1414
"preLaunchTask": "${defaultBuildTask}",
1515
"env": {
16-
"NODE_ENV": "Development"
16+
"NODE_ENV": "Development",
17+
"NODE_TLS_REJECT_UNAUTHORIZED": "0"
1718
}
1819
},
1920
{

src/commands/pdf/export-pdf.command.ts

Lines changed: 21 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,8 @@ import { extensionViews } from '../../tree-view-providers/tree-view-registration
1010
import { postPdfTemplateBuilder } from './post-pdf-template-builder';
1111
import { chromiumPathProvider } from '../../utils/chromium-path-provider';
1212
import { Settings } from '../../services/settings.service';
13+
import { accountService } from '../../services/account.service';
14+
import { AlertService } from '../../services/alert.service';
1315

1416
const launchBrowser = async (
1517
chromiumPath: string
@@ -42,7 +44,8 @@ const exportOne = async (
4244
post: Post,
4345
page: puppeteer.Page,
4446
targetFileUri: Uri,
45-
progress: Progress<{ message: string; increment: number }>
47+
progress: Progress<{ message: string; increment: number }>,
48+
blogApp: string
4649
) => {
4750
let message = `[${idx + 1}/${total}]正在导出 - ${post.title}`;
4851
const report = (increment: number) => {
@@ -52,7 +55,7 @@ const exportOne = async (
5255
});
5356
};
5457
report(10);
55-
let html = await postPdfTemplateBuilder.build(post);
58+
let html = await postPdfTemplateBuilder.build(post, blogApp);
5659
report(15);
5760
// Wait for code block highlight finished
5861
await Promise.all([
@@ -151,23 +154,20 @@ const handlePostInput = (post: Post): Promise<Post[]> => {
151154

152155
const handleUriInput = async (uri: Uri): Promise<Post[]> => {
153156
const posts: Post[] = [];
154-
const postId = PostFileMapManager.getPostId(uri.fsPath);
155-
let inputPost: Post | undefined;
156-
if (postId && postId > 0) {
157-
inputPost = (await postService.fetchPostEditDto(postId))?.post;
158-
} else {
159-
const { fsPath } = uri;
160-
inputPost = Object.assign((await postService.fetchPostEditDto(-1))?.post, {
157+
const { fsPath } = uri;
158+
const postId = PostFileMapManager.getPostId(fsPath);
159+
const { post: inputPost } = (await postService.fetchPostEditDto(postId && postId > 0 ? postId : -1)) ?? {};
160+
161+
if (!inputPost) {
162+
return [];
163+
} else if (inputPost.id <= 0) {
164+
Object.assign(inputPost, {
161165
id: -1,
162166
title: path.basename(fsPath, path.extname(fsPath)),
163167
postBody: new TextDecoder().decode(await workspace.fs.readFile(uri)),
164168
} as Post);
165169
}
166170

167-
if (!inputPost) {
168-
return [];
169-
}
170-
171171
posts.push(inputPost);
172172

173173
return posts;
@@ -187,6 +187,13 @@ const exportPostToPdf = async (input: Post | Uri): Promise<void> => {
187187
if (!chromiumPath) {
188188
return;
189189
}
190+
const {
191+
curUser: { blogApp },
192+
} = accountService;
193+
194+
if (!blogApp) {
195+
return AlertService.warning('无法获取到博客地址, 请检查登录状态');
196+
}
190197

191198
reportErrors(
192199
await window.withProgress<string[] | undefined>(
@@ -216,7 +223,7 @@ const exportPostToPdf = async (input: Post | Uri): Promise<void> => {
216223
const { length: total } = selectedPosts;
217224
for (const post of selectedPosts) {
218225
try {
219-
await exportOne(idx++, total, post, page, dir!, progress);
226+
await exportOne(idx++, total, post, page, dir!, progress, blogApp);
220227
} catch (err) {
221228
errors.push(`导出"${post.title}失败", ${err}`);
222229
}

src/commands/pdf/post-pdf-template-builder.ts

Lines changed: 10 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -5,12 +5,14 @@ import { markdownItFactory } from '@cnblogs-gitlab/markdown-it-presets';
55
import { blogSettingsService } from '../../services/blog-settings.service';
66
import { accountService } from '../../services/account.service';
77
import { postCategoryService } from '../../services/post-category.service';
8+
import { PostCategory } from '../../models/post-category';
89

910
export namespace postPdfTemplateBuilder {
1011
export const highlightedMessage = 'markdown-highlight-finished';
1112

12-
export const build = async (post: Post): Promise<string> => {
13+
export const build = async (post: Post, blogApp: string): Promise<string> => {
1314
let { postBody, isMarkdown, id: postId } = post;
15+
1416
const localFilePath = PostFileMapManager.getFilePath(postId);
1517
postBody = localFilePath ? fs.readFileSync(localFilePath).toString('utf-8') : postBody;
1618

@@ -26,7 +28,7 @@ export namespace postPdfTemplateBuilder {
2628
const buildTagHtml = (): Promise<string> => {
2729
let html =
2830
post.tags && post.tags.length > 0
29-
? post.tags.map(t => `<a href="https://www.cnblogs.com/laggage/tag/linux/">${t}</a>`).join(', ')
31+
? post.tags.map(t => `<a href="https://www.cnblogs.com/${blogApp}/tag/${t}/">${t}</a>`).join(', ')
3032
: '';
3133
html = html ? `<div id="EntryTag">标签: ${html}</div>` : '';
3234
return Promise.resolve(html);
@@ -35,13 +37,15 @@ export namespace postPdfTemplateBuilder {
3537
const buildCategoryHtml = async (): Promise<string> => {
3638
let categories = await postCategoryService.fetchCategories();
3739
const postCategories =
38-
post.categoryIds?.map(categoryId => categories.find(x => x.categoryId === categoryId)) ?? [];
40+
post.categoryIds
41+
?.map(categoryId => categories.find(x => x.categoryId === categoryId))
42+
.filter((x): x is PostCategory => x != null) ?? [];
3943
let html =
4044
postCategories.length > 0
4145
? postCategories
4246
.map(
4347
c =>
44-
`<a href="https://www.cnblogs.com/laggage/category/1565066.html" target="_blank">${c?.title}</a>`
48+
`<a href="https://www.cnblogs.com/${blogApp}/category/${c.categoryId}.html" target="_blank">${c?.title}</a>`
4549
)
4650
.join(', ')
4751
: '';
@@ -51,7 +55,7 @@ export namespace postPdfTemplateBuilder {
5155

5256
const tagHtml = await buildTagHtml();
5357
const categoryHtml = await buildCategoryHtml();
54-
const { codeHighlightEngine, codeHighlightTheme, enableCodeLineNumber, blogId, application } =
58+
const { codeHighlightEngine, codeHighlightTheme, enableCodeLineNumber, blogId } =
5559
await blogSettingsService.getBlogSettings();
5660
const { userId } = accountService.curUser;
5761
return `<html>
@@ -75,7 +79,7 @@ export namespace postPdfTemplateBuilder {
7579
<link rel="stylesheet" href="https://www.cnblogs.com/css/blog-common.min.css">
7680
<script>
7781
var currentBlogId = ${blogId};
78-
var currentBlogApp = '${application}';
82+
var currentBlogApp = '${blogApp}';
7983
var cb_enable_mathjax = true;
8084
var isLogined = true;
8185
var isBlogOwner = true;

src/models/user-settings.ts

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,24 @@
1+
import { trim } from 'lodash';
2+
13
export class UserAuthorizationInfo {
24
constructor(public idToken: string, public accessToken: string, expiresIn: number, public tokenType: string) {}
35
}
46

57
export class UserInfo {
8+
private _blogApp?: string | null;
9+
610
get userId() {
711
return this.sub;
812
}
913

14+
get blogApp(): string | null {
15+
if (this._blogApp == null) {
16+
this._blogApp = this.parseBlogApp();
17+
}
18+
19+
return this._blogApp;
20+
}
21+
1022
/**
1123
* Creates an instance of UserInfo.
1224
* @param {UserAuthorizationInfo} [authorizationInfo]
@@ -26,4 +38,12 @@ export class UserInfo {
2638
public sub: string = '',
2739
public accountId: number = -1
2840
) {}
41+
42+
private parseBlogApp(): string | null {
43+
return (
44+
trim(this.website ?? '', '/')
45+
.split('/')
46+
.pop() ?? null
47+
);
48+
}
2949
}

src/services/account.service.ts

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -38,7 +38,10 @@ export class AccountService extends vscode.Disposable {
3838
}
3939

4040
get curUser(): UserInfo {
41-
return this._curUser ? this._curUser : globalState.storage.get('user') ?? new UserInfo();
41+
return (
42+
this._curUser ||
43+
(this._curUser = Object.assign(new UserInfo(), globalState.storage.get('user') ?? new UserInfo()))
44+
);
4245
}
4346

4447
protected constructor() {
@@ -80,6 +83,7 @@ export class AccountService extends vscode.Disposable {
8083
const token = this.curUser?.authorizationInfo?.accessToken;
8184

8285
await globalState.storage.update('user', {});
86+
this._curUser = undefined;
8387
await this.setIsAuthorized(false);
8488

8589
if (token) {

0 commit comments

Comments
 (0)