feat(project): 初始化项目结构和配置

- 添加.gitignore和.flaskenv环境配置文件
- 创建Flask应用基础架构,包括models、services、utils模块
- 配置数据库模型User和Setting,集成SQLAlchemy和Alembic迁移
- 添加前端Vue项目结构,包含Element Plus组件库
- 配置前后端API路由和蓝prints模块
- 实现书籍下载服务BookService功能模块
- 添加代码规范配置.editorconfig、.oxfmtrc.json、.oxlintrc.json
- 配置VSCode推荐插件和前端构建工具链
- 实现文件服务FileService和相关业务逻辑
This commit is contained in:
2026-04-19 15:43:45 +08:00
parent b9fad6344f
commit ade1b6c9b0
63 changed files with 9610 additions and 1 deletions
+8
View File
@@ -0,0 +1,8 @@
[*.{js,jsx,mjs,cjs,ts,tsx,mts,cts,vue,css,scss,sass,less,styl}]
charset = utf-8
indent_size = 2
indent_style = space
insert_final_newline = true
trim_trailing_whitespace = true
end_of_line = lf
max_line_length = 100
+1
View File
@@ -0,0 +1 @@
* text=auto eol=lf
+39
View File
@@ -0,0 +1,39 @@
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
pnpm-debug.log*
lerna-debug.log*
node_modules
.DS_Store
dist
dist-ssr
coverage
*.local
# Editor directories and files
.vscode/*
!.vscode/extensions.json
.idea
*.suo
*.ntvs*
*.njsproj
*.sln
*.sw?
*.tsbuildinfo
.eslintcache
# Cypress
/cypress/videos/
/cypress/screenshots/
# Vitest
__screenshots__/
# Vite
*.timestamp-*-*.mjs
+5
View File
@@ -0,0 +1,5 @@
{
"$schema": "./node_modules/oxfmt/configuration_schema.json",
"semi": false,
"singleQuote": true
}
+10
View File
@@ -0,0 +1,10 @@
{
"$schema": "./node_modules/oxlint/configuration_schema.json",
"plugins": ["eslint", "typescript", "unicorn", "oxc", "vue"],
"env": {
"browser": true
},
"categories": {
"correctness": "error"
}
}
+8
View File
@@ -0,0 +1,8 @@
{
"recommendations": [
"Vue.volar",
"dbaeumer.vscode-eslint",
"EditorConfig.EditorConfig",
"oxc.oxc-vscode"
]
}
+48
View File
@@ -0,0 +1,48 @@
# flask-ui
This template should help get you started developing with Vue 3 in Vite.
## Recommended IDE Setup
[VS Code](https://code.visualstudio.com/) + [Vue (Official)](https://marketplace.visualstudio.com/items?itemName=Vue.volar) (and disable Vetur).
## Recommended Browser Setup
- Chromium-based browsers (Chrome, Edge, Brave, etc.):
- [Vue.js devtools](https://chromewebstore.google.com/detail/vuejs-devtools/nhdogjmejiglipccpnnnanhbledajbpd)
- [Turn on Custom Object Formatter in Chrome DevTools](http://bit.ly/object-formatters)
- Firefox:
- [Vue.js devtools](https://addons.mozilla.org/en-US/firefox/addon/vue-js-devtools/)
- [Turn on Custom Object Formatter in Firefox DevTools](https://fxdx.dev/firefox-devtools-custom-object-formatters/)
## Type Support for `.vue` Imports in TS
TypeScript cannot handle type information for `.vue` imports by default, so we replace the `tsc` CLI with `vue-tsc` for type checking. In editors, we need [Volar](https://marketplace.visualstudio.com/items?itemName=Vue.volar) to make the TypeScript language service aware of `.vue` types.
## Customize configuration
See [Vite Configuration Reference](https://vite.dev/config/).
## Project Setup
```sh
npm install
```
### Compile and Hot-Reload for Development
```sh
npm run dev
```
### Type-Check, Compile and Minify for Production
```sh
npm run build
```
### Lint with [ESLint](https://eslint.org/)
```sh
npm run lint
```
+10
View File
@@ -0,0 +1,10 @@
/* eslint-disable */
/* prettier-ignore */
// @ts-nocheck
// noinspection JSUnusedGlobalSymbols
// Generated by unplugin-auto-import
// biome-ignore lint: disable
export {}
declare global {
}
+75
View File
@@ -0,0 +1,75 @@
/* eslint-disable */
// @ts-nocheck
// biome-ignore lint: disable
// oxlint-disable
// ------
// Generated by unplugin-vue-components
// Read more: https://github.com/vuejs/core/pull/3399
import { GlobalComponents } from 'vue'
export {}
/* prettier-ignore */
declare module 'vue' {
export interface GlobalComponents {
ElAlert: typeof import('element-plus/es')['ElAlert']
ElAside: typeof import('element-plus/es')['ElAside']
ElButton: typeof import('element-plus/es')['ElButton']
ElButtonGroup: typeof import('element-plus/es')['ElButtonGroup']
ElCard: typeof import('element-plus/es')['ElCard']
ElCol: typeof import('element-plus/es')['ElCol']
ElContainer: typeof import('element-plus/es')['ElContainer']
ElForm: typeof import('element-plus/es')['ElForm']
ElHeader: typeof import('element-plus/es')['ElHeader']
ElIcon: typeof import('element-plus/es')['ElIcon']
ElInput: typeof import('element-plus/es')['ElInput']
ElMain: typeof import('element-plus/es')['ElMain']
ElMenu: typeof import('element-plus/es')['ElMenu']
ElMenuItem: typeof import('element-plus/es')['ElMenuItem']
ElMenuItemGroup: typeof import('element-plus/es')['ElMenuItemGroup']
ElOption: typeof import('element-plus/es')['ElOption']
ElRadioButton: typeof import('element-plus/es')['ElRadioButton']
ElRadioGroup: typeof import('element-plus/es')['ElRadioGroup']
ElRow: typeof import('element-plus/es')['ElRow']
ElScrollbar: typeof import('element-plus/es')['ElScrollbar']
ElSelect: typeof import('element-plus/es')['ElSelect']
ElSplitter: typeof import('element-plus/es')['ElSplitter']
ElSplitterPanel: typeof import('element-plus/es')['ElSplitterPanel']
ElSubMenu: typeof import('element-plus/es')['ElSubMenu']
RouterLink: typeof import('vue-router')['RouterLink']
RouterView: typeof import('vue-router')['RouterView']
}
export interface GlobalDirectives {
vLoading: typeof import('element-plus/es')['ElLoadingDirective']
}
}
// For TSX support
declare global {
const ElAlert: typeof import('element-plus/es')['ElAlert']
const ElAside: typeof import('element-plus/es')['ElAside']
const ElButton: typeof import('element-plus/es')['ElButton']
const ElButtonGroup: typeof import('element-plus/es')['ElButtonGroup']
const ElCard: typeof import('element-plus/es')['ElCard']
const ElCol: typeof import('element-plus/es')['ElCol']
const ElContainer: typeof import('element-plus/es')['ElContainer']
const ElForm: typeof import('element-plus/es')['ElForm']
const ElHeader: typeof import('element-plus/es')['ElHeader']
const ElIcon: typeof import('element-plus/es')['ElIcon']
const ElInput: typeof import('element-plus/es')['ElInput']
const ElMain: typeof import('element-plus/es')['ElMain']
const ElMenu: typeof import('element-plus/es')['ElMenu']
const ElMenuItem: typeof import('element-plus/es')['ElMenuItem']
const ElMenuItemGroup: typeof import('element-plus/es')['ElMenuItemGroup']
const ElOption: typeof import('element-plus/es')['ElOption']
const ElRadioButton: typeof import('element-plus/es')['ElRadioButton']
const ElRadioGroup: typeof import('element-plus/es')['ElRadioGroup']
const ElRow: typeof import('element-plus/es')['ElRow']
const ElScrollbar: typeof import('element-plus/es')['ElScrollbar']
const ElSelect: typeof import('element-plus/es')['ElSelect']
const ElSplitter: typeof import('element-plus/es')['ElSplitter']
const ElSplitterPanel: typeof import('element-plus/es')['ElSplitterPanel']
const ElSubMenu: typeof import('element-plus/es')['ElSubMenu']
const RouterLink: typeof import('vue-router')['RouterLink']
const RouterView: typeof import('vue-router')['RouterView']
}
+1
View File
@@ -0,0 +1 @@
/// <reference types="vite/client" />
+26
View File
@@ -0,0 +1,26 @@
import { globalIgnores } from 'eslint/config'
import { defineConfigWithVueTs, vueTsConfigs } from '@vue/eslint-config-typescript'
import pluginVue from 'eslint-plugin-vue'
import pluginOxlint from 'eslint-plugin-oxlint'
import skipFormatting from 'eslint-config-prettier/flat'
// To allow more languages other than `ts` in `.vue` files, uncomment the following lines:
// import { configureVueProject } from '@vue/eslint-config-typescript'
// configureVueProject({ scriptLangs: ['ts', 'tsx'] })
// More info at https://github.com/vuejs/eslint-config-typescript/#advanced-setup
export default defineConfigWithVueTs(
{
name: 'app/files-to-lint',
files: ['**/*.{vue,ts,mts,tsx}'],
},
globalIgnores(['**/dist/**', '**/dist-ssr/**', '**/coverage/**']),
...pluginVue.configs['flat/essential'],
vueTsConfigs.recommended,
...pluginOxlint.buildFromOxlintConfigFile('.oxlintrc.json'),
skipFormatting,
)
+13
View File
@@ -0,0 +1,13 @@
<!DOCTYPE html>
<html lang="">
<head>
<meta charset="UTF-8">
<link rel="icon" href="/favicon.ico">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Vite App</title>
</head>
<body>
<div id="app"></div>
<script type="module" src="/src/main.ts"></script>
</body>
</html>
+7291
View File
File diff suppressed because it is too large Load Diff
+66
View File
@@ -0,0 +1,66 @@
{
"name": "flask-ui",
"version": "0.0.0",
"private": true,
"type": "module",
"scripts": {
"dev": "vite",
"build": "run-p type-check \"build-only {@}\" --",
"preview": "vite preview",
"build-only": "vite build",
"type-check": "vue-tsc --build",
"lint": "run-s lint:*",
"lint:oxlint": "oxlint . --fix",
"lint:eslint": "eslint . --fix --cache",
"format": "oxfmt src/"
},
"dependencies": {
"@element-plus/icons-vue": "^2.3.2",
"axios": "^1.13.6",
"element-plus": "^2.13.6",
"pinia": "^3.0.4",
"vue": "beta",
"vue-router": "^5.0.3"
},
"devDependencies": {
"@tsconfig/node24": "^24.0.4",
"@types/node": "^24.11.0",
"@vitejs/plugin-vue": "^6.0.4",
"@vitejs/plugin-vue-jsx": "^5.1.4",
"@vue/eslint-config-typescript": "^14.7.0",
"@vue/tsconfig": "^0.8.1",
"eslint": "^10.0.2",
"eslint-config-prettier": "^10.1.8",
"eslint-plugin-oxlint": "~1.50.0",
"eslint-plugin-vue": "~10.8.0",
"jiti": "^2.6.1",
"npm-run-all2": "^8.0.4",
"oxfmt": "^0.35.0",
"oxlint": "~1.50.0",
"sass-embedded": "^1.98.0",
"typescript": "~5.9.3",
"unplugin-auto-import": "^21.0.0",
"unplugin-vue-components": "^31.0.0",
"vite": "beta",
"vite-plugin-vue-devtools": "^8.0.6",
"vue-tsc": "^3.2.5"
},
"engines": {
"node": "^20.19.0 || >=22.12.0"
},
"overrides": {
"vue": "beta",
"@vue/compiler-core": "beta",
"@vue/compiler-dom": "beta",
"@vue/compiler-sfc": "beta",
"@vue/compiler-ssr": "beta",
"@vue/compiler-vapor": "beta",
"@vue/reactivity": "beta",
"@vue/runtime-core": "beta",
"@vue/runtime-dom": "beta",
"@vue/runtime-vapor": "beta",
"@vue/server-renderer": "beta",
"@vue/shared": "beta",
"@vue/compat": "beta"
}
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 4.2 KiB

+9
View File
@@ -0,0 +1,9 @@
<script setup lang="ts">
import {RouterView} from 'vue-router'
</script>
<template>
<RouterView/>
</template>
<style scoped></style>
+67
View File
@@ -0,0 +1,67 @@
import request from "../utils/request.ts"
export function book_download() {
return request({
url: "/book/download",
})
}
export function video_findDeduplication() {
return request({
url: "/video/findDeduplication",
})
}
export function video_deduplication() {
return request({
url: "/video/deduplication",
})
}
export function video_hasTorrent() {
return request({
url: "/video/hasTorrent",
})
}
export function files_rename() {
return request({
url: "/files/rename",
})
}
export function torrent_deduplication() {
return request({
url: "/torrent/deduplication",
})
}
export function image_export() {
return request({
url: "/image/export",
})
}
export function image_hasTorrent() {
return request({
url: "/image/hasTorrent",
})
}
export function music_rename() {
return request({
url: "/music/rename",
})
}
export function test() {
return request({
url: "/test",
})
}
export function torrent_statistics(){
return request({
url: "/torrent/statistics",
})
}
+86
View File
@@ -0,0 +1,86 @@
/* color palette from <https://github.com/vuejs/theme> */
:root {
--vt-c-white: #ffffff;
--vt-c-white-soft: #f8f8f8;
--vt-c-white-mute: #f2f2f2;
--vt-c-black: #181818;
--vt-c-black-soft: #222222;
--vt-c-black-mute: #282828;
--vt-c-indigo: #2c3e50;
--vt-c-divider-light-1: rgba(60, 60, 60, 0.29);
--vt-c-divider-light-2: rgba(60, 60, 60, 0.12);
--vt-c-divider-dark-1: rgba(84, 84, 84, 0.65);
--vt-c-divider-dark-2: rgba(84, 84, 84, 0.48);
--vt-c-text-light-1: var(--vt-c-indigo);
--vt-c-text-light-2: rgba(60, 60, 60, 0.66);
--vt-c-text-dark-1: var(--vt-c-white);
--vt-c-text-dark-2: rgba(235, 235, 235, 0.64);
}
/* semantic color variables for this project */
:root {
--color-background: var(--vt-c-white);
--color-background-soft: var(--vt-c-white-soft);
--color-background-mute: var(--vt-c-white-mute);
--color-border: var(--vt-c-divider-light-2);
--color-border-hover: var(--vt-c-divider-light-1);
--color-heading: var(--vt-c-text-light-1);
--color-text: var(--vt-c-text-light-1);
--section-gap: 160px;
}
@media (prefers-color-scheme: dark) {
:root {
--color-background: var(--vt-c-black);
--color-background-soft: var(--vt-c-black-soft);
--color-background-mute: var(--vt-c-black-mute);
--color-border: var(--vt-c-divider-dark-2);
--color-border-hover: var(--vt-c-divider-dark-1);
--color-heading: var(--vt-c-text-dark-1);
--color-text: var(--vt-c-text-dark-2);
}
}
*,
*::before,
*::after {
box-sizing: border-box;
margin: 0;
font-weight: normal;
}
body {
min-height: 100vh;
color: var(--color-text);
background: var(--color-background);
transition:
color 0.5s,
background-color 0.5s;
line-height: 1.6;
font-family:
Inter,
-apple-system,
BlinkMacSystemFont,
'Segoe UI',
Roboto,
Oxygen,
Ubuntu,
Cantarell,
'Fira Sans',
'Droid Sans',
'Helvetica Neue',
sans-serif;
font-size: 15px;
text-rendering: optimizeLegibility;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}
+41
View File
@@ -0,0 +1,41 @@
/*@import './base.css';*/
/*#app {*/
/* max-width: 1280px;*/
/* margin: 0 auto;*/
/* padding: 2rem;*/
/* font-weight: normal;*/
/*}*/
/*a,*/
/*.green {*/
/* text-decoration: none;*/
/* color: hsla(160, 100%, 37%, 1);*/
/* transition: 0.4s;*/
/* padding: 3px;*/
/*}*/
/*@media (hover: hover) {*/
/* a:hover {*/
/* background-color: hsla(160, 100%, 37%, 0.2);*/
/* }*/
/*}*/
/*@media (min-width: 1024px) {*/
/* body {*/
/* display: flex;*/
/* place-items: center;*/
/* }*/
/* #app {*/
/* display: grid;*/
/* grid-template-columns: 1fr 1fr;*/
/* padding: 0 2rem;*/
/* }*/
/*}*/
html, body, #app {
height: 100%;
margin: 0;
padding: 0;
}
@@ -0,0 +1,9 @@
<script setup lang="ts">
</script>
<template>
<router-view></router-view>
</template>
<style scoped lang="scss">
</style>
@@ -0,0 +1,75 @@
<script setup lang="ts">
import {ref} from "vue";
defineProps<{
isCollapse: boolean
}>()
const iconComponent = ref("location")
</script>
<template>
<el-aside>
<el-scrollbar>
<el-menu
default-active="2"
:collapse="isCollapse"
class="el-menu-vertical-demo"
router>
<el-sub-menu index="1">
<template #title>
<el-icon>
<component :is="iconComponent"></component>
</el-icon>
<span>Navigator One</span>
</template>
<el-menu-item-group title="Group One">
<el-menu-item index="1-1">
<el-icon>
<location/>
</el-icon>
item one
</el-menu-item>
<el-menu-item index="1-2">item two</el-menu-item>
</el-menu-item-group>
<el-menu-item-group title="Group Two">
<el-menu-item index="1-3">item three</el-menu-item>
</el-menu-item-group>
<el-sub-menu index="1-4">
<template #title>item four</template>
<el-menu-item index="1-4-1">item one</el-menu-item>
</el-sub-menu>
</el-sub-menu>
<el-menu-item index="2" route="about">
<el-icon>
<Menu/>
</el-icon>
<span>统计</span>
</el-menu-item>
<el-menu-item index="3" disabled>
<el-icon>
<document/>
</el-icon>
<span>Navigator Three</span>
</el-menu-item>
<el-menu-item index="4">
<el-icon>
<setting/>
</el-icon>
<span>Navigator Four</span>
</el-menu-item>
</el-menu>
</el-scrollbar>
</el-aside>
</template>
<style scoped lang="scss">
.el-aside {
width: auto;
}
:deep(.el-scrollbar__wrap) {
max-height: calc(100vh - 60px);
}
</style>
+35
View File
@@ -0,0 +1,35 @@
<script setup lang="ts">
import {ref} from 'vue'
import AppMain from "@/layout/components/AppMain.vue"
import Sidebar from "@/layout/components/Sidebar/index.vue"
let isCollapse = ref(false);
</script>
<template>
<el-container>
<el-header>
<template #default>
<el-radio-group v-model="isCollapse">
<el-radio-button :value="false">expand</el-radio-button>
<el-radio-button :value="true">collapse</el-radio-button>
</el-radio-group>
</template>
</el-header>
<el-container>
<Sidebar :isCollapse="isCollapse"></Sidebar>
<AppMain></AppMain>
</el-container>
</el-container>
</template>
<style lang="scss" scoped>
:deep(.el-header) {
border-bottom: 1px solid var(--el-menu-border-color);
display: flex;
}
.el-menu-vertical-demo {
min-height: calc(100vh - 60px);
}
</style>
+20
View File
@@ -0,0 +1,20 @@
import './assets/main.css'
import { createApp } from 'vue'
import { createPinia } from 'pinia'
import App from './App.vue'
import router from './router'
import * as ElementPlusIconsVue from '@element-plus/icons-vue'
const app = createApp(App)
for (const [key, component] of Object.entries(ElementPlusIconsVue)) {
app.component(key, component)
}
app.use(createPinia())
app.use(router)
app.mount('#app')
+35
View File
@@ -0,0 +1,35 @@
import {createRouter, createWebHistory} from 'vue-router'
import Layout from '../layout/index.vue'
const router = createRouter({
history: createWebHistory(import.meta.env.BASE_URL),
routes: [
{
path: '',
redirect: 'index',
component: Layout,
children: [
{
path: 'index',
name: 'Index',
component: () => import('../views/HomeView.vue'),
},
{
path: 'about',
name: 'About',
component: () => import('../views/AboutView.vue'),
},
],
},
{
path: '/about',
name: 'about',
// route level code-splitting
// this generates a separate chunk (About.[hash].js) for this route
// which is lazy-loaded when the route is visited.
component: () => import('../views/AboutView.vue'),
},
],
})
export default router
+12
View File
@@ -0,0 +1,12 @@
import { ref, computed } from 'vue'
import { defineStore } from 'pinia'
export const useCounterStore = defineStore('counter', () => {
const count = ref(0)
const doubleCount = computed(() => count.value * 2)
function increment() {
count.value++
}
return { count, doubleCount, increment }
})
+54
View File
@@ -0,0 +1,54 @@
import axios, {
type AxiosError,
type AxiosInstance,
type AxiosResponse,
type InternalAxiosRequestConfig
} from "axios"
// 定义响应数据结构
interface ResponseData<T = any> {
code: number
msg: string
data?: T
}
interface RequestCache {
url: string
data: string
time: number
}
let downloadLoadingInstance: any
export let isRelogin: { show: boolean } = {show: false}
axios.defaults.headers["Content-Type"] = "application/json; charset=UTF-8"
const service: AxiosInstance = axios.create({
baseURL: "http://localhost:5000/api/",
// baseURL: "/api",
timeout: 10000,
})
service.interceptors.request.use((config: InternalAxiosRequestConfig) => {
const isToken = (config.headers || {}).isToken === false
console.log(config)
return config
}, (error: AxiosError) => {
// 请求错误处理
console.error('请求拦截器错误:', error);
return Promise.reject(error);
})
service.interceptors.response.use((res: AxiosResponse) => {
const code = (res.data as ResponseData).code || 200
if (res.request.responseType === 'blob' || res.request.responseType === 'arraybuffer') {
return res.data
}
if (code !== 200) {
return Promise.reject("error")
} else {
return res.data
}
}, (error: AxiosError) => {
return Promise.reject(error)
})
export default service
+77
View File
@@ -0,0 +1,77 @@
<script setup lang="ts">
import {onMounted, ref} from 'vue'
import {torrent_statistics} from '@/api'
interface StatisticsData {
[key: string]: any
}
let aa = ref<StatisticsData>({})
let bb = ref("")
let cc = ref("")
let dd = ref("")
onMounted(async () => {
const res = await torrent_statistics()
console.log(res.message)
aa.value = res.message
})
const getSecondLevelOptions = () => {
if (!bb.value || !aa.value[bb.value]) {
return []
}
return aa.value[bb.value]
}
const getThirdLevelOptions = () => {
if (!bb.value || !cc.value || !aa.value[bb.value] || !aa.value[bb.value][cc.value]) {
return []
}
console.log(aa.value[bb.value])
return aa.value[bb.value][cc.value]
}
</script>
<template>
<el-main>
<el-card shadow="never">
<template #default>
<div v-for="(v,i) in getSecondLevelOptions()">
<div>{{i}}</div>
<el-button v-for="(v2,i2) in v" :key="i2">{{ v2 }}</el-button>
</div>
</template>
<template #footer>
<el-select style="width: 120px" placeholder="请选择" v-model="bb">
<el-option v-for="(v,i) in aa" :key="i" :label="i" :value="i"></el-option>
</el-select>
<el-select style="width: 120px" placeholder="请选择" v-model="cc">
<el-option v-for="(v,i) in getSecondLevelOptions()" :key="i" :label="i"
:value="i"></el-option>
</el-select>
<el-select style="width: 120px" placeholder="请选择" v-model="dd">
<el-option v-for="(v,i) in getThirdLevelOptions()" :key="i" :label="v"
:value="v"></el-option>
</el-select>
<el-button type="primary" @click="">
<el-icon>
<Plus/>
</el-icon>
添加
</el-button>
</template>
</el-card>
</el-main>
</template>
<style scoped lang="scss">
:deep(.el-card__body) {
//height: calc(100vh - 211px + 60px);
height: calc(100vh - 211px);
}
</style>
+147
View File
@@ -0,0 +1,147 @@
<script setup lang="ts">
import {ref, onUnmounted} from "vue";
import {
files_rename,
music_rename,
image_hasTorrent,
video_hasTorrent,
video_deduplication,
torrent_deduplication,
video_findDeduplication,
torrent_statistics
} from "@/api"
// 警告项接口
interface messageItem {
id: number
text: string
}
interface BtnItem {
id: number
title: string
handle?: () => Promise<any>
}
let loading = ref(false)
let eventSource: EventSource // 保存 EventSource 实例
const status = ref('closed') // 连接状态:closed, connecting, connected
const messages = ref<messageItem[]>([{id: Date.now(), text: '输出结果'}])
const buttons = [
{id: 0, title: "小说下载"},
{id: 1, title: "文件重命名", handle: files_rename},
{id: 2, title: "视频查找重复", handle: video_findDeduplication},
{id: 3, title: "视频去重", handle: video_deduplication},
{id: 4, title: "种子去重", handle: torrent_deduplication},
{id: 5, title: "判断视频是否有torrent", handle: video_hasTorrent},
{id: 6, title: "判断图片是否有torrent", handle: image_hasTorrent},
{id: 7, title: "音乐文件重命名", handle: music_rename},
{id: 8, title: "种子统计", handle: torrent_statistics}
]
function closeAlert(id: number) {
console.log(id)
messages.value = messages.value.filter(item => item.id !== id)
}
const handleClick = async (btnObj: BtnItem) => {
if (btnObj.title === "断开") return
if (btnObj.title === "小说下载") {
connect("http://localhost:5000/api/book/download")
return
}
loading.value = true
try {
const res = await btnObj.handle?.()
const res_msg = Array.isArray(res.message) ? res.message : [res.message]
messages.value = res_msg.map((msg: string, index: number) => ({
id: Date.now() + index, // 简单生成唯一 ID,生产环境建议使用更可靠的 ID 生成器
text: msg
}))
messages.value.push({id: Date.now() + messages.value.length, text: '已完成'})
messages.value.reverse()
} finally {
loading.value = false
}
}
const connect = (url: string) => {
messages.value = []
if (eventSource) {
eventSource.close()
}
eventSource = new EventSource(url)
// 连接成功
eventSource.addEventListener("open", (event) => {
console.log('SSE 连接已打开')
status.value = 'connected'
})
// 监听普通消息
eventSource.addEventListener('message', (event) => {
messages.value.unshift({id: Date.now() + messages.value.length, text: event.data})
})
// 监听关闭事件
eventSource.addEventListener('close', (event) => {
messages.value.unshift({id: Date.now() + messages.value.length, text: event.data})
closeConnection()
})
// 错误处理
eventSource.addEventListener('error', (event) => {
console.log('连接断开或失败', new Date());
// 如果这里也频繁触发,确认了是断连重连
if (eventSource.readyState === EventSource.CLOSED) {
console.log('状态为 CLOSED');
}
})
}
const closeConnection = () => {
if (eventSource) {
eventSource.close()
// eventSource = null
status.value = 'closed'
console.log('SSE 连接已关闭')
}
}
onUnmounted(() => {
closeConnection()
})
</script>
<template>
<el-main>
<el-card>
<template #default>
<div v-loading="loading" :style="{height: '100%'}">
<el-alert v-for="item in messages" :key="item.id" :title="item.text"
type="primary"
@close="closeAlert(item.id)"/>
</div>
</template>
<template #footer>
<el-button-group>
<el-button type="primary" v-for="btn in buttons" :key="btn.id"
@click="handleClick(btn)">
{{ btn.title }}
</el-button>
</el-button-group>
</template>
</el-card>
</el-main>
</template>
<style scoped lang="scss">
.el-alert + .el-alert {
margin-top: 20px;
}
:deep(.el-card__footer) {
display: flex;
justify-content: center;
}
:deep(.el-card__body) {
//height: calc(100vh - 211px + 60px);
height: calc(100vh - 211px);
}
</style>
+18
View File
@@ -0,0 +1,18 @@
{
"extends": "@vue/tsconfig/tsconfig.dom.json",
"include": ["env.d.ts", "src/**/*", "src/**/*.vue"],
"exclude": ["src/**/__tests__/*"],
"compilerOptions": {
// Extra safety for array and object lookups, but may have false positives.
"noUncheckedIndexedAccess": true,
// Path mapping for cleaner imports.
"paths": {
"@/*": ["./src/*"]
},
// `vue-tsc --build` produces a .tsbuildinfo file for incremental type-checking.
// Specified here to keep it out of the root directory.
"tsBuildInfoFile": "./node_modules/.tmp/tsconfig.app.tsbuildinfo"
}
}
+11
View File
@@ -0,0 +1,11 @@
{
"files": [],
"references": [
{
"path": "./tsconfig.node.json"
},
{
"path": "./tsconfig.app.json"
}
]
}
+28
View File
@@ -0,0 +1,28 @@
// TSConfig for modules that run in Node.js environment via either transpilation or type-stripping.
{
"extends": "@tsconfig/node24/tsconfig.json",
"include": [
"vite.config.*",
"vitest.config.*",
"cypress.config.*",
"nightwatch.conf.*",
"playwright.config.*",
"eslint.config.*"
],
"compilerOptions": {
// Most tools use transpilation instead of Node.js's native type-stripping.
// Bundler mode provides a smoother developer experience.
"module": "preserve",
"moduleResolution": "bundler",
// Include Node.js types and avoid accidentally including other `@types/*` packages.
"types": ["node"],
// Disable emitting output during `vue-tsc --build`, which is used for type-checking only.
"noEmit": true,
// `vue-tsc --build` produces a .tsbuildinfo file for incremental type-checking.
// Specified here to keep it out of the root directory.
"tsBuildInfoFile": "./node_modules/.tmp/tsconfig.node.tsbuildinfo"
}
}
+43
View File
@@ -0,0 +1,43 @@
import {fileURLToPath, URL} from 'node:url'
import {defineConfig} from 'vite'
import vue from '@vitejs/plugin-vue'
import vueJsx from '@vitejs/plugin-vue-jsx'
// import vueDevTools from 'vite-plugin-vue-devtools'
import AutoImport from 'unplugin-auto-import/vite'
import Components from 'unplugin-vue-components/vite'
import {ElementPlusResolver} from 'unplugin-vue-components/resolvers'
// https://vite.dev/config/
export default defineConfig({
plugins: [
vue(),
vueJsx(),
// vueDevTools(),
AutoImport({
resolvers: [
ElementPlusResolver()
], // 自动导入 Element Plus 相关函数
}),
Components({
resolvers: [
ElementPlusResolver()
], // 自动注册组件
}),
],
resolve: {
alias: {
'@': fileURLToPath(new URL('./src', import.meta.url))
},
},
// server: {
// proxy: {
// '/api': {
// target: 'http://127.0.0.1:5000',
// changeOrigin: true,
// // rewrite: (path) => path.replace(/^\/api/, '')
// // 关键:确保代理不会缓冲响应
// }
// }
// },
})