Skip to content

Commit d2286bd

Browse files
committed
Merge branch 'dataurl-img-extract' into fix-login-no-response
2 parents d24be59 + edd4af2 commit d2286bd

File tree

5 files changed

+313
-239
lines changed

5 files changed

+313
-239
lines changed

Diff for: src/commands/extract-images.ts

+53-44
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,9 @@
11
import { MessageItem, MessageOptions, ProgressLocation, Range, Uri, window, workspace, WorkspaceEdit } from 'vscode'
2-
import { ImageSrc, MarkdownImagesExtractor, ImageInfo, newImageSrcFilter } from '@/services/images-extractor.service'
2+
import { ImageInfo, ImageSrc, MkdImgExtractor, newImageSrcFilter } from '@/services/mkd-img-extractor.service'
33

44
type ExtractOption = MessageItem & Partial<{ imageSrc: ImageSrc }>
5-
const extractOptions: readonly ExtractOption[] = [
6-
{ title: '提取本地图片', imageSrc: ImageSrc.local },
7-
{ title: '提取网络图片', imageSrc: ImageSrc.web },
8-
{ title: '提取全部', imageSrc: ImageSrc.any },
9-
{ title: '取消', imageSrc: undefined, isCloseAffordance: true },
10-
]
11-
12-
export async function extractImages(arg: unknown, inputImageSrc: ImageSrc | undefined) {
5+
6+
export async function extractImages(arg: unknown, inputImageSrc?: ImageSrc) {
137
if (!(arg instanceof Uri && arg.scheme === 'file')) return
148

159
const editor = window.visibleTextEditors.find(x => x.document.fileName === arg.fsPath)
@@ -19,44 +13,58 @@ export async function extractImages(arg: unknown, inputImageSrc: ImageSrc | unde
1913
await textDocument.save()
2014

2115
const markdown = (await workspace.fs.readFile(arg)).toString()
22-
const extractor = new MarkdownImagesExtractor(markdown, arg)
16+
const extractor = new MkdImgExtractor(markdown, arg)
2317

2418
const images = extractor.findImages()
25-
26-
// TODO: consider: && inputImageSrc != null
27-
if (images.length <= 0) {
28-
await window.showInformationMessage('没有找到可以提取的图片')
29-
return
30-
}
31-
32-
const availableWebImagesCount = images.filter(newImageSrcFilter(ImageSrc.web)).length
33-
const availableLocalImagesCount = images.filter(newImageSrcFilter(ImageSrc.local)).length
34-
const result =
35-
extractOptions.find(x => inputImageSrc != null && x.imageSrc === inputImageSrc) ??
36-
(await window.showInformationMessage<ExtractOption>(
19+
if (images.length <= 0)
20+
void (!inputImageSrc != null ? window.showWarningMessage('没有找到可以提取的图片') : undefined)
21+
22+
const getExtractOption = () => {
23+
const webImgCount = images.filter(newImageSrcFilter(ImageSrc.web)).length
24+
const dataUrlImgCount = images.filter(newImageSrcFilter(ImageSrc.dataUrl)).length
25+
const fsImgCount = images.filter(newImageSrcFilter(ImageSrc.fs)).length
26+
27+
const displayOptions: ExtractOption[] = [
28+
{ title: '提取全部', imageSrc: ImageSrc.any },
29+
{ title: '提取网络图片', imageSrc: ImageSrc.web },
30+
{ title: '提取 Data Url 图片', imageSrc: ImageSrc.dataUrl },
31+
{ title: '提取本地图片', imageSrc: ImageSrc.fs },
32+
{ title: '取消', imageSrc: undefined, isCloseAffordance: true },
33+
]
34+
35+
if (inputImageSrc !== undefined)
36+
return Promise.resolve(displayOptions.find(ent => ent.imageSrc === inputImageSrc))
37+
38+
// if src is not specified:
39+
return window.showInformationMessage<ExtractOption>(
3740
'要提取哪些图片? 此操作会替换源文件中的图片链接!',
3841
{
3942
modal: true,
4043
detail:
41-
`共找到 ${availableWebImagesCount} 张可以提取的网络图片\n` +
42-
`${availableLocalImagesCount} 张可以提取的本地图片`,
44+
'共找到:\n' +
45+
`${webImgCount} 张可以提取的网络图片\n` +
46+
`${dataUrlImgCount} 张可以提取的 Data Url 图片\n` +
47+
`${fsImgCount} 张可以提取的本地图片`,
4348
} as MessageOptions,
44-
...extractOptions
45-
))
49+
...displayOptions
50+
)
51+
}
52+
53+
const extractImageSrc = (await getExtractOption())?.imageSrc
4654

47-
if (!(result && result.imageSrc !== undefined)) return
55+
if (extractImageSrc === undefined) return
4856

49-
extractor.imageSrc = result.imageSrc
57+
extractor.imageSrc = extractImageSrc
5058

5159
const failedImages = await window.withProgress(
52-
{ title: '提取图片', location: ProgressLocation.Notification },
60+
{ title: '正在提取图片', location: ProgressLocation.Notification },
5361
async progress => {
54-
extractor.onProgress = (idx, images) => {
55-
const total = images.length
56-
const image = images[idx]
62+
extractor.onProgress = (count, info) => {
63+
const total = info.length
64+
const image = info[count]
5765
progress.report({
58-
increment: (idx / total) * 80,
59-
message: `[${idx + 1} / ${total}] 正在提取 ${image.link}`,
66+
increment: (count / total) * 80,
67+
message: `[${count + 1} / ${total}] 正在提取 ${image.data}`,
6068
})
6169
}
6270

@@ -69,25 +77,26 @@ export async function extractImages(arg: unknown, inputImageSrc: ImageSrc | unde
6977
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
7078
.map(([src, dst]) => [src, dst!])
7179
.map(([src, dst]) => {
72-
const startPos = textDocument.positionAt(src.startOffset)
73-
const endPos = textDocument.positionAt(
74-
src.startOffset + src.prefix.length + src.link.length + src.postfix.length
80+
const posL = textDocument.positionAt(src.startOffset)
81+
const posR = textDocument.positionAt(
82+
src.startOffset + src.prefix.length + src.data.length + src.postfix.length
7583
)
76-
const range = new Range(startPos, endPos)
84+
const range = new Range(posL, posR)
7785

86+
// just for ts type inferring
7887
const ret: [Range, ImageInfo] = [range, dst]
7988
return ret
8089
})
8190
.reduce((we, [range, dst]) => {
8291
if (range) {
8392
progress.report({
8493
increment: (idx / extractedLen) * 20 + 80,
85-
message: `[${idx + 1} / ${extractedLen}] 正在替换图片链接 ${dst.link}`,
94+
message: `[${idx + 1} / ${extractedLen}] 正在替换图片链接 ${dst.data}`,
8695
})
87-
const newText = dst.prefix + dst.link + dst.postfix
96+
const newText = dst.prefix + dst.data + dst.postfix
8897
we.replace(textDocument.uri, range, newText, {
8998
needsConfirmation: false,
90-
label: dst.link,
99+
label: dst.data,
91100
})
92101
}
93102

@@ -100,10 +109,10 @@ export async function extractImages(arg: unknown, inputImageSrc: ImageSrc | unde
100109
}
101110
)
102111

103-
if (failedImages && failedImages.length > 0) {
112+
if (failedImages.length > 0) {
104113
const info = failedImages
105-
.map(x => [x.link, extractor.errors.find(([link]) => link === x.link)?.[1] ?? ''].join(','))
114+
.map(info => [info.data, extractor.errors.find(([link]) => link === info.data)?.[1] ?? ''].join(','))
106115
.join('\n')
107-
window.showErrorMessage(`${failedImages.length}张图片提取失败: ${info}`).then(undefined, console.error)
116+
window.showErrorMessage(`${failedImages.length} 张图片提取失败: ${info}`).then(undefined, console.warn)
108117
}
109118
}

Diff for: src/services/image.service.ts

+9-7
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import { globalCtx } from './global-state'
1+
import { globalContext } from './global-state'
22
import { Readable } from 'stream'
33
import { isString, merge, pick } from 'lodash-es'
44
import httpClient from '@/utils/http-client'
@@ -7,18 +7,20 @@ import path from 'path'
77
class ImageService {
88
async upload<T extends Readable & { name?: string; fileName?: string; filename?: string; path?: string | Buffer }>(
99
file: T
10-
): Promise<string> {
10+
) {
1111
// eslint-disable-next-line @typescript-eslint/naming-convention
12-
const FormData = (await import('form-data')).default
13-
const form = new FormData()
1412
const { name, fileName, filename, path: _path } = file
1513
const finalName = path.basename(isString(_path) ? _path : fileName || filename || name || 'image.png')
1614
const ext = path.extname(finalName)
15+
1716
const mime = await import('mime')
1817
const mimeType = mime.lookup(ext, 'image/png')
19-
form.append('image', file, { filename: finalName, contentType: mimeType })
20-
const response = await httpClient.post(`${globalCtx.config.apiBaseUrl}/api/posts/body/images`, {
21-
body: form,
18+
19+
const fd = new (await import('form-data')).default()
20+
fd.append('image', file, { filename: finalName, contentType: mimeType })
21+
22+
const response = await httpClient.post(`${globalContext.config.apiBaseUrl}/api/posts/body/images`, {
23+
body: fd,
2224
})
2325

2426
return response.body

Diff for: src/services/images-extractor.service.ts

-184
This file was deleted.

0 commit comments

Comments
 (0)