mirror of
https://gitee.com/qqtt-ah/ecom-dmb.git
synced 2026-11-23 23:19:19 +08:00
feat: 添加浏览器扩展下载功能
This commit is contained in:
@@ -1,5 +1,6 @@
|
||||
dist
|
||||
dist-features
|
||||
artifacts
|
||||
node_modules
|
||||
*.local
|
||||
.DS_Store
|
||||
|
||||
@@ -28,23 +28,28 @@ pnpm dev
|
||||
pnpm build
|
||||
```
|
||||
|
||||
产物:
|
||||
产物(统一在 `artifacts/`,已 gitignore):
|
||||
|
||||
| 目录 | 说明 |
|
||||
| 路径 | 说明 |
|
||||
|------|------|
|
||||
| `dist/` | 扩展壳(装到浏览器) |
|
||||
| `dist-features/` | 功能清单 `manifest.json` + 各功能 JS(部署到后端静态目录) |
|
||||
| `artifacts/extension/` | 扩展壳(可解压加载到浏览器) |
|
||||
| `artifacts/features/` | 功能清单 `manifest.json` + 各功能 JS |
|
||||
| `artifacts/ecbi-data-sync-extension.zip` | 扩展壳压缩包(内含一层 `ecbi-data-sync-extension/` 目录) |
|
||||
|
||||
`pnpm build` 会顺带把 `dist-features/` 同步到
|
||||
`ecom-dmb-backend/src/main/resources/static/extension-features/`(本地联调)。
|
||||
`pnpm build` 会同步到后端静态目录(本地联调 / 打进 jar):
|
||||
|
||||
生产更新功能时:只拷贝 `dist-features/*` 到服务器对应静态目录并重启/热加载即可,扩展壳不必每次重装(壳内 API 未变时)。
|
||||
| 本地产物 | 后端静态目录 |
|
||||
|----------|--------------|
|
||||
| `artifacts/features/*` | `static/extension-features/` |
|
||||
| `ecbi-data-sync-extension.zip` | `static/extension/` |
|
||||
|
||||
生产更新功能时:只拷贝 `artifacts/features/*` 到服务器 `extension-features/` 即可,扩展壳不必每次重装(壳内 API 未变时)。
|
||||
|
||||
## 安装到 Chrome / Edge
|
||||
|
||||
1. 打开 `chrome://extensions/` 或 `edge://extensions/`
|
||||
2. 开启「开发者模式」
|
||||
3. 「加载已解压的扩展程序」→ 选择本项目的 `dist` 目录
|
||||
3. 「加载已解压的扩展程序」→ 选择 `artifacts/extension`,或后台「开放密钥」页下载 zip 后解压加载
|
||||
|
||||
## 项目架构
|
||||
|
||||
|
||||
@@ -1,24 +1,90 @@
|
||||
import { createHash } from 'node:crypto';
|
||||
import { copyFileSync, mkdirSync, readFileSync, writeFileSync, existsSync, rmSync } from 'node:fs';
|
||||
import { execFileSync } from 'node:child_process';
|
||||
import {
|
||||
copyFileSync,
|
||||
existsSync,
|
||||
mkdirSync,
|
||||
readFileSync,
|
||||
renameSync,
|
||||
rmSync,
|
||||
unlinkSync,
|
||||
writeFileSync,
|
||||
} from 'node:fs';
|
||||
import { dirname, resolve } from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import { build } from 'vite';
|
||||
|
||||
/**
|
||||
* 构建功能脚本 → artifacts/features,打 zip 壳,并同步到后端 static。
|
||||
*/
|
||||
const __dirname = dirname(fileURLToPath(import.meta.url));
|
||||
const root = resolve(__dirname, '..');
|
||||
const outDir = resolve(root, 'dist-features');
|
||||
const backendStatic = resolve(
|
||||
const artifactsRoot = resolve(root, 'artifacts');
|
||||
const featuresOutDir = resolve(artifactsRoot, 'features');
|
||||
const extensionOutDir = resolve(artifactsRoot, 'extension');
|
||||
const zipName = 'ecbi-data-sync-extension.zip';
|
||||
const zipLocalPath = resolve(artifactsRoot, zipName);
|
||||
|
||||
const backendFeaturesStatic = resolve(
|
||||
root,
|
||||
'../ecom-dmb-backend/src/main/resources/static/extension-features',
|
||||
);
|
||||
const backendExtensionStatic = resolve(
|
||||
root,
|
||||
'../ecom-dmb-backend/src/main/resources/static/extension',
|
||||
);
|
||||
|
||||
function syncDirContents(srcDir, destDir) {
|
||||
if (existsSync(destDir)) {
|
||||
rmSync(destDir, { recursive: true, force: true });
|
||||
}
|
||||
mkdirSync(destDir, { recursive: true });
|
||||
for (const name of ['manifest.json', 'pdd-ad-fee.js', 'pdd-ad-fee.js.map']) {
|
||||
const src = resolve(srcDir, name);
|
||||
if (existsSync(src)) {
|
||||
copyFileSync(src, resolve(destDir, name));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function packExtensionZip() {
|
||||
if (!existsSync(extensionOutDir)) {
|
||||
throw new Error(
|
||||
`扩展壳目录不存在: ${extensionOutDir}(请先执行 vite build)`,
|
||||
);
|
||||
}
|
||||
if (existsSync(zipLocalPath)) {
|
||||
unlinkSync(zipLocalPath);
|
||||
}
|
||||
|
||||
// zip 内一层目录:ecbi-data-sync-extension/…,解压后直接「加载已解压的扩展」
|
||||
const packageDirName = 'ecbi-data-sync-extension';
|
||||
const packageDir = resolve(artifactsRoot, packageDirName);
|
||||
if (existsSync(packageDir)) {
|
||||
rmSync(packageDir, { recursive: true, force: true });
|
||||
}
|
||||
renameSync(extensionOutDir, packageDir);
|
||||
try {
|
||||
execFileSync('zip', ['-r', '-q', zipLocalPath, packageDirName], {
|
||||
cwd: artifactsRoot,
|
||||
});
|
||||
} finally {
|
||||
renameSync(packageDir, extensionOutDir);
|
||||
}
|
||||
|
||||
mkdirSync(backendExtensionStatic, { recursive: true });
|
||||
copyFileSync(zipLocalPath, resolve(backendExtensionStatic, zipName));
|
||||
}
|
||||
|
||||
async function main() {
|
||||
mkdirSync(artifactsRoot, { recursive: true });
|
||||
|
||||
await build({
|
||||
configFile: resolve(root, 'vite.features.config.ts'),
|
||||
});
|
||||
|
||||
const entryFile = 'pdd-ad-fee.js';
|
||||
const jsPath = resolve(outDir, entryFile);
|
||||
const jsPath = resolve(featuresOutDir, entryFile);
|
||||
const code = readFileSync(jsPath, 'utf8');
|
||||
const sha256 = createHash('sha256').update(code).digest('hex');
|
||||
|
||||
@@ -43,23 +109,20 @@ async function main() {
|
||||
],
|
||||
};
|
||||
|
||||
writeFileSync(resolve(outDir, 'manifest.json'), `${JSON.stringify(manifest, null, 2)}\n`, 'utf8');
|
||||
writeFileSync(
|
||||
resolve(featuresOutDir, 'manifest.json'),
|
||||
`${JSON.stringify(manifest, null, 2)}\n`,
|
||||
'utf8',
|
||||
);
|
||||
|
||||
// 同步到后端 classpath 静态目录,便于本地联调;部署时也可只拷 dist-features
|
||||
if (existsSync(backendStatic)) {
|
||||
rmSync(backendStatic, { recursive: true, force: true });
|
||||
}
|
||||
mkdirSync(backendStatic, { recursive: true });
|
||||
copyFileSync(jsPath, resolve(backendStatic, entryFile));
|
||||
copyFileSync(resolve(outDir, 'manifest.json'), resolve(backendStatic, 'manifest.json'));
|
||||
// sourcemap 可选
|
||||
const mapPath = `${jsPath}.map`;
|
||||
if (existsSync(mapPath)) {
|
||||
copyFileSync(mapPath, resolve(backendStatic, `${entryFile}.map`));
|
||||
}
|
||||
syncDirContents(featuresOutDir, backendFeaturesStatic);
|
||||
packExtensionZip();
|
||||
|
||||
console.log(`[build-features] wrote ${outDir}`);
|
||||
console.log(`[build-features] synced → ${backendStatic}`);
|
||||
console.log(`[build-features] wrote ${featuresOutDir}`);
|
||||
console.log(`[build-features] synced features → ${backendFeaturesStatic}`);
|
||||
console.log(
|
||||
`[build-features] packed zip → ${resolve(backendExtensionStatic, zipName)}`,
|
||||
);
|
||||
console.log(`[build-features] pdd-ad-fee sha256=${sha256}`);
|
||||
}
|
||||
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/**
|
||||
* 远程功能包入口(IIFE → dist-features/pdd-ad-fee.js)。
|
||||
* 远程功能包入口(IIFE → artifacts/features/pdd-ad-fee.js)。
|
||||
* 在页面 MAIN world 执行;Open API / 设置走壳侧 postMessage 桥接。
|
||||
*/
|
||||
import { installMainWorldAdapters } from '@/features/runtime/mainWorldAdapters';
|
||||
|
||||
@@ -14,7 +14,7 @@ export default defineConfig({
|
||||
},
|
||||
build: {
|
||||
sourcemap: true,
|
||||
outDir: 'dist',
|
||||
outDir: 'artifacts/extension',
|
||||
emptyOutDir: true,
|
||||
},
|
||||
server: {
|
||||
|
||||
@@ -2,7 +2,7 @@ import { resolve } from 'node:path';
|
||||
import { defineConfig } from 'vite';
|
||||
import vue from '@vitejs/plugin-vue';
|
||||
|
||||
/** 功能脚本独立构建 → dist-features/(部署到后端静态目录) */
|
||||
/** 功能脚本独立构建 → artifacts/features/(部署到后端静态目录) */
|
||||
export default defineConfig({
|
||||
plugins: [vue()],
|
||||
resolve: {
|
||||
@@ -14,7 +14,7 @@ export default defineConfig({
|
||||
'process.env.NODE_ENV': JSON.stringify('production'),
|
||||
},
|
||||
build: {
|
||||
outDir: 'dist-features',
|
||||
outDir: 'artifacts/features',
|
||||
emptyOutDir: true,
|
||||
lib: {
|
||||
entry: resolve(__dirname, 'src/features/pdd-ad-fee/index.ts'),
|
||||
|
||||
+41
@@ -0,0 +1,41 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.open.extension.controller;
|
||||
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.core.io.Resource;
|
||||
import org.springframework.http.HttpHeaders;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
import top.xyquan.ecomdmbbackend.common.annotation.RequirePermission;
|
||||
import top.xyquan.ecomdmbbackend.modules.open.extension.service.ExtensionPackageService;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
/**
|
||||
* 管理端:浏览器扩展安装包下载(JWT,暂挂密钥查看权限)。
|
||||
*/
|
||||
@RestController
|
||||
@RequestMapping("/api/sys/open-extension")
|
||||
@RequiredArgsConstructor
|
||||
public class ExtensionPackageController {
|
||||
|
||||
private final ExtensionPackageService extensionPackageService;
|
||||
|
||||
@GetMapping("/download")
|
||||
@RequirePermission(value = "open:api-key:read", description = "下载浏览器扩展", allowSuper = true)
|
||||
public ResponseEntity<Resource> download() throws IOException {
|
||||
Resource resource = extensionPackageService.getPackageResource();
|
||||
ResponseEntity.BodyBuilder builder = ResponseEntity.ok()
|
||||
.header(
|
||||
HttpHeaders.CONTENT_DISPOSITION,
|
||||
"attachment; filename=\"" + ExtensionPackageService.PACKAGE_FILE_NAME + "\"")
|
||||
.contentType(MediaType.APPLICATION_OCTET_STREAM);
|
||||
long length = resource.contentLength();
|
||||
if (length >= 0) {
|
||||
builder.contentLength(length);
|
||||
}
|
||||
return builder.body(resource);
|
||||
}
|
||||
}
|
||||
+14
@@ -0,0 +1,14 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.open.extension.service;
|
||||
|
||||
import org.springframework.core.io.Resource;
|
||||
|
||||
/**
|
||||
* 浏览器扩展安装包(zip)读取。
|
||||
*/
|
||||
public interface ExtensionPackageService {
|
||||
|
||||
String PACKAGE_FILE_NAME = "ecbi-data-sync-extension.zip";
|
||||
|
||||
/** 解析可下载的扩展 zip;不存在时抛业务异常。 */
|
||||
Resource getPackageResource();
|
||||
}
|
||||
+37
@@ -0,0 +1,37 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.open.extension.service.impl;
|
||||
|
||||
import org.springframework.core.io.ClassPathResource;
|
||||
import org.springframework.core.io.FileSystemResource;
|
||||
import org.springframework.core.io.Resource;
|
||||
import org.springframework.stereotype.Service;
|
||||
import top.xyquan.ecomdmbbackend.common.exception.BusinessException;
|
||||
import top.xyquan.ecomdmbbackend.modules.open.extension.service.ExtensionPackageService;
|
||||
|
||||
import java.nio.file.Paths;
|
||||
|
||||
/**
|
||||
* 读取扩展 zip;优先 ./static/extension/(部署挂载),否则 classpath。
|
||||
*/
|
||||
@Service
|
||||
public class ExtensionPackageServiceImpl implements ExtensionPackageService {
|
||||
|
||||
private static final String PACKAGE_REL = "extension/" + PACKAGE_FILE_NAME;
|
||||
|
||||
@Override
|
||||
public Resource getPackageResource() {
|
||||
Resource resource = resolvePackageResource();
|
||||
if (!resource.exists()) {
|
||||
throw new BusinessException(
|
||||
"浏览器扩展安装包不存在,请先在 browser-extension 执行 pnpm build");
|
||||
}
|
||||
return resource;
|
||||
}
|
||||
|
||||
private Resource resolvePackageResource() {
|
||||
FileSystemResource mounted = new FileSystemResource(Paths.get("static", PACKAGE_REL));
|
||||
if (mounted.exists()) {
|
||||
return mounted;
|
||||
}
|
||||
return new ClassPathResource("static/" + PACKAGE_REL);
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"schemaVersion": 1,
|
||||
"updatedAt": "2026-08-27T06:21:25.418Z",
|
||||
"updatedAt": "2026-08-30T15:28:14.671Z",
|
||||
"features": [
|
||||
{
|
||||
"id": "pdd-ad-fee",
|
||||
|
||||
File diff suppressed because one or more lines are too long
@@ -0,0 +1,3 @@
|
||||
# 扩展安装包由 browser-extension `pnpm build` 生成,勿手改
|
||||
*
|
||||
!.gitignore
|
||||
@@ -32,3 +32,7 @@ export async function enableOpenApiKeyApi(id: number) {
|
||||
export async function deleteOpenApiKeyApi(id: number) {
|
||||
return requestClient.delete<void>(`/sys/open-api-key/${id}`);
|
||||
}
|
||||
|
||||
/** 下载浏览器扩展安装包(需 open:api-key:read) */
|
||||
export const OPEN_EXTENSION_DOWNLOAD_PATH = '/sys/open-extension/download';
|
||||
export const OPEN_EXTENSION_ZIP_NAME = 'ecbi-data-sync-extension.zip';
|
||||
|
||||
@@ -2,12 +2,11 @@
|
||||
* 通用文件导出工具
|
||||
* 用于下载 Excel、PDF 等二进制文件
|
||||
*/
|
||||
import { useAppConfig } from '@vben/hooks';
|
||||
import { useAccessStore } from '@vben/stores';
|
||||
|
||||
import { message } from 'ant-design-vue';
|
||||
|
||||
import { useAppConfig } from '@vben/hooks';
|
||||
|
||||
const { apiURL } = useAppConfig(import.meta.env, import.meta.env.PROD);
|
||||
|
||||
function formatToken(token: null | string) {
|
||||
@@ -34,6 +33,67 @@ function parseFilenameFromContentDisposition(
|
||||
return null;
|
||||
}
|
||||
|
||||
async function triggerBlobDownload(
|
||||
response: Response,
|
||||
fallbackFilename: string,
|
||||
) {
|
||||
const contentType = response.headers.get('Content-Type') || '';
|
||||
const blob = await response.blob();
|
||||
|
||||
if (blob.size === 0) {
|
||||
throw new Error('下载文件为空');
|
||||
}
|
||||
|
||||
if (contentType.includes('application/json')) {
|
||||
const text = await blob.text();
|
||||
try {
|
||||
const json = JSON.parse(text);
|
||||
message.error(json.message || '下载失败');
|
||||
} catch {
|
||||
message.error('下载失败');
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
const headerName =
|
||||
parseFilenameFromContentDisposition(
|
||||
response.headers.get('Content-Disposition'),
|
||||
) || fallbackFilename;
|
||||
|
||||
const downloadUrl = window.URL.createObjectURL(blob);
|
||||
const link = document.createElement('a');
|
||||
link.href = downloadUrl;
|
||||
link.download = headerName;
|
||||
document.body.appendChild(link);
|
||||
link.click();
|
||||
document.body.removeChild(link);
|
||||
window.URL.revokeObjectURL(downloadUrl);
|
||||
}
|
||||
|
||||
export async function exportByGet(url: string, filename: string) {
|
||||
const accessStore = useAccessStore();
|
||||
const fullUrl = `${apiURL}${url}`;
|
||||
|
||||
try {
|
||||
const response = await fetch(fullUrl, {
|
||||
method: 'GET',
|
||||
headers: {
|
||||
Authorization: formatToken(accessStore.accessToken) || '',
|
||||
},
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(`HTTP ${response.status}: ${response.statusText}`);
|
||||
}
|
||||
|
||||
await triggerBlobDownload(response, filename);
|
||||
message.success('下载成功');
|
||||
} catch (error) {
|
||||
console.error('下载失败:', error);
|
||||
message.error('下载失败,请稍后重试');
|
||||
}
|
||||
}
|
||||
|
||||
export async function exportByPost(
|
||||
url: string,
|
||||
params: Record<string, unknown>,
|
||||
@@ -56,39 +116,7 @@ export async function exportByPost(
|
||||
throw new Error(`HTTP ${response.status}: ${response.statusText}`);
|
||||
}
|
||||
|
||||
const contentType = response.headers.get('Content-Type') || '';
|
||||
const blob = await response.blob();
|
||||
|
||||
if (blob.size === 0) {
|
||||
throw new Error('下载文件为空');
|
||||
}
|
||||
|
||||
// 如果返回的是 JSON 错误(而非文件),提示错误信息
|
||||
if (contentType.includes('application/json')) {
|
||||
const text = await blob.text();
|
||||
try {
|
||||
const json = JSON.parse(text);
|
||||
message.error(json.message || '导出失败');
|
||||
} catch {
|
||||
message.error('导出失败');
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
const headerName =
|
||||
parseFilenameFromContentDisposition(
|
||||
response.headers.get('Content-Disposition'),
|
||||
) || filename;
|
||||
|
||||
// 触发浏览器下载
|
||||
const downloadUrl = window.URL.createObjectURL(blob);
|
||||
const link = document.createElement('a');
|
||||
link.href = downloadUrl;
|
||||
link.download = headerName;
|
||||
document.body.appendChild(link);
|
||||
link.click();
|
||||
document.body.removeChild(link);
|
||||
window.URL.revokeObjectURL(downloadUrl);
|
||||
await triggerBlobDownload(response, filename);
|
||||
message.success('导出成功');
|
||||
} catch (error) {
|
||||
console.error('导出失败:', error);
|
||||
|
||||
@@ -15,12 +15,15 @@ import {
|
||||
disableOpenApiKeyApi,
|
||||
enableOpenApiKeyApi,
|
||||
getOpenApiKeyListApi,
|
||||
OPEN_EXTENSION_DOWNLOAD_PATH,
|
||||
OPEN_EXTENSION_ZIP_NAME,
|
||||
} from '#/api/open/api-key';
|
||||
import { PermissionGate } from '#/components/permission';
|
||||
import {
|
||||
syncVxeGridColumns,
|
||||
useActionColumnVisible,
|
||||
} from '#/composables/use-vxe-action-column';
|
||||
import { exportByGet } from '#/utils/export';
|
||||
|
||||
import CreateApiKeyModal from './components/CreateApiKeyModal.vue';
|
||||
import OpenApiBaseUrlDisplay from './components/OpenApiBaseUrlDisplay.vue';
|
||||
@@ -28,7 +31,9 @@ import OpenApiBaseUrlDisplay from './components/OpenApiBaseUrlDisplay.vue';
|
||||
defineOptions({ name: 'OpenApiKeyManagement' });
|
||||
|
||||
const PlusIcon = createIconifyIcon('lucide:plus');
|
||||
const DownloadIcon = createIconifyIcon('lucide:download');
|
||||
const loading = ref(false);
|
||||
const downloading = ref(false);
|
||||
const createModalRef = ref<InstanceType<typeof CreateApiKeyModal>>();
|
||||
|
||||
function formatExpireAt(cellValue?: null | string) {
|
||||
@@ -139,6 +144,16 @@ function openCreateModal() {
|
||||
createModalRef.value?.open();
|
||||
}
|
||||
|
||||
async function handleDownloadExtension() {
|
||||
if (downloading.value) return;
|
||||
downloading.value = true;
|
||||
try {
|
||||
await exportByGet(OPEN_EXTENSION_DOWNLOAD_PATH, OPEN_EXTENSION_ZIP_NAME);
|
||||
} finally {
|
||||
downloading.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
function getPermissionCount(row: OpenApiKeyVO.OpenApiKeyInfoVO) {
|
||||
return row.permissionCodes?.length ?? row.permissions?.length ?? 0;
|
||||
}
|
||||
@@ -157,12 +172,20 @@ function getPermissionTooltip(row: OpenApiKeyVO.OpenApiKeyInfoVO) {
|
||||
|
||||
<Grid :loading="loading">
|
||||
<template #toolbar-tools>
|
||||
<PermissionGate code="open:api-key:create">
|
||||
<Button type="primary" @click="openCreateModal">
|
||||
<PlusIcon class="size-4" />
|
||||
创建 API Key
|
||||
</Button>
|
||||
</PermissionGate>
|
||||
<Space>
|
||||
<PermissionGate code="open:api-key:read">
|
||||
<Button :loading="downloading" @click="handleDownloadExtension">
|
||||
<DownloadIcon class="size-4" />
|
||||
下载浏览器扩展
|
||||
</Button>
|
||||
</PermissionGate>
|
||||
<PermissionGate code="open:api-key:create">
|
||||
<Button type="primary" @click="openCreateModal">
|
||||
<PlusIcon class="size-4" />
|
||||
创建 API Key
|
||||
</Button>
|
||||
</PermissionGate>
|
||||
</Space>
|
||||
</template>
|
||||
|
||||
<template #permissions="{ row }">
|
||||
|
||||
Reference in New Issue
Block a user