repo_id
stringlengths 6
101
| size
int64 367
5.14M
| file_path
stringlengths 2
269
| content
stringlengths 367
5.14M
|
|---|---|---|---|
297854895/vue-tsx-admin
| 2,501
|
src/views/List/SearchTable/FilterBox/index.tsx
|
import { Component, Vue, Prop, Emit } from 'vue-property-decorator'
import { Form, Input, Row, Col, Button, Select } from 'ant-design-vue'
import styles from './index.less'
@Component
class FilterBox extends Vue {
form: object;
@Prop(Object) locale: { [x: string]: string };
@Prop(Object) formData: { [x: string]: any };
@Emit() private search() {}
@Emit() private reset() {}
@Emit() private formchange(data: any) {
return data
}
protected render() {
const locale = this.locale
return <div class={styles.box}>
<Form>
<Row>
<Col span={6}>
<Form.Item
labelCol={{ span: 6 }}
wrapperCol={{ span: 18 }}
label={locale.name}>
<Input onChange={(e: any) => this.formchange({ key: 'name', value: e.target.value })} placeholder={locale.inputName} value={this.formData.name} />
</Form.Item>
</Col>
<Col span={6}>
<Form.Item
labelCol={{ span: 6 }}
wrapperCol={{ span: 18 }}
label={locale.age}>
<Input onChange={(e: any) => this.formchange({ key: 'age', value: e.target.value })} placeholder={locale.inputAge} value={this.formData.age} />
</Form.Item>
</Col>
<Col span={6}>
<Form.Item
placeholder={locale.inputGender}
labelCol={{ span: 6 }}
wrapperCol={{ span: 18 }}
label={locale.gender}>
<Select
placeholder={locale.inputGender}
onChange={(e: any) => this.formchange({ key: 'gender', value: e })}
value={this.formData.gender}>
<Select.Option value={-1}>
{locale.not}
</Select.Option>
<Select.Option value={0}>
{locale.man}
</Select.Option>
<Select.Option value={1}>
{locale.woman}
</Select.Option>
</Select>
</Form.Item>
</Col>
</Row>
</Form>
<Row>
<Col span={24} style={{ textAlign: 'right' }}>
<Button onClick={this.reset}>{locale.reset}</Button>
<Button onClick={this.search} type="primary" style={{ marginLeft: '10px' }}>{locale.search}</Button>
</Col>
</Row>
</div>
}
}
export default Form.create({
props: {
locale: Object,
formData: Object
}
})(FilterBox)
|
297854895/vue-tsx-admin
| 1,225
|
src/views/List/SearchTable/Table/index.tsx
|
import { Component, Vue, Prop, Emit } from 'vue-property-decorator'
import { Table } from 'ant-design-vue'
import styles from './index.less'
@Component
export default class TableData extends Vue {
@Prop(Object) locale: { [x: string]: string };
@Prop(Array) data: Array<any>;
@Prop(Number) size: number;
@Prop(Number) currentPage: number;
@Prop(Number) total: number;
@Prop(Boolean) loading: boolean;
@Emit()
private pagechange(page: number) { return page }
private createHead() {
return [
{
title: this.locale.name,
dataIndex: 'name'
},
{
title: this.locale.gender,
dataIndex: 'gender',
customRender: (gender: number) => gender === 0 ? this.locale.man : this.locale.woman
},
{
title: this.locale.age,
dataIndex: 'age'
}
]
}
protected render() {
return <div class={styles.table}>
<Table
rowKey="key"
pagination={{
pageSize: this.size,
current: this.currentPage,
total: this.total,
onChange: this.pagechange
}}
loading={this.loading}
dataSource={this.data}
columns={this.createHead()} />
</div>
}
}
|
297854895/vue-tsx-admin
| 7,057
|
src/layouts/BasicLayout/index.tsx
|
import { Component, Vue } from 'vue-property-decorator'
import { Icon, Drawer, Spin } from 'ant-design-vue'
import { State, Action } from 'vuex-class'
import { siderMenu, deviceType, navLayout, tabMode, routesInfoMap, menuItem } from '@/store/types'
import { theme } from '@/store/types'
import { SiderMenu, Logo, TabTool, RightBox, TabManager } from '@/components'
import styles from './index.less'
@Component
export default class BasicLayout extends Vue {
// 主题
@State('theme') theme: theme;
// 导航位置
@State('navLayout') navLayout: navLayout;
// 是否固定顶部
@State('fixedHeader') fixedHeader: boolean;
// 是否固定左侧menu
@State('fixedLeftMenu') fixedLeftMenu: boolean;
// 是否展示tab组件
@State('tabTool') tabTool: boolean;
// 当前激活状态的tab
@State('tabActive') tabActive : string;
// tab排列方式
@State('tabMode') tabMode: tabMode;
// 是否全局滚动
@State('globalScroll') globalScroll: boolean;
// 左侧siderMenu状态
@State('siderMenu') siderMenu: siderMenu;
// 菜单的MenuTree
@State('menuTree') menuTree: Array<menuItem>;
// 当前客户端类型
@State('deviceType') deviceType: deviceType;
// 路由信息
@State('routesInfoMap') routesInfoMap: routesInfoMap;
// 登录信息
@Action('handleTab') handleTab!: Function;
// 左侧menu展开二级菜单
@Action('openSiderSubMenu') openSiderSubMenu!: Function;
// 切换左侧menu的收折状态
@Action('toggleSiderMenuCollapsed') toggleSiderMenuCollapsed!: Function;
// 监听路由变化
protected mounted() {
this.$router.beforeEach(this.listenRouteChange)
// 验证路由
this.validateActiveRouter()
}
// 监听路由变化,统一维护tab的新增或者切换
listenRouteChange(
newpath: { [prospName: string]: any },
_oldpath: any,
next: Function
) {
if (this.routesInfoMap[newpath.name] && !this.routesInfoMap[newpath.name].public) {
this.handleTab({
id: newpath.name,
keyPath: newpath.path
})
}
next()
}
// 验证当前路由是否与当前active的tab一致,若不一致,进行active tab path跳转
validateActiveRouter() {
// 不一致
if (this.$route.name !== this.tabActive) this.$router.push({
name: this.tabActive
})
}
render() {
// 获取需要实用的状态
const {
theme,
tabMode,
tabTool,
menuTree,
navLayout,
tabActive,
deviceType,
fixedHeader,
globalScroll,
siderMenu: {
collapsed,
open
},
fixedLeftMenu
} = this
return <section
class={`${styles.basicLayout} ${ theme === 'dark' ? styles.dark : styles.light }`}>
{
// 非mobile设备
navLayout === 'left' || deviceType === 'mobile'
? (deviceType !== 'mobile'
? (<aside
id="s_siderMenu"
style={{ width: !collapsed ? '256px' : '80px' }}
class={`
${fixedLeftMenu ? styles.fixedLeftMenu : ''}
`}>
<div>
<Logo type="menu" theme={theme} />
<div class={styles.leftMenuWrap}>
<SiderMenu
open={open}
theme={theme}
menu={menuTree}
tabActive={tabActive}
collapsed={collapsed}
class={`${styles.siderMenu}`}
openSiderSubMenu={this.openSiderSubMenu} />
</div>
</div>
</aside>)
: <Drawer
width="256"
placement="left"
closable={false}
visible={!collapsed}
wrapClassName={styles[`${theme}Menu`]}
onClose={() => this.toggleSiderMenuCollapsed(deviceType)}>
<Logo type="menu" theme={theme} />
<SiderMenu
open={open}
theme={theme}
menu={menuTree}
tabActive={tabActive}
class={styles.siderMenu}
deviceType={this.deviceType}
closeMenu={() => this.toggleSiderMenuCollapsed(deviceType)}
openSiderSubMenu={this.openSiderSubMenu} />
</Drawer>
) : null
}
<section class={`
${styles.contentLayout}
${fixedHeader && !globalScroll ? styles.notGlobalScroll : ''}
`}>
{
navLayout === 'left' || deviceType === 'mobile'
? <header
style={
fixedHeader && globalScroll
? { background: '#fff!important', width: `calc(100% - ${collapsed ? deviceType === 'mobile' ? 0 : 80 : 256}px)` }
: { background: '#fff!important' } }
class={`
${styles[`${theme}Header`]}
${fixedHeader && globalScroll ? styles.fixedHeader : ''}
`}>
<Icon
title="切换"
class={styles.trigger}
type={deviceType === 'mobile' ? 'menu' : collapsed ? 'menu-unfold' : 'menu-fold'}
onClick={() => this.toggleSiderMenuCollapsed(deviceType)} />
{
deviceType === 'desktop'
? <TabTool
deviceType={deviceType}
mode={tabMode}
navLayout={navLayout}
show={tabTool} />
: null
}
<RightBox deviceType={deviceType} />
</header>
: <header
style={ navLayout === 'top' && !globalScroll ? { position: 'relative' } : {} }
class={`
${styles[`${theme}Header`]}
${fixedHeader && globalScroll ? styles.fixedHeader : ''}
`}>
<Logo type="top" theme={theme} />
<div class={styles.navTop}>
<SiderMenu
top
theme={theme}
open={open}
menu={menuTree}
tabActive={tabActive}
class={`${styles.siderMenu} ${styles.siderMenuTop} ${theme === 'dark' ? styles.siderMenuTopDark : ''}`}
openSiderSubMenu={this.openSiderSubMenu} />
</div>
<RightBox
top
theme={theme}
deviceType={deviceType} />
</header>
}
<main
class={`
${navLayout === 'top' && deviceType === 'desktop' ? styles.contentTopNav : ''}
${fixedHeader && globalScroll ? styles.paddingTopHeader : ''}
${navLayout === 'top' && fixedHeader ? styles.topNavOwnerScroll : ''}
`}>
{
navLayout === 'top'
&& deviceType === 'desktop'
? <TabTool
deviceType={deviceType}
mode={tabMode}
navLayout={navLayout}
show={tabTool} />
: deviceType !== 'desktop'
? <TabManager
menuCollapsed={collapsed}
deviceType={deviceType} /> : null
}
<div style={{ height: 'inherit', overflowX: 'hidden' }}>
<transition name="router-fade">
<router-view></router-view>
</transition>
</div>
</main>
</section>
</section>
}
}
|
2977094657/BiliHistoryFrontend
| 55,110
|
src/components/tailwind/Settings.vue
|
<template>
<div class="min-h-screen bg-gray-50/30">
<div class="py-4">
<div class="max-w-4xl mx-auto px-4">
<!-- 设置导航 -->
<div class="mb-6">
<div class="border-b border-gray-200">
<nav class="-mb-px flex space-x-6 overflow-x-auto" aria-label="设置选项卡">
<button
v-for="(tab, index) in settingTabs"
:key="index"
@click="activeTab = tab.key"
class="py-3 px-1 border-b-2 font-medium text-sm flex items-center space-x-2"
:class="activeTab === tab.key
? 'border-[#fb7299] text-[#fb7299]'
: 'border-transparent text-gray-500 hover:text-gray-700 hover:border-gray-300'"
>
<div class="w-5 h-5" v-html="tab.icon"></div>
<span>{{ tab.label }}</span>
</button>
</nav>
</div>
</div>
<!-- 设置内容 -->
<div class="space-y-4">
<!-- 基础设置 -->
<section v-if="activeTab === 'basic'">
<div class="bg-white rounded-lg border border-gray-200 divide-y divide-gray-200">
<!-- 服务器配置 -->
<div class="p-4 transition-colors duration-200 hover:bg-gray-50">
<div class="flex items-center justify-between mb-3">
<div>
<h3 class="text-base font-medium text-gray-900">服务器配置</h3>
<p class="text-sm text-gray-500">配置API服务器地址,修改后将自动刷新页面</p>
</div>
</div>
<div class="flex space-x-2">
<input
v-model="serverUrl"
type="text"
class="flex-1 block rounded-md border-gray-300 shadow-sm focus:border-[#fb7299] focus:ring-[#fb7299] sm:text-sm"
placeholder="例如:http://localhost:8899"
/>
<button
@click="resetServerUrl"
class="inline-flex items-center px-3 py-2 text-sm font-medium text-[#fb7299] bg-[#fb7299]/5 rounded-lg hover:bg-[#fb7299]/10"
>
<svg class="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15" />
</svg>
</button>
<button
@click="saveServerUrl"
class="inline-flex items-center px-4 py-2 text-sm font-medium text-white bg-[#fb7299] rounded-lg hover:bg-[#fb7299]/90"
>
保存
</button>
</div>
</div>
<!-- 图片源设置 -->
<div class="p-4 transition-colors duration-200 hover:bg-gray-50">
<div class="flex items-center justify-between">
<div>
<h3 class="text-base font-medium text-gray-900">使用本地图片源</h3>
<p class="text-sm text-gray-500">选择使用本地图片源或在线图片源,本地图片源适合离线访问</p>
</div>
<label class="relative inline-flex items-center cursor-pointer">
<input type="checkbox" v-model="useLocalImages" class="sr-only peer" @change="handleImageSourceChange">
<div class="w-11 h-6 bg-gray-200 peer-focus:ring-4 peer-focus:ring-[#fb7299]/20 rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-[#fb7299]"></div>
</label>
</div>
</div>
<!-- 隐私模式 -->
<div class="p-4 transition-colors duration-200 hover:bg-gray-50">
<div class="flex items-center justify-between">
<div>
<h3 class="text-base font-medium text-gray-900">隐私模式</h3>
<p class="text-sm text-gray-500">开启后将模糊显示标题、封面、UP主名称等敏感信息</p>
</div>
<label class="relative inline-flex items-center cursor-pointer">
<input type="checkbox" v-model="privacyMode" class="sr-only peer">
<div class="w-11 h-6 bg-gray-200 peer-focus:ring-4 peer-focus:ring-[#fb7299]/20 rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-[#fb7299]"></div>
</label>
</div>
</div>
<!-- 侧边栏设置 -->
<div class="p-4 transition-colors duration-200 hover:bg-gray-50">
<div class="flex items-center justify-between">
<div>
<h3 class="text-base font-medium text-gray-900">侧边栏显示</h3>
<p class="text-sm text-gray-500">设置是否默认显示侧边栏,关闭后侧边栏将自动收起</p>
</div>
<label class="relative inline-flex items-center cursor-pointer">
<input type="checkbox" v-model="showSidebar" class="sr-only peer" @change="handleSidebarChange">
<div class="w-11 h-6 bg-gray-200 peer-focus:ring-4 peer-focus:ring-[#fb7299]/20 rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-[#fb7299]"></div>
</label>
</div>
</div>
<!-- 首页默认布局设置 -->
<div class="p-4 transition-colors duration-200 hover:bg-gray-50">
<div class="flex items-center justify-between">
<div>
<h3 class="text-base font-medium text-gray-900">首页默认布局</h3>
<p class="text-sm text-gray-500">设置历史记录页面的默认展示方式,开启为网格视图,关闭为列表视图</p>
</div>
<label class="relative inline-flex items-center cursor-pointer">
<input type="checkbox" v-model="isGridLayout" class="sr-only peer" @change="handleLayoutChange">
<div class="w-11 h-6 bg-gray-200 peer-focus:ring-4 peer-focus:ring-[#fb7299]/20 rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-[#fb7299]"></div>
</label>
</div>
</div>
<!-- 同步已删除记录 -->
<div class="p-4 transition-colors duration-200 hover:bg-gray-50">
<div class="flex items-center justify-between">
<div>
<h3 class="text-base font-medium text-gray-900">同步已删除记录</h3>
<p class="text-sm text-gray-500">开启后将同步已删除的历史记录,建议仅在需要恢复记录时开启</p>
</div>
<label class="relative inline-flex items-center cursor-pointer">
<input type="checkbox" v-model="syncDeleted" class="sr-only peer">
<div class="w-11 h-6 bg-gray-200 peer-focus:ring-4 peer-focus:ring-[#fb7299]/20 rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-[#fb7299]"></div>
</label>
</div>
</div>
<!-- 同步删除B站历史记录 -->
<div class="p-4 transition-colors duration-200 hover:bg-gray-50">
<div class="flex items-center justify-between">
<div>
<h3 class="text-base font-medium text-gray-900">同步删除B站历史记录</h3>
<p class="text-sm text-gray-500">开启后删除本地历史记录时,同时删除B站服务器上的对应记录</p>
</div>
<label class="relative inline-flex items-center cursor-pointer">
<input type="checkbox" v-model="syncDeleteToBilibili" class="sr-only peer" @change="handleSyncDeleteToBilibiliChange">
<div class="w-11 h-6 bg-gray-200 peer-focus:ring-4 peer-focus:ring-[#fb7299]/20 rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-[#fb7299]"></div>
</label>
</div>
</div>
<!-- 启动时数据完整性校验 -->
<div class="p-4 transition-colors duration-200 hover:bg-gray-50">
<div class="flex items-center justify-between">
<div>
<h3 class="text-base font-medium text-gray-900">启动时数据完整性校验</h3>
<p class="text-sm text-gray-500">开启后每次启动应用时都会进行数据完整性校验,关闭可加快启动速度</p>
</div>
<label class="relative inline-flex items-center cursor-pointer">
<input type="checkbox" v-model="checkIntegrityOnStartup" class="sr-only peer" @change="handleIntegrityCheckChange">
<div class="w-11 h-6 bg-gray-200 peer-focus:ring-4 peer-focus:ring-[#fb7299]/20 rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-[#fb7299]"></div>
</label>
</div>
</div>
<!-- 邮件配置 -->
<div class="p-4 transition-colors duration-200 hover:bg-gray-50">
<div class="flex items-center justify-between mb-2">
<h3 class="text-base font-medium text-gray-900">邮件配置</h3>
<div class="flex space-x-2">
<button
@click="resetEmailConfig"
class="inline-flex items-center px-3 py-1.5 text-sm font-medium text-[#fb7299] bg-[#fb7299]/5 rounded-lg hover:bg-[#fb7299]/10"
>
<svg class="w-4 h-4 mr-1" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15" />
</svg>
重置
</button>
<button
@click="saveEmailConfig"
class="inline-flex items-center px-3 py-1.5 text-sm font-medium text-white bg-[#fb7299] rounded-lg hover:bg-[#fb7299]/90"
>
保存
</button>
<button
@click="testEmailConfig"
class="inline-flex items-center px-3 py-1.5 text-sm font-medium text-white bg-[#fb7299] rounded-lg hover:bg-[#fb7299]/90"
:disabled="!isEmailConfigComplete"
>
<svg class="w-4 h-4 mr-1" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M3 19v-8.93a2 2 0 01.89-1.664l7-4.666a2 2 0 012.22 0l7 4.666A2 2 0 0121 10.07V19M3 19a2 2 0 002 2h14a2 2 0 002-2M3 19l6.75-4.5M21 19l-6.75-4.5M3 10l6.75 4.5M21 10l-6.75 4.5m0 0l-1.14.76a2 2 0 01-2.22 0l-1.14-.76" />
</svg>
测试
</button>
</div>
</div>
<div class="grid grid-cols-2 gap-3 mt-2">
<div class="space-y-3">
<div>
<label class="block text-sm font-medium text-gray-700 mb-1">SMTP服务器</label>
<input
v-model="emailConfig.smtp_server"
type="text"
class="block w-full rounded-md border-gray-300 shadow-sm focus:border-[#fb7299] focus:ring-[#fb7299] sm:text-sm"
placeholder="smtp.qq.com"
/>
</div>
<div>
<label class="block text-sm font-medium text-gray-700 mb-1">发件人邮箱</label>
<input
v-model="emailConfig.sender"
type="email"
class="block w-full rounded-md border-gray-300 shadow-sm focus:border-[#fb7299] focus:ring-[#fb7299] sm:text-sm"
placeholder="[email protected]"
/>
</div>
<div>
<label class="block text-sm font-medium text-gray-700 mb-1">收件人邮箱</label>
<input
v-model="emailConfig.receiver"
type="email"
class="block w-full rounded-md border-gray-300 shadow-sm focus:border-[#fb7299] focus:ring-[#fb7299] sm:text-sm"
placeholder="[email protected]"
/>
</div>
</div>
<div class="space-y-3">
<div>
<label class="block text-sm font-medium text-gray-700 mb-1">SMTP端口</label>
<input
v-model.number="emailConfig.smtp_port"
type="number"
class="block w-full rounded-md border-gray-300 shadow-sm focus:border-[#fb7299] focus:ring-[#fb7299] sm:text-sm"
placeholder="587"
/>
</div>
<div>
<label class="block text-sm font-medium text-gray-700 mb-1">邮箱授权码</label>
<input
v-model="emailConfig.password"
type="password"
class="block w-full rounded-md border-gray-300 shadow-sm focus:border-[#fb7299] focus:ring-[#fb7299] sm:text-sm"
placeholder="授权码"
/>
</div>
</div>
</div>
</div>
</div>
</section>
<!-- DeepSeek配置 -->
<section v-if="activeTab === 'ai'">
<div class="bg-white rounded-lg border border-gray-200 divide-y divide-gray-200">
<!-- DeepSeek API密钥 -->
<div class="p-4 transition-colors duration-200 hover:bg-gray-50">
<div class="flex items-center justify-between mb-3">
<div>
<h3 class="text-base font-medium text-gray-900">DeepSeek API密钥</h3>
<p class="text-sm text-gray-500">配置DeepSeek API密钥,用于AI摘要生成</p>
</div>
<!-- API密钥状态显示 -->
<div v-if="deepseekApiKeyStatus.is_set" class="flex items-center space-x-1 px-2 py-1 rounded-full text-xs"
:class="deepseekApiKeyStatus.is_valid ? 'bg-green-50 text-green-700' : 'bg-red-50 text-red-700'">
<svg v-if="deepseekApiKeyStatus.is_valid" class="w-3.5 h-3.5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 13l4 4L19 7" />
</svg>
<svg v-else class="w-3.5 h-3.5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z" />
</svg>
<span>{{ deepseekApiKeyStatus.message }}</span>
</div>
</div>
<div class="flex space-x-2">
<input
v-model="deepseekApiKey"
type="password"
class="flex-1 block rounded-md border-gray-300 shadow-sm focus:border-[#4D6BFE] focus:ring-[#4D6BFE] sm:text-sm"
:placeholder="deepseekApiKeyStatus.is_valid ? '已配置有效的API密钥,如需更换请输入新的密钥' : '请输入DeepSeek API密钥'"
/>
<button
@click="saveDeepSeekApiKey"
class="inline-flex items-center px-4 py-2 text-sm font-medium text-white bg-[#4D6BFE] rounded-lg hover:bg-[#4D6BFE]/90"
>
{{ deepseekApiKeyStatus.is_valid ? '更新' : '保存' }}
</button>
</div>
</div>
<!-- DeepSeek余额信息 -->
<div class="p-4 transition-colors duration-200 hover:bg-gray-50">
<div class="flex items-center justify-between">
<div>
<h3 class="text-base font-medium text-gray-900">DeepSeek余额</h3>
<p class="text-sm text-gray-500">查询DeepSeek账户余额信息</p>
</div>
<div class="flex items-center space-x-2">
<button
@click="refreshDeepSeekBalance"
class="inline-flex items-center px-3 py-1.5 text-sm font-medium text-[#4D6BFE] bg-[#4D6BFE]/5 rounded-lg hover:bg-[#4D6BFE]/10"
>
<svg class="w-4 h-4 mr-1" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15" />
</svg>
刷新
</button>
</div>
</div>
<!-- 余额信息显示 -->
<div v-if="deepseekBalance.is_available" class="mt-3 p-3 bg-[#4D6BFE]/5 rounded-lg">
<div v-for="(balance, index) in deepseekBalance.balance_infos" :key="index" class="flex items-center justify-between">
<div class="text-sm text-gray-700">
<span class="font-medium">{{ balance.currency }}</span> 余额:
</div>
<div class="text-sm font-medium text-[#4D6BFE]">
{{ balance.total_balance }}
</div>
</div>
<div class="mt-2 text-xs text-gray-500">
<div v-for="(balance, index) in deepseekBalance.balance_infos" :key="'detail-'+index">
<div class="flex justify-between">
<span>赠送余额:</span>
<span>{{ balance.granted_balance }}</span>
</div>
<div class="flex justify-between">
<span>充值余额:</span>
<span>{{ balance.topped_up_balance }}</span>
</div>
</div>
</div>
</div>
<!-- 未查询或查询失败状态 -->
<div v-else class="mt-3 p-3 bg-gray-50 rounded-lg text-sm text-gray-500 text-center">
{{ deepseekBalanceMessage || '点击刷新按钮查询余额' }}
</div>
</div>
</div>
<!-- AI摘要配置 -->
<div class="mt-4">
<div class="bg-white rounded-lg border border-gray-200">
<div class="p-4">
<h3 class="text-base font-medium text-gray-900 mb-2">AI摘要配置</h3>
<SummaryConfig />
</div>
</div>
</div>
</section>
<!-- 数据管理 -->
<section v-if="activeTab === 'data'">
<div class="bg-white rounded-lg border border-gray-200 divide-y divide-gray-200">
<!-- 数据导出 -->
<div class="p-4 transition-colors duration-200 hover:bg-gray-50">
<div>
<div class="flex items-center justify-between mb-4">
<div>
<h3 class="text-base font-medium text-gray-900">数据导出</h3>
<p class="text-sm text-gray-500">导出历史记录数据到Excel文件,支持按年份、月份或日期范围导出</p>
</div>
</div>
<!-- 导出选项 -->
<div class="bg-gray-50 p-4 rounded-lg">
<div class="flex flex-wrap items-end gap-4">
<!-- 年份选择 (始终显示) -->
<div class="w-32">
<label class="block text-sm font-medium text-gray-700 mb-1">年份</label>
<select
v-model="exportOptions.year"
class="block w-full rounded-md border-gray-300 shadow-sm focus:border-[#fb7299] focus:ring-[#fb7299] sm:text-sm"
>
<option v-for="year in availableYears" :key="year" :value="year">
{{ year }}年
</option>
</select>
</div>
<!-- 导出类型选择 -->
<div class="w-40">
<label class="block text-sm font-medium text-gray-700 mb-1">导出类型</label>
<select
v-model="exportOptions.exportType"
class="block w-full rounded-md border-gray-300 shadow-sm focus:border-[#fb7299] focus:ring-[#fb7299] sm:text-sm"
>
<option value="year">全年数据</option>
<option value="month">按月份</option>
<option value="dateRange">按日期范围</option>
</select>
</div>
<!-- 按月选择框 -->
<div v-if="exportOptions.exportType === 'month'" class="w-24">
<label class="block text-sm font-medium text-gray-700 mb-1">月份</label>
<select
v-model="exportOptions.month"
class="block w-full rounded-md border-gray-300 shadow-sm focus:border-[#fb7299] focus:ring-[#fb7299] sm:text-sm"
>
<option v-for="month in 12" :key="month" :value="month">
{{ month }}月
</option>
</select>
</div>
<!-- 日期范围选择框 -->
<template v-if="exportOptions.exportType === 'dateRange'">
<div class="w-40">
<label class="block text-sm font-medium text-gray-700 mb-1">开始日期</label>
<input
type="date"
v-model="exportOptions.startDate"
class="block w-full rounded-md border-gray-300 shadow-sm focus:border-[#fb7299] focus:ring-[#fb7299] sm:text-sm"
/>
</div>
<div class="w-40">
<label class="block text-sm font-medium text-gray-700 mb-1">结束日期</label>
<input
type="date"
v-model="exportOptions.endDate"
class="block w-full rounded-md border-gray-300 shadow-sm focus:border-[#fb7299] focus:ring-[#fb7299] sm:text-sm"
/>
</div>
</template>
<!-- 导出按钮 -->
<button
@click="exportAndDownloadExcel"
:disabled="isExporting"
class="inline-flex items-center px-4 py-2 text-sm font-medium text-white bg-[#fb7299] rounded-lg hover:bg-[#fb7299]/90 disabled:opacity-50 h-10"
>
<svg v-if="isExporting" class="animate-spin -ml-1 mr-2 h-4 w-4" fill="none" viewBox="0 0 24 24">
<circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
<path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
</svg>
{{ isExporting ? '导出中...' : '导出Excel' }}
</button>
</div>
</div>
</div>
</div>
<!-- 数据库下载 -->
<div class="p-4 transition-colors duration-200 hover:bg-gray-50">
<div class="flex items-center justify-between">
<div>
<h3 class="text-base font-medium text-gray-900">数据库下载</h3>
<p class="text-sm text-gray-500">下载完整的SQLite数据库文件,包含所有历史记录数据</p>
</div>
<button
@click="downloadSqlite"
class="inline-flex items-center px-4 py-2 text-sm font-medium text-white bg-[#fb7299] rounded-lg hover:bg-[#fb7299]/90"
>
<svg class="mr-2 h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-4l-4 4m0 0l-4-4m4 4V4" />
</svg>
下载SQLite数据库
</button>
</div>
</div>
</div>
<!-- 危险操作 -->
<div class="mt-4">
<div class="bg-white rounded-lg border border-gray-200">
<div class="p-4 transition-colors duration-200 hover:bg-red-50 rounded-lg">
<h3 class="text-base font-medium text-gray-900 mb-2">危险操作</h3>
<div class="flex items-center justify-between p-2 border border-red-100 rounded-lg bg-red-50">
<div>
<h4 class="text-sm font-medium text-red-700">数据库重置</h4>
<p class="text-xs text-red-600">删除现有数据库并重新导入数据(此操作不可逆)</p>
</div>
<button
@click="handleResetDatabase"
class="inline-flex items-center px-3 py-1.5 text-sm font-medium text-white bg-red-500 rounded-lg hover:bg-red-600"
>
<svg class="mr-1.5 h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16" />
</svg>
重置数据库
</button>
</div>
</div>
</div>
</div>
</section>
<!-- 关于页面 -->
<section v-if="activeTab === 'about'">
<div class="bg-white rounded-lg border border-gray-200 p-6">
<!-- 页面标题 -->
<div class="mb-6">
<h1 class="text-2xl font-bold text-gray-800 flex items-center">
<span class="bg-gradient-to-r from-[#fb7299] to-[#fc9b7a] bg-clip-text text-transparent">关于本项目</span>
</h1>
<p class="text-gray-500 mt-2">哔哩哔哩历史记录管理与分析工具</p>
</div>
<!-- 项目介绍卡片 -->
<div class="mb-6">
<h2 class="text-xl font-medium text-gray-800 mb-4 flex items-center">
<svg class="w-5 h-5 mr-2 text-[#fb7299]" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
</svg>
项目简介
</h2>
<div class="text-gray-600 space-y-3">
<p>
此项目是一个哔哩哔哩历史记录管理与分析工具,帮助用户更好地管理和分析自己的B站观看历史。基于Vue 3构建,通过现代的界面设计提供强大的功能,包括历史记录查询、视频下载、数据分析等多项功能。
</p>
<div class="mt-4 space-y-3">
<div class="flex items-center">
<svg class="w-5 h-5 mr-2 text-[#fb7299]" fill="currentColor" viewBox="0 0 24 24">
<path fill-rule="evenodd" d="M12 2C6.477 2 2 6.484 2 12.017c0 4.425 2.865 8.18 6.839 9.504.5.092.682-.217.682-.483 0-.237-.008-.868-.013-1.703-2.782.605-3.369-1.343-3.369-1.343-.454-1.158-1.11-1.466-1.11-1.466-.908-.62.069-.608.069-.608 1.003.07 1.531 1.032 1.531 1.032.892 1.53 2.341 1.088 2.91.832.092-.647.35-1.088.636-1.338-2.22-.253-4.555-1.113-4.555-4.951 0-1.093.39-1.988 1.029-2.688-.103-.253-.446-1.272.098-2.65 0 0 .84-.27 2.75 1.026A9.564 9.564 0 0112 6.844c.85.004 1.705.115 2.504.337 1.909-1.296 2.747-1.027 2.747-1.027.546 1.379.202 2.398.1 2.651.64.7 1.028 1.595 1.028 2.688 0 3.848-2.339 4.695-4.566 4.943.359.309.678.92.678 1.855 0 1.338-.012 2.419-.012 2.747 0 .268.18.58.688.482A10.019 10.019 0 0022 12.017C22 6.484 17.522 2 12 2z" clip-rule="evenodd" />
</svg>
<span class="text-gray-500 w-24 flex-shrink-0">前端项目</span>
<a href="https://github.com/2977094657/BiliHistoryFrontend" target="_blank" rel="noopener noreferrer" class="text-[#fb7299] hover:underline break-all">https://github.com/2977094657/BiliHistoryFrontend</a>
</div>
<div class="flex items-center">
<svg class="w-5 h-5 mr-2 text-[#fb7299]" fill="currentColor" viewBox="0 0 24 24">
<path fill-rule="evenodd" d="M12 2C6.477 2 2 6.484 2 12.017c0 4.425 2.865 8.18 6.839 9.504.5.092.682-.217.682-.483 0-.237-.008-.868-.013-1.703-2.782.605-3.369-1.343-3.369-1.343-.454-1.158-1.11-1.466-1.11-1.466-.908-.62.069-.608.069-.608 1.003.07 1.531 1.032 1.531 1.032.892 1.53 2.341 1.088 2.91.832.092-.647.35-1.088.636-1.338-2.22-.253-4.555-1.113-4.555-4.951 0-1.093.39-1.988 1.029-2.688-.103-.253-.446-1.272.098-2.65 0 0 .84-.27 2.75 1.026A9.564 9.564 0 0112 6.844c.85.004 1.705.115 2.504.337 1.909-1.296 2.747-1.027 2.747-1.027.546 1.379.202 2.398.1 2.651.64.7 1.028 1.595 1.028 2.688 0 3.848-2.339 4.695-4.566 4.943.359.309.678.92.678 1.855 0 1.338-.012 2.419-.012 2.747 0 .268.18.58.688.482A10.019 10.019 0 0022 12.017C22 6.484 17.522 2 12 2z" clip-rule="evenodd" />
</svg>
<span class="text-gray-500 w-24 flex-shrink-0">后端项目</span>
<a href="https://github.com/2977094657/BilibiliHistoryFetcher" target="_blank" rel="noopener noreferrer" class="text-[#fb7299] hover:underline break-all">https://github.com/2977094657/BilibiliHistoryFetcher</a>
</div>
</div>
</div>
</div>
<!-- 技术致谢卡片 -->
<div>
<h2 class="text-xl font-medium text-gray-800 mb-4 flex items-center">
<svg class="w-5 h-5 mr-2 text-[#fb7299]" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 11H5m14 0a2 2 0 012 2v6a2 2 0 01-2 2H5a2 2 0 01-2-2v-6a2 2 0 012-2m14 0V9a2 2 0 00-2-2M5 11V9a2 2 0 012-2m0 0V5a2 2 0 012-2h6a2 2 0 012 2v2M7 7h10" />
</svg>
技术致谢
</h2>
<div class="text-gray-600 space-y-4 mt-4">
<ul class="list-disc pl-5 space-y-2">
<li><a href="https://github.com/SocialSisterYi/bilibili-API-collect" target="_blank" rel="noopener noreferrer" class="text-[#fb7299] hover:underline">bilibili-API-collect</a> - 没有它就没有这个项目</li>
<li><a href="https://yutto.nyakku.moe/" target="_blank" rel="noopener noreferrer" class="text-[#fb7299] hover:underline">Yutto</a> - 可爱的B站视频下载工具</li>
<li><a href="https://github.com/SYSTRAN/faster-whisper" target="_blank" rel="noopener noreferrer" class="text-[#fb7299] hover:underline">FasterWhisper</a> - 音频转文字</li>
<li><a href="https://github.com/deepseek-ai/DeepSeek-R1" target="_blank" rel="noopener noreferrer" class="text-[#fb7299] hover:underline">DeepSeek</a> - DeepSeek AI API</li>
<li><a href="https://github.com/zhw2590582/ArtPlayer" target="_blank" rel="noopener noreferrer" class="text-[#fb7299] hover:underline">ArtPlayer</a> - 强大且灵活的HTML5视频播放器</li>
<li><a href="https://www.aicu.cc/" target="_blank" rel="noopener noreferrer" class="text-[#fb7299] hover:underline">aicu.cc</a> - 第三方B站用户评论API</li>
<li>
<div class="flex items-center">
<a href="https://www.xiaoheihe.cn/app/bbs/link/153880174" target="_blank" rel="noopener noreferrer" class="flex items-center hover:opacity-80 transition-opacity mr-1.5">
<span class="text-[#fb7299] hover:underline">shengyI</span>
</a>
- 视频观看总时长功能思路提供者
</div>
</li>
<li>所有贡献者</li>
</ul>
</div>
</div>
</div>
</section>
</div>
</div>
</div>
</div>
</template>
<script setup>
import { ref, computed, onMounted, watch, onUnmounted } from 'vue'
import { showNotify } from 'vant'
import 'vant/es/notify/style'
import 'vant/es/toast/style'
import 'vant/es/dialog/style'
import {
exportHistory,
downloadExcelFile,
downloadDatabase,
resetDatabase,
getAvailableYears,
importSqliteData,
getEmailConfig,
updateEmailConfig,
testEmailConfig as testEmailApi,
checkDeepSeekApiKey,
setDeepSeekApiKey,
getDeepSeekBalance,
getIntegrityCheckConfig,
updateIntegrityCheckConfig
} from '../../api/api'
import { setBaseUrl, getCurrentBaseUrl } from '../../api/api'
import { usePrivacyStore } from '../../store/privacy'
import { showDialog } from 'vant'
import SummaryConfig from './SummaryConfig.vue'
import { useRoute } from 'vue-router'
import privacyManager from '../../utils/privacyManager'
// 设置选项卡
const settingTabs = [
{
key: 'basic',
label: '基础设置',
icon: '<svg class="text-[#fb7299]" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 12h14M5 12a2 2 0 01-2-2V6a2 2 0 012-2h14a2 2 0 012 2v4a2 2 0 01-2 2M5 12a2 2 0 00-2 2v4a2 2 0 002 2h14a2 2 0 002-2m-2-4h.01M17 16h.01" /></svg>'
},
{
key: 'ai',
label: 'AI与摘要',
icon: '<svg class="text-[#4D6BFE]" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9.75 17L9 20l-1 1h8l-1-1-.75-3M3 13h18M5 17h14a2 2 0 002-2V5a2 2 0 00-2-2H5a2 2 0 00-2 2v10a2 2 0 002 2z" /></svg>'
},
{
key: 'data',
label: '数据管理',
icon: '<svg class="text-[#fb7299]" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 7v10c0 2.21 3.582 4 8 4s8-1.79 8-4V7M4 7c0 2.21 3.582 4 8 4s8-1.79 8-4M4 7c0-2.21 3.582-4 8-4s8 1.79 8 4m0 5c0 2.21-3.582 4-8 4s-8-1.79-8-4" /></svg>'
},
{
key: 'about',
label: '关于',
icon: '<svg class="text-[#4D6BFE]" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" /></svg>'
}
]
const route = useRoute()
const activeTab = ref('basic')
// 监听路由参数变化,切换标签页
watch(() => route.query.tab, (newTab) => {
if (newTab && settingTabs.some(tab => tab.key === newTab)) {
activeTab.value = newTab
}
}, { immediate: true })
const availableYears = ref([])
const isExporting = ref(false)
// 导出选项
const exportOptions = ref({
year: new Date().getFullYear(),
month: null,
startDate: '',
endDate: '',
exportType: 'year' // 默认导出全年数据
})
const serverUrl = ref('')
const useLocalImages = ref(localStorage.getItem('useLocalImages') === 'true')
const DEFAULT_EMAIL_CONFIG = {
smtp_server: 'smtp.qq.com',
smtp_port: 587,
sender: '',
password: '',
receiver: ''
}
const emailConfig = ref({ ...DEFAULT_EMAIL_CONFIG })
// DeepSeek相关状态
const deepseekApiKey = ref('')
const deepseekApiKeyStatus = ref({
is_set: false,
is_valid: false,
message: ''
})
const deepseekBalance = ref({
is_available: false,
balance_infos: []
})
const deepseekBalanceMessage = ref('')
// 隐私模式
const { isPrivacyMode, setPrivacyMode } = usePrivacyStore()
const privacyMode = ref(isPrivacyMode.value)
// 同步已删除记录
const syncDeleted = ref(localStorage.getItem('syncDeleted') === 'true')
// 监听同步已删除记录变化
watch(syncDeleted, (newVal) => {
localStorage.setItem('syncDeleted', newVal.toString())
showNotify({
type: 'success',
message: newVal ? '已开启同步已删除记录' : '已关闭同步已删除记录'
})
})
// 同步删除B站历史记录
const syncDeleteToBilibili = ref(localStorage.getItem('syncDeleteToBilibili') === 'true')
// 处理同步删除B站历史记录变更
const handleSyncDeleteToBilibiliChange = () => {
localStorage.setItem('syncDeleteToBilibili', syncDeleteToBilibili.value.toString())
showNotify({
type: 'success',
message: syncDeleteToBilibili.value ? '已开启同步删除B站历史记录' : '已关闭同步删除B站历史记录'
})
}
// 启动时数据完整性校验
const checkIntegrityOnStartup = ref(true)
// 处理数据完整性校验设置变更
const handleIntegrityCheckChange = async () => {
try {
const response = await updateIntegrityCheckConfig(checkIntegrityOnStartup.value)
if (response.data && response.data.success) {
showNotify({
type: 'success',
message: checkIntegrityOnStartup.value ? '已开启启动时数据完整性校验' : '已关闭启动时数据完整性校验'
})
} else {
throw new Error(response.data?.message || '更新配置失败')
}
} catch (error) {
console.error('更新数据完整性校验配置失败:', error)
showNotify({
type: 'danger',
message: `更新配置失败: ${error.message}`
})
// 恢复原值
checkIntegrityOnStartup.value = !checkIntegrityOnStartup.value
}
}
// 首页默认布局设置 - 网格布局或列表布局
const isGridLayout = ref(localStorage.getItem('defaultLayout') === 'list' ? false : true) // 默认为网格视图
// 处理布局变更
const handleLayoutChange = () => {
// 更新localStorage,保存用户选择的布局模式
const newLayout = isGridLayout.value ? 'grid' : 'list'
localStorage.setItem('defaultLayout', newLayout)
// 触发全局事件,通知其他组件更新布局
try {
const event = new CustomEvent('layout-setting-changed', {
detail: { layout: newLayout }
})
window.dispatchEvent(event)
console.log('已触发布局设置更新事件:', newLayout)
} catch (error) {
console.error('触发布局设置更新事件失败:', error)
}
showNotify({
type: 'success',
message: `已切换到${isGridLayout.value ? '网格' : '列表'}视图`
})
}
// 监听隐私模式变化
watch(privacyMode, (newVal) => {
// 更新store中的隐私模式状态
setPrivacyMode(newVal)
// 更新localStorage中的隐私模式状态并触发自定义事件
if (newVal) {
privacyManager.enable()
} else {
privacyManager.disable()
}
})
// 侧边栏显示设置
const showSidebar = ref(localStorage.getItem('showSidebar') !== 'false') // 默认为true
// 处理侧边栏设置变更
const handleSidebarChange = () => {
localStorage.setItem('showSidebar', showSidebar.value.toString())
// 触发全局事件,通知侧边栏组件更新设置
try {
const event = new CustomEvent('sidebar-setting-changed', {
detail: { showSidebar: showSidebar.value }
})
window.dispatchEvent(event)
console.log('已触发侧边栏设置更新事件:', showSidebar.value)
} catch (error) {
console.error('触发侧边栏设置更新事件失败:', error)
}
showNotify({
type: 'success',
message: `已${showSidebar.value ? '启用' : '禁用'}侧边栏显示`
})
}
// 初始化服务器地址
onMounted(async () => {
console.log('Settings组件开始挂载')
// 添加隐私模式监听器
privacyManager.addListener((isEnabled) => {
console.log('Settings组件接收到隐私模式变化:', isEnabled)
// 更新组件内的隐私模式状态
if (privacyMode.value !== isEnabled) {
privacyMode.value = isEnabled
}
})
// 同步当前隐私模式状态
const currentPrivacyMode = privacyManager.isEnabled()
if (privacyMode.value !== currentPrivacyMode) {
privacyMode.value = currentPrivacyMode
}
try {
serverUrl.value = getCurrentBaseUrl()
console.log('当前服务器地址:', serverUrl.value)
// 监听侧边栏切换事件
window.addEventListener('sidebar-toggle-changed', handleSidebarToggleEvent)
// 监听布局切换事件
window.addEventListener('layout-changed', handleLayoutChangedEvent)
// 获取可用年份数据
await getAvailableYears().then(response => {
if (response.data.status === 'success') {
availableYears.value = response.data.data
if (availableYears.value.length > 0) {
exportOptions.value.year = availableYears.value[0]
}
}
}).catch(error => {
console.error('获取可用年份失败:', error)
})
await Promise.all([
(async () => {
console.log('开始初始化邮件配置')
await initEmailConfig()
console.log('邮件配置初始化完成')
})(),
(async () => {
console.log('开始获取可用年份')
try {
const response = await getAvailableYears()
console.log('获取年份响应:', response.data)
if (response.data.status === 'success') {
availableYears.value = response.data.data.sort((a, b) => b - a)
if (availableYears.value.length > 0) {
// 设置导出选项的年份
exportOptions.value.year = availableYears.value[0]
}
console.log('获取可用年份成功:', availableYears.value)
} else {
throw new Error(response.data.message || '获取年份列表失败')
}
} catch (error) {
console.error('获取可用年份失败:', error)
showNotify({
type: 'danger',
message: '获取年份列表失败'
})
// 设置当前年份作为默认值
const currentYear = new Date().getFullYear()
availableYears.value = [currentYear]
// 重置导出选项
exportOptions.value = {
year: currentYear,
month: null,
startDate: '',
endDate: '',
exportType: 'year'
}
}
})(),
(async () => {
console.log('开始获取DeepSeek配置')
await checkDeepSeekApiKeyStatus()
await refreshDeepSeekBalance()
console.log('DeepSeek配置获取完成')
})(),
(async () => {
console.log('开始获取数据完整性校验配置')
try {
const response = await getIntegrityCheckConfig()
if (response.data && response.data.success) {
checkIntegrityOnStartup.value = response.data.check_on_startup
console.log('数据完整性校验配置获取成功:', checkIntegrityOnStartup.value)
} else {
throw new Error(response.data?.message || '获取配置失败')
}
} catch (error) {
console.error('获取数据完整性校验配置失败:', error)
// 使用默认值
checkIntegrityOnStartup.value = true
}
console.log('数据完整性校验配置获取完成')
})()
])
console.log('Settings组件初始化完成')
} catch (error) {
console.error('Settings组件初始化失败:', error)
}
})
// 导出并下载Excel
const exportAndDownloadExcel = async () => {
if (isExporting.value) return
try {
// 准备导出参数
let exportParams = {}
// 根据导出类型设置参数
switch (exportOptions.value.exportType) {
case 'month':
// 检查月份是否选择
if (!exportOptions.value.month) {
showNotify({
type: 'danger',
message: '请选择要导出的月份'
})
return
}
exportParams = {
year: exportOptions.value.year,
month: exportOptions.value.month
}
break
case 'dateRange':
// 验证日期范围
if (!exportOptions.value.startDate || !exportOptions.value.endDate) {
showNotify({
type: 'danger',
message: '请选择完整的日期范围'
})
return
}
const startDate = new Date(exportOptions.value.startDate)
const endDate = new Date(exportOptions.value.endDate)
if (startDate > endDate) {
showNotify({
type: 'danger',
message: '开始日期不能晚于结束日期'
})
return
}
// 只传递日期范围参数,不传递年份参数
exportParams = {
start_date: exportOptions.value.startDate,
end_date: exportOptions.value.endDate
}
break
case 'year':
default:
// 全年数据,只需要year参数
exportParams = {
year: exportOptions.value.year
}
break
}
isExporting.value = true
showNotify({
type: 'primary',
message: '正在导出数据...'
})
console.log('导出选项:', exportParams)
const response = await exportHistory(exportParams)
console.log('导出响应:', response.data)
if (response.data.status === 'success') {
showNotify({
type: 'success',
message: '导出成功,准备下载...'
})
// 使用响应中的文件名
const filename = response.data.filename
console.log('准备下载文件:', filename)
await downloadExcelFile(filename)
showNotify({
type: 'success',
message: '下载完成'
})
} else {
throw new Error(response.data.message)
}
} catch (error) {
console.error('导出错误:', error)
let errorMessage = error.message
// 尝试获取服务器返回的错误信息
if (error.response && error.response.data) {
if (error.response.data.detail) {
errorMessage = error.response.data.detail
} else if (typeof error.response.data === 'string') {
errorMessage = error.response.data
}
}
showNotify({
type: 'danger',
message: `操作失败:${errorMessage}`
})
} finally {
isExporting.value = false
}
}
// 下载SQLite数据库
const downloadSqlite = async () => {
try {
await downloadDatabase()
} catch (error) {
showNotify({
type: 'danger',
message: `下载失败:${error.message}`
})
}
}
// 保存服务器地址
const saveServerUrl = () => {
try {
// 简单的URL格式验证
const url = new URL(serverUrl.value)
setBaseUrl(serverUrl.value)
showNotify({
type: 'success',
message: '服务器地址已更新,页面即将刷新'
})
} catch (error) {
showNotify({
type: 'danger',
message: '请输入有效的URL地址'
})
}
}
// 在script setup部分添加重置功能
const FALLBACK_DEFAULT_SERVER_URL = 'http://localhost:8899';
const DEFAULT_SERVER_URL = import.meta.env.VITE_DEFAULT_BACKEND_URL || FALLBACK_DEFAULT_SERVER_URL;
// 重置服务器地址
const resetServerUrl = () => {
showDialog({
title: '重置服务器地址',
message: '确定要将服务器地址重置为默认值吗?',
showCancelButton: true,
confirmButtonText: '确定',
cancelButtonText: '取消',
confirmButtonColor: '#fb7299'
}).then((result) => {
if (result === 'confirm') {
serverUrl.value = DEFAULT_SERVER_URL
setBaseUrl(DEFAULT_SERVER_URL)
showNotify({
type: 'success',
message: '服务器地址已重置,页面即将刷新'
})
}
})
}
// 处理数据库重置
const handleResetDatabase = () => {
showDialog({
title: '危险操作确认',
message: '此操作将删除现有数据库并重新导入数据。此操作不可逆,确定要继续吗?',
showCancelButton: true,
confirmButtonText: '确定重置',
cancelButtonText: '取消',
confirmButtonColor: '#dc2626'
}).then(async (result) => {
if (result === 'confirm') {
try {
showNotify({
type: 'warning',
message: '正在重置数据库...'
})
// 重置数据库
const resetResponse = await resetDatabase()
if (resetResponse.data.status === 'success') {
showNotify({
type: 'success',
message: '数据库已重置,正在重新导入数据...'
})
// 重新导入数据
try {
const importResponse = await importSqliteData()
if (importResponse.data.status === 'success') {
showNotify({
type: 'success',
message: '数据导入完成,页面即将刷新'
})
// 等待1秒后刷新页面,确保用户看到成功提示
setTimeout(() => {
window.location.reload()
}, 1000)
} else {
throw new Error(importResponse.data.message || '数据导入失败')
}
} catch (importError) {
showNotify({
type: 'danger',
message: `数据导入失败:${importError.message}`
})
}
}
} catch (error) {
showNotify({
type: 'danger',
message: `重置失败:${error.message}`
})
}
}
})
}
// 处理图片源变更
const handleImageSourceChange = () => {
localStorage.setItem('useLocalImages', useLocalImages.value.toString())
showNotify({
type: 'success',
message: `已${useLocalImages.value ? '启用' : '禁用'}本地图片源`
})
// 刷新页面以应用新设置
window.location.reload()
}
// 初始化邮件配置
const initEmailConfig = async () => {
try {
const response = await getEmailConfig()
if (response.data) { // 直接检查 response.data
// 使用解构赋值来更新配置,保留默认值
emailConfig.value = {
...DEFAULT_EMAIL_CONFIG,
...response.data // 直接使用 response.data
}
} else {
emailConfig.value = { ...DEFAULT_EMAIL_CONFIG }
}
} catch (error) {
console.error('获取邮件配置失败:', error)
showNotify({
type: 'warning',
message: '获取邮件配置失败,使用默认配置'
})
emailConfig.value = { ...DEFAULT_EMAIL_CONFIG }
}
}
// 保存邮件配置
const saveEmailConfig = async () => {
try {
// 验证邮箱格式
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
if (!emailRegex.test(emailConfig.value.sender)) {
throw new Error('发件人邮箱格式不正确')
}
if (!emailRegex.test(emailConfig.value.receiver)) {
throw new Error('收件人邮箱格式不正确')
}
// 验证端口号
if (emailConfig.value.smtp_port < 0 || emailConfig.value.smtp_port > 65535) {
throw new Error('端口号必须在0-65535之间')
}
const response = await updateEmailConfig(emailConfig.value)
if (response.data.status === 'success') {
showNotify({
type: 'success',
message: '邮件配置已保存'
})
} else {
throw new Error(response.data.message || '保存失败')
}
} catch (error) {
showNotify({
type: 'danger',
message: `保存失败:${error.message}`
})
}
}
// 重置邮件配置
const resetEmailConfig = () => {
showDialog({
title: '重置邮件配置',
message: '确定要重置邮件配置吗?这将清空所有配置并恢复默认的SMTP服务器和端口设置。',
showCancelButton: true,
confirmButtonText: '确定',
cancelButtonText: '取消',
confirmButtonColor: '#fb7299'
}).then(async (result) => {
if (result === 'confirm') {
try {
// 完全重置为默认配置
const resetConfig = { ...DEFAULT_EMAIL_CONFIG }
emailConfig.value = resetConfig
// 调用后端API保存重置后的配置
const response = await updateEmailConfig(resetConfig)
if (response.data.status === 'success') {
showNotify({
type: 'success',
message: '邮件配置已重置'
})
} else {
throw new Error(response.data.message || '重置失败')
}
} catch (error) {
showNotify({
type: 'danger',
message: `重置失败:${error.message}`
})
// 如果保存失败,重新获取配置
await initEmailConfig()
}
}
})
}
// 检查DeepSeek API密钥状态
const checkDeepSeekApiKeyStatus = async () => {
try {
const response = await checkDeepSeekApiKey()
deepseekApiKeyStatus.value = response.data
} catch (error) {
console.error('检查DeepSeek API密钥状态失败:', error)
deepseekApiKeyStatus.value = {
is_set: false,
is_valid: false,
message: '检查API密钥状态失败'
}
}
}
// 保存DeepSeek API密钥
const saveDeepSeekApiKey = async () => {
if (!deepseekApiKey.value) {
showNotify({
type: 'warning',
message: 'API密钥不能为空'
})
return
}
try {
const response = await setDeepSeekApiKey(deepseekApiKey.value)
if (response.data.success) {
showNotify({
type: 'success',
message: response.data.message || 'API密钥已保存'
})
// 清空输入框
deepseekApiKey.value = ''
// 更新API密钥状态和余额信息
await checkDeepSeekApiKeyStatus()
await refreshDeepSeekBalance()
} else {
throw new Error(response.data.message || 'API密钥保存失败')
}
} catch (error) {
showNotify({
type: 'danger',
message: `保存失败:${error.message || '未知错误'}`
})
}
}
// 刷新DeepSeek余额
const refreshDeepSeekBalance = async () => {
try {
deepseekBalanceMessage.value = '正在查询余额...'
const response = await getDeepSeekBalance()
deepseekBalance.value = response.data
deepseekBalanceMessage.value = ''
} catch (error) {
console.error('获取DeepSeek余额失败:', error)
deepseekBalance.value = { is_available: false }
deepseekBalanceMessage.value = error.response?.data?.message || '获取余额失败,请检查API密钥是否正确'
}
}
// 检查邮件配置是否完整
const isEmailConfigComplete = computed(() => {
return emailConfig.value.smtp_server &&
emailConfig.value.smtp_port &&
emailConfig.value.sender &&
emailConfig.value.password &&
emailConfig.value.receiver
})
// 测试邮件配置
const testEmailConfig = async () => {
try {
if (!isEmailConfigComplete.value) {
showNotify({
type: 'warning',
message: '请先完善邮件配置'
})
return
}
// 先保存邮件配置
try {
await saveEmailConfig()
} catch (error) {
// 如果保存配置失败,则终止测试
return
}
showNotify({
type: 'primary',
message: '正在发送测试邮件...'
})
const testData = {
to_email: emailConfig.value.receiver,
subject: '测试邮件',
content: '这是一封测试邮件,用于验证邮箱配置是否有效。'
}
const response = await testEmailApi(testData)
if (response.data.status === 'success') {
showNotify({
type: 'success',
message: '测试邮件发送成功'
})
} else {
throw new Error(response.data.message || '发送失败')
}
} catch (error) {
showNotify({
type: 'danger',
message: `发送失败:${error.message || '未知错误'}`
})
}
}
// 处理侧边栏切换事件
const handleSidebarToggleEvent = (event) => {
if (event.detail && typeof event.detail.showSidebar === 'boolean') {
showSidebar.value = event.detail.showSidebar
}
}
// 在script setup部分添加卸载功能
onUnmounted(() => {
// 移除事件监听
window.removeEventListener('sidebar-toggle-changed', handleSidebarToggleEvent)
window.removeEventListener('layout-changed', handleLayoutChangedEvent)
})
// 处理布局变更事件 - 从首页接收的布局变化
const handleLayoutChangedEvent = (event) => {
if (event.detail && typeof event.detail.layout === 'string') {
isGridLayout.value = event.detail.layout === 'grid'
}
}
</script>
|
2977094657/BiliHistoryFrontend
| 3,514
|
src/components/tailwind/SummaryConfig.vue
|
<template>
<div class="p-4">
<div class="flex items-center space-x-2 text-gray-900 mb-2">
<div class="p-1.5 bg-[#fb7299]/5 rounded-lg">
<svg class="w-5 h-5 text-[#fb7299]" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z" />
</svg>
</div>
<h2 class="text-lg font-medium">摘要配置</h2>
</div>
<p class="text-sm text-gray-500 mb-3">配置AI摘要的缓存策略,优化请求效率和存储空间</p>
<div v-if="loading" class="flex justify-center py-4">
<div class="animate-spin h-5 w-5 border-2 border-[#fb7299] border-t-transparent rounded-full"></div>
</div>
<div v-else-if="error" class="text-red-500 text-sm py-2">
{{ error }}
<button
@click="fetchConfig"
class="ml-2 text-xs bg-gray-100 hover:bg-gray-200 text-gray-700 rounded px-2 py-1"
>
重试
</button>
</div>
<div v-else>
<div class="flex items-center justify-between p-2 bg-gray-50 rounded-lg">
<span class="text-sm font-medium text-gray-700">缓存空摘要</span>
<label class="relative inline-flex items-center cursor-pointer">
<input
type="checkbox"
v-model="config.cache_empty_summary"
class="sr-only peer"
@change="updateConfig"
>
<div
class="w-11 h-6 bg-gray-200 peer-focus:outline-none peer-focus:ring-4 peer-focus:ring-[#fb7299]/20 rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-[#fb7299]"></div>
</label>
</div>
<div class="text-xs text-gray-500 mt-3">
<p class="mb-1"><strong>提示:</strong></p>
<ul class="list-disc pl-5 space-y-1">
<li>开启缓存空摘要可减少API请求次数,但会增加数据库存储空间</li>
<li>关闭缓存空摘要可减少数据库存储空间,但会增加API请求次数</li>
</ul>
</div>
</div>
</div>
</template>
<script setup>
import { ref, reactive, onMounted } from 'vue'
import { getSummaryConfig, updateSummaryConfig } from '../../api/api'
import { showNotify } from 'vant'
import 'vant/es/notify/style'
const loading = ref(false)
const error = ref(null)
const config = reactive({
cache_empty_summary: true,
})
// 获取当前配置
const fetchConfig = async () => {
loading.value = true
error.value = null
try {
const response = await getSummaryConfig()
if (response.data) {
config.cache_empty_summary = response.data.cache_empty_summary
}
} catch (err) {
error.value = err.response?.data?.detail || err.message || '获取配置失败'
console.error('获取摘要配置失败:', err)
} finally {
loading.value = false
}
}
// 更新配置
const updateConfig = async () => {
loading.value = true
try {
const response = await updateSummaryConfig({
cache_empty_summary: config.cache_empty_summary,
})
if (response.data) {
showNotify({
type: 'success',
message: '配置已更新',
})
}
} catch (err) {
error.value = err.response?.data?.detail || err.message || '更新配置失败'
console.error('更新摘要配置失败:', err)
// 恢复原值
fetchConfig()
} finally {
loading.value = false
}
}
// 组件挂载时获取配置
onMounted(() => {
fetchConfig()
})
</script>
|
2977094657/BiliHistoryFrontend
| 1,716
|
src/components/tailwind/VideoCategories.vue
|
<template>
<!-- 圆角弹窗(底部) -->
<van-popup v-model:show="localShowBottom" round position="bottom" :style="{ height: '80%' }">
<van-tree-select
class="m-2"
height="95%"
v-model:active-id="activeId"
v-model:main-active-index="activeIndex"
:items="items"
@click-item="onSelectItem"
/>
</van-popup>
</template>
<script setup>
import { computed, onMounted, ref } from 'vue'
import { getVideoCategories } from '../../api/api.js'
const emit = defineEmits(['update:category', 'update:showBottom', 'selectSubCategory'])
const props = defineProps({
category: {
type: String,
default: ''
},
showBottom: {
type: Boolean,
default: false,
},
})
// 定义状态
const activeId = ref(null)
const activeIndex = ref(0)
const items = ref([]) // 用于存放转换后的items结构
// 计算属性,用于实现双向绑定
const localShowBottom = computed({
get() {
return props.showBottom
},
set(value) {
emit('update:showBottom', value)
},
})
// 获取视频分类并转换数据结构
const fetchCategories = async () => {
try {
const response = await getVideoCategories()
if (response.data.status === 'success') {
// 转换数据结构以适应组件
items.value = response.data.data.map((category) => ({
text: category.name,
type: 'main',
children: category.sub_categories.map((sub) => ({
text: sub.name,
id: sub.tid,
type: 'sub',
})),
}))
}
} catch (error) {
console.error('Error fetching categories:', error)
}
}
// 当选中分类时,发出事件并传递 name 和 type
const onSelectItem = (item) => {
emit('selectSubCategory', { name: item.text, type: item.type })
}
// 页面加载时获取数据
onMounted(() => {
fetchCategories()
})
</script>
<style scoped></style>
|
2977094657/BiliHistoryFrontend
| 11,906
|
src/components/tailwind/VideoSummary.vue
|
<template>
<div class="w-full bg-white rounded-lg shadow-sm p-4">
<!-- 摘要内容显示区域 -->
<div v-if="summary && !loading && !error" class="space-y-4">
<div class="flex items-center justify-between">
<h3 class="text-sm font-medium text-gray-900 flex items-center">
<svg xmlns="http://www.w3.org/2000/svg" class="h-4 w-4 mr-1 text-[#fb7299]" fill="none" viewBox="0 0 24 24"
stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z" />
</svg>
<span>AI视频摘要</span>
</h3>
<button
@click="refreshSummary"
class="text-xs text-gray-500 hover:text-[#fb7299] flex items-center space-x-1"
:disabled="loading"
>
<svg xmlns="http://www.w3.org/2000/svg" class="h-3.5 w-3.5" fill="none" viewBox="0 0 24 24"
stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15" />
</svg>
<span>刷新</span>
</button>
</div>
<!-- 总体摘要 -->
<div class="bg-gray-50 rounded-lg p-3">
<p class="text-xs text-gray-700 whitespace-pre-line leading-relaxed">{{ summary }}</p>
</div>
<!-- 视频大纲 -->
<div v-if="outline && outline.length > 0" class="mt-4">
<h4 class="text-xs font-medium text-gray-800 mb-2 flex items-center">
<svg xmlns="http://www.w3.org/2000/svg" class="h-3.5 w-3.5 mr-1 text-[#fb7299]" fill="none"
viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2" />
</svg>
<span>视频大纲</span>
</h4>
<div class="space-y-3">
<div v-for="(section, index) in outline" :key="index" class="border-l-2 border-[#fb7299]/30 pl-3 py-1">
<!-- 章节标题 -->
<div class="flex items-start">
<a
:href="`https://www.bilibili.com/video/${props.bvid}?t=${section.timestamp}`"
target="_blank"
class="inline-flex items-center text-xs font-medium text-[#fb7299] hover:underline"
>
<svg xmlns="http://www.w3.org/2000/svg" class="h-3 w-3 mr-1" fill="none" viewBox="0 0 24 24"
stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
d="M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z" />
</svg>
{{ formatTime(section.timestamp) }}
</a>
<h5 class="text-xs font-medium text-gray-800 ml-2">{{ section.title }}</h5>
</div>
<!-- 章节要点 -->
<div v-if="section.part_outline && section.part_outline.length > 0" class="mt-1 ml-4 space-y-1">
<div v-for="(point, pIndex) in section.part_outline" :key="`${index}-${pIndex}`" class="flex items-start">
<a
:href="`https://www.bilibili.com/video/${props.bvid}?t=${point.timestamp}`"
target="_blank"
class="inline-flex items-center text-[10px] text-gray-500 hover:text-[#fb7299] hover:underline mt-0.5"
>
{{ formatTime(point.timestamp) }}
</a>
<p class="text-[11px] text-gray-600 ml-2">{{ point.content }}</p>
</div>
</div>
</div>
</div>
</div>
<div v-if="fromCache" class="text-xs text-gray-400 flex items-center mt-2">
<svg xmlns="http://www.w3.org/2000/svg" class="h-3 w-3 mr-1" fill="none" viewBox="0 0 24 24"
stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
d="M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
</svg>
<span>摘要来自缓存</span>
</div>
</div>
<!-- 加载状态 -->
<div v-if="loading" class="py-6 space-y-3">
<div class="flex items-center">
<svg class="animate-spin h-4 w-4 text-[#fb7299] mr-2" fill="none" viewBox="0 0 24 24">
<circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
<path class="opacity-75" fill="currentColor"
d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
</svg>
<h3 class="text-sm font-medium text-gray-900 ">AI正在生成视频摘要...</h3>
</div>
<div class="animate-pulse flex space-x-4">
<div class="flex-1 space-y-3">
<div class="h-2 bg-gray-200 rounded"></div>
<div class="h-2 bg-gray-200 rounded"></div>
<div class="h-2 bg-gray-200 rounded"></div>
<div class="h-2 bg-gray-200 rounded w-5/6"></div>
</div>
</div>
<p class="text-xs text-gray-400">首次生成可能需要一些时间,请耐心等待</p>
</div>
<!-- 错误状态 -->
<div v-if="error && !loading" class="py-8 flex flex-col items-center justify-center">
<h3 class="text-sm font-medium text-gray-900 flex items-center">
<svg v-if="errorIsWarning" xmlns="http://www.w3.org/2000/svg" class="h-4 w-4 text-amber-500 mr-1" fill="none"
viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z" />
</svg>
<svg v-else-if="isGenerating" xmlns="http://www.w3.org/2000/svg" class="h-4 w-4 text-blue-500 mr-1" fill="none"
viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13 10V3L4 14h7v7l9-11h-7z" />
</svg>
<svg v-else xmlns="http://www.w3.org/2000/svg" class="h-4 w-4 text-red-500 mr-1" fill="none" viewBox="0 0 24 24"
stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
d="M12 8v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
</svg>
<span>{{ errorTitle }}</span>
</h3>
<p class="text-xs text-gray-500 mt-2 text-center">{{ error }}</p>
<div class="mt-4 flex items-center space-x-3">
<button
v-if="shouldShowRetryButton"
@click="() => fetchSummary(false)"
class="text-xs bg-gray-100 hover:bg-gray-200 text-gray-700 rounded px-3 py-1.5"
>
重试
</button>
<button
v-if="isGenerating"
@click="() => fetchSummary(false)"
class="text-xs bg-[#fb7299] hover:bg-[#fc8bad] text-white rounded px-3 py-1.5"
>
查看进度
</button>
</div>
</div>
</div>
</template>
<script setup>
import { ref, onMounted, computed, watch } from 'vue'
import { getVideoSummary } from '../../api/api'
import { showNotify } from 'vant'
import 'vant/es/notify/style'
const props = defineProps({
bvid: {
type: String,
required: true,
},
cid: {
type: [String, Number],
required: true,
},
upMid: {
type: [String, Number],
required: true,
},
})
const summary = ref('')
const outline = ref(null)
const loading = ref(false)
const error = ref(null)
const fromCache = ref(false)
const stid = ref('')
// 当props变化时,清除旧数据并重新获取摘要
watch(
() => [props.bvid, props.cid, props.upMid],
(newValues, oldValues) => {
// 如果是组件首次加载,不需要处理
if (!oldValues[0]) return
// 如果有任一值变化,说明是新的视频,清除旧数据并重新获取
if (
newValues[0] !== oldValues[0] ||
newValues[1] !== oldValues[1] ||
newValues[2] !== oldValues[2]
) {
// 清除旧数据
clearSummaryData()
// 获取新数据
fetchSummary()
}
},
)
// 清除摘要数据
const clearSummaryData = () => {
summary.value = ''
outline.value = null
error.value = null
fromCache.value = false
stid.value = ''
}
// 将秒数格式化为时分秒
const formatTime = (seconds) => {
if (!seconds && seconds !== 0) return '00:00'
const hours = Math.floor(seconds / 3600)
const minutes = Math.floor((seconds % 3600) / 60)
const secs = Math.floor(seconds % 60)
if (hours > 0) {
return `${String(hours).padStart(2, '0')}:${String(minutes).padStart(2, '0')}:${String(secs).padStart(2, '0')}`
} else {
return `${String(minutes).padStart(2, '0')}:${String(secs).padStart(2, '0')}`
}
}
// 获取视频摘要
const fetchSummary = async (forceRefresh = false) => {
if (!props.bvid || !props.cid || !props.upMid) {
error.value = '缺少必要参数,无法获取视频摘要'
return
}
loading.value = true
error.value = null
try {
const response = await getVideoSummary(
props.bvid,
props.cid,
props.upMid,
forceRefresh,
)
// 处理API返回的数据
const data = response.data
// 保存stid
stid.value = data.stid || ''
// 根据has_summary和result_type判断状态
if (data.has_summary) {
// 有摘要内容
summary.value = data.summary || ''
outline.value = data.outline || null
fromCache.value = data.from_cache !== undefined ? data.from_cache : false
} else {
// 根据result_type判断状态
switch (data.result_type) {
case -1:
error.value = '该视频不支持AI摘要(可能包含敏感内容)'
break
case 0:
error.value = data.status_message || '该视频没有摘要'
break
case 1:
// 仅存在摘要总结
summary.value = data.summary || ''
outline.value = null
fromCache.value = data.from_cache !== undefined ? data.from_cache : false
break
case 2:
// 存在摘要以及提纲
summary.value = data.summary || ''
outline.value = data.outline || null
fromCache.value = data.from_cache !== undefined ? data.from_cache : false
break
default:
error.value = data.status_message || '获取摘要失败'
}
}
} catch (err) {
error.value = err.response?.data?.detail || err.message || '网络错误,请稍后重试'
console.error('获取视频摘要失败:', err)
} finally {
loading.value = false
}
}
// 强制刷新摘要
const refreshSummary = async (event) => {
// 忽略事件对象,传递true作为force_refresh参数
await fetchSummary(true)
showNotify({
type: 'success',
message: '摘要已更新',
})
}
// 组件挂载时获取摘要
onMounted(() => {
if (props.bvid && props.cid && props.upMid) {
// 先清除数据以显示加载状态
clearSummaryData()
loading.value = true
// 延迟一下再获取,确保加载状态能够显示
setTimeout(() => {
fetchSummary()
}, 100)
}
})
// 计算是否显示重试按钮
const shouldShowRetryButton = computed(() => {
// 网络错误或处理错误时显示重试按钮
if (!error.value) return false
// 这些情况下不显示重试按钮,因为重试没有意义
const noRetryMessages = [
'未识别到视频语音,无法生成摘要',
'该视频不支持AI摘要',
'缺少必要参数',
]
return !noRetryMessages.some(msg => error.value.includes(msg))
})
// 判断错误是否为警告类型(黄色图标)
const errorIsWarning = computed(() => {
if (!error.value) return false
const warningMessages = [
'未识别到视频语音',
'此视频暂无摘要',
'该视频不支持AI摘要',
]
return warningMessages.some(msg => error.value.includes(msg))
})
// 根据错误类型返回适当的标题
const errorTitle = computed(() => {
if (!error.value) return '获取摘要失败'
if (isGenerating.value) {
return '摘要生成中'
} else if (errorIsWarning.value) {
return '无法生成摘要'
} else {
return '获取摘要失败'
}
})
// 判断是否为"生成中"状态
const isGenerating = computed(() => {
if (!error.value) return false
return error.value.includes('正在生成')
})
</script>
<style scoped>
/* 平滑滚动 */
html {
scroll-behavior: smooth;
}
</style>
|
281677160/openwrt-package
| 4,516
|
luci-app-passwall2/luasrc/passwall2/util_hysteria2.lua
|
module("luci.passwall2.util_hysteria2", package.seeall)
local api = require "luci.passwall2.api"
local uci = api.uci
local jsonc = api.jsonc
function gen_config_server(node)
local config = {
listen = ":" .. node.port,
tls = {
cert = node.tls_certificateFile,
key = node.tls_keyFile,
},
obfs = (node.hysteria2_obfs) and {
type = "salamander",
salamander = {
password = node.hysteria2_obfs
}
} or nil,
auth = {
type = "password",
password = node.hysteria2_auth_password
},
bandwidth = (node.hysteria2_up_mbps or node.hysteria2_down_mbps) and {
up = node.hysteria2_up_mbps and node.hysteria2_up_mbps .. " mbps" or nil,
down = node.hysteria2_down_mbps and node.hysteria2_down_mbps .. " mbps" or nil
} or nil,
ignoreClientBandwidth = (node.hysteria2_ignoreClientBandwidth == "1") and true or false,
disableUDP = (node.hysteria2_udp == "0") and true or false,
}
return config
end
function gen_config(var)
local node_id = var["-node"]
if not node_id then
print("-node 不能为空")
return
end
local node = uci:get_all("passwall2", node_id)
local local_socks_address = var["-local_socks_address"] or "0.0.0.0"
local local_socks_port = var["-local_socks_port"]
local local_socks_username = var["-local_socks_username"]
local local_socks_password = var["-local_socks_password"]
local local_http_address = var["-local_http_address"] or "0.0.0.0"
local local_http_port = var["-local_http_port"]
local local_http_username = var["-local_http_username"]
local local_http_password = var["-local_http_password"]
local server_host = var["-server_host"] or node.address
local server_port = var["-server_port"] or node.port
if api.is_ipv6(server_host) then
server_host = api.get_ipv6_full(server_host)
end
local server = server_host .. ":" .. server_port
if (node.hysteria2_hop) then
server = server .. "," .. string.gsub(node.hysteria2_hop, ":", "-")
end
local config = {
server = server,
transport = {
type = node.protocol or "udp",
udp = {
hopInterval = (function()
local HopIntervalStr = tostring(node.hysteria2_hop_interval or "30s")
local HopInterval = tonumber(HopIntervalStr:match("^%d+"))
if HopInterval and HopInterval >= 5 then
return tostring(HopInterval) .. "s"
end
return "30s"
end)(),
}
},
obfs = (node.hysteria2_obfs) and {
type = "salamander",
salamander = {
password = node.hysteria2_obfs
}
} or nil,
auth = node.hysteria2_auth_password,
tls = {
sni = node.tls_serverName,
insecure = (node.tls_allowInsecure == "1") and true or false,
pinSHA256 = (node.hysteria2_tls_pinSHA256) and node.hysteria2_tls_pinSHA256 or nil,
},
quic = {
initStreamReceiveWindow = (node.hysteria2_recv_window) and tonumber(node.hysteria2_recv_window) or nil,
initConnReceiveWindow = (node.hysteria2_recv_window_conn) and tonumber(node.hysteria2_recv_window_conn) or nil,
maxIdleTimeout = (function()
local timeoutStr = tostring(node.hysteria2_idle_timeout or "")
local timeout = tonumber(timeoutStr:match("^%d+"))
if timeout and timeout >= 4 and timeout <= 120 then
return tostring(timeout) .. "s"
end
return nil
end)(),
disablePathMTUDiscovery = (node.hysteria2_disable_mtu_discovery) and true or false,
},
bandwidth = (node.hysteria2_up_mbps or node.hysteria2_down_mbps) and {
up = node.hysteria2_up_mbps and node.hysteria2_up_mbps .. " mbps" or nil,
down = node.hysteria2_down_mbps and node.hysteria2_down_mbps .. " mbps" or nil
} or nil,
fast_open = (node.fast_open == "1") and true or false,
lazy = (node.hysteria2_lazy_start == "1") and true or false,
socks5 = (local_socks_address and local_socks_port) and {
listen = local_socks_address .. ":" .. local_socks_port,
username = (local_socks_username and local_socks_password) and local_socks_username or nil,
password = (local_socks_username and local_socks_password) and local_socks_password or nil,
disableUDP = false,
} or nil,
http = (local_http_address and local_http_port) and {
listen = local_http_address .. ":" .. local_http_port,
username = (local_http_username and local_http_password) and local_http_username or nil,
password = (local_http_username and local_http_password) and local_http_password or nil,
} or nil
}
return jsonc.stringify(config, 1)
end
_G.gen_config = gen_config
if arg[1] then
local func =_G[arg[1]]
if func then
print(func(api.get_function_args(arg)))
end
end
|
2881099/FreeSql.AdminLTE
| 1,045
|
FreeSql.AdminLTE.Tools/FreeSql.AdminLTE.Tools.csproj
|
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<Version>3.2.808</Version>
<OutputType>Exe</OutputType>
<TargetFramework>net6.0</TargetFramework>
<GeneratePackageOnBuild>true</GeneratePackageOnBuild>
<IsPackable>true</IsPackable>
<PackAsTool>true</PackAsTool>
<Authors>2881099</Authors>
<Company>2881099</Company>
<Product>FreeSql</Product>
<Description>快速创建 .NETCore + MVC + Razor + AdminLTE 后台管理项目,安装:dotnet tool install -g FreeSql.AdminLTE.Tools</Description>
<PackageProjectUrl>https://github.com/2881099/FreeSql.AdminLTE</PackageProjectUrl>
<RepositoryUrl>https://github.com/2881099/FreeSql.AdminLTE</RepositoryUrl>
<PackageTags>生成器,.net,core,AdminLTE</PackageTags>
<SignAssembly>false</SignAssembly>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Colorful.Console" Version="1.2.11" />
<PackageReference Include="System.Text.Encoding.CodePages" Version="6.0.0" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\FreeSql.AdminLTE\FreeSql.AdminLTE.csproj" />
</ItemGroup>
</Project>
|
2881099/FreeSql.AdminLTE
| 12,576
|
FreeSql.AdminLTE.Tools/ConsoleApp.cs
|
using System;
using System.IO;
using System.Linq;
using System.Threading;
using System.Drawing;
using Console = Colorful.Console;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using System.Reflection;
using System.Text;
namespace FreeSql.AdminLTE.Tools
{
public class ConsoleApp {
public GeneratorOptions ArgsOptions = new GeneratorOptions();
public string ArgsFind;
public string ArgsOutput;
public bool ArgsFirst;
public ConsoleApp(string[] args, ManualResetEvent wait) {
Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
var gb2312 = Encoding.GetEncoding("GB2312");
if (gb2312 != null)
{
try
{
Console.OutputEncoding = gb2312;
Console.InputEncoding = gb2312;
}
catch { }
}
//var ntjson = Assembly.LoadFile(@"C:\Users\28810\Desktop\testfreesql\bin\Debug\netcoreapp2.2\publish\testfreesql.dll");
//using (var gen = new Generator(new GeneratorOptions()))
//{
// gen.TraceLog = log => Console.WriteFormatted(log + "\r\n", Color.DarkGray);
// gen.Build(ArgsOutput, new[] { typeof(ojbk.Entities.AuthRole) }, false);
//}
Console.WriteAscii(" FreeSql", Color.Violet);
Console.WriteFormatted(@"
# Github # {0}
", Color.SlateGray,
new Colorful.Formatter("https://github.com/2881099/FreeSql.AdminLTE", Color.DeepSkyBlue));
this.ArgsOutput = Directory.GetCurrentDirectory();
string args0 = args[0].Trim().ToLower();
if (args[0] == "?" || args0 == "--help" || args0 == "-help") {
Console.WriteFormatted(@"
{0}
# 生成条件 #
{1}
{2}
# 快速开始 #
> {3} {4} MyTest\.Model\..+
-Find * 匹配实体类FullName的正则表达式
-ControllerNameSpace 控制器命名空间(默认:FreeSql.AdminLTE)
-ControllerRouteBase 控制器请求路径前辍(默认:/AdminLTE/)
-ControllerBase 控制器基类(默认:Controller)
-First 是否生成 ApiResult.cs、index.html、htm 静态资源(首次生成)
-Output 输出路径(默认:当前目录)
# 生成到其他目录 #
> {3} {4} MyTest\.Model\..+ -Output d:/test
", Color.SlateGray,
new Colorful.Formatter("基于 .net6.0 环境,在控制台当前目录的项目下,根据实体类生成 AdminLTE 后台管理功能的相关文件。", Color.SlateGray),
new Colorful.Formatter("1、实体类的注释(请开启项目XML文档);", Color.SlateGray),
new Colorful.Formatter("2、实体类的导航属性配置(可生成繁琐的常用后台管理功能)。", Color.SlateGray),
new Colorful.Formatter("FreeSql.AdminLTE.Tools", Color.White),
new Colorful.Formatter("-Find", Color.ForestGreen)
);
return;
}
for (int a = 0; a < args.Length; a++) {
switch (args[a]) {
case "-Find":
ArgsFind = args[a + 1];
a++;
break;
case "-ControllerNameSpace":
ArgsOptions.ControllerNameSpace = args[a + 1];
a++;
break;
case "-ControllerRouteBase":
ArgsOptions.ControllerRouteBase = args[a + 1];
a++;
break;
case "-ControllerBase":
ArgsOptions.ControllerBase = args[a + 1];
a++;
break;
case "-First":
ArgsFirst = true;
break;
case "-Output":
ArgsOutput = args[a + 1];
a++;
break;
}
}
if (string.IsNullOrEmpty(ArgsFind))
throw new ArgumentException("-Find 参数不能为空");
Regex findExp = null;
try
{
findExp = new Regex(ArgsFind, RegexOptions.Compiled);
}
catch
{
throw new ArgumentException($"-Find 参数值不是有效的正式表达式,当前值:{ArgsFind}");
}
Console.WriteFormatted($@"
-Find={ArgsFind}
-ControllerNameSpace={ArgsOptions.ControllerNameSpace}
-ControllerRouteBase={ArgsOptions.ControllerRouteBase}
-ControllerBase={ArgsOptions.ControllerBase}
-First={ArgsFirst}
-Output={ArgsOutput}
", Color.DarkGray);
var dllFiles = new List<string>();
Console.WriteFormatted("正在发布当前项目(dotnet publish -r linux-x64) …\r\n", Color.DarkGreen);
var shellret = ShellRun(null, "dotnet publish -r linux-x64");
if (!string.IsNullOrEmpty(shellret.err))
{
Console.WriteFormatted(shellret.err + "\r\n\r\n", Color.Red);
return;
}
if (!string.IsNullOrEmpty(shellret.info))
{
Console.WriteFormatted(shellret.info + "\r\n\r\n", Color.DarkGray);
if (int.TryParse(Regex.Match(shellret.info, @"(\d+) 个错误").Groups[1].Value, out var tryint) && tryint > 0)
return;
}
var lines = shellret.info.Split('\n');
var publishDir = lines.Where(a => a.Contains(" -> ") && a.TrimEnd('/', '\\').EndsWith("publish")).Select(a => a.Substring(a.IndexOf(" -> ") + 4).Trim()).LastOrDefault();
dllFiles.AddRange(lines.Where(a => a.Contains(" -> ") && a.Trim().EndsWith(".dll")).Select(a => publishDir + a.Trim().Split('/', '\\').LastOrDefault()));
Console.WriteFormatted("正在创建临时项目 …\r\n", Color.DarkGreen);
var tmpdir = Path.Combine(Path.GetTempPath(), "temp_freesql_adminlte_tools");
Action<string, string> writeTmpFile = (path, content) =>
{
var filename = $"{tmpdir}/{path.TrimStart('/', '\\')}";
Directory.CreateDirectory(Path.GetDirectoryName(filename));
using (StreamWriter sw = new StreamWriter(filename, false, Encoding.UTF8))
{
sw.Write(content);
sw.Close();
}
Console.WriteFormatted($"OUT -> {filename}\r\n", Color.DarkGray);
};
var currentCsproj = Directory.GetFiles(Directory.GetCurrentDirectory(), "*.csproj").FirstOrDefault();
var currentVersion = "netcoreapp3.1";
if (!string.IsNullOrEmpty(currentCsproj))
{
var csprojContent = File.ReadAllText(currentCsproj);
currentVersion = Regex.Match(csprojContent, @"<TargetFramework>([^<]+)</TargetFramework>")?.Groups[1].Value;
}
if (string.IsNullOrEmpty(currentVersion)) currentVersion = "netcoreapp3.1";
writeTmpFile("temp_freesql_adminlte_tools.csproj", $@"<Project Sdk=""Microsoft.NET.Sdk"">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>{currentVersion}</TargetFramework>
</PropertyGroup>
<ItemGroup>
<PackageReference Include=""FreeSql.Provider.Sqlite"" Version=""3.2.808"" />
<PackageReference Include=""FreeSql.AdminLTE"" Version=""3.2.808"" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include=""{currentCsproj}"" />
</ItemGroup>
</Project>
");
writeTmpFile("Program.cs", $@"using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text.RegularExpressions;
namespace temp_freesql_adminlte_tools
{{
class Program
{{
static void Main(string[] args)
{{
var findRegexp = new Regex(@""{ArgsFind.Replace("\"", "\"\"")}"", RegexOptions.Compiled);
var entityTypes = new List<Type>();
foreach (var dllFile in new [] {{ @""{string.Join("\", @\"", dllFiles.Select(a => a.Replace("\"", "\"\"")))}"" }}) {{
var assembly = Assembly.LoadFrom(dllFile);
var alltypes = assembly.ExportedTypes;//.GetTypes();
foreach (var type in alltypes)
{{
if (type.IsClass && !type.IsInterface && !type.IsAbstract && !type.IsAnonymousType() &&
!type.IsEnum && !type.IsGenericType && !type.IsImport &&
!type.IsNested && !type.IsSealed && !type.IsValueType && type.IsVisible &&
findRegexp.IsMatch(type.FullName))
{{
Console.WriteLine($""READY -> {{type.FullName}}"");
entityTypes.Add(type);
}}
}}
}}
using (var gen = new FreeSql.AdminLTE.Generator(new FreeSql.AdminLTE.GeneratorOptions
{{
ControllerBase = @""{ArgsOptions.ControllerBase.Replace("\"", "\"\"")}"",
ControllerNameSpace = @""{ArgsOptions.ControllerNameSpace.Replace("\"", "\"\"")}"",
ControllerRouteBase = @""{ArgsOptions.ControllerRouteBase.Replace("\"", "\"\"")}""
}}))
{{
var method = entityTypes?.Select(a => a.Assembly.GetType(""FreeSql.BaseEntity"")?.GetMethods().First(a => a.Name == ""Initialization"" && a.GetParameters().FirstOrDefault()?.ParameterType.FullName == ""IFreeSql""))
.Where(a => a != null).FirstOrDefault();
method?.Invoke(null, method.GetParameters().Select(a => a.ParameterType.FullName == ""IFreeSql"" ? (object)gen.Orm : (object)null).ToArray());
gen.TraceLog = log => Console.WriteLine(log);
gen.Build(@""{ArgsOutput.Replace("\"", "\"\"")}"", entityTypes.ToArray(), {(ArgsFirst ? "true" : "false")});
}}
Console.Write($""--freesql_adminlte_tools_success--"");
}}
}}
}}
");
Console.WriteFormatted("\r\n正在运行生成程序 …\r\n", Color.DarkGreen);
shellret = ShellRun(tmpdir, "dotnet run");
if (!string.IsNullOrEmpty(shellret.err))
{
Console.WriteFormatted(shellret.err + "\r\n\r\n", Color.Red);
return;
}
if (!string.IsNullOrEmpty(shellret.info))
{
if (!shellret.info.Trim().EndsWith("--freesql_adminlte_tools_success--"))
Console.WriteFormatted(shellret.info + "\r\n\r\n", Color.DarkGray);
else
{
var infolines = shellret.info.Trim().Split('\n');
foreach(var infoline in infolines)
{
if (infoline.TrimStart().StartsWith("READY -> "))
Console.WriteFormatted(infoline.Trim() + "\r\n", Color.Magenta);
else if (infoline.TrimStart().StartsWith("OUT -> "))
Console.WriteFormatted(infoline.Trim() + "\r\n", Color.DarkGray);
else if (string.IsNullOrEmpty(infoline.TrimStart()))
Console.WriteFormatted("\r\n", Color.DarkGray);
}
}
}
GC.Collect();
Console.WriteFormatted("\r\n[" + DateTime.Now.ToString("MM-dd HH:mm:ss") + "] The code files be maked in \"" + ArgsOutput + "\", please check.\r\n", Color.DarkGreen);
}
public static (string info, string warn, string err) ShellRun(string cddir, params string[] bat) {
if (bat == null || bat.Any() == false) return ("", "", "");
if (string.IsNullOrEmpty(cddir)) cddir = Directory.GetCurrentDirectory();
var proc = new System.Diagnostics.Process();
proc.StartInfo = new System.Diagnostics.ProcessStartInfo {
CreateNoWindow = true,
FileName = "cmd.exe",
UseShellExecute = false,
RedirectStandardError = true,
RedirectStandardInput = true,
RedirectStandardOutput = true,
WorkingDirectory = cddir
};
proc.Start();
foreach (var cmd in bat)
proc.StandardInput.WriteLine(cmd);
proc.StandardInput.WriteLine("exit");
var outStr = proc.StandardOutput.ReadToEnd();
var errStr = proc.StandardError.ReadToEnd();
proc.Close();
var idx = outStr.IndexOf($">{bat[0]}");
if (idx != -1) {
idx = outStr.IndexOf("\n", idx);
if (idx != -1) outStr = outStr.Substring(idx + 1);
}
idx = outStr.LastIndexOf(">exit");
if (idx != -1) {
idx = outStr.LastIndexOf("\n", idx);
if (idx != -1) outStr = outStr.Remove(idx);
}
outStr = outStr.Trim();
if (outStr == "") outStr = null;
if (errStr == "") errStr = null;
return (outStr, string.IsNullOrEmpty(outStr) ? null : errStr, string.IsNullOrEmpty(outStr) ? errStr : null);
}
}
}
|
297854895/vue-tsx-admin
| 2,986
|
src/layouts/BasicLayout/index.less
|
@import "~@/style/theme.less";
.basicLayout {
min-height: 100vh;
overflow: hidden;
flex-direction: row;
display: flex;
> aside {
transition: width .2s;
flex: none;
box-shadow: 2px 0 8px rgba(29, 35, 41, .05);
}
> section {
background: #f0f2f5;
}
.fixedLeftMenu {
> div {
display: flex;
position: fixed;
height: 100%;
width: inherit;
flex-direction: column;
.leftMenuWrap{
flex: 1;
width: 100%;
overflow-y: auto;
}
}
}
.contentLayout{
display: flex;
flex: 1;
flex-direction: column;
.fixedHeader {
position: fixed;
width: 100%;
top: 0;
right: 0;
overflow: hidden;
}
> header {
display: flex;
width: 100%;
z-index: 10;
height: 64px;
background: #fff;
padding: 0 16px 0 0;
transition: width .2s;
line-height: 64px;
box-shadow: 0 1px 4px rgba(0, 21, 41, 0.08);
z-index: 9;
.trigger {
font-size: 20px;
display: inline-block;
width: 64px;
line-height: 64px;
vertical-align: top;
transition: background-color .2s ease-out;
cursor: pointer;
}
.trigger:hover {
background: rgba(0, 0, 0, .1);
}
.trigger:active {
background: rgba(0, 0, 0, .2);
}
}
> main {
flex: 1;
}
}
}
.dark {
> aside {
background: #001529!important;
}
> section {
background: #f0f2f5;
}
}
.darkMenu{
:nth-child(2) {
> div {
> div {
background: #001529!important;
> div {
padding: 0;
}
}
}
}
}
.lightMenu {
:nth-child(2) {
> div {
> div {
background: #fff!important;
> div {
padding: 0;
}
}
}
}
}
.lightHeader {
position: relative;
background: #fff!important;
}
.darkHeader, {
position: relative;
background: #001529!important;
}
.mobileLogo {
font-size: 20px;
}
.siderMenuWrap {
border-right: 1px solid #e8e8e8!important;
box-shadow: 2px 0 8px 0 rgba(29, 35, 41, 0.5);
}
.siderMenu {
border-right: none!important;
}
.light {
.siderMenu {
width: calc(~"100% - 1px")!important;
}
}
.siderMenuTop {
line-height: 64px!important;
}
.navTop {
flex: 1;
height: inherit;
overflow: hidden;
}
.leftMenuWrap{
padding: 16px 0;
}
.light {
.leftMenuWrap {
border-right: 1px solid #e8e8e8;
}
}
.siderMenuTopDark {
width: 100%!important;
}
.notGlobalScroll {
display: flex;
flex: 1;
height: 100vh;
width: inherit;
overflow-x: hidden;
flex-direction: column;
> main {
flex: 1;
height: 100%;
width: inherit;
overflow: auto;
}
}
.topNavOwnerScroll {
>:last-child {
height: calc(~"100% - 54px")!important;
}
}
.contentTopNav{
flex-direction: column;
display: flex;
> div:nth-child(2) {
flex: 1;
overflow: auto;
}
}
.paddingTopHeader {
padding-top: 64px;
}
|
297854895/vue-tsx-admin
| 6,704
|
src/layouts/BasicLayout-ant-layout/index.tsx
|
import { Component, Vue } from 'vue-property-decorator'
import { Layout, Icon, Drawer } from 'ant-design-vue'
import { State, Action } from 'vuex-class'
import { siderMenu, deviceType, navLayout, tabMode, routesInfoMap, menuItem } from '@/store/types'
import { theme } from '@/store/types'
import { SiderMenu, Logo, TabTool, RightBox, TabManager } from '@/components'
import styles from './index.less'
const { Content, Sider, Header } = Layout
@Component
export default class BasicLayout extends Vue {
// 主题
@State('theme') theme: theme;
// 导航位置
@State('navLayout') navLayout: navLayout;
// 是否固定顶部
@State('fixedHeader') fixedHeader: boolean;
// 是否固定左侧menu
@State('fixedLeftMenu') fixedLeftMenu: boolean;
// 是否展示tab组件
@State('tabTool') tabTool: boolean;
// 当前激活状态的tab
@State('tabActive') tabActive : string;
// tab排列方式
@State('tabMode') tabMode: tabMode;
// 是否全局滚动
@State('globalScroll') globalScroll: boolean;
// 左侧siderMenu状态
@State('siderMenu') siderMenu: siderMenu;
// 菜单的MenuTree
@State('menuTree') menuTree: Array<menuItem>;
// 当前客户端类型
@State('deviceType') deviceType: deviceType;
// 路由信息
@State('routesInfoMap') routesInfoMap: routesInfoMap;
// 登录信息
@Action('handleTab') handleTab!: Function;
// 左侧menu展开二级菜单
@Action('openSiderSubMenu') openSiderSubMenu!: Function;
// 切换左侧menu的收折状态
@Action('toggleSiderMenuCollapsed') toggleSiderMenuCollapsed!: Function;
// 监听路由变化
protected mounted() {
this.$router.beforeEach(this.listenRouteChange)
// 验证路由
this.validateActiveRouter()
}
// 监听路由变化,统一维护tab的新增或者切换
listenRouteChange(
newpath: { [prospName: string]: any },
_oldpath: any,
next: Function
) {
if (this.routesInfoMap[newpath.name] && !this.routesInfoMap[newpath.name].public) {
this.handleTab({
id: newpath.name,
keyPath: newpath.path
})
}
next()
}
// 验证当前路由是否与当前active的tab一致,若不一致,进行active tab path跳转
validateActiveRouter() {
// 不一致
if (this.$route.name !== this.tabActive) this.$router.push({
name: this.tabActive
})
}
render() {
// 获取需要实用的状态
const {
theme,
tabMode,
tabTool,
menuTree,
navLayout,
tabActive,
deviceType,
fixedHeader,
globalScroll,
siderMenu: {
collapsed,
open
},
fixedLeftMenu
} = this
return <Layout>
{
// 非mobile设备
navLayout === 'left' || deviceType === 'mobile'
? (deviceType !== 'mobile'
? (<Sider
id="s_siderMenu"
theme={theme}
width="256"
class={`${theme === 'light' ? styles.siderMenuWrap : ''} ${fixedLeftMenu ? styles.fixedLeftMenu : ''}`}
trigger={null}
collapsible
collapsed={collapsed}>
<Logo type="menu" theme={theme} />
<div class={styles.leftMenuWrap}>
<SiderMenu
open={open}
theme={theme}
menu={menuTree}
tabActive={tabActive}
class={styles.siderMenu}
openSiderSubMenu={this.openSiderSubMenu} />
</div>
</Sider>)
: <Drawer
width="256"
placement="left"
closable={false}
visible={!collapsed}
wrapClassName={styles[theme]}
onClose={() => this.toggleSiderMenuCollapsed(deviceType)}>
<Logo type="menu" theme={theme} />
<SiderMenu
open={open}
theme={theme}
menu={menuTree}
tabActive={tabActive}
class={styles.siderMenu}
deviceType={this.deviceType}
closeMenu={() => this.toggleSiderMenuCollapsed(deviceType)}
openSiderSubMenu={this.openSiderSubMenu} />
</Drawer>
) : null
}
<Layout
class={ `${fixedHeader && !globalScroll ? styles.notGlobalScroll : ''}` }>
{
navLayout === 'left' || deviceType === 'mobile'
? <Header
style={ fixedHeader && globalScroll ? { width: `calc(100% - ${collapsed ? deviceType === 'mobile' ? 0 : 80 : 256}px)` } : {} }
class={`${styles.header} ${styles[theme+'Header']} ${fixedHeader && globalScroll ? styles.fixedHeader : ''}`}>
<Icon
title="切换"
class={styles.trigger}
type={deviceType === 'mobile' ? 'menu' : collapsed ? 'menu-unfold' : 'menu-fold'}
onClick={() => this.toggleSiderMenuCollapsed(deviceType)} />
{
deviceType === 'desktop'
? <TabTool
deviceType={deviceType}
mode={tabMode}
navLayout={navLayout}
show={tabTool} />
: null
}
<RightBox deviceType={deviceType} />
</Header>
: <Header
style={ navLayout === 'top' && !globalScroll ? { position: 'relative' } : {} }
class={`${styles.header} ${theme === 'light' ? styles.lightHeader : ''} ${fixedHeader ? styles.fixedHeader : ''}`}>
<Logo type="top" theme={theme} />
<div class={styles.navTop}>
<SiderMenu
top
theme={theme}
open={open}
menu={menuTree}
tabActive={tabActive}
class={`${styles.siderMenu} ${styles.siderMenuTop} ${theme === 'dark' ? styles.siderMenuTopDark : ''}`}
openSiderSubMenu={this.openSiderSubMenu} />
</div>
<RightBox
top
theme={theme}
deviceType={deviceType} />
</Header>
}
<Content
class={
`${navLayout === 'top' && deviceType === 'desktop' ? styles.contentTopNav : ''}
${fixedHeader && globalScroll ? styles.paddingTopHeader : ''}
${navLayout === 'top' && fixedHeader ? styles.topNavOwnerScroll : ''}
`
}>
{
navLayout === 'top'
&& deviceType === 'desktop'
? <TabTool
deviceType={deviceType}
mode={tabMode}
navLayout={navLayout}
show={tabTool} />
: deviceType !== 'desktop'
? <TabManager
menuCollapsed={collapsed}
deviceType={deviceType} /> : null
}
<transition name="router-fade">
<router-view></router-view>
</transition>
</Content>
</Layout>
</Layout>
}
}
|
2977094657/BiliHistoryFrontend
| 6,142
|
src/components/tailwind/VideoPlayerDialog.vue
|
<template>
<Teleport to="body">
<div v-if="show" class="fixed inset-0 z-[9999] flex items-center justify-center">
<!-- 遮罩层 -->
<div class="fixed inset-0 bg-black/80 backdrop-blur-sm" @click="handleClose"></div>
<!-- 视频播放器 -->
<div class="relative bg-black rounded-lg shadow-xl w-[90%] max-w-4xl max-h-[90vh] z-10 overflow-hidden">
<!-- 关闭按钮 -->
<button
@click="handleClose"
class="absolute right-4 top-4 text-white/70 hover:text-white z-20 bg-black/40 p-2 rounded-full"
>
<svg class="w-5 h-5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12" />
</svg>
</button>
<!-- 视频标题 -->
<div class="absolute top-0 left-0 right-0 p-4 bg-gradient-to-b from-black/80 to-transparent z-10">
<h3 class="text-white text-lg font-medium truncate">
{{ getFileName(videoPath) }}
</h3>
<div v-if="danmakuFile" class="text-green-400 text-xs mt-1 flex items-center">
<svg class="w-3.5 h-3.5 mr-1" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 13l4 4L19 7" />
</svg>
<span>已加载弹幕</span>
</div>
</div>
<!-- 视频播放器 -->
<div class="w-full h-full aspect-video max-h-[80vh] relative">
<!-- ArtPlayer播放器 -->
<div v-show="activeVideo" class="w-full h-full">
<ArtPlayerWithDanmaku
v-if="activeVideo"
ref="artPlayerRef"
:videoSrc="videoSrc"
:cid="currentCid"
:danmakuFilePath="danmakuFile"
:title="getFileName(videoPath)"
:autoplay="true"
:width="'100%'"
:height="'100%'"
/>
</div>
</div>
<!-- 错误提示 -->
<div v-if="error" class="absolute inset-0 flex items-center justify-center bg-black/90">
<div class="text-center p-6">
<svg class="w-16 h-16 text-red-500 mx-auto mb-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z" />
</svg>
<h3 class="text-xl font-medium text-white mb-2">视频播放失败</h3>
<p class="text-white/70 mb-4">{{ errorMessage }}</p>
<button
@click="handleClose"
class="px-4 py-2 bg-[#fb7299] text-white rounded-md hover:bg-[#fb7299]/90 transition-colors"
>
关闭
</button>
</div>
</div>
</div>
</div>
</Teleport>
</template>
<script setup>
import { ref, computed, watch, onMounted, onUnmounted, nextTick } from 'vue'
import { getVideoStream, getDanmakuFile } from '../../api/api'
import ArtPlayerWithDanmaku from './ArtPlayerWithDanmaku.vue'
defineOptions({
name: 'VideoPlayerDialog'
})
const props = defineProps({
show: {
type: Boolean,
default: false
},
videoPath: {
type: String,
default: ''
}
})
const emit = defineEmits(['update:show'])
// 播放器引用
const artPlayerRef = ref(null)
const isLoading = ref(false)
const activeVideo = ref(false)
const videoSrc = ref('')
const danmakuFile = ref('')
const currentCid = ref('')
// 错误状态
const error = ref(false)
const errorMessage = ref('')
// 获取文件名
const getFileName = (path) => {
if (!path) return '未知文件'
return path.split('\\').pop().split('/').pop() || '未知文件'
}
// 从视频路径中提取CID
const extractCid = (path) => {
if (!path) return ''
// 尝试从文件名中提取CID
const fileName = getFileName(path)
const cidMatch = fileName.match(/_(\d+)\.mp4$/) || fileName.match(/_(\d+)\.flv$/) || fileName.match(/_(\d+)\.m4a$/)
if (cidMatch && cidMatch[1]) {
return cidMatch[1]
}
// 如果文件名中没有CID,尝试从目录路径中提取
const dirMatch = path.match(/(\d{8,})/)
return dirMatch ? dirMatch[1] : ''
}
// 获取弹幕文件路径
const findDanmakuFile = (videoPath) => {
if (!videoPath) return ''
// 根据视频文件路径推断弹幕文件路径
const fileNameWithoutExt = videoPath.replace(/\.(mp4|flv|m4a)$/i, '')
return `${fileNameWithoutExt}.ass`
}
// 处理播放错误
const handlePlayError = (error) => {
console.error('视频播放错误:', error)
isLoading.value = false
error.value = true
errorMessage.value = `无法播放视频,错误信息: ${error?.message || '未知错误'}`
}
// 销毁播放器
const destroyPlayer = () => {
if (artPlayerRef.value && artPlayerRef.value.player) {
artPlayerRef.value.player.destroy()
}
// 重置变量
videoSrc.value = ''
danmakuFile.value = ''
currentCid.value = ''
activeVideo.value = false
}
// 关闭对话框
const handleClose = () => {
// 销毁播放器
destroyPlayer()
// 重置错误状态
error.value = false
errorMessage.value = ''
isLoading.value = false
// 通知父组件关闭对话框
emit('update:show', false)
}
// 加载视频
const loadVideo = () => {
if (!props.videoPath) return
// 确保之前的播放器已被销毁
destroyPlayer()
// 提取CID
currentCid.value = extractCid(props.videoPath)
// 查找弹幕文件
danmakuFile.value = findDanmakuFile(props.videoPath)
// 使用api生成视频流URL
videoSrc.value = getVideoStream(props.videoPath)
// 激活视频元素
nextTick(() => {
activeVideo.value = true
})
}
// 监听show变化
watch(() => props.show, (newVal) => {
if (newVal) {
// 对话框打开时加载视频
loadVideo()
} else {
// 对话框关闭时销毁播放器
destroyPlayer()
}
})
// 监听videoPath变化
watch(() => props.videoPath, (newVal) => {
if (props.show && newVal) {
// 如果对话框已打开并且视频路径变化,重新加载视频
loadVideo()
}
})
// 组件挂载时初始化
onMounted(() => {
if (props.show && props.videoPath) {
loadVideo()
}
})
// 组件卸载时清理资源
onUnmounted(() => {
destroyPlayer()
})
</script>
<style scoped>
/* 当对话框显示时禁用页面滚动 */
:deep(body) {
overflow: hidden;
}
.animate-spin {
animation: spin 1s linear infinite;
}
@keyframes spin {
from {
transform: rotate(0deg);
}
to {
transform: rotate(360deg);
}
}
</style>
|
297854895/vue-tsx-admin
| 1,939
|
src/layouts/BasicLayout-ant-layout/index.less
|
@import "~@/style/theme.less";
.dark {
:nth-child(2) {
> div {
> div {
background: #001529!important;
> div {
padding: 0;
}
}
}
}
}
.light {
:nth-child(2) {
> div {
> div {
background: #fff!important;
> div {
padding: 0;
}
}
}
}
}
.header {
display: flex;
padding: 0 16px 0 0;
box-shadow: 0 1px 4px rgba(0, 21, 41, 0.08);
transition: width .2s;
z-index: 10;
.trigger {
font-size: 20px;
display: inline-block;
width: 64px;
line-height: 64px;
vertical-align: top;
transition: background-color .2s ease-out;
cursor: pointer;
}
.trigger:hover {
background: rgba(0, 0, 0, .1);
}
.trigger:active {
background: rgba(0, 0, 0, .2);
}
}
.darkHeader, .lightHeader {
position: relative;
background: #fff!important;
}
.mobileLogo {
font-size: 20px;
}
.siderMenuWrap {
border-right: 1px solid #e8e8e8!important;
box-shadow: 2px 0 8px 0 rgba(29, 35, 41, 0.05);
ul {
width: calc(~"100% - 1px");
}
}
.siderMenu {
border-right: none!important;
}
.siderMenuTop {
line-height: 64px!important;
}
.navTop {
flex: 1;
height: inherit;
overflow: hidden;
}
.leftMenuWrap{
padding: 16px 0;
}
.fixedLeftMenu {
> div {
display: flex;
position: fixed;
height: 100%;
width: inherit;
flex-direction: column;
.leftMenuWrap{
flex: 1;
width: 100%;
overflow-y: auto;
}
}
}
.fixedHeader {
position: fixed;
width: 100%;
top: 0;
right: 0;
}
.notGlobalScroll {
display: flex;
flex: 1;
height: 100vh;
flex-direction: column;
> div:nth-child(2) {
flex: 1;
>:last-child {
height: 100%;
overflow: auto;
}
}
}
.topNavOwnerScroll {
>:last-child {
height: calc(~"100% - 54px")!important;
}
}
.contentTopNav{
flex-direction: column;
}
.paddingTopHeader {
padding-top: 64px;
}
|
281677160/openwrt-package
| 35,035
|
luci-app-passwall2/luasrc/passwall2/api.lua
|
module("luci.passwall2.api", package.seeall)
local com = require "luci.passwall2.com"
bin = require "nixio".bin
fs = require "nixio.fs"
sys = require "luci.sys"
uci = require"luci.model.uci".cursor()
util = require "luci.util"
datatypes = require "luci.cbi.datatypes"
jsonc = require "luci.jsonc"
i18n = require "luci.i18n"
appname = "passwall2"
curl_args = { "-skfL", "--connect-timeout 3", "--retry 3" }
command_timeout = 300
OPENWRT_ARCH = nil
DISTRIB_ARCH = nil
LOG_FILE = "/tmp/log/passwall2.log"
CACHE_PATH = "/tmp/etc/passwall2_tmp"
TMP_PATH = "/tmp/etc/" .. appname
TMP_IFACE_PATH = TMP_PATH .. "/iface"
function log(...)
local result = os.date("%Y-%m-%d %H:%M:%S: ") .. table.concat({...}, " ")
local f, err = io.open(LOG_FILE, "a")
if f and err == nil then
f:write(result .. "\n")
f:close()
end
end
function is_old_uci()
return sys.call("grep -E 'require[ \t]*\"uci\"' /usr/lib/lua/luci/model/uci.lua >/dev/null 2>&1") == 0
end
function uci_save(cursor, config, commit, apply)
if is_old_uci() then
cursor:save(config)
if commit then
cursor:commit(config)
if apply then
sys.call("/etc/init.d/" .. config .. " reload > /dev/null 2>&1 &")
end
end
else
commit = true
if commit then
if apply then
cursor:commit(config)
else
sh_uci_commit(config)
end
end
end
end
function sh_uci_get(config, section, option)
local _, val = exec_call(string.format("uci -q get %s.%s.%s", config, section, option))
return val
end
function sh_uci_set(config, section, option, val, commit)
exec_call(string.format("uci -q set %s.%s.%s=\"%s\"", config, section, option, val))
if commit then sh_uci_commit(config) end
end
function sh_uci_del(config, section, option, commit)
exec_call(string.format("uci -q delete %s.%s.%s", config, section, option))
if commit then sh_uci_commit(config) end
end
function sh_uci_add_list(config, section, option, val, commit)
exec_call(string.format("uci -q del_list %s.%s.%s=\"%s\"", config, section, option, val))
exec_call(string.format("uci -q add_list %s.%s.%s=\"%s\"", config, section, option, val))
if commit then sh_uci_commit(config) end
end
function sh_uci_commit(config)
exec_call(string.format("uci -q commit %s", config))
end
function set_cache_var(key, val)
sys.call(string.format('/usr/share/passwall2/app.sh set_cache_var %s "%s"', key, val))
end
function get_cache_var(key)
local val = sys.exec(string.format('echo -n $(/usr/share/passwall2/app.sh get_cache_var %s)', key))
if val == "" then val = nil end
return val
end
function exec_call(cmd)
local process = io.popen(cmd .. '; echo -e "\n$?"')
local lines = {}
local result = ""
local return_code
for line in process:lines() do
lines[#lines + 1] = line
end
process:close()
if #lines > 0 then
return_code = lines[#lines]
for i = 1, #lines - 1 do
result = result .. lines[i] .. ((i == #lines - 1) and "" or "\n")
end
end
return tonumber(return_code), trim(result)
end
function base64Decode(text)
local raw = text
if not text then return '' end
text = text:gsub("%z", "")
text = text:gsub("%c", "")
text = text:gsub("_", "/")
text = text:gsub("-", "+")
local mod4 = #text % 4
text = text .. string.sub('====', mod4 + 1)
local result = nixio.bin.b64decode(text)
if result then
return result:gsub("%z", "")
else
return raw
end
end
function base64Encode(text)
local result = nixio.bin.b64encode(text)
return result
end
--提取URL中的域名和端口(no ip)
function get_domain_port_from_url(url)
local scheme, domain, port = string.match(url, "^(https?)://([%w%.%-]+):?(%d*)")
if not domain then
scheme, domain, port = string.match(url, "^(https?)://(%b[])([^:/]*)/?")
end
if not domain then return nil, nil end
if domain:sub(1, 1) == "[" then domain = domain:sub(2, -2) end
port = port ~= "" and tonumber(port) or (scheme == "https" and 443 or 80)
if datatypes.ipaddr(domain) or datatypes.ip6addr(domain) then return nil, nil end
return domain, port
end
--解析域名
function domainToIPv4(domain, dns)
local Dns = dns or "223.5.5.5"
local IPs = luci.sys.exec('nslookup %s %s | awk \'/^Name:/{getline; if ($1 == "Address:") print $2}\'' % { domain, Dns })
for IP in string.gmatch(IPs, "%S+") do
if datatypes.ipaddr(IP) and not datatypes.ip6addr(IP) then return IP end
end
return nil
end
function curl_base(url, file, args)
if not args then args = {} end
if file then
args[#args + 1] = "-o " .. file
end
local cmd = string.format('curl %s "%s"', table_join(args), url)
return exec_call(cmd)
end
function curl_proxy(url, file, args)
--使用代理
local socks_server = get_cache_var("GLOBAL_SOCKS_server")
if socks_server and socks_server ~= "" then
if not args then args = {} end
local tmp_args = clone(args)
tmp_args[#tmp_args + 1] = "-x socks5h://" .. socks_server
return curl_base(url, file, tmp_args)
end
return nil, nil
end
function curl_logic(url, file, args)
local return_code, result = curl_proxy(url, file, args)
if not return_code or return_code ~= 0 then
return_code, result = curl_base(url, file, args)
end
return return_code, result
end
function curl_direct(url, file, args)
--直连访问
if not args then args = {} end
local tmp_args = clone(args)
local domain, port = get_domain_port_from_url(url)
if domain then
local ip = domainToIPv4(domain)
if ip then
tmp_args[#tmp_args + 1] = "--resolve " .. domain .. ":" .. port .. ":" .. ip
end
end
return curl_base(url, file, tmp_args)
end
function curl_auto(url, file, args)
local localhost_proxy = uci:get(appname, "@global[0]", "localhost_proxy") or "1"
if localhost_proxy == "1" then
return curl_base(url, file, args)
else
local return_code, result = curl_proxy(url, file, args)
if not return_code or return_code ~= 0 then
return_code, result = curl_direct(url, file, args)
end
return return_code, result
end
end
function url(...)
local url = string.format("admin/services/%s", appname)
local args = { ... }
for i, v in pairs(args) do
if v ~= "" then
url = url .. "/" .. v
end
end
return require "luci.dispatcher".build_url(url)
end
function trim(text)
if not text or text == "" then return "" end
return text:match("^%s*(.-)%s*$")
end
-- 分割字符串
function split(full, sep)
if full then
full = full:gsub("%z", "") -- 这里不是很清楚 有时候结尾带个\0
local off, result = 1, {}
while true do
local nStart, nEnd = full:find(sep, off)
if not nEnd then
local res = string.sub(full, off, string.len(full))
if #res > 0 then -- 过滤掉 \0
table.insert(result, res)
end
break
else
table.insert(result, string.sub(full, off, nStart - 1))
off = nEnd + 1
end
end
return result
end
return {}
end
function is_exist(table, value)
for index, k in ipairs(table) do
if k == value then
return true
end
end
return false
end
function repeat_exist(table, value)
local count = 0
for index, k in ipairs(table) do
if k:find("-") and k == value then
count = count + 1
end
end
if count > 1 then
return true
end
return false
end
function remove(...)
for index, value in ipairs({...}) do
if value and #value > 0 and value ~= "/" then
sys.call(string.format("rm -rf %s", value))
end
end
end
function is_install(package)
if package and #package > 0 then
local file_path = "/usr/lib/opkg/info"
local file_ext = ".control"
local has = sys.call("[ -d " .. file_path .. " ]")
if has ~= 0 then
file_path = "/lib/apk/packages"
file_ext = ".list"
end
return sys.call(string.format('[ -s "%s/%s%s" ]', file_path, package, file_ext)) == 0
end
return false
end
function get_args(arg)
local var = {}
for i, arg_k in pairs(arg) do
if i > 0 then
local v = arg[i + 1]
if v then
if repeat_exist(arg, v) == false then
var[arg_k] = v
end
end
end
end
return var
end
function get_function_args(arg)
local var = nil
if arg and #arg > 1 then
local param = {}
for i = 2, #arg do
param[#param + 1] = arg[i]
end
var = get_args(param)
end
return var
end
function strToTable(str)
if str == nil or type(str) ~= "string" then
return {}
end
return loadstring("return " .. str)()
end
function is_normal_node(e)
if e and e.type and e.protocol and (e.protocol == "_balancing" or e.protocol == "_shunt" or e.protocol == "_iface" or e.protocol == "_urltest") then
return false
end
return true
end
function is_special_node(e)
return is_normal_node(e) == false
end
function is_ip(val)
if is_ipv6(val) then
val = get_ipv6_only(val)
end
return datatypes.ipaddr(val)
end
function is_ipv6(val)
local str = val
local address = val:match('%[(.*)%]')
if address then
str = address
end
if datatypes.ip6addr(str) then
return true
end
return false
end
function is_ipv6addrport(val)
if is_ipv6(val) then
local address, port = val:match('%[(.*)%]:([^:]+)$')
if port then
return datatypes.port(port)
end
end
return false
end
function get_ipv6_only(val)
local result = ""
if is_ipv6(val) then
result = val
if val:match('%[(.*)%]') then
result = val:match('%[(.*)%]')
end
end
return result
end
function get_ipv6_full(val)
local result = ""
if is_ipv6(val) then
result = val
if not val:match('%[(.*)%]') then
result = "[" .. result .. "]"
end
end
return result
end
function get_ip_type(val)
if is_ipv6(val) then
return "6"
elseif datatypes.ip4addr(val) then
return "4"
end
return ""
end
function is_mac(val)
return datatypes.macaddr(val)
end
function ip_or_mac(val)
if val then
if get_ip_type(val) == "4" then
return "ip"
end
if is_mac(val) then
return "mac"
end
end
return ""
end
function iprange(val)
if val then
local ipStart, ipEnd = val:match("^([^/]+)-([^/]+)$")
if (ipStart and datatypes.ip4addr(ipStart)) and (ipEnd and datatypes.ip4addr(ipEnd)) then
return true
end
end
return false
end
function get_domain_from_url(url)
local domain = string.match(url, "//([^/]+)")
if domain then
return domain
end
return url
end
function get_node_name(node_id)
local e
if type(node_id) == "table" then
e = node_id
else
e = uci:get_all(appname, node_id)
end
if e then
if e.type and e.remarks then
if e.protocol and (e.protocol == "_balancing" or e.protocol == "_shunt" or e.protocol == "_iface") then
local type = e.type
if type == "sing-box" then type = "Sing-Box" end
local remark = "%s:[%s] " % {type .. " " .. i18n.translatef(e.protocol), e.remarks}
return remark
end
end
end
return ""
end
function get_valid_nodes()
local show_node_info = uci_get_type("global_other", "show_node_info") or "0"
local nodes = {}
uci:foreach(appname, "nodes", function(e)
e.id = e[".name"]
if e.type and e.remarks then
if e.protocol and (e.protocol == "_balancing" or e.protocol == "_shunt" or e.protocol == "_iface" or e.protocol == "_urltest") then
local type = e.type
if type == "sing-box" then type = "Sing-Box" end
e["remark"] = "%s:[%s] " % {type .. " " .. i18n.translatef(e.protocol), e.remarks}
e["node_type"] = "special"
nodes[#nodes + 1] = e
end
local port = e.port or e.hysteria_hop or e.hysteria2_hop
if port and e.address then
local address = e.address
if is_ip(address) or datatypes.hostname(address) then
local type = e.type
if (type == "sing-box" or type == "Xray") and e.protocol then
local protocol = e.protocol
if protocol == "vmess" then
protocol = "VMess"
elseif protocol == "vless" then
protocol = "VLESS"
elseif protocol == "shadowsocks" then
protocol = "SS"
elseif protocol == "shadowsocksr" then
protocol = "SSR"
elseif protocol == "wireguard" then
protocol = "WG"
elseif protocol == "hysteria" then
protocol = "HY"
elseif protocol == "hysteria2" then
protocol = "HY2"
elseif protocol == "anytls" then
protocol = "AnyTLS"
elseif protocol == "ssh" then
protocol = "SSH"
else
protocol = protocol:gsub("^%l",string.upper)
end
if type == "sing-box" then type = "Sing-Box" end
type = type .. " " .. protocol
end
if is_ipv6(address) then address = get_ipv6_full(address) end
e["remark"] = "%s:[%s]" % {type, e.remarks}
if show_node_info == "1" then
port = port:gsub(":", "-")
e["remark"] = "%s:[%s] %s:%s" % {type, e.remarks, address, port}
end
e.node_type = "normal"
nodes[#nodes + 1] = e
end
end
end
end)
return nodes
end
function get_node_remarks(n)
local remarks = ""
if n then
if n.protocol and (n.protocol == "_balancing" or n.protocol == "_shunt" or n.protocol == "_iface" or n.protocol == "_urltest") then
remarks = "%s:[%s] " % {n.type .. " " .. i18n.translatef(n.protocol), n.remarks}
else
local type2 = n.type
if (n.type == "sing-box" or n.type == "Xray") and n.protocol then
local protocol = n.protocol
if protocol == "vmess" then
protocol = "VMess"
elseif protocol == "vless" then
protocol = "VLESS"
elseif protocol == "shadowsocks" then
protocol = "SS"
elseif protocol == "shadowsocksr" then
protocol = "SSR"
elseif protocol == "wireguard" then
protocol = "WG"
elseif protocol == "hysteria" then
protocol = "HY"
elseif protocol == "hysteria2" then
protocol = "HY2"
elseif protocol == "anytls" then
protocol = "AnyTLS"
elseif protocol == "ssh" then
protocol = "SSH"
else
protocol = protocol:gsub("^%l",string.upper)
end
if type2 == "sing-box" then type2 = "Sing-Box" end
type2 = type2 .. " " .. protocol
end
remarks = "%s:[%s]" % {type2, n.remarks}
end
end
return remarks
end
function get_full_node_remarks(n)
local remarks = get_node_remarks(n)
if #remarks > 0 then
local port = n.port or n.hysteria_hop or n.hysteria2_hop
if n.address and port then
port = port:gsub(":", "-")
remarks = remarks .. " " .. n.address .. ":" .. port
end
end
return remarks
end
function gen_uuid(format)
local uuid = sys.exec("echo -n $(cat /proc/sys/kernel/random/uuid)")
if format == nil then
uuid = string.gsub(uuid, "-", "")
end
return uuid
end
function gen_short_uuid()
return sys.exec("echo -n $(head /dev/urandom | tr -dc A-Za-z0-9 | head -c 8)")
end
function uci_get_type(type, config, default)
local value = uci:get_first(appname, type, config, default) or sys.exec("echo -n $(uci -q get " .. appname .. ".@" .. type .."[0]." .. config .. ")")
if (value == nil or value == "") and (default and default ~= "") then
value = default
end
return value
end
function uci_get_type_id(id, config, default)
local value = uci:get(appname, id, config, default) or sys.exec("echo -n $(uci -q get " .. appname .. "." .. id .. "." .. config .. ")")
if (value == nil or value == "") and (default and default ~= "") then
value = default
end
return value
end
function chmod_755(file)
if file and file ~= "" then
if not fs.access(file, "rwx", "rx", "rx") then
fs.chmod(file, 755)
end
end
end
function get_customed_path(e)
return uci_get_type("global_app", e .. "_file")
end
function finded_com(e)
local bin = get_app_path(e)
if not bin then return end
local s = luci.sys.exec('echo -n $(type -t -p "%s" | head -n1)' % { bin })
if s == "" then
s = nil
end
return s
end
function finded(e)
return luci.sys.exec('echo -n $(type -t -p "/bin/%s" -p "/usr/bin/%s" "%s" | head -n1)' % {e, e, e})
end
function is_finded(e)
return finded(e) ~= "" and true or false
end
function clone(org)
local function copy(org, res)
for k,v in pairs(org) do
if type(v) ~= "table" then
res[k] = v;
else
res[k] = {};
copy(v, res[k])
end
end
end
local res = {}
copy(org, res)
return res
end
local function get_bin_version_cache(file, cmd)
sys.call("mkdir -p /tmp/etc/passwall2_tmp")
if fs.access(file) then
chmod_755(file)
local md5 = sys.exec("echo -n $(md5sum " .. file .. " | awk '{print $1}')")
if fs.access("/tmp/etc/passwall2_tmp/" .. md5) then
return sys.exec("echo -n $(cat /tmp/etc/passwall2_tmp/%s)" % md5)
else
local version = sys.exec(string.format("echo -n $(%s %s)", file, cmd))
if version and version ~= "" then
sys.call("echo '" .. version .. "' > " .. "/tmp/etc/passwall2_tmp/" .. md5)
return version
end
end
end
return ""
end
function get_app_path(app_name)
if com[app_name] then
local def_path = com[app_name].default_path
local path = uci_get_type("global_app", app_name:gsub("%-","_") .. "_file")
path = path and (#path>0 and path or def_path) or def_path
return path
end
end
function get_app_version(app_name, file)
if file == nil then file = get_app_path(app_name) end
return get_bin_version_cache(file, com[app_name].cmd_version)
end
function is_file(path)
if path and #path > 1 then
if sys.exec('[ -f "%s" ] && echo -n 1' % path) == "1" then
return true
end
end
return nil
end
function is_dir(path)
if path and #path > 1 then
if sys.exec('[ -d "%s" ] && echo -n 1' % path) == "1" then
return true
end
end
return nil
end
function get_final_dir(path)
if is_dir(path) then
return path
else
return get_final_dir(fs.dirname(path))
end
end
function get_free_space(dir)
if dir == nil then dir = "/" end
if sys.call("df -k " .. dir .. " >/dev/null 2>&1") == 0 then
return tonumber(sys.exec("echo -n $(df -k " .. dir .. " | awk 'NR>1' | awk '{print $4}')"))
end
return 0
end
function get_file_space(file)
if file == nil then return 0 end
if fs.access(file) then
return tonumber(sys.exec("echo -n $(du -k " .. file .. " | awk '{print $1}')"))
end
return 0
end
function _unpack(t, i)
i = i or 1
if t[i] ~= nil then return t[i], _unpack(t, i + 1) end
end
function table_join(t, s)
if not s then
s = " "
end
local str = ""
for index, value in ipairs(t) do
str = str .. t[index] .. (index == #t and "" or s)
end
return str
end
function exec(cmd, args, writer, timeout)
local os = require "os"
local nixio = require "nixio"
local fdi, fdo = nixio.pipe()
local pid = nixio.fork()
if pid > 0 then
fdo:close()
if writer or timeout then
local starttime = os.time()
while true do
if timeout and os.difftime(os.time(), starttime) >= timeout then
nixio.kill(pid, nixio.const.SIGTERM)
return 1
end
if writer then
local buffer = fdi:read(2048)
if buffer and #buffer > 0 then
writer(buffer)
end
end
local wpid, stat, code = nixio.waitpid(pid, "nohang")
if wpid and stat == "exited" then return code end
if not writer and timeout then nixio.nanosleep(1) end
end
else
local wpid, stat, code = nixio.waitpid(pid)
return wpid and stat == "exited" and code
end
elseif pid == 0 then
nixio.dup(fdo, nixio.stdout)
fdi:close()
fdo:close()
nixio.exece(cmd, args, nil)
nixio.stdout:close()
os.exit(1)
end
end
function parseURL(url)
if not url or url == "" then
return nil
end
local pattern = "^(%w+)://"
local protocol = url:match(pattern)
if not protocol then
--error("Invalid URL: " .. url)
return nil
end
local auth_host_port = url:sub(#protocol + 4)
local auth_pattern = "^([^@]+)@"
local auth = auth_host_port:match(auth_pattern)
local username, password
if auth then
username, password = auth:match("^([^:]+):([^:]+)$")
auth_host_port = auth_host_port:sub(#auth + 2)
end
local host, port = auth_host_port:match("^([^:]+):(%d+)$")
if not host or not port then
--error("Invalid URL: " .. url)
return nil
end
return {
protocol = protocol,
username = username,
password = password,
host = host,
port = tonumber(port)
}
end
function compare_versions(ver1, comp, ver2)
local table = table
if not ver1 then ver1 = "" end
if not ver2 then ver2 = "" end
local av1 = util.split(ver1, "[%.%-]", nil, true)
local av2 = util.split(ver2, "[%.%-]", nil, true)
local max = table.getn(av1)
local n2 = table.getn(av2)
if (max < n2) then max = n2 end
for i = 1, max, 1 do
local s1 = tonumber(av1[i] or 0) or 0
local s2 = tonumber(av2[i] or 0) or 0
if comp == "~=" and (s1 ~= s2) then return true end
if (comp == "<" or comp == "<=") and (s1 < s2) then return true end
if (comp == ">" or comp == ">=") and (s1 > s2) then return true end
if (s1 ~= s2) then return false end
end
return not (comp == "<" or comp == ">")
end
local function auto_get_arch()
local arch = nixio.uname().machine or ""
if not OPENWRT_ARCH and fs.access("/usr/lib/os-release") then
OPENWRT_ARCH = sys.exec("echo -n $(grep 'OPENWRT_ARCH' /usr/lib/os-release | awk -F '[\\042\\047]' '{print $2}')")
if OPENWRT_ARCH == "" then OPENWRT_ARCH = nil end
end
if not DISTRIB_ARCH and fs.access("/etc/openwrt_release") then
DISTRIB_ARCH = sys.exec("echo -n $(grep 'DISTRIB_ARCH' /etc/openwrt_release | awk -F '[\\042\\047]' '{print $2}')")
if DISTRIB_ARCH == "" then DISTRIB_ARCH = nil end
end
if arch:match("^i[%d]86$") then
arch = "x86"
elseif arch:match("armv5") then -- armv5l
arch = "armv5"
elseif arch:match("armv6") then
arch = "armv6"
elseif arch:match("armv7") then -- armv7l
arch = "armv7"
end
if OPENWRT_ARCH or DISTRIB_ARCH then
if arch == "mips" then
if OPENWRT_ARCH and OPENWRT_ARCH:match("mipsel") == "mipsel"
or DISTRIB_ARCH and DISTRIB_ARCH:match("mipsel") == "mipsel" then
arch = "mipsel"
end
elseif arch == "armv7" then
if OPENWRT_ARCH and not OPENWRT_ARCH:match("vfp") and not OPENWRT_ARCH:match("neon")
or DISTRIB_ARCH and not DISTRIB_ARCH:match("vfp") and not DISTRIB_ARCH:match("neon") then
arch = "armv5"
end
end
end
return trim(arch)
end
local default_file_tree = {
x86_64 = "amd64",
x86 = "386",
aarch64 = "arm64",
rockchip = "arm64",
mips = "mips",
mips64 = "mips64",
mipsel = "mipsel",
mips64el = "mips64el",
armv5 = "arm.*5",
armv6 = "arm.*6[^4]*",
armv7 = "arm.*7",
armv8 = "arm64",
riscv64 = "riscv64"
}
function get_api_json(url)
local jsonc = require "luci.jsonc"
local return_code, content = curl_logic(url, nil, curl_args)
if return_code ~= 0 or content == "" then return {} end
return jsonc.parse(content) or {}
end
local function check_path(app_name)
local path = get_app_path(app_name) or ""
if path == "" then
return {
code = 1,
error = i18n.translatef("You did not fill in the %s path. Please save and apply then update manually.", app_name)
}
end
return {
code = 0,
app_path = path
}
end
function to_check(arch, app_name)
local result = check_path(app_name)
if result.code ~= 0 then
return result
end
if not arch or arch == "" then arch = auto_get_arch() end
local file_tree = com[app_name].file_tree[arch] or default_file_tree[arch] or ""
if file_tree == "" then
return {
code = 1,
error = i18n.translate("Can't determine ARCH, or ARCH not supported.")
}
end
local local_version = get_app_version(app_name)
local match_file_name = string.format(com[app_name].match_fmt_str, file_tree)
local json = get_api_json(com[app_name]:get_url())
if #json > 0 then
json = json[1]
end
if json.tag_name == nil then
return {
code = 1,
error = i18n.translate("Get remote version info failed.")
}
end
local remote_version = json.tag_name
if com[app_name].remote_version_str_replace then
remote_version = remote_version:gsub(com[app_name].remote_version_str_replace, "")
end
local has_update = compare_versions(local_version:match("[^v]+"), "<", remote_version:match("[^v]+"))
--[[
if not has_update then
return {
code = 0,
local_version = local_version,
remote_version = remote_version
}
end
]]
local asset = {}
for _, v in ipairs(json.assets) do
if v.name and v.name:match(match_file_name) then
asset = v
break
end
end
if not asset.browser_download_url then
return {
code = 1,
local_version = local_version,
remote_version = remote_version,
html_url = json.html_url,
data = asset,
error = i18n.translate("New version found, but failed to get new version download url.")
}
end
return {
code = 0,
has_update = has_update,
local_version = local_version,
remote_version = remote_version,
html_url = json.html_url,
data = asset
}
end
function to_download(app_name, url, size)
local result = check_path(app_name)
if result.code ~= 0 then
return result
end
if not url or url == "" then
return {code = 1, error = i18n.translate("Download url is required.")}
end
sys.call("/bin/rm -f /tmp/".. app_name .."_download.*")
local tmp_file = trim(util.exec("mktemp -u -t ".. app_name .."_download.XXXXXX"))
if size then
local kb1 = get_free_space("/tmp")
if tonumber(size) > tonumber(kb1) then
return {code = 1, error = i18n.translatef("%s not enough space.", "/tmp")}
end
end
local _curl_args = clone(curl_args)
table.insert(_curl_args, "--speed-limit 51200 --speed-time 15 --max-time 300")
local return_code, result = curl_logic(url, tmp_file, _curl_args)
result = return_code == 0
if not result then
exec("/bin/rm", {"-f", tmp_file})
return {
code = 1,
error = i18n.translatef("File download failed or timed out: %s", url)
}
end
return {code = 0, file = tmp_file, zip = com[app_name].zipped }
end
function to_extract(app_name, file, subfix)
local result = check_path(app_name)
if result.code ~= 0 then
return result
end
if not file or file == "" or not fs.access(file) then
return {code = 1, error = i18n.translate("File path required.")}
end
local tools_name
if com[app_name].zipped then
if not com[app_name].zipped_suffix or com[app_name].zipped_suffix == "zip" then
tools_name = "unzip"
end
if com[app_name].zipped_suffix and com[app_name].zipped_suffix == "tar.gz" then
tools_name = "tar"
end
if tools_name then
if sys.exec("echo -n $(command -v %s)" % { tools_name }) == "" then
exec("/bin/rm", {"-f", file})
return {
code = 1,
error = i18n.translate("Not installed %s, Can't unzip!" % { tools_name })
}
end
end
end
sys.call("/bin/rm -rf /tmp/".. app_name .."_extract.*")
local new_file_size = get_file_space(file)
local tmp_free_size = get_free_space("/tmp")
if tmp_free_size <= 0 or tmp_free_size <= new_file_size then
return {code = 1, error = i18n.translatef("%s not enough space.", "/tmp")}
end
local tmp_dir = trim(util.exec("mktemp -d -t ".. app_name .."_extract.XXXXXX"))
local output = {}
if tools_name then
if tools_name == "unzip" then
local bin = sys.exec("echo -n $(command -v unzip)")
exec(bin, {"-o", file, app_name, "-d", tmp_dir}, function(chunk) output[#output + 1] = chunk end)
elseif tools_name == "tar" then
local bin = sys.exec("echo -n $(command -v tar)")
if com[app_name].zipped_suffix == "tar.gz" then
exec(bin, {"-zxf", file, "-C", tmp_dir}, function(chunk) output[#output + 1] = chunk end)
sys.call("/bin/mv -f " .. tmp_dir .. "/*/" .. com[app_name].name:lower() .. " " .. tmp_dir)
end
end
end
local files = util.split(table.concat(output))
exec("/bin/rm", {"-f", file})
return {code = 0, file = tmp_dir}
end
function to_move(app_name,file)
local result = check_path(app_name)
if result.code ~= 0 then
return result
end
local app_path = result.app_path
local bin_path = file
local cmd_rm_tmp = "/bin/rm -rf /tmp/" .. app_name .. "_download.*"
if fs.stat(file, "type") == "dir" then
bin_path = file .. "/" .. com[app_name].name:lower()
cmd_rm_tmp = "/bin/rm -rf /tmp/" .. app_name .. "_extract.*"
end
if not file or file == "" then
sys.call(cmd_rm_tmp)
return {code = 1, error = i18n.translate("Client file is required.")}
end
local new_version = get_app_version(app_name, bin_path)
if new_version == "" then
sys.call(cmd_rm_tmp)
return {
code = 1,
error = i18n.translate("The client file is not suitable for current device.")..app_name.."__"..bin_path
}
end
local flag = sys.call('pgrep -af "passwall2/.*'.. app_name ..'" >/dev/null')
if flag == 0 then
sys.call("/etc/init.d/passwall2 stop")
end
local old_app_size = 0
if fs.access(app_path) then
old_app_size = get_file_space(app_path)
end
local new_app_size = get_file_space(bin_path)
local final_dir = get_final_dir(app_path)
local final_dir_free_size = get_free_space(final_dir)
if final_dir_free_size > 0 then
final_dir_free_size = final_dir_free_size + old_app_size
if new_app_size > final_dir_free_size then
sys.call(cmd_rm_tmp)
return {code = 1, error = i18n.translatef("%s not enough space.", final_dir)}
end
end
result = exec("/bin/mv", { "-f", bin_path, app_path }, nil, command_timeout) == 0
sys.call(cmd_rm_tmp)
if flag == 0 then
sys.call("/etc/init.d/passwall2 restart >/dev/null 2>&1 &")
end
if not result or not fs.access(app_path) then
return {
code = 1,
error = i18n.translatef("Can't move new file to path: %s", app_path)
}
end
return {code = 0}
end
function get_version()
local version = sys.exec("opkg list-installed luci-app-passwall2 2>/dev/null | awk '{print $3}'")
if not version or #version == 0 then
version = sys.exec("apk list luci-app-passwall2 2>/dev/null | awk '/installed/ {print $1}' | cut -d'-' -f4-")
end
return version or ""
end
function to_check_self()
local url = "https://raw.githubusercontent.com/xiaorouji/openwrt-passwall2/main/luci-app-passwall2/Makefile"
local tmp_file = "/tmp/passwall2_makefile"
local return_code, result = curl_logic(url, tmp_file, curl_args)
result = return_code == 0
if not result then
exec("/bin/rm", {"-f", tmp_file})
return {
code = 1,
error = i18n.translatef("Failed")
}
end
local local_version = get_version()
local remote_version = sys.exec("echo -n $(grep 'PKG_VERSION' /tmp/passwall2_makefile|awk -F '=' '{print $2}')")
.. "-" .. sys.exec("echo -n $(grep 'PKG_RELEASE' /tmp/passwall2_makefile|awk -F '=' '{print $2}')")
local has_update = compare_versions(local_version, "<", remote_version)
if not has_update then
return {
code = 0,
local_version = local_version,
remote_version = remote_version
}
end
return {
code = 1,
has_update = true,
local_version = local_version,
remote_version = remote_version,
error = i18n.translatef("The latest version: %s, currently does not support automatic update, if you need to update, please compile or download the ipk and then manually install.", remote_version)
}
end
function cacheFileCompareToLogic(file, str)
local result = nil
if file and str then
local file_str = ""
if fs.access(file) then
file_str = sys.exec("cat " .. file)
end
if file_str ~= str then
sys.call("rm -f " .. file)
result = false
else
result = true
end
local f_out = io.open(file, "w")
if f_out then
f_out:write(str)
f_out:close()
end
end
return result
end
function is_js_luci()
return sys.call('[ -f "/www/luci-static/resources/uci.js" ]') == 0
end
function set_apply_on_parse(map)
if not map then
return
end
if is_js_luci() == true then
map.apply_on_parse = false
map.on_after_apply = function(self)
if self.redirect then
os.execute("sleep 1")
luci.http.redirect(self.redirect)
end
end
end
map.render = function(self, ...)
getmetatable(self).__index.render(self, ...) -- 保持原渲染流程
optimize_cbi_ui()
end
end
function luci_types(id, m, s, type_name, option_prefix)
local rewrite_option_table = {}
for key, value in pairs(s.fields) do
if key:find(option_prefix) == 1 then
if not s.fields[key].not_rewrite then
if s.fields[key].rewrite_option then
if not rewrite_option_table[s.fields[key].rewrite_option] then
rewrite_option_table[s.fields[key].rewrite_option] = 1
else
rewrite_option_table[s.fields[key].rewrite_option] = rewrite_option_table[s.fields[key].rewrite_option] + 1
end
end
s.fields[key].cfgvalue = function(self, section)
-- 添加自定义 custom_cfgvalue 属性,如果有自定义的 custom_cfgvalue 函数,则使用自定义的 cfgvalue 逻辑
if self.custom_cfgvalue then
return self:custom_cfgvalue(section)
else
if self.rewrite_option then
return m:get(section, self.rewrite_option)
else
if self.option:find(option_prefix) == 1 then
return m:get(section, self.option:sub(1 + #option_prefix))
end
end
end
end
s.fields[key].write = function(self, section, value)
if s.fields["type"]:formvalue(id) == type_name then
-- 添加自定义 custom_write 属性,如果有自定义的 custom_write 函数,则使用自定义的 write 逻辑
if self.custom_write then
self:custom_write(section, value)
else
if self.rewrite_option then
m:set(section, self.rewrite_option, value)
else
if self.option:find(option_prefix) == 1 then
m:set(section, self.option:sub(1 + #option_prefix), value)
end
end
end
end
end
s.fields[key].remove = function(self, section)
if s.fields["type"]:formvalue(id) == type_name then
-- 添加自定义 custom_remove 属性,如果有自定义的 custom_remove 函数,则使用自定义的 remove 逻辑
if self.custom_remove then
self:custom_remove(section)
else
if self.rewrite_option and rewrite_option_table[self.rewrite_option] == 1 then
m:del(section, self.rewrite_option)
else
if self.option:find(option_prefix) == 1 then
m:del(section, self.option:sub(1 + #option_prefix))
end
end
end
end
end
end
local deps = s.fields[key].deps
if #deps > 0 then
for index, value in ipairs(deps) do
deps[index]["type"] = type_name
end
else
s.fields[key]:depends({ type = type_name })
end
end
end
end
function format_go_time(input)
input = input and trim(input)
local N = 0
if input and input:match("^%d+$") then
N = tonumber(input)
elseif input and input ~= "" then
for value, unit in input:gmatch("(%d+)%s*([hms])") do
value = tonumber(value)
if unit == "h" then
N = N + value * 3600
elseif unit == "m" then
N = N + value * 60
elseif unit == "s" then
N = N + value
end
end
end
if N <= 0 then
return "0s"
end
local result = ""
local h = math.floor(N / 3600)
local m = math.floor(N % 3600 / 60)
local s = N % 60
if h > 0 then result = result .. h .. "h" end
if m > 0 then result = result .. m .. "m" end
if s > 0 or result == "" then result = result .. s .. "s" end
return result
end
function optimize_cbi_ui()
luci.http.write([[
<script type="text/javascript">
//修正上移、下移按钮名称
document.querySelectorAll("input.btn.cbi-button.cbi-button-up").forEach(function(btn) {
btn.value = "]] .. i18n.translate("Move up") .. [[";
});
document.querySelectorAll("input.btn.cbi-button.cbi-button-down").forEach(function(btn) {
btn.value = "]] .. i18n.translate("Move down") .. [[";
});
//删除控件和说明之间的多余换行
document.querySelectorAll("div.cbi-value-description").forEach(function(descDiv) {
var prev = descDiv.previousSibling;
while (prev && prev.nodeType === Node.TEXT_NODE && prev.textContent.trim() === "") {
prev = prev.previousSibling;
}
if (prev && prev.nodeType === Node.ELEMENT_NODE && prev.tagName === "BR") {
prev.remove();
}
});
</script>
]])
end
|
2977094657/BiliHistoryFrontend
| 8,405
|
src/components/tailwind/LoginDialog.vue
|
<!-- 登录弹窗 -->
<template>
<div v-if="show" class="fixed inset-0 z-50 flex items-center justify-center">
<!-- 遮罩层 -->
<div class="absolute inset-0 bg-black/50" @click="handleClose"></div>
<!-- 弹窗内容 -->
<div class="relative bg-white rounded-lg shadow-xl w-[360px] max-h-[90vh] overflow-y-auto">
<!-- 关闭按钮 -->
<button
@click="handleClose"
class="absolute right-4 top-4 text-gray-400 hover:text-gray-500"
>
<svg class="w-5 h-5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12" />
</svg>
</button>
<!-- 标题 -->
<div class="p-6 pb-0">
<h3 class="text-lg font-medium text-gray-900">账号登录</h3>
<p class="mt-2 text-sm text-gray-500">扫描二维码登录B站账号</p>
</div>
<!-- 登录内容 -->
<div class="p-6 flex flex-col items-center space-y-4">
<!-- 二维码区域 -->
<div v-if="qrcodeKey" class="relative">
<img :src="qrcodeImageUrl" alt="登录二维码" class="w-48 h-48 rounded-lg shadow-sm">
<!-- 二维码失效遮罩 -->
<div v-if="qrcodeExpired" class="absolute inset-0 bg-black/50 rounded-lg flex items-center justify-center">
<button
@click="refreshQRCode"
class="px-4 py-2 bg-white text-gray-900 rounded-md text-sm hover:bg-gray-50"
>
点击刷新
</button>
</div>
</div>
<!-- 状态提示 -->
<div class="text-sm" :class="statusClass">
{{ loginStatusText }}
</div>
<!-- 刷新按钮 -->
<button
v-if="!qrcodeKey || qrcodeExpired"
@click="refreshQRCode"
class="px-4 py-2 text-sm text-[#fb7299] hover:bg-[#fb7299]/5 rounded-md transition-colors duration-200"
>
{{ qrcodeKey ? '重新获取二维码' : '获取登录二维码' }}
</button>
</div>
</div>
</div>
</template>
<script setup>
import { ref, computed, onMounted, onUnmounted, watch } from 'vue'
import { showNotify } from 'vant'
import {
generateLoginQRCode,
getQRCodeImageURL,
getQRCodeImageBlob,
pollQRCodeStatus,
getLoginStatus
} from '../../api/api'
const props = defineProps({
show: {
type: Boolean,
default: false
}
})
const emit = defineEmits(['update:show', 'login-success'])
// 登录相关状态
const qrcodeKey = ref('')
const qrcodeImageUrl = ref('')
const qrcodeExpired = ref(false)
const loginStatus = ref(86101) // 初始状态:未扫码
const pollingInterval = ref(null)
const pollingErrors = ref(0)
// 登录状态文本
const loginStatusText = computed(() => {
switch (loginStatus.value) {
case 0:
return '登录成功'
case 86038:
return '二维码已失效'
case 86090:
return '已扫码,请在手机上确认'
case 86101:
return '请使用B站APP扫描二维码登录'
default:
return '获取二维码中...'
}
})
// 状态样式
const statusClass = computed(() => {
switch (loginStatus.value) {
case 0:
return 'text-green-500'
case 86038:
return 'text-red-500'
case 86090:
return 'text-[#fb7299]'
default:
return 'text-gray-500'
}
})
// 开始轮询
const startPolling = () => {
if (pollingInterval.value) {
clearInterval(pollingInterval.value)
}
let attempts = 0
const maxAttempts = 90 // 180秒内尝试90次
pollingErrors.value = 0 // 重置错误计数
pollingInterval.value = setInterval(async () => {
try {
if (!qrcodeKey.value) {
console.error('缺少qrcode_key参数')
clearInterval(pollingInterval.value)
showNotify({
type: 'danger',
message: '登录参数错误,请刷新页面重试'
})
return
}
const response = await pollQRCodeStatus(qrcodeKey.value)
if (!response?.data) {
throw new Error('服务器响应格式错误')
}
if (response.data.status === 'success' && response.data.data) {
const code = response.data.data.code
if (typeof code === 'undefined') {
throw new Error('响应中缺少状态码')
}
loginStatus.value = code
pollingErrors.value = 0
if (loginStatus.value === 0) {
// 登录成功
clearInterval(pollingInterval.value)
showNotify({
type: 'success',
message: '登录成功'
})
// 获取用户信息并发送登录成功事件
try {
const userResponse = await getLoginStatus()
if (userResponse.data && userResponse.data.code === 0) {
console.log('登录对话框获取到用户信息:', userResponse.data)
// 发送登录成功事件,并传递用户信息
emit('login-success', userResponse.data.data)
} else {
// 如果获取用户信息失败,仍然发送登录成功事件
emit('login-success')
}
} catch (error) {
console.error('获取用户信息失败:', error)
// 如果出错,仍然发送登录成功事件
emit('login-success')
}
// 关闭弹窗
setTimeout(() => {
handleClose()
}, 1000)
} else if (loginStatus.value === 86038) {
// 二维码失效
clearInterval(pollingInterval.value)
qrcodeExpired.value = true
showNotify({
type: 'warning',
message: '二维码已失效,请点击刷新'
})
} else if (loginStatus.value === 86090) {
// 已扫码待确认
showNotify({
type: 'primary',
message: '已扫码,请在手机上确认'
})
}
} else {
const errorMsg = response.data.detail || response.data.message || '获取状态失败'
throw new Error(errorMsg)
}
attempts++
if (attempts >= maxAttempts) {
clearInterval(pollingInterval.value)
qrcodeExpired.value = true
loginStatus.value = 86038
showNotify({
type: 'warning',
message: '登录超时,请重新获取二维码'
})
}
} catch (error) {
console.error('轮询出错:', error)
pollingErrors.value++
if (error.response?.status === 500) {
clearInterval(pollingInterval.value)
qrcodeExpired.value = true
showNotify({
type: 'danger',
message: '服务器错误,请稍后重试'
})
return
}
if (pollingErrors.value >= 3) {
clearInterval(pollingInterval.value)
qrcodeExpired.value = true
showNotify({
type: 'danger',
message: '网络异常,请检查网络后重试'
})
}
}
}, 2000)
}
// 获取二维码
const getQRCode = async () => {
try {
const response = await generateLoginQRCode()
if (!response?.data) {
throw new Error('服务器响应格式错误')
}
if (response.data.status === 'success' && response.data.data?.qrcode_key) {
qrcodeKey.value = response.data.data.qrcode_key
try {
// 使用axios获取二维码图片(带API密钥验证)
qrcodeImageUrl.value = await getQRCodeImageBlob()
} catch (imgError) {
console.error('获取二维码图片失败:', imgError)
// 如果获取图片失败,回退到直接使用URL
qrcodeImageUrl.value = getQRCodeImageURL()
}
qrcodeExpired.value = false
loginStatus.value = 86101
pollingErrors.value = 0
startPolling()
} else {
const errorMsg = response.data.detail || response.data.message || '获取二维码失败'
throw new Error(errorMsg)
}
} catch (error) {
console.error('获取二维码失败:', error)
showNotify({
type: 'danger',
message: error.response?.status === 500 ?
'服务器错误,请稍后重试' :
`获取二维码失败: ${error.message}`
})
qrcodeExpired.value = true
}
}
// 刷新二维码
const refreshQRCode = () => {
if (pollingInterval.value) {
clearInterval(pollingInterval.value)
}
getQRCode()
}
// 关闭弹窗
const handleClose = () => {
emit('update:show', false)
// 清理轮询
if (pollingInterval.value) {
clearInterval(pollingInterval.value)
}
// 如果是blob URL,需要释放
if (qrcodeImageUrl.value && qrcodeImageUrl.value.startsWith('blob:')) {
URL.revokeObjectURL(qrcodeImageUrl.value)
}
// 重置状态
qrcodeKey.value = ''
qrcodeImageUrl.value = ''
qrcodeExpired.value = false
loginStatus.value = 86101
pollingErrors.value = 0
}
// 监听show变化
watch(() => props.show, (newVal) => {
if (newVal) {
getQRCode()
} else {
handleClose()
}
})
// 组件卸载时清除轮询和释放资源
onUnmounted(() => {
if (pollingInterval.value) {
clearInterval(pollingInterval.value)
}
// 释放blob URL
if (qrcodeImageUrl.value && qrcodeImageUrl.value.startsWith('blob:')) {
URL.revokeObjectURL(qrcodeImageUrl.value)
}
})
// 定义组件选项
defineOptions({
name: 'LoginDialog'
})
</script>
|
2977094657/BiliHistoryFrontend
| 15,907
|
src/components/tailwind/DataSyncManager.vue
|
<template>
<div class="fixed inset-0 z-50 flex items-center justify-center bg-black bg-opacity-50" v-if="showModal">
<div class="bg-white p-6 rounded-lg shadow-lg max-w-2xl w-full max-h-[80vh] overflow-y-auto">
<!-- 头部标题 -->
<div class="flex justify-between items-center mb-4">
<h2 class="text-xl font-bold text-gray-800">{{ currentTab === 'sync' ? '数据同步' : '数据完整性检查' }}</h2>
<button @click="closeModal" class="text-gray-500 hover:text-gray-700">
<svg class="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"></path>
</svg>
</button>
</div>
<!-- 导航标签 -->
<div class="flex border-b mb-4">
<button
@click="currentTab = 'sync'"
class="py-2 px-4 font-medium text-sm transition-colors duration-200"
:class="currentTab === 'sync' ? 'text-pink-500 border-b-2 border-pink-500' : 'text-gray-600 hover:text-pink-400'"
>
数据同步
</button>
<button
@click="currentTab = 'integrity'"
class="py-2 px-4 font-medium text-sm transition-colors duration-200"
:class="currentTab === 'integrity' ? 'text-pink-500 border-b-2 border-pink-500' : 'text-gray-600 hover:text-pink-400'"
>
数据完整性检查
</button>
</div>
<!-- 数据同步面板 -->
<div v-if="currentTab === 'sync'">
<div class="mb-4">
<p class="text-sm text-gray-600 mb-2">同步数据库和JSON文件之间的历史记录数据。</p>
<div class="flex flex-col sm:flex-row gap-4 mb-4">
<div class="flex-1">
<label class="block text-sm font-medium text-gray-700 mb-1">数据库路径</label>
<input
v-model="dbPath"
type="text"
class="w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-pink-500 focus:border-pink-500 text-sm"
/>
</div>
<div class="flex-1">
<label class="block text-sm font-medium text-gray-700 mb-1">JSON文件路径</label>
<input
v-model="jsonPath"
type="text"
class="w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-pink-500 focus:border-pink-500 text-sm"
/>
</div>
</div>
<button
@click="startSync"
class="w-full bg-pink-600 hover:bg-pink-700 text-white font-medium py-2 px-4 rounded-md shadow-sm focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-pink-500 disabled:opacity-50 disabled:cursor-not-allowed"
:disabled="isSyncing"
>
<span v-if="isSyncing" class="flex items-center justify-center">
<svg class="animate-spin -ml-1 mr-2 h-4 w-4 text-white" fill="none" viewBox="0 0 24 24">
<circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
<path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
</svg>
数据同步中...
</span>
<span v-else>开始同步</span>
</button>
</div>
<!-- 同步结果显示 -->
<div v-if="syncResult" class="mt-6 border-t pt-4">
<h3 class="font-medium text-gray-900 mb-2">最近同步结果</h3>
<div class="bg-gray-50 p-3 rounded-md">
<div class="grid grid-cols-2 gap-2 mb-3">
<div class="text-sm">
<span class="text-gray-500">同步时间:</span>
<span class="text-gray-900">{{ formatDateTime(syncResult.timestamp) }}</span>
</div>
<div class="text-sm">
<span class="text-gray-500">总同步记录:</span>
<span class="text-gray-900 font-medium">{{ syncResult.total_synced }}</span>
</div>
<div class="text-sm">
<span class="text-gray-500">JSON导入数据库:</span>
<span class="text-gray-900">{{ syncResult.json_to_db_count }}</span>
</div>
<div class="text-sm">
<span class="text-gray-500">数据库导出JSON:</span>
<span class="text-gray-900">{{ syncResult.db_to_json_count }}</span>
</div>
</div>
<div v-if="syncResult.synced_days && syncResult.synced_days.length > 0">
<h4 class="text-sm font-medium text-gray-700 mb-2">同步的日期</h4>
<div class="max-h-48 overflow-y-auto bg-white rounded border border-gray-200">
<div v-for="(day, index) in syncResult.synced_days" :key="index" class="p-2 text-sm border-b last:border-b-0">
<div class="flex justify-between items-center mb-1">
<div>
<span class="font-medium">{{ day.date }}</span>
<span class="ml-2 text-gray-500">({{ day.imported_count }}条记录)</span>
</div>
<span class="text-xs px-2 py-1 rounded" :class="day.source === 'json_to_db' ? 'bg-blue-100 text-blue-800' : 'bg-green-100 text-green-800'">
{{ day.source === 'json_to_db' ? 'JSON→数据库' : '数据库→JSON' }}
</span>
</div>
<div v-if="day.titles && day.titles.length" class="pl-2 border-l-2 border-gray-200">
<div v-for="(title, titleIndex) in day.titles.slice(0, 3)" :key="titleIndex" class="text-gray-600 truncate">
{{ title }}
</div>
<div v-if="day.titles.length > 3" class="text-gray-400 text-xs">
还有{{ day.titles.length - 3 }}条记录...
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<!-- 数据完整性检查面板 -->
<div v-if="currentTab === 'integrity'">
<!-- 直接显示完整性报告 -->
<div v-if="reportHtml" class="mb-6 prose prose-sm max-w-none bg-white p-4 rounded-md border border-gray-200">
<div v-html="reportHtml"></div>
</div>
<div class="mb-4">
<p class="text-sm text-gray-600 mb-2">检查数据库和JSON文件之间的数据完整性。</p>
<div class="flex flex-col sm:flex-row gap-4 mb-4">
<div class="flex-1">
<label class="block text-sm font-medium text-gray-700 mb-1">数据库路径</label>
<input
v-model="dbPath"
type="text"
class="w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-pink-500 focus:border-pink-500 text-sm"
/>
</div>
<div class="flex-1">
<label class="block text-sm font-medium text-gray-700 mb-1">JSON文件路径</label>
<input
v-model="jsonPath"
type="text"
class="w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-pink-500 focus:border-pink-500 text-sm"
/>
</div>
</div>
<button
@click="startCheck"
class="w-full bg-pink-600 hover:bg-pink-700 text-white font-medium py-2 px-4 rounded-md shadow-sm focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-pink-500 disabled:opacity-50 disabled:cursor-not-allowed"
:disabled="isChecking"
>
<span v-if="isChecking" class="flex items-center justify-center">
<svg class="animate-spin -ml-1 mr-2 h-4 w-4 text-white" fill="none" viewBox="0 0 24 24">
<circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
<path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
</svg>
检查数据中...
</span>
<span v-else>开始检查</span>
</button>
</div>
<!-- 检查结果显示 -->
<div v-if="checkResult" class="mt-6 border-t pt-4">
<h3 class="font-medium text-gray-900 mb-2">数据完整性检查结果</h3>
<div class="bg-gray-50 p-3 rounded-md">
<div class="grid grid-cols-2 gap-3 mb-3">
<div class="text-sm">
<span class="text-gray-500">检查时间:</span>
<span class="text-gray-900">{{ formatDateTime(checkResult.timestamp) }}</span>
</div>
<div class="text-sm">
<span class="text-gray-500">JSON文件总数:</span>
<span class="text-gray-900">{{ checkResult.total_json_files }}</span>
</div>
<div class="text-sm">
<span class="text-gray-500">JSON记录总数:</span>
<span class="text-gray-900">{{ checkResult.total_json_records }}</span>
</div>
<div class="text-sm">
<span class="text-gray-500">数据库记录总数:</span>
<span class="text-gray-900">{{ checkResult.total_db_records }}</span>
</div>
</div>
<div class="text-sm p-2 mb-3 rounded-md" :class="[checkResult.difference === 0 ? 'bg-green-100 text-green-800' : 'bg-yellow-100 text-yellow-800']">
<span class="font-medium">数据差异:</span>
<span v-if="checkResult.difference === 0">数据一致</span>
<span v-else-if="checkResult.difference > 0">数据库缺少 {{ checkResult.difference }} 条记录</span>
<span v-else>数据库多出 {{ -checkResult.difference }} 条记录</span>
</div>
</div>
</div>
</div>
</div>
</div>
</template>
<script setup>
import { ref, onMounted, watch } from 'vue'
import { syncData, getSyncResult, checkDataIntegrity, getIntegrityReport } from '../../api/api'
import { showNotify } from 'vant'
import 'vant/es/notify/style'
// 定义Props
const props = defineProps({
showModal: {
type: Boolean,
default: false
},
initialTab: {
type: String,
default: 'integrity'
}
})
// 定义事件
const emit = defineEmits(['update:showModal', 'sync-complete', 'check-complete'])
// 状态变量
const currentTab = ref(props.initialTab)
const dbPath = ref('output/bilibili_history.db')
const jsonPath = ref('output/history_by_date')
const isSyncing = ref(false)
const isChecking = ref(false)
const syncResult = ref(null)
const checkResult = ref(null)
const reportHtml = ref('')
// 格式化日期时间
const formatDateTime = (dateTimeString) => {
if (!dateTimeString) return ''
const date = new Date(dateTimeString)
return date.toLocaleString('zh-CN', {
year: 'numeric',
month: '2-digit',
day: '2-digit',
hour: '2-digit',
minute: '2-digit',
second: '2-digit'
})
}
// 关闭模态框
const closeModal = () => {
emit('update:showModal', false)
}
// 获取上次同步结果
const fetchSyncResult = async () => {
try {
const response = await getSyncResult()
if (response.data && response.data.success) {
syncResult.value = response.data
}
} catch (error) {
console.error('获取同步结果失败:', error)
showNotify({ type: 'danger', message: '获取同步结果失败' })
}
}
// 开始同步数据
const startSync = async () => {
isSyncing.value = true
try {
const response = await syncData(dbPath.value, jsonPath.value, false) // 禁用异步模式
if (response.data.success) {
syncResult.value = response.data
showNotify({ type: 'success', message: `同步完成,共同步${response.data.total_synced}条记录` })
emit('sync-complete', response.data)
} else {
showNotify({ type: 'danger', message: response.data.message || '同步失败' })
}
} catch (error) {
console.error('同步数据失败:', error)
showNotify({ type: 'danger', message: error.response?.data?.detail || '同步数据失败' })
} finally {
isSyncing.value = false
}
}
// 开始数据完整性检查
const startCheck = async () => {
isChecking.value = true
try {
// 强制执行检查,忽略配置设置
const response = await checkDataIntegrity(dbPath.value, jsonPath.value, false, true)
if (response.data.success) {
checkResult.value = response.data
// 检查是否有消息提示(可能是配置禁用了检查)
if (response.data.message && response.data.message.includes('数据完整性校验已在配置中禁用')) {
showNotify({
type: 'warning',
message: '数据完整性校验已在配置中禁用,但已强制执行检查'
})
} else {
showNotify({ type: 'success', message: '数据完整性检查完成' })
}
emit('check-complete', response.data)
// 检查完成后自动获取报告内容
await fetchIntegrityReport()
} else {
showNotify({ type: 'danger', message: response.data.message || '检查失败' })
}
} catch (error) {
console.error('数据完整性检查失败:', error)
showNotify({ type: 'danger', message: error.response?.data?.detail || '数据完整性检查失败' })
} finally {
isChecking.value = false
}
}
// 获取完整性报告内容
const fetchIntegrityReport = async () => {
try {
const response = await getIntegrityReport()
// 检查是否有报告内容
if (response.data && response.data.content) {
// 更完善的Markdown到HTML转换
let content = response.data.content
// 预处理 - 先移除单独的#行和不带空格的#开头
.replace(/^#\s*$/gm, '') // 移除单独的#行
.replace(/^\s*#\s*$/gm, '') // 移除仅有空格和#的行
.replace(/^#(?!\s)/gm, '') // 移除不带空格的#开头
// 整理标题格式
content = content.replace(/### ([^\n]+)/g, '<h3 class="text-base font-medium my-2">$1</h3>')
.replace(/## ([^\n]+)/g, '<h2 class="text-lg font-semibold my-3">$1</h2>')
.replace(/# ([^\n]+)/g, '<h1 class="text-xl font-bold my-4">$1</h1>')
// 处理列表项
content = content.replace(/^\* (.*?)$/gm, '<li class="ml-4">$1</li>')
// 将列表项包装在ul标签中
content = content.replace(/<li class="ml-4">(.*?)<\/li>(\s*)<li/g, '<li class="ml-4">$1</li></ul><ul><li')
.replace(/<li class="ml-4">(.*?)<\/li>(?!\s*<li|\s*<\/ul>)/g, '<li class="ml-4">$1</li></ul>')
.replace(/<li/g, '<ul><li')
// 修复可能的重复ul标签
content = content.replace(/<\/ul>\s*<ul>/g, '')
// 段落处理
content = content.replace(/\n\n/g, '</p><p class="my-2">')
// 处理一些特殊格式
content = content.replace(/\*\*(.*?)\*\*/g, '<strong>$1</strong>')
.replace(/\*(.*?)\*/g, '<em>$1</em>')
// 确保所有内容都有封装标签
if (!content.startsWith('<')) {
content = '<p class="my-2">' + content + '</p>'
}
reportHtml.value = content
return true
} else if (response.data && response.data.message && response.data.message.includes('数据完整性校验已在配置中禁用')) {
// 如果报告为空是因为配置禁用了校验
reportHtml.value = `<div class="p-4 bg-yellow-50 text-yellow-800 rounded-md">
<h3 class="font-medium">数据完整性校验已在配置中禁用</h3>
<p class="mt-2">您已在设置中禁用启动时数据完整性校验。如需查看报告,请点击"开始检查"按钮强制执行检查。</p>
</div>`
return true
} else {
// 其他原因导致报告为空
showNotify({ type: 'warning', message: '报告内容为空' })
reportHtml.value = `<div class="p-4 bg-gray-50 text-gray-600 rounded-md">
<p>暂无报告内容。请点击"开始检查"按钮执行数据完整性检查。</p>
</div>`
return false
}
} catch (error) {
console.error('获取报告失败:', error)
reportHtml.value = `<div class="p-4 bg-red-50 text-red-600 rounded-md">
<h3 class="font-medium">获取报告失败</h3>
<p class="mt-2">错误信息: ${error.message || '未知错误'}</p>
<p class="mt-1">请点击"开始检查"按钮重新执行数据完整性检查。</p>
</div>`
return false
}
}
// 监听模态框状态变化
watch(() => props.showModal, async (newVal) => {
if (newVal) {
// 模态框打开时,获取最新数据
await fetchIntegrityReport() // 先获取报告
await fetchSyncResult() // 再获取同步结果
}
})
// 监听initialTab变化
watch(() => props.initialTab, (newVal) => {
currentTab.value = newVal
})
// 组件挂载时
onMounted(async () => {
if (props.showModal) {
await fetchIntegrityReport() // 默认加载报告
await fetchSyncResult()
}
})
</script>
|
281677160/openwrt-package
| 1,562
|
luci-app-passwall2/luasrc/passwall2/com.lua
|
local _M = {}
local function gh_release_url(self)
--return "https://api.github.com/repos/" .. self.repo .. "/releases/latest"
return "https://github.com/xiaorouji/openwrt-passwall-packages/releases/download/api-cache/" .. string.lower(self.name) .. "-release-api.json"
end
local function gh_pre_release_url(self)
--return "https://api.github.com/repos/" .. self.repo .. "/releases?per_page=1"
return "https://github.com/xiaorouji/openwrt-passwall-packages/releases/download/api-cache/" .. string.lower(self.name) .. "-pre-release-api.json"
end
_M.hysteria = {
name = "Hysteria",
repo = "HyNetwork/hysteria",
get_url = gh_release_url,
cmd_version = "version | awk '/^Version:/ {print $2}'",
remote_version_str_replace = "app/",
zipped = false,
default_path = "/usr/bin/hysteria",
match_fmt_str = "linux%%-%s$",
file_tree = {
armv6 = "arm",
armv7 = "arm"
}
}
_M["sing-box"] = {
name = "Sing-Box",
repo = "SagerNet/sing-box",
get_url = gh_release_url,
cmd_version = "version | awk '{print $3}' | sed -n 1P",
zipped = true,
zipped_suffix = "tar.gz",
default_path = "/usr/bin/sing-box",
match_fmt_str = "linux%%-%s",
file_tree = {
x86_64 = "amd64",
mips64el = "mips64le"
}
}
_M.xray = {
name = "Xray",
repo = "XTLS/Xray-core",
get_url = gh_pre_release_url,
cmd_version = "version | awk '{print $2}' | sed -n 1P",
zipped = true,
default_path = "/usr/bin/xray",
match_fmt_str = "linux%%-%s",
file_tree = {
x86_64 = "64",
x86 = "32",
mips = "mips32",
mipsel = "mips32le",
mips64el = "mips64le"
}
}
return _M
|
2977094657/BiliHistoryFrontend
| 59,425
|
src/components/tailwind/VideoDetailDialog.vue
|
<template>
<van-dialog
:show="dialogVisible"
@update:show="updateVisible"
:title="video?.title || '视频详情'"
class="video-detail-dialog"
close-on-click-overlay
:show-confirm-button="false"
:style="{ width: '1000px', maxWidth: '90%', position: 'fixed', top: '50%', left: '50%', transform: 'translate(-50%, -50%)', borderRadius: '0.5rem', boxShadow: '0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -2px rgba(0, 0, 0, 0.05)' }"
>
<div v-if="video" class="p-4 overflow-y-auto" style="height: 600px">
<!-- 视频基础信息 -->
<div class="flex flex-col md:flex-row gap-3">
<!-- 左侧:视频封面 -->
<div class="md:w-[30%] flex-shrink-0">
<div class="relative w-full h-28 md:h-32 rounded-lg overflow-hidden">
<img
:src="normalizeImageUrl(video.cover || video.covers?.[0])"
class="w-full h-full object-cover"
:class="{ 'blur-md': isPrivacyMode }"
alt="视频封面"
/>
<!-- 视频时长 -->
<div class="absolute bottom-2 right-2 bg-black/70 text-white text-xs px-2 py-1 rounded">
{{ formatDuration(video.duration) }}
</div>
<!-- 进度条 -->
<div v-if="video.business !== 'article-list' && video.business !== 'article' && video.business !== 'live'"
class="absolute bottom-0 left-0 w-full h-1 bg-gray-700/50">
<div
class="h-full bg-[#FF6699]"
:style="{ width: getProgressWidth(video.progress, video.duration) }">
</div>
</div>
</div>
<!-- 视频下载信息 -->
<div v-if="isVideoDownloaded && downloadedFiles.length > 0" class="mt-3">
<div class="text-xs text-gray-500 p-2 bg-pink-50 rounded-lg">
<div class="flex items-center mb-1">
<svg class="w-3 h-3 text-[#fb7299] mr-1" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 13l4 4L19 7" />
</svg>
<span class="font-medium text-[#fb7299]">视频已下载</span>
</div>
<div v-for="(file, index) in downloadedFiles" :key="index" class="ml-4 truncate" :title="file.file_path">
{{ file.file_name }} ({{ file.size_mb.toFixed(1) }} MB)
</div>
</div>
</div>
</div>
<!-- 右侧:视频详情 -->
<div class="md:w-[70%]">
<!-- 视频信息 -->
<div class="space-y-2 text-xs flex flex-col h-28 md:h-32 min-h-0">
<!-- UP主信息 + 检测信息并排显示 -->
<div v-if="video.business !== 'cheese' && video.business !== 'pgc'"
class="flex items-center space-x-2"
@click.stop>
<div class="flex-shrink-0">
<img
:src="normalizeImageUrl(video.author_face)"
alt="author"
class="h-7 w-7 cursor-pointer rounded-full transition-all duration-300 hover:scale-110"
:class="{ 'blur-md': isPrivacyMode }"
@click="openAuthorPage"
:title="isPrivacyMode ? '隐私模式已开启' : `访问 ${video.author_name} 的个人空间`"
/>
</div>
<div class="flex-1 min-w-0">
<p
class="cursor-pointer text-gray-800 transition-colors hover:text-[#FF6699]"
@click="openAuthorPage"
:title="isPrivacyMode ? '隐私模式已开启' : `访问 ${video.author_name} 的个人空间`"
v-html="isPrivacyMode ? '******' : video.author_name"
></p>
<p class="text-xs text-gray-500">UP主</p>
</div>
<div class="flex items-center space-x-2 ml-auto">
<EnvironmentCheck inline compact />
<div class="hidden sm:block h-4 w-px bg-gray-200"></div>
<!-- DeepSeek 余额(紧凑显示) -->
<div class="flex items-center space-x-1 text-[11px] text-gray-600">
<svg class="w-3.5 h-3.5 text-[#4D6BFE]" viewBox="0 0 30 30" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M27.501 8.46875C27.249 8.3457 27.1406 8.58008 26.9932 8.69922C26.9434 8.73828 26.9004 8.78906 26.8584 8.83398C26.4902 9.22852 26.0605 9.48633 25.5 9.45508C24.6787 9.41016 23.9785 9.66797 23.3594 10.2969C23.2275 9.52148 22.79 9.05859 22.125 8.76172C21.7764 8.60742 21.4238 8.45312 21.1807 8.11719C21.0098 7.87891 20.9639 7.61328 20.8779 7.35156C20.8242 7.19336 20.7695 7.03125 20.5879 7.00391C20.3906 6.97266 20.3135 7.13867 20.2363 7.27734C19.9258 7.84375 19.8066 8.46875 19.8174 9.10156C19.8447 10.5234 20.4453 11.6562 21.6367 12.4629C21.7725 12.5547 21.8076 12.6484 21.7646 12.7832C21.6836 13.0605 21.5869 13.3301 21.501 13.6074C21.4473 13.7852 21.3662 13.8242 21.1768 13.7461C20.5225 13.4727 19.957 13.0684 19.458 12.5781C18.6104 11.7578 17.8438 10.8516 16.8877 10.1426C16.6631 9.97656 16.4395 9.82227 16.207 9.67578C15.2314 8.72656 16.335 7.94727 16.5898 7.85547C16.8574 7.75977 16.6826 7.42773 15.8193 7.43164C14.957 7.43555 14.167 7.72461 13.1611 8.10938C13.0137 8.16797 12.8594 8.21094 12.7002 8.24414C11.7871 8.07227 10.8389 8.0332 9.84766 8.14453C7.98242 8.35352 6.49219 9.23633 5.39648 10.7441C4.08105 12.5547 3.77148 14.6133 4.15039 16.7617C4.54883 19.0234 5.70215 20.8984 7.47559 22.3633C9.31348 23.8809 11.4307 24.625 13.8457 24.4824C15.3125 24.3984 16.9463 24.2012 18.7881 22.6406C19.2529 22.8711 19.7402 22.9629 20.5498 23.0332C21.1729 23.0918 21.7725 23.002 22.2373 22.9062C22.9648 22.752 22.9141 22.0781 22.6514 21.9531C20.5186 20.959 20.9863 21.3633 20.5605 21.0371C21.6445 19.752 23.2783 18.418 23.917 14.0977C23.9668 13.7539 23.9238 13.5391 23.917 13.2598C23.9131 13.0918 23.9512 13.0254 24.1445 13.0059C24.6787 12.9453 25.1973 12.7988 25.6738 12.5352C27.0557 11.7793 27.6123 10.5391 27.7441 9.05078C27.7637 8.82422 27.7402 8.58789 27.501 8.46875ZM15.46 21.8613C13.3926 20.2344 12.3906 19.6992 11.9766 19.7227C11.5898 19.7441 11.6592 20.1875 11.7441 20.4766C11.833 20.7617 11.9492 20.959 12.1123 21.209C12.2246 21.375 12.3018 21.623 12 21.8066C11.334 22.2207 10.1768 21.668 10.1221 21.6406C8.77539 20.8477 7.64941 19.7988 6.85547 18.3652C6.08984 16.9844 5.64453 15.5039 5.57129 13.9238C5.55176 13.541 5.66406 13.4062 6.04297 13.3379C6.54199 13.2461 7.05762 13.2266 7.55664 13.2988C9.66602 13.6074 11.4619 14.5527 12.9668 16.0469C13.8262 16.9004 14.4766 17.918 15.1465 18.9121C15.8584 19.9688 16.625 20.9746 17.6006 21.7988C17.9443 22.0879 18.2197 22.3086 18.4824 22.4707C17.6895 22.5586 16.3652 22.5781 15.46 21.8613ZM16.4502 15.4805C16.4502 15.3105 16.5859 15.1758 16.7568 15.1758C16.7949 15.1758 16.8301 15.1836 16.8613 15.1953C16.9033 15.2109 16.9424 15.2344 16.9727 15.2695C17.0273 15.3223 17.0586 15.4004 17.0586 15.4805C17.0586 15.6504 16.9229 15.7852 16.7529 15.7852C16.582 15.7852 16.4502 15.6504 16.4502 15.4805ZM19.5273 17.0625C19.3301 17.1426 19.1328 17.2129 18.9434 17.2207C18.6494 17.2344 18.3281 17.1152 18.1533 16.9688C17.8828 16.7422 17.6895 16.6152 17.6074 16.2168C17.5732 16.0469 17.5928 15.7852 17.623 15.6348C17.6934 15.3105 17.6152 15.1035 17.3877 14.9141C17.2012 14.7598 16.9658 14.7188 16.7061 14.7188C16.6094 14.7188 16.5205 14.6758 16.4541 14.6406C16.3457 14.5859 16.2568 14.4512 16.3418 14.2852C16.3691 14.2324 16.501 14.1016 16.5322 14.0781C16.8838 13.877 17.29 13.9434 17.666 14.0938C18.0146 14.2363 18.2773 14.498 18.6562 14.8672C19.0439 15.3145 19.1133 15.4395 19.334 15.7734C19.5078 16.0371 19.667 16.3066 19.7754 16.6152C19.8408 16.8066 19.7559 16.9648 19.5273 17.0625Z" fill="#4D6BFE" />
</svg>
<div v-if="deepseekBalance.is_available" class="text-[11px]">
<span class="text-gray-500">余额:</span>
<span class="font-medium text-[#4D6BFE]">{{ deepseekBalance.balance_infos[0]?.total_balance || '0.00' }}</span>
<span class="text-gray-500">{{ deepseekBalance.balance_infos[0]?.currency }}</span>
</div>
<button @click="refreshDeepSeekBalance" class="p-0.5 text-[#4D6BFE] hover:bg-[#4D6BFE]/10 rounded-full transition-colors duration-200" :title="deepseekBalance.is_available ? '刷新余额' : '点击查询余额'">
<svg class="w-3.5 h-3.5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15" />
</svg>
</button>
</div>
</div>
</div>
<!-- 视频分区/观看时间/设备 行已按需求去除 -->
<!-- 备注 -->
<div class="mt-2 flex-1 flex flex-col min-h-0">
<textarea
v-model="remarkContent"
@blur="handleRemarkBlur"
:disabled="isPrivacyMode"
placeholder="添加备注..."
rows="2"
class="w-full flex-1 resize-none px-2 py-1.5 text-xs text-gray-800 bg-gray-50 rounded border border-gray-200 focus:border-[#fb7299] focus:ring-[#fb7299] transition-colors duration-200"
:class="{ 'blur-sm': isPrivacyMode }"
></textarea>
<div v-if="remarkTime" class="text-xs text-gray-400 mt-1">
上次编辑: {{ formatRemarkTime(remarkTime) }}
</div>
</div>
</div>
</div>
</div>
<!-- 视频摘要 -->
<div v-if="video.business === 'archive'" class="mt-6">
<!-- 标签页 -->
<div class="border-b border-gray-200">
<nav class="flex -mb-px">
<button
v-for="tab in tabs"
:key="tab.id"
@click="currentTab = tab.id"
class="px-4 py-2 text-sm font-medium border-b-2 transition-colors duration-200"
:class="[
currentTab === tab.id
? 'border-[#fb7299] text-[#fb7299]'
: 'border-transparent text-gray-500 hover:text-gray-700 hover:border-gray-300'
]"
>
{{ tab.name }}
</button>
</nav>
</div>
<!-- 标签页内容 -->
<div class="mt-4">
<!-- B站AI摘要 -->
<div v-show="currentTab === 'bilibili'" class="space-y-4">
<VideoSummary
:key="videoSummaryKey"
:bvid="video.bvid"
:cid="String(video.cid)"
:upMid="String(video.author_mid)"
/>
</div>
<!-- 本地摘要部分 -->
<div v-show="currentTab === 'local'" class="space-y-6">
<!-- 检查环境中的加载状态 -->
<div v-if="isCheckingEnvironment" class="flex items-center justify-center p-6">
<div class="flex flex-col items-center">
<div
class="animate-spin h-10 w-10 border-4 border-[#fb7299] border-t-transparent rounded-full mb-3"></div>
<span class="text-gray-600">正在检查系统环境...</span>
</div>
</div>
<!-- 系统资源不足提示 -->
<div v-else-if="!canRunSpeechToText"
class="flex items-center justify-center p-6 bg-red-50 text-red-700 rounded-lg">
<div class="flex flex-col items-center text-center">
<svg class="w-12 h-12 mb-3" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z" />
</svg>
<span class="font-medium text-lg mb-2">无法使用本地摘要功能</span>
<span class="text-sm">{{ systemLimitationReason || '系统资源不足,无法运行语音转文字功能' }}</span>
</div>
</div>
<!-- CUDA不可用提示 -->
<div v-if="!cudaAvailable && cudaSetupGuide && showCudaGuide"
class="flex flex-col p-6 bg-yellow-50 text-yellow-800 rounded-lg">
<div class="flex items-center mb-4">
<svg class="w-8 h-8 mr-3" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
d="M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
</svg>
<div>
<h3 class="font-medium text-lg">CUDA 不可用</h3>
<p class="text-sm">本地摘要功能可以使用,但速度会较慢。安装CUDA可以显著提升处理速度。</p>
</div>
</div>
<div class="mt-2">
<h4 class="font-medium mb-2">CUDA 安装指南</h4>
<pre
class="text-xs bg-gray-100 p-3 rounded-md overflow-auto max-h-60 whitespace-pre-wrap">{{ cudaSetupGuide
}}</pre>
</div>
<div class="mt-4 flex justify-end">
<button
@click="showCudaGuide = false"
class="px-4 py-2 bg-yellow-600 text-white rounded-md text-sm hover:bg-yellow-700 transition-colors"
>
我已了解,继续使用
</button>
</div>
</div>
<!-- 只有在系统资源足够且CUDA可用或用户已确认时才显示以下内容 -->
<template v-else-if="canRunSpeechToText && (!cudaAvailable ? !showCudaGuide : true)">
<!-- 本地摘要显示部分 -->
<div v-if="hasLocalSummary" class="bg-white rounded-lg border border-gray-200 p-4">
<div class="flex items-center justify-between mb-4">
<h3 class="text-base font-medium text-gray-900">本地摘要</h3>
<!-- DeepSeek余额显示 -->
<div class="flex items-center space-x-2">
<svg class="w-4 h-4 text-[#4D6BFE]" viewBox="0 0 30 30" fill="none"
xmlns="http://www.w3.org/2000/svg">
<path
d="M27.501 8.46875C27.249 8.3457 27.1406 8.58008 26.9932 8.69922C26.9434 8.73828 26.9004 8.78906 26.8584 8.83398C26.4902 9.22852 26.0605 9.48633 25.5 9.45508C24.6787 9.41016 23.9785 9.66797 23.3594 10.2969C23.2275 9.52148 22.79 9.05859 22.125 8.76172C21.7764 8.60742 21.4238 8.45312 21.1807 8.11719C21.0098 7.87891 20.9639 7.61328 20.8779 7.35156C20.8242 7.19336 20.7695 7.03125 20.5879 7.00391C20.3906 6.97266 20.3135 7.13867 20.2363 7.27734C19.9258 7.84375 19.8066 8.46875 19.8174 9.10156C19.8447 10.5234 20.4453 11.6562 21.6367 12.4629C21.7725 12.5547 21.8076 12.6484 21.7646 12.7832C21.6836 13.0605 21.5869 13.3301 21.501 13.6074C21.4473 13.7852 21.3662 13.8242 21.1768 13.7461C20.5225 13.4727 19.957 13.0684 19.458 12.5781C18.6104 11.7578 17.8438 10.8516 16.8877 10.1426C16.6631 9.97656 16.4395 9.82227 16.207 9.67578C15.2314 8.72656 16.335 7.94727 16.5898 7.85547C16.8574 7.75977 16.6826 7.42773 15.8193 7.43164C14.957 7.43555 14.167 7.72461 13.1611 8.10938C13.0137 8.16797 12.8594 8.21094 12.7002 8.24414C11.7871 8.07227 10.8389 8.0332 9.84766 8.14453C7.98242 8.35352 6.49219 9.23633 5.39648 10.7441C4.08105 12.5547 3.77148 14.6133 4.15039 16.7617C4.54883 19.0234 5.70215 20.8984 7.47559 22.3633C9.31348 23.8809 11.4307 24.625 13.8457 24.4824C15.3125 24.3984 16.9463 24.2012 18.7881 22.6406C19.2529 22.8711 19.7402 22.9629 20.5498 23.0332C21.1729 23.0918 21.7725 23.002 22.2373 22.9062C22.9648 22.752 22.9141 22.0781 22.6514 21.9531C20.5186 20.959 20.9863 21.3633 20.5605 21.0371C21.6445 19.752 23.2783 18.418 23.917 14.0977C23.9668 13.7539 23.9238 13.5391 23.917 13.2598C23.9131 13.0918 23.9512 13.0254 24.1445 13.0059C24.6787 12.9453 25.1973 12.7988 25.6738 12.5352C27.0557 11.7793 27.6123 10.5391 27.7441 9.05078C27.7637 8.82422 27.7402 8.58789 27.501 8.46875ZM15.46 21.8613C13.3926 20.2344 12.3906 19.6992 11.9766 19.7227C11.5898 19.7441 11.6592 20.1875 11.7441 20.4766C11.833 20.7617 11.9492 20.959 12.1123 21.209C12.2246 21.375 12.3018 21.623 12 21.8066C11.334 22.2207 10.1768 21.668 10.1221 21.6406C8.77539 20.8477 7.64941 19.7988 6.85547 18.3652C6.08984 16.9844 5.64453 15.5039 5.57129 13.9238C5.55176 13.541 5.66406 13.4062 6.04297 13.3379C6.54199 13.2461 7.05762 13.2266 7.55664 13.2988C9.66602 13.6074 11.4619 14.5527 12.9668 16.0469C13.8262 16.9004 14.4766 17.918 15.1465 18.9121C15.8584 19.9688 16.625 20.9746 17.6006 21.7988C17.9443 22.0879 18.2197 22.3086 18.4824 22.4707C17.6895 22.5586 16.3652 22.5781 15.46 21.8613ZM16.4502 15.4805C16.4502 15.3105 16.5859 15.1758 16.7568 15.1758C16.7949 15.1758 16.8301 15.1836 16.8613 15.1953C16.9033 15.2109 16.9424 15.2344 16.9727 15.2695C17.0273 15.3223 17.0586 15.4004 17.0586 15.4805C17.0586 15.6504 16.9229 15.7852 16.7529 15.7852C16.582 15.7852 16.4502 15.6504 16.4502 15.4805ZM19.5273 17.0625C19.3301 17.1426 19.1328 17.2129 18.9434 17.2207C18.6494 17.2344 18.3281 17.1152 18.1533 16.9688C17.8828 16.7422 17.6895 16.6152 17.6074 16.2168C17.5732 16.0469 17.5928 15.7852 17.623 15.6348C17.6934 15.3105 17.6152 15.1035 17.3877 14.9141C17.2012 14.7598 16.9658 14.7188 16.7061 14.7188C16.6094 14.7188 16.5205 14.6758 16.4541 14.6406C16.3457 14.5859 16.2568 14.4512 16.3418 14.2852C16.3691 14.2324 16.501 14.1016 16.5322 14.0781C16.8838 13.877 17.29 13.9434 17.666 14.0938C18.0146 14.2363 18.2773 14.498 18.6562 14.8672C19.0439 15.3145 19.1133 15.4395 19.334 15.7734C19.5078 16.0371 19.667 16.3066 19.7754 16.6152C19.8408 16.8066 19.7559 16.9648 19.5273 17.0625Z"
fill="#4D6BFE" />
</svg>
<div v-if="deepseekBalance.is_available" class="text-xs">
<span class="text-gray-500">余额:</span>
<span
class="font-medium text-[#4D6BFE]">{{ deepseekBalance.balance_infos[0]?.total_balance || '0.00'
}}</span>
<span class="text-gray-500">{{ deepseekBalance.balance_infos[0]?.currency }}</span>
</div>
<button
@click="refreshDeepSeekBalance"
class="p-1 text-[#4D6BFE] hover:bg-[#4D6BFE]/10 rounded-full transition-colors duration-200"
:title="deepseekBalance.is_available ? '刷新余额' : '点击查询余额'"
>
<svg class="w-3.5 h-3.5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15" />
</svg>
</button>
</div>
</div>
<!-- 处理信息和Token信息 -->
<div class="mb-4 p-3 bg-gray-50 rounded-lg">
<div class="text-xs text-gray-500 space-y-2">
<p>处理用时:{{ Math.round(localSummaryData?.processing_time || 0) }}秒</p>
<p>使用模型:{{ localSummaryData?.from_deepseek ? 'DeepSeek' : 'GPT' }}</p>
<div class="border-t border-gray-200 my-2 pt-2">
<p class="font-medium mb-1">Token 使用统计:</p>
<p>• 提示词:{{ localSummaryData?.tokens_used?.prompt_tokens || 0 }} tokens</p>
<p>• 生成内容:{{ localSummaryData?.tokens_used?.completion_tokens || 0 }} tokens</p>
<p>• 总计:{{ localSummaryData?.tokens_used?.total_tokens || 0 }} tokens</p>
<p v-if="localSummaryData?.tokens_used?.prompt_tokens_details?.cached_tokens">
• 命中缓存:{{ localSummaryData?.tokens_used?.prompt_tokens_details?.cached_tokens }} tokens
</p>
</div>
</div>
</div>
<!-- 摘要内容 -->
<div class="text-sm text-gray-700 whitespace-pre-line">
<div v-if="localSummaryData?.summary" class="space-y-4">
<template v-for="(section, index) in localSummaryData.summary.split('\n')" :key="index">
<div v-if="hasTimeStamp(section)"
class="cursor-pointer hover:bg-[#fb7299]/10 hover:text-[#fb7299] transition-colors duration-200 px-2 py-1 rounded"
@click="handleTimeClick(section)">
<span class="text-[#fb7299]">{{ extractTimeStamp(section) }}</span>
<span>{{ section.replace(extractTimeStamp(section), '') }}</span>
</div>
<div v-else>{{ section }}</div>
</template>
</div>
</div>
</div>
<!-- 音频文件状态检查 -->
<div class="bg-white rounded-lg border border-gray-200 p-4">
<div class="flex items-start justify-between">
<div class="flex items-start space-x-2">
<div v-if="isCheckingAudio" class="flex items-center space-x-2 text-gray-500">
<div
class="animate-spin h-4 w-4 border-2 border-gray-300 border-t-transparent rounded-full"></div>
<span>正在检查音频文件...</span>
</div>
<template v-else>
<div v-if="audioPath" class="flex-1">
<div class="flex items-center space-x-2">
<svg class="w-5 h-5 text-green-600" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 13l4 4L19 7" />
</svg>
<span class="text-sm font-medium text-gray-900">已找到音频文件</span>
</div>
<p class="mt-1 text-xs text-gray-500 break-all">{{ audioPath }}</p>
</div>
<div v-else class="flex-1">
<div class="flex items-center space-x-2">
<svg class="w-5 h-5 text-yellow-500" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z"></path>
</svg>
<span class="text-sm font-medium text-gray-900">未找到音频文件</span>
</div>
<p class="mt-1 text-xs text-gray-500">请下载音频文件</p>
</div>
</template>
</div>
<!-- 下载按钮 -->
<button
v-if="!audioPath && !isCheckingAudio"
@click="handleShowDownload"
class="px-4 py-2 text-sm font-medium text-white bg-[#fb7299] rounded-md hover:bg-[#fb7299]/90"
>
下载音频
</button>
</div>
<!-- 已存在的转录文件信息 -->
<div v-if="hasExistingStt" class="mt-4 border-t pt-4">
<div class="flex items-center space-x-2">
<svg class="w-5 h-5 text-green-600" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 13l4 4L19 7" />
</svg>
<span class="text-sm font-medium text-gray-900">已找到转录文件</span>
</div>
<p v-if="sttFilePath" class="mt-1 text-xs text-gray-500 break-all">{{ sttFilePath }}</p>
</div>
</div>
<!-- 转录状态和结果横幅 -->
<div
v-if="transcriptionStatus && (isTranscribing || transcriptionResult || transcriptionStatus !== '音频文件已找到,可以开始转录')"
class="rounded-lg p-4" :class="{
'bg-blue-50 border border-blue-200': isTranscribing,
'bg-green-50 border border-green-200': transcriptionResult && !isTranscribing,
'bg-gray-50 border border-gray-200': !transcriptionResult && !isTranscribing
}">
<div class="flex items-center space-x-3">
<div v-if="isTranscribing" class="flex-shrink-0">
<svg class="animate-spin h-5 w-5 text-blue-500" fill="none" viewBox="0 0 24 24">
<circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
<path class="opacity-75" fill="currentColor"
d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
</svg>
</div>
<div v-else-if="transcriptionResult" class="flex-shrink-0">
<svg class="h-5 w-5 text-green-500" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 13l4 4L19 7" />
</svg>
</div>
<div class="flex-1">
<p class="text-sm font-medium" :class="{
'text-blue-700': isTranscribing,
'text-green-700': transcriptionResult && !isTranscribing,
'text-gray-700': !transcriptionResult && !isTranscribing
}">{{ transcriptionStatus }}</p>
<div v-if="transcriptionResult && !isTranscribing" class="mt-2 grid grid-cols-3 gap-4">
<div class="text-xs text-gray-600">
<span class="font-medium">视频时长:</span>
{{ formatDuration(transcriptionResult.duration) }}
</div>
<div class="text-xs text-gray-600">
<span class="font-medium">处理用时:</span>
{{ Math.round(transcriptionResult.processingTime) }}秒
</div>
<div class="text-xs text-gray-600">
<span class="font-medium">检测语言:</span>
{{ transcriptionResult.languageDetected === 'zh' ? '中文' : '英文' }}
</div>
</div>
</div>
</div>
</div>
<!-- 生成摘要按钮和状态 -->
<div v-if="!isTranscribing && (hasExistingStt || transcriptionResult)">
<button
@click="startGeneratingSummary"
:disabled="isSummarizing"
class="w-full flex items-center justify-center px-4 py-2 text-sm font-medium text-white bg-[#fb7299] rounded-md hover:bg-[#fb7299]/90 disabled:opacity-50"
>
<svg v-if="isSummarizing" class="animate-spin -ml-1 mr-2 h-4 w-4 text-white" fill="none"
viewBox="0 0 24 24">
<circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
<path class="opacity-75" fill="currentColor"
d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
</svg>
{{ isSummarizing ? '正在生成摘要...' : '生成摘要' }}
</button>
<p v-if="isSummarizing" class="mt-2 text-sm text-gray-500 text-center">
正在使用AI分析视频内容,请稍候...
</p>
</div>
<!-- 模型选择部分 -->
<div class="bg-white rounded-lg border border-gray-200 p-4">
<div class="flex items-center justify-between mb-2">
<h4 class="text-base font-medium text-gray-900">选择语音识别模型</h4>
<button
@click="startTranscription"
:disabled="!selectedModel || !selectedModel.is_downloaded || isTranscribing"
class="px-3 py-1.5 text-xs md:text-sm font-medium text-white rounded-md hover:bg-[#fb7299]/90 disabled:opacity-50 disabled:cursor-not-allowed"
:class="isTranscribing ? 'bg-blue-500' : 'bg-[#fb7299]'"
>
<span v-if="isTranscribing" class="flex items-center">
<svg class="animate-spin -ml-1 mr-2 h-4 w-4 text-white" fill="none" viewBox="0 0 24 24">
<circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
<path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
</svg>
正在转换中...
</span>
<span v-else>开始音频转文字</span>
</button>
</div>
<!-- 长视频警告 -->
<div v-if="video && video.duration > 1800"
class="mb-4 p-3 bg-yellow-50 border border-yellow-100 rounded-lg">
<div class="flex items-start">
<svg class="w-5 h-5 text-yellow-600 mt-0.5 mr-2 flex-shrink-0" fill="none" viewBox="0 0 24 24"
stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z" />
</svg>
<div>
<p class="text-sm font-medium text-yellow-800">长视频警告</p>
<p class="text-sm text-yellow-700 mt-1">
该视频时长超过30分钟,音频转文字后可能产生大量文本。这可能导致上下文过长,使AI无法接受请求。请谨慎操作
</p>
</div>
</div>
</div>
<!-- 语言选择 -->
<div class="mb-4">
<label class="block text-sm font-medium text-gray-700 mb-2">选择语言</label>
<div class="grid grid-cols-2 gap-2">
<button
@click="selectedLanguage = 'zh'"
class="px-4 py-2 text-sm font-medium rounded-lg transition-colors duration-200"
:class="[
selectedLanguage === 'zh'
? 'bg-[#fb7299] text-white'
: 'bg-gray-100 text-gray-700 hover:bg-gray-200'
]"
>
中文
</button>
<button
@click="selectedLanguage = 'en'"
class="px-4 py-2 text-sm font-medium rounded-lg transition-colors duration-200"
:class="[
selectedLanguage === 'en'
? 'bg-[#fb7299] text-white'
: 'bg-gray-100 text-gray-700 hover:bg-gray-200'
]"
>
英文
</button>
</div>
</div>
<!-- 模型列表 -->
<div class="grid grid-cols-1 md:grid-cols-2 gap-4">
<div v-for="model in whisperModels"
:key="model.name"
@click="selectModel(model)"
@mouseenter="hoveredModel = model"
@mouseleave="hoveredModel = null"
class="relative border rounded-lg p-4 cursor-pointer transition-all duration-200 hover:border-[#fb7299]"
:class="[
selectedModel?.name === model.name ? 'border-[#fb7299] bg-pink-50' : 'border-gray-200',
!model.is_downloaded ? 'opacity-50' : ''
]"
>
<div class="flex items-start justify-between">
<div>
<h5 class="text-sm font-medium text-gray-900">
{{ model.description }}
<span
v-if="model.name === 'tiny' || (model.description && model.description.includes('极小型'))"
class="ml-2 inline-flex items-center px-1.5 py-0.5 rounded bg-[#fb7299]/10 text-[#fb7299] text-[10px]"
>推荐</span>
</h5>
<p class="text-xs text-gray-500 mt-1">{{ model.params_size }}</p>
<p v-if="model.is_downloaded" class="text-xs text-gray-400 mt-1 truncate" :title="model.path">
{{ model.path }}
</p>
</div>
<div v-if="model.is_downloaded"
class="flex-shrink-0 text-green-600">
<svg class="w-5 h-5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 13l4 4L19 7" />
</svg>
</div>
</div>
<p class="mt-2 text-xs text-gray-600">{{ model.recommended_use }}</p>
<!-- 已下载模型的删除按钮 -->
<div
v-if="model.is_downloaded && hoveredModel && hoveredModel.name === model.name && !isDeletingModel"
class="absolute top-2 right-2 z-10">
<button @click.stop="showModelDeleteConfirm(model)"
class="p-1 bg-red-500 text-white rounded-full hover:bg-red-600 transition-colors duration-200">
<svg class="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
d="M6 18L18 6M6 6l12 12" />
</svg>
</button>
</div>
<!-- 删除模型中状态 -->
<div v-if="isDeletingModel && modelToDelete && modelToDelete.name === model.name"
class="absolute inset-0 bg-white/80 backdrop-blur-sm flex items-center justify-center rounded-lg">
<div class="flex flex-col items-center space-y-2">
<div
class="animate-spin h-6 w-6 border-2 border-red-500 border-t-transparent rounded-full"></div>
<span class="text-sm text-red-500">删除中...</span>
</div>
</div>
<!-- 未下载提示 -->
<div v-if="!model.is_downloaded"
class="absolute inset-0 bg-white/80 backdrop-blur-sm flex items-center justify-center rounded-lg">
<!-- 下载按钮 -->
<div v-if="hoveredModel && hoveredModel.name === model.name && !isDownloadingModel"
class="flex flex-col items-center space-y-2"
@click.stop="showModelDownloadConfirm(model)">
<button
class="px-3 py-1.5 bg-[#fb7299] text-white rounded-md text-sm hover:bg-[#fb7299]/90 transition-colors duration-200">
下载模型
</button>
<span class="text-xs text-gray-500">{{ model.params_size }}</span>
</div>
<!-- 下载中状态 -->
<div v-else-if="isDownloadingModel && downloadingModel && downloadingModel.name === model.name"
class="flex flex-col items-center space-y-2">
<div
class="animate-spin h-6 w-6 border-2 border-[#fb7299] border-t-transparent rounded-full"></div>
<span class="text-sm text-[#fb7299]">下载中...</span>
</div>
<!-- 默认状态 -->
<span v-else class="text-sm text-gray-500">需要下载</span>
</div>
</div>
</div>
</div>
</template>
</div>
</div>
</div>
</div>
<!-- 加载中 -->
<div v-else class="p-6 flex justify-center">
<div class="animate-spin h-8 w-8 border-4 border-[#fb7299] border-t-transparent rounded-full"></div>
</div>
<!-- 下载对话框组件 -->
<DownloadDialog
v-model:show="showDownloadDialog"
:video-info="{
title: video?.title || '',
author: video?.author_name || '',
bvid: video?.bvid || '',
cover: video?.cover || video?.covers?.[0] || '',
cid: video?.cid || 0
}"
:default-only-audio="currentTab === 'local'"
@download-complete="handleDownloadComplete"
/>
<!-- 下载模型确认对话框 -->
<van-dialog
v-model:show="showDownloadConfirm"
title="下载模型确认"
show-cancel-button
@confirm="startDownloadModel"
>
<div class="p-4">
<p class="text-gray-700 mb-3">您确定要下载{{ modelToDownload?.description }}吗?</p>
<div v-if="modelToDownload" class="bg-gray-50 p-3 rounded-lg">
<p class="font-medium text-gray-900">{{ modelToDownload.description }}</p>
<p class="text-sm text-gray-500 mt-1">{{ modelToDownload.params_size }}</p>
<p class="text-sm text-gray-500 mt-1">{{ modelToDownload.recommended_use }}</p>
</div>
<p class="mt-3 text-sm text-gray-500">下载模型将占用一定的磁盘空间</p>
</div>
</van-dialog>
<!-- 模型删除确认对话框 -->
<van-dialog
v-model:show="showDeleteConfirm"
title="删除模型确认"
show-cancel-button
@confirm="startDeleteModel"
>
<div class="p-4">
<p class="text-gray-700 mb-3">您确定要删除{{ modelToDelete?.description }}吗?</p>
<div v-if="modelToDelete" class="bg-gray-50 p-3 rounded-lg">
<p class="font-medium text-gray-900">{{ modelToDelete.description }}</p>
<p class="text-sm text-gray-500 mt-1">{{ modelToDelete.params_size }}</p>
<p class="text-sm text-gray-500 mt-1">{{ modelToDelete.recommended_use }}</p>
</div>
<p class="mt-3 text-sm text-gray-500">删除模型将释放磁盘空间</p>
</div>
</van-dialog>
</van-dialog>
<!-- 视频下载对话框 -->
<DownloadDialog
v-model:show="showDownloadDialog"
:video-info="{
title: video?.title || '',
author: video?.author || '',
bvid: video?.bvid || '',
cover: video?.cover || video?.covers?.[0] || '',
cid: video?.cid || 0
}"
:default-only-audio="currentTab === 'local'"
@download-complete="handleDownloadComplete"
/>
</template>
<script setup>
import { ref, computed, watch } from 'vue'
import { showNotify, showDialog } from 'vant'
import { usePrivacyStore } from '../../store/privacy'
import 'vant/es/notify/style'
import 'vant/es/dialog/style'
import {
updateVideoRemark,
getWhisperModels,
findAudioPath,
transcribeAudio,
checkSttFile,
summarizeByCid,
checkLocalSummary,
downloadWhisperModel,
deleteWhisperModel,
checkAudioToTextEnvironment,
getDeepSeekBalance,
checkSystemResources,
checkVideoDownload,
} from '../../api/api'
import VideoSummary from './VideoSummary.vue'
import EnvironmentCheck from './EnvironmentCheck.vue'
import DownloadDialog from './DownloadDialog.vue'
import 'vant/es/dialog/style'
import { openInBrowser } from '@/utils/openUrl.js'
import { normalizeImageUrl } from '@/utils/imageUrl.js'
const props = defineProps({
modelValue: {
type: Boolean,
default: false,
},
video: {
type: Object,
default: null,
},
remarkData: {
type: Object,
default: () => ({}),
},
})
const emit = defineEmits(['update:modelValue', 'remark-updated'])
// 在脚本顶部导入部分之后加入这个ref
const videoSummaryKey = ref(0)
// 使用计算属性处理dialog可见性
const dialogVisible = computed(() => props.modelValue)
const updateVisible = (value) => {
emit('update:modelValue', value)
// 当对话框关闭时重置状态
if (!value) {
// 重置标签页到默认的B站摘要tab
currentTab.value = 'bilibili'
// 重置摘要相关状态
isCheckingEnvironment.value = false
canRunSpeechToText.value = false
cudaAvailable.value = false
cudaSetupGuide.value = ''
showCudaGuide.value = true
audioPath.value = null
isCheckingAudio.value = false
isTranscribing.value = false
transcriptionResult.value = null
isSummarizing.value = false
summaryStatus.value = ''
summaryResult.value = null
hasExistingStt.value = false
sttFilePath.value = null
hasLocalSummary.value = false
localSummaryData.value = null
// 通过改变key值强制重新创建摘要组件
videoSummaryKey.value += 1
} else {
// 弹窗打开时默认刷新一次 DeepSeek 余额,防止不显示
refreshDeepSeekBalance()
}
}
// 监听弹窗显隐,进入弹窗即刷新一次余额(不依赖标签页)
watch(() => props.modelValue, (visible) => {
if (visible) {
refreshDeepSeekBalance()
}
})
const { isPrivacyMode } = usePrivacyStore()
// 备注相关
const remarkContent = ref('')
const originalRemark = ref('')
const remarkTime = ref(null)
// 格式化时间戳
const formatTimestamp = (timestamp) => {
if (!timestamp) return '时间未知'
try {
const date = new Date(timestamp * 1000)
return date.toLocaleString('zh-CN', {
year: 'numeric',
month: '2-digit',
day: '2-digit',
hour: '2-digit',
minute: '2-digit',
})
} catch (error) {
console.error('格式化时间戳失败:', error)
return '时间未知'
}
}
// 格式化备注时间
const formatRemarkTime = (timestamp) => {
if (!timestamp) return ''
const date = new Date(timestamp * 1000)
return date.toLocaleString('zh-CN', {
month: '2-digit',
day: '2-digit',
hour: '2-digit',
minute: '2-digit',
})
}
// 格式化时长
const formatDuration = (seconds) => {
if (seconds === -1) return '已看完'
const minutes = String(Math.floor(seconds / 60)).padStart(2, '0')
const secs = String(seconds % 60).padStart(2, '0')
return `${minutes}:${secs}`
}
// 计算进度条宽度百分比
const getProgressWidth = (progress, duration) => {
if (!duration || duration <= 0 || !progress || progress < 0) return '0%'
const percentage = Math.min(100, (progress / duration) * 100)
return `${percentage}%`
}
// 获取设备类型
const getDeviceType = (dt) => {
if (dt === 1 || dt === 3 || dt === 5 || dt === 7) return '手机'
if (dt === 2 || dt === 33) return '电脑'
if (dt === 4 || dt === 6) return '平板'
return '未知设备'
}
// 获取业务类型
const getBusinessType = (business) => {
const businessTypes = {
archive: '稿件',
cheese: '课堂',
pgc: '电影',
live: '直播',
'article-list': '专栏',
article: '专栏',
}
return businessTypes[business] || '其他类型'
}
// 初始化备注内容
const initRemark = () => {
if (!props.video) return
const key = `${props.video.bvid}_${props.video.view_at}`
const data = props.remarkData[key]
if (data) {
remarkContent.value = data.remark || ''
remarkTime.value = data.remark_time || null
originalRemark.value = remarkContent.value // 保存原始值
} else {
remarkContent.value = ''
remarkTime.value = null
originalRemark.value = ''
}
}
// 处理备注失去焦点
const handleRemarkBlur = async () => {
// 如果内容没有变化,不发送请求
if (remarkContent.value === originalRemark.value || !props.video) {
return
}
try {
const response = await updateVideoRemark(
props.video.bvid,
props.video.view_at,
remarkContent.value,
)
if (response.data.success || response.data.status === 'success') {
if (remarkContent.value) { // 只在有内容时显示提示
showNotify({
type: 'success',
message: '备注已保存',
})
}
originalRemark.value = remarkContent.value // 更新原始值
remarkTime.value = response.data.data.remark_time // 更新备注时间
// 通知父组件备注已更新
emit('remark-updated', {
bvid: props.video.bvid,
view_at: props.video.view_at,
remark: remarkContent.value,
remark_time: response.data.data.remark_time,
})
}
} catch (error) {
showNotify({
type: 'danger',
message: `保存备注失败:${error.message}`,
})
remarkContent.value = originalRemark.value // 恢复原始值
}
}
// 在B站打开视频
const openInBilibili = async () => {
if (!props.video) return
let url = ''
switch (props.video.business) {
case 'archive':
url = `https://www.bilibili.com/video/${props.video.bvid}`
break
case 'article':
url = `https://www.bilibili.com/read/cv${props.video.oid}`
break
case 'article-list':
url = `https://www.bilibili.com/read/readlist/rl${props.video.oid}`
break
case 'live':
url = `https://live.bilibili.com/${props.video.oid}`
break
case 'pgc':
url = props.video.uri || `https://www.bilibili.com/bangumi/play/ep${props.video.epid}`
break
case 'cheese':
url = props.video.uri || `https://www.bilibili.com/cheese/play/ep${props.video.epid}`
break
default:
console.warn('未知的业务类型:', props.video.business)
return
}
if (url) {
await openInBrowser(url)
}
}
// 打开UP主页面
const openAuthorPage = async () => {
if (!props.video || !props.video.author_mid) return
const url = `https://space.bilibili.com/${props.video.author_mid}`
await openInBrowser(url)
}
// 监听video变化,初始化备注
watch(() => props.video, () => {
if (props.video) {
initRemark()
}
}, { deep: true, immediate: true })
const tabs = [
{ id: 'bilibili', name: 'B站AI摘要' },
{ id: 'local', name: '使用本地摘要' },
]
const currentTab = ref('bilibili')
// Whisper模型相关
const whisperModels = ref([])
const selectedModel = ref(null)
const transcriptionStatus = ref('')
const audioPath = ref(null)
const isCheckingAudio = ref(false)
const showDownloadDialog = ref(false)
const selectedLanguage = ref('zh')
const isTranscribing = ref(false)
const transcriptionResult = ref(null)
const isSummarizing = ref(false)
const summaryStatus = ref('')
const summaryResult = ref(null)
// 模型下载相关状态
const downloadingModel = ref(null) // 当前正在下载的模型
const isDownloadingModel = ref(false) // 是否正在下载模型
const showDownloadConfirm = ref(false) // 是否显示下载确认对话框
const modelToDownload = ref(null) // 要下载的模型
const hoveredModel = ref(null) // 当前悬停的模型
// 模型删除相关状态
const isDeletingModel = ref(false) // 是否正在删除模型
const showDeleteConfirm = ref(false) // 是否显示删除确认对话框
const modelToDelete = ref(null) // 要删除的模型
// 显示下载对话框
const handleShowDownload = () => {
if (!props.video) return
showDownloadDialog.value = true
}
// 获取Whisper模型列表
const fetchWhisperModels = async () => {
try {
const response = await getWhisperModels()
// 对模型进行排序:多语言模型在前,英语模型在后
whisperModels.value = response.data.sort((a, b) => {
// 如果一个是英语模型(包含.en),一个不是,将非英语模型排在前面
const aIsEnglish = a.name.includes('.en')
const bIsEnglish = b.name.includes('.en')
if (aIsEnglish !== bIsEnglish) {
return aIsEnglish ? 1 : -1
}
// 如果都是同类型(都是英语或都是多语言),按照大小排序(tiny -> base -> small -> medium -> large)
const sizeOrder = ['tiny', 'base', 'small', 'medium', 'large-v1', 'large-v2', 'large-v3']
const aBaseName = a.name.replace('.en', '')
const bBaseName = b.name.replace('.en', '')
return sizeOrder.indexOf(aBaseName) - sizeOrder.indexOf(bBaseName)
})
// 选择推荐的模型
if (whisperModels.value.length > 0) {
// 选择tiny模型
const tinyModel = whisperModels.value.find(model =>
model.name === 'tiny' && model.is_downloaded,
)
// 如果找到tiny模型,选择它
if (tinyModel) {
selectModel(tinyModel)
} else {
// 如果没有找到tiny模型,选择第一个下载好的模型
const firstDownloadedModel = whisperModels.value.find(model => model.is_downloaded)
if (firstDownloadedModel) {
selectModel(firstDownloadedModel)
}
}
}
} catch (error) {
console.error('获取Whisper模型列表失败:', error)
showNotify({
type: 'danger',
message: '获取模型列表失败',
})
}
}
// 选择模型
const selectModel = (model) => {
if (model.is_downloaded) {
selectedModel.value = model
} else {
showNotify({
type: 'warning',
message: '该模型尚未下载,请选择已下载的模型',
})
}
}
// 获取音频文件路径
const checkAudioFile = async () => {
try {
isCheckingAudio.value = true
transcriptionStatus.value = '检查音频文件...'
const response = await findAudioPath(props.video.cid)
audioPath.value = response.data.audio_path
if (audioPath.value) {
transcriptionStatus.value = '音频文件已找到,可以开始转录'
}
return true
} catch (error) {
console.error('查找音频文件失败:', error)
transcriptionStatus.value = ''
return false
} finally {
isCheckingAudio.value = false
}
}
// 在 script setup 部分添加
const hasExistingStt = ref(false)
const sttFilePath = ref(null)
// 检查是否存在转换后的文件
const checkExistingStt = async () => {
try {
if (!props.video?.cid) return
const response = await checkSttFile(props.video.cid)
if (response.data.success) {
hasExistingStt.value = response.data.exists
sttFilePath.value = response.data.file_path
if (response.data.exists) {
transcriptionStatus.value = '已存在转换后的文件'
}
}
} catch (error) {
console.error('检查转换文件失败:', error)
}
}
// 在 script setup 部分添加新的响应式变量
const localSummaryData = ref(null)
const hasLocalSummary = ref(false)
// 添加检查本地摘要的函数
const checkLocalSummaryFile = async () => {
try {
if (!props.video?.cid) return
const response = await checkLocalSummary(props.video.cid)
if (response.data.exists) {
hasLocalSummary.value = true
localSummaryData.value = response.data.full_response
transcriptionStatus.value = '已找到本地摘要'
}
} catch (error) {
console.error('检查本地摘要失败:', error)
}
}
// 修改 watch currentTab
watch(currentTab, async (newTab) => {
if (newTab === 'local') {
// 首先检查环境
isCheckingEnvironment.value = true
canRunSpeechToText.value = false
cudaSetupGuide.value = ''
try {
// 1. 检查系统资源
const resourceResponse = await checkSystemResources()
canRunSpeechToText.value = resourceResponse.data.can_run_speech_to_text
systemLimitationReason.value = resourceResponse.data.limitation_reason
// 2. 如果系统资源足够,再检查CUDA
if (canRunSpeechToText.value) {
const cudaResponse = await checkAudioToTextEnvironment()
cudaAvailable.value = cudaResponse.data.system_info.cuda_available
cudaSetupGuide.value = cudaResponse.data.system_info.cuda_setup_guide || ''
// 只有在系统资源足够时才加载其他内容
fetchWhisperModels()
await checkAudioFile()
await checkExistingStt()
await checkLocalSummaryFile()
await refreshDeepSeekBalance()
}
} catch (error) {
console.error('检查系统资源失败:', error)
canRunSpeechToText.value = false
systemLimitationReason.value = '检查系统资源失败: ' + (error.message || '未知错误')
} finally {
isCheckingEnvironment.value = false
}
}
})
// 修改 startTranscription 函数
const startTranscription = async () => {
if (!selectedModel.value) {
showNotify({
type: 'warning',
message: '请先选择一个模型',
})
return
}
if (!audioPath.value) {
await checkAudioFile()
if (!audioPath.value) {
return
}
}
// 检查视频时长,如果超过30分钟,显示额外确认
if (props.video && props.video.duration > 1800) {
const result = await showDialog({
title: '长视频警告',
message: '该视频时长超过30分钟,转录后可能产生大量文本,导致AI无法处理。是否继续?',
showCancelButton: true,
})
if (!result) {
return
}
}
if (hasExistingStt.value) {
const result = await showDialog({
title: '提示',
message: '已存在转换后的文件,是否重新转换?',
showCancelButton: true,
})
if (!result) {
return
}
}
try {
isTranscribing.value = true
transcriptionStatus.value = '准备开始转换...'
const response = await transcribeAudio({
audio_path: audioPath.value,
model_size: selectedModel.value.name,
language: selectedLanguage.value,
cid: props.video.cid,
})
if (response.data.success || response.data.status === 'success') {
transcriptionStatus.value = '转录任务已开始,正在处理中...'
showNotify({
type: 'success',
message: '转录任务已开始',
})
handleTranscriptionComplete(response.data)
} else {
isTranscribing.value = false
showNotify({
type: 'danger',
message: response.data.message || '开始转录失败',
})
}
} catch (error) {
console.error('转录失败:', error)
transcriptionStatus.value = `转录失败: ${error.message || '未知错误'}`
isTranscribing.value = false
}
}
// 检查转录状态
const handleTranscriptionComplete = async (response) => {
isTranscribing.value = false
transcriptionStatus.value = '转录完成'
transcriptionResult.value = {
duration: response.duration,
processingTime: response.processing_time,
languageDetected: response.language_detected,
}
showNotify({
type: 'success',
message: '转录完成',
})
// 重置摘要相关状态
summaryStatus.value = ''
summaryResult.value = null
isSummarizing.value = false
// 转录完成后,刷新标签内容
await checkExistingStt()
await checkLocalSummaryFile()
}
// 添加生成摘要的函数
const startGeneratingSummary = async () => {
try {
// 检查视频时长,如果超过30分钟,显示额外确认
if (props.video && props.video.duration > 1800) {
const result = await showDialog({
title: '长视频警告',
message: '该视频时长超过30分钟,转录文本可能过长,导致AI无法处理摘要请求。是否继续?',
showCancelButton: true,
})
if (!result) {
return
}
}
isSummarizing.value = true
summaryStatus.value = '正在生成摘要...'
const response = await summarizeByCid(props.video.cid)
if (response.data.success || response.data.status === 'success') {
summaryStatus.value = '摘要生成完成'
summaryResult.value = response.data.summary
showNotify({
type: 'success',
message: '摘要生成完成',
})
// 摘要生成完成后,刷新标签内容
await checkLocalSummaryFile()
} else {
summaryStatus.value = '摘要生成失败:' + (response.data.message || '未知错误')
showNotify({
type: 'warning',
message: '摘要生成失败',
})
}
} catch (error) {
console.error('生成摘要失败:', error)
summaryStatus.value = '摘要生成失败:' + (error.message || '未知错误')
showNotify({
type: 'danger',
message: '生成摘要失败:' + (error.message || '未知错误'),
})
} finally {
isSummarizing.value = false
}
}
// 在 script setup 部分添加
const environmentCheck = ref(null)
const isCheckingEnvironment = ref(true)
const canRunSpeechToText = ref(false)
const systemLimitationReason = ref('')
const cudaAvailable = ref(false)
const cudaSetupGuide = ref('')
const showCudaGuide = ref(true) // 默认显示CUDA安装指南
// 处理环境检查结果
const handleEnvironmentCheck = (result) => {
isCheckingEnvironment.value = false
canRunSpeechToText.value = result.canRun
systemLimitationReason.value = result.limitationReason
}
// 修改 handleTimeClick 函数和添加 hasTimeStamp 函数
const hasTimeStamp = (text) => {
return /\d{2}:\d{2}[-–]\d{2}:\d{2}/.test(text)
}
const handleTimeClick = async (section) => {
const timeMatch = section.match(/(\d{2}):(\d{2})[-–](\d{2}):(\d{2})/)
if (timeMatch) {
const startMinutes = parseInt(timeMatch[1])
const startSeconds = parseInt(timeMatch[2])
const startTime = startMinutes * 60 + startSeconds
// 构建B站视频URL并跳转
const url = `https://www.bilibili.com/video/${props.video.bvid}?t=${startTime}`
await openInBrowser(url)
}
}
// 提取时间戳的函数
const extractTimeStamp = (text) => {
const match = text.match(/(\d{2}:\d{2}[-–]\d{2}:\d{2})/)
return match ? match[1] : ''
}
// 处理下载完成事件
const handleDownloadComplete = async () => {
// 下载完成后,刷新标签内容
checkAudioFile()
checkExistingStt()
checkLocalSummaryFile()
// 重新检查视频下载状态
await checkIsVideoDownloaded()
showNotify({
type: 'success',
message: '下载完成',
duration: 2000,
})
}
// 下载模型确认对话框相关
const showModelDownloadConfirm = (model) => {
modelToDownload.value = model
showDownloadConfirm.value = true
}
const startDownloadModel = async () => {
if (!modelToDownload.value) return
try {
isDownloadingModel.value = true
downloadingModel.value = modelToDownload.value
const response = await downloadWhisperModel(modelToDownload.value.name)
if (response.data.success || response.data.status === 'success') {
showNotify({
type: 'success',
message: response.data.message || '模型下载成功',
})
// 下载完成后,刷新模型列表
fetchWhisperModels()
} else {
showNotify({
type: 'danger',
message: response.data.message || '模型下载失败',
})
}
} catch (error) {
console.error('下载模型失败:', error)
showNotify({
type: 'danger',
message: '下载模型失败',
})
} finally {
isDownloadingModel.value = false
downloadingModel.value = null
}
}
// 模型删除确认对话框相关
const showModelDeleteConfirm = (model) => {
modelToDelete.value = model
showDeleteConfirm.value = true
}
const startDeleteModel = async () => {
if (!modelToDelete.value) return
try {
isDeletingModel.value = true
const response = await deleteWhisperModel(modelToDelete.value.name)
if (response.data.success || response.data.status === 'success') {
showNotify({
type: 'success',
message: response.data.message || '模型删除成功',
})
// 删除完成后,刷新模型列表
fetchWhisperModels()
} else {
showNotify({
type: 'danger',
message: response.data.message || '模型删除失败',
})
}
} catch (error) {
console.error('删除模型失败:', error)
showNotify({
type: 'danger',
message: '删除模型失败',
})
} finally {
isDeletingModel.value = false
modelToDelete.value = null
}
}
// DeepSeek相关状态
const deepseekBalance = ref({
is_available: false,
balance_infos: [],
})
// 添加刷新DeepSeek余额的方法
const refreshDeepSeekBalance = async () => {
try {
const response = await getDeepSeekBalance()
deepseekBalance.value = response.data
} catch (error) {
console.error('获取DeepSeek余额失败:', error)
deepseekBalance.value = { is_available: false }
}
}
// 下载相关
const isVideoDownloaded = ref(false)
const downloadedFiles = ref([])
// 检查视频是否已下载
const checkIsVideoDownloaded = async () => {
try {
// 如果没有CID,则无法检查
if (!props.video?.cid) return
const response = await checkVideoDownload(props.video.cid)
if (response.data && response.data.status === 'success') {
isVideoDownloaded.value = response.data.downloaded
if (isVideoDownloaded.value && response.data.files) {
downloadedFiles.value = response.data.files
} else {
downloadedFiles.value = []
}
}
} catch (error) {
console.error('检查视频下载状态出错:', error)
isVideoDownloaded.value = false
downloadedFiles.value = []
}
}
// 监听视频变化,检查下载状态
watch(() => props.video?.cid, (newCid) => {
if (newCid) {
checkIsVideoDownloaded()
} else {
isVideoDownloaded.value = false
downloadedFiles.value = []
}
})
</script>
<style>
.video-detail-dialog :deep(.van-dialog) {
border-radius: 0.5rem;
overflow: hidden;
}
.video-detail-dialog :deep(.van-dialog__header) {
padding: 12px 16px;
border-bottom: 1px solid #f3f4f6;
}
</style>
|
281677160/openwrt-package
| 1,768
|
luci-app-passwall2/luasrc/passwall2/util_tuic.lua
|
module("luci.passwall2.util_tuic", package.seeall)
local api = require "luci.passwall2.api"
local uci = api.uci
local json = api.jsonc
function gen_config(var)
local node_id = var["-node"]
if not node_id then
print("-node 不能为空")
return
end
local node = uci:get_all("passwall2", node_id)
local local_addr = var["-local_addr"]
local local_port = var["-local_port"]
local server_host = var["-server_host"] or node.address
local server_port = var["-server_port"] or node.port
local loglevel = var["-loglevel"] or "warn"
local tuic= {
relay = {
server = server_host .. ":" .. server_port,
ip = node.tuic_ip,
uuid = node.uuid,
password = node.tuic_password,
-- certificates = node.tuic_certificate and { node.tuic_certpath } or nil,
udp_relay_mode = node.tuic_udp_relay_mode,
congestion_control = node.tuic_congestion_control,
heartbeat = node.tuic_heartbeat .. "s",
timeout = node.tuic_timeout .. "s",
gc_interval = node.tuic_gc_interval .. "s",
gc_lifetime = node.tuic_gc_lifetime .. "s",
alpn = node.tuic_tls_alpn,
disable_sni = (node.tuic_disable_sni == "1"),
zero_rtt_handshake = (node.tuic_zero_rtt_handshake == "1"),
send_window = tonumber(node.tuic_send_window),
receive_window = tonumber(node.tuic_receive_window)
},
["local"] = {
server = "[::]:" .. local_port,
username = node.tuic_socks_username,
password = node.tuic_socks_password,
dual_stack = (node.tuic_dual_stack == "1") and true or false,
max_packet_size = tonumber(node.tuic_max_package_size)
},
log_level = loglevel
}
return json.stringify(tuic, 1)
end
_G.gen_config = gen_config
if arg[1] then
local func =_G[arg[1]]
if func then
print(func(api.get_function_args(arg)))
end
end
|
2977094657/BiliHistoryFrontend
| 10,039
|
src/components/tailwind/ArtPlayerWithDanmaku.vue
|
<template>
<div ref="artPlayerContainer" class="art-player-container"></div>
</template>
<script setup>
import { ref, onMounted, onUnmounted, watch } from 'vue'
import Artplayer from 'artplayer'
import artplayerPluginDanmuku from 'artplayer-plugin-danmuku'
import { getDanmakuFile } from '../../api/api'
// 定义组件属性
const props = defineProps({
// 视频源URL
videoSrc: {
type: String,
required: true
},
// 弹幕文件路径
danmakuFilePath: {
type: String,
default: ''
},
// 视频CID(用于获取弹幕)
cid: {
type: String,
default: ''
},
// 视频封面
poster: {
type: String,
default: ''
},
// 视频标题
title: {
type: String,
default: '视频播放'
},
// 是否自动播放
autoplay: {
type: Boolean,
default: false
},
// 播放器宽度
width: {
type: String,
default: '100%'
},
// 播放器高度
height: {
type: String,
default: '100%'
}
})
// 定义事件
const emit = defineEmits(['ready', 'error'])
// DOM引用
const artPlayerContainer = ref(null)
// 播放器实例
const player = ref(null)
// 弹幕数据
const danmakuData = ref([])
// 加载弹幕文件内容
const loadDanmaku = async () => {
if (!props.danmakuFilePath && !props.cid) {
console.log('没有提供弹幕文件路径或CID,跳过弹幕加载')
return []
}
try {
// 优先使用文件路径
const path = props.danmakuFilePath || ''
const cid = props.cid || ''
// 获取弹幕文件内容
const response = await getDanmakuFile(cid, path)
if (!response || !response.data) {
console.warn('弹幕文件内容为空')
return []
}
// 解析ASS格式弹幕
const danmakuItems = parseAssDanmaku(response.data)
danmakuData.value = danmakuItems
// 如果播放器已存在,更新弹幕
if (player.value && player.value.plugins.artplayerPluginDanmuku) {
player.value.plugins.artplayerPluginDanmuku.config({
danmuku: danmakuItems
})
}
return danmakuItems
} catch (error) {
console.error('加载弹幕文件失败:', error)
return []
}
}
// 解析ASS格式弹幕
const parseAssDanmaku = (assContent) => {
if (!assContent) return []
const danmakuItems = []
const lines = assContent.split('\n')
console.log("弹幕文件总行数:", lines.length)
// 查找Dialogue行
lines.forEach((line, index) => {
if (line.startsWith('Dialogue:')) {
try {
// ASS格式: Dialogue: Layer, Start, End, Style, Name, MarginL, MarginR, MarginV, Effect, Text
const parts = line.split(',')
if (parts.length >= 10) {
// 提取开始时间
const startTimeStr = parts[1].trim()
// 转换时间格式为秒 (h:mm:ss.ms)
const startTime = parseAssTime(startTimeStr)
// 提取样式名称,可能用于确定弹幕位置
const styleName = parts[3].trim()
// 提取弹幕文本 (最后一个部分)
const textParts = parts.slice(9)
let text = textParts.join(',')
// 提取颜色信息
let color = '#ffffff' // 默认白色
// B站弹幕可能使用大括号包裹样式,如 {\\c&HFFFFFF&}
// 或者直接使用反斜杠,如 \\c&HFFFFFF&
let colorRegex = /(\\c|{\\c)&H([0-9A-Fa-f]{2,6})&/
let colorMatch = text.match(colorRegex)
if (colorMatch) {
let colorCode = colorMatch[2]
console.log(`找到颜色代码: ${colorCode}, 行: ${index}, 文本: ${text}`)
// 标准化颜色代码为6位
while (colorCode.length < 6) {
colorCode = '0' + colorCode
}
// B站弹幕的颜色格式通常是BBGGRR,需要转换为网页的RGB格式
if (colorCode.length === 6) {
const blue = colorCode.substring(0, 2)
const green = colorCode.substring(2, 4)
const red = colorCode.substring(4, 6)
color = `#${red}${green}${blue}`
console.log(`转换后颜色: ${color}`)
}
}
// 确定弹幕模式
// mode: 0=滚动弹幕, 1=顶部弹幕, 2=底部弹幕
let mode = 0 // 默认为滚动弹幕
// B站弹幕定位可能有多种形式:
// 1. 使用\an指定位置,\an8是顶部,\an2是底部
// 2. 使用\pos固定位置显示
// 3. 使用\move实现滚动效果
// 检查是否有位置标记
if (text.includes('\\an8') || text.includes('{\\an8}')) {
mode = 1 // 顶部弹幕
console.log("找到顶部弹幕: ", text)
} else if (text.includes('\\an2') || text.includes('{\\an2}')) {
mode = 2 // 底部弹幕
console.log("找到底部弹幕: ", text)
} else if (text.includes('\\pos') || text.includes('{\\pos')) {
// 根据Y坐标判断是顶部还是底部弹幕
const posMatch = text.match(/\\pos\((\d+),\s*(\d+)\)/) || text.match(/{\\pos\((\d+),\s*(\d+)\)}/)
if (posMatch) {
const yPos = parseInt(posMatch[2])
// 屏幕高度一般为1080,上半部分认为是顶部弹幕,下半部分认为是底部弹幕
if (yPos < 540) {
mode = 1 // 顶部弹幕
console.log("找到顶部定位弹幕: ", text)
} else {
mode = 2 // 底部弹幕
console.log("找到底部定位弹幕: ", text)
}
}
} else if (text.includes('\\move') || text.includes('{\\move')) {
// 移动弹幕默认为滚动弹幕(mode=0)
console.log("找到滚动弹幕: ", text)
} else if (styleName.toLowerCase().includes('top')) {
mode = 1 // 通过样式名称判断顶部弹幕
} else if (styleName.toLowerCase().includes('bottom')) {
mode = 2 // 通过样式名称判断底部弹幕
}
// 移除ASS格式标签,保留纯文本
text = text.replace(/{[^}]*}/g, '') // 去除{}中的内容
text = text.replace(/\\[a-zA-Z0-9]+(&H[0-9A-Fa-f]+&)?/g, '') // 去除\command&Hxxxx&类格式
text = text.replace(/\\[a-zA-Z0-9]+\([^)]*\)/g, '') // 去除\command(params)类格式
text = text.trim()
// 创建弹幕对象
danmakuItems.push({
text,
time: startTime,
color: color, // 设置提取的颜色
border: false,
mode: mode, // 设置弹幕模式
})
}
} catch (error) {
console.warn('解析弹幕行失败:', line, error)
}
}
})
console.log(`成功解析${danmakuItems.length}条弹幕`)
return danmakuItems
}
// 将ASS时间格式转换为秒
const parseAssTime = (timeStr) => {
const parts = timeStr.split(':')
if (parts.length === 3) {
const hours = parseInt(parts[0])
const minutes = parseInt(parts[1])
const seconds = parseFloat(parts[2])
return hours * 3600 + minutes * 60 + seconds
}
return 0
}
// 初始化播放器
const initPlayer = async () => {
if (!artPlayerContainer.value) return
// 销毁现有播放器实例
if (player.value) {
player.value.destroy()
player.value = null
}
// 加载弹幕数据
await loadDanmaku()
// 创建播放器选项
const options = {
container: artPlayerContainer.value,
url: props.videoSrc,
title: props.title,
poster: props.poster,
volume: 0.7,
autoplay: props.autoplay,
autoSize: false,
autoMini: true,
loop: false,
flip: true,
playbackRate: true,
aspectRatio: true,
setting: true,
hotkey: true,
pip: true,
fullscreen: true,
fullscreenWeb: true,
subtitleOffset: true,
miniProgressBar: true,
playsInline: true,
lock: true,
fastForward: true,
autoPlayback: true,
theme: '#fb7299', // B站粉色主题
lang: 'zh-cn',
moreVideoAttr: {
crossOrigin: 'anonymous',
},
icons: {
loading: '<svg xmlns="http://www.w3.org/2000/svg" width="50" height="50" viewBox="0 0 24 24"><path fill="#fb7299" d="M12,1A11,11,0,1,0,23,12,11,11,0,0,0,12,1Zm0,19a8,8,0,1,1,8-8A8,8,0,0,1,12,20Z" opacity=".25"/><path fill="#fb7299" d="M12,4a8,8,0,0,1,7.89,6.7A1.53,1.53,0,0,0,21.38,12h0a1.5,1.5,0,0,0,1.48-1.75,11,11,0,0,0-21.72,0A1.5,1.5,0,0,0,2.62,12h0a1.53,1.53,0,0,0,1.49-1.3A8,8,0,0,1,12,4Z"><animateTransform attributeName="transform" dur="0.75s" repeatCount="indefinite" type="rotate" values="0 12 12;360 12 12"/></path></svg>',
},
customType: {},
}
// 如果有弹幕数据,添加弹幕插件
if (danmakuData.value.length > 0) {
options.plugins = [
artplayerPluginDanmuku({
danmuku: danmakuData.value,
speed: 5, // 弹幕速度
opacity: 0.8, // 弹幕透明度
fontSize: 25, // 弹幕字体大小
color: '#ffffff', // 默认颜色,实际会被每条弹幕自己的颜色覆盖
mode: 0, // 默认弹幕模式
margin: [10, '25%'], // 弹幕上下边距
antiOverlap: true, // 防重叠
useWorker: true, // 使用Web Worker
synchronousPlayback: true, // 同步播放(随视频播放速度变化)
filter: () => true, // 弹幕过滤
lockTime: 0, // 锁定弹幕时间
maxLength: 100, // 最大长度
minWidth: 200, // 弹幕最小宽度
maxWidth: 400, // 弹幕最大宽度
theme: 'dark', // 弹幕主题
disableDanmuku: false, // 不禁用弹幕
defaultOff: false, // 默认开启弹幕
controls: [
{
name: 'danmuku',
position: 'right',
html: '弹幕',
tooltip: '显示/隐藏弹幕',
style: {
padding: '0 10px',
fontSize: '14px',
fontWeight: 'bold'
}
}
]
}),
]
}
try {
// 初始化播放器
player.value = new Artplayer(options)
// 注册事件监听
player.value.on('ready', () => {
emit('ready', player.value)
})
player.value.on('error', (error) => {
console.error('播放器错误:', error)
emit('error', error)
})
} catch (error) {
console.error('初始化播放器失败:', error)
emit('error', error)
}
}
// 监听属性变化
watch(() => props.videoSrc, () => {
if (player.value) {
player.value.switchUrl(props.videoSrc)
// 如果有弹幕,重新加载
if (props.danmakuFilePath || props.cid) {
loadDanmaku()
}
} else {
initPlayer()
}
}, { immediate: false })
// 监听弹幕路径变化
watch([() => props.danmakuFilePath, () => props.cid], () => {
if (player.value && (props.danmakuFilePath || props.cid)) {
loadDanmaku()
}
}, { immediate: false })
// 组件挂载时初始化
onMounted(() => {
if (props.videoSrc) {
initPlayer()
}
})
// 组件卸载时销毁播放器
onUnmounted(() => {
if (player.value) {
player.value.destroy()
player.value = null
}
})
// 暴露播放器实例和方法
defineExpose({
player: player,
reload: initPlayer,
loadDanmaku
})
</script>
<style scoped>
.art-player-container {
width: v-bind(width);
height: v-bind(height);
background-color: #000;
position: relative;
}
</style>
|
2977094657/BiliHistoryFrontend
| 23,501
|
src/components/tailwind/Sidebar.vue
|
<!-- 侧边栏组件 -->
<template>
<div class="flex h-screen">
<!-- 左侧导航栏 -->
<div :class="[
'transition-all duration-300 ease-in-out bg-white/10 backdrop-blur-lg border-r border-gray-200/50 hidden sm:block',
isCollapsed ? 'w-10' : 'w-40'
]">
<!-- 侧边栏内容 -->
<div class="h-full flex flex-col">
<!-- 顶部 Logo -->
<div class="p-1 border-b border-gray-200/50">
<router-link to="/" class="w-full flex justify-center items-center">
<img v-if="isCollapsed" src="/logo.svg" class="w-full object-contain" alt="Logo" />
<img v-else src="/logo.png" class="w-full object-contain" alt="Logo" />
</router-link>
</div>
<!-- 导航菜单 -->
<nav class="flex-1 overflow-y-auto py-4 space-y-2" :class="{ 'px-4': !isCollapsed }">
<!-- 历史记录 -->
<button
@click="changeContent('history')"
:title="isCollapsed ? '历史记录' : ''"
class="w-full flex items-center py-1.5 text-gray-700 transition-all duration-300 ease-in-out text-sm"
:class="[
{ 'bg-[#fb7299]/10 text-[#fb7299]': currentContent === 'history' && !showRemarks },
{ 'justify-center': isCollapsed },
isCollapsed ? 'px-2' : 'px-3 rounded-lg'
]"
>
<svg class="w-5 h-5 flex-shrink-0" :class="{ 'mr-3': !isCollapsed }" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z" />
</svg>
<span v-show="!isCollapsed" class="truncate">历史记录</span>
</button>
<!-- 我的收藏 -->
<router-link
to="/favorites"
:title="isCollapsed ? '我的收藏' : ''"
class="flex items-center py-1.5 text-gray-700 transition-all duration-300 ease-in-out text-sm"
:class="[
{ 'bg-[#fb7299]/10 text-[#fb7299]': currentContent === 'favorites' },
{ 'justify-center': isCollapsed },
isCollapsed ? 'px-2' : 'px-3 rounded-lg'
]"
>
<svg class="w-5 h-5 flex-shrink-0" :class="{ 'mr-3': !isCollapsed }" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 5a2 2 0 012-2h10a2 2 0 012 2v16l-7-3.5L5 21V5z" />
</svg>
<span v-show="!isCollapsed" class="truncate">我的收藏</span>
</router-link>
<!-- 年度总结 -->
<router-link
to="/analytics"
:title="isCollapsed ? '年度总结' : ''"
class="flex items-center py-1.5 text-gray-700 transition-all duration-300 ease-in-out text-sm"
:class="[
{ 'bg-[#fb7299]/10 text-[#fb7299]': currentContent === 'analytics' },
{ 'justify-center': isCollapsed },
isCollapsed ? 'px-2' : 'px-3 rounded-lg'
]"
>
<svg class="w-5 h-5 flex-shrink-0" :class="{ 'mr-3': !isCollapsed }" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 19v-6a2 2 0 00-2-2H5a2 2 0 00-2 2v6a2 2 0 002 2h2a2 2 0 002-2zm0 0V9a2 2 0 012-2h2a2 2 0 012 2v10m-6 0a2 2 0 002 2h2a2 2 0 002-2m0 0V5a2 2 0 012-2h2a2 2 0 012 2v14a2 2 0 01-2 2h-2a2 2 0 01-2-2z" />
</svg>
<span v-show="!isCollapsed" class="truncate">年度总结</span>
</router-link>
<!-- 媒体管理(整合图片管理和视频下载) -->
<router-link
to="/media"
:title="isCollapsed ? '媒体管理' : ''"
class="flex items-center py-1.5 text-gray-700 transition-all duration-300 ease-in-out text-sm"
:class="[
{ 'bg-[#fb7299]/10 text-[#fb7299]': currentContent === 'media' },
{ 'justify-center': isCollapsed },
isCollapsed ? 'px-2' : 'px-3 rounded-lg'
]"
>
<svg class="w-5 h-5 flex-shrink-0" :class="{ 'mr-3': !isCollapsed }" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 17V7m0 10a2 2 0 01-2 2H5a2 2 0 01-2-2V7a2 2 0 012-2h2a2 2 0 012 2m0 10a2 2 0 002 2h2a2 2 0 002-2M9 7a2 2 0 012-2h2a2 2 0 012 2m0 10V7m0 10a2 2 0 002 2h2a2 2 0 002-2V7a2 2 0 00-2-2h-2a2 2 0 00-2 2" />
</svg>
<span v-show="!isCollapsed" class="truncate">媒体管理</span>
</router-link>
<!-- B站助手 -->
<router-link
to="/bili-tools"
:title="isCollapsed ? 'B站助手' : ''"
class="flex items-center py-1.5 text-gray-700 transition-all duration-300 ease-in-out text-sm"
:class="[
{ 'bg-[#fb7299]/10 text-[#fb7299]': currentContent === 'bili-tools' },
{ 'justify-center': isCollapsed },
isCollapsed ? 'px-2' : 'px-3 rounded-lg'
]"
>
<svg class="w-5 h-5 flex-shrink-0" :class="{ 'mr-3': !isCollapsed }" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13 10V3L4 14h7v7l9-11h-7z" />
</svg>
<span v-show="!isCollapsed" class="truncate">B站助手</span>
</router-link>
<!-- 计划任务 -->
<router-link
to="/scheduler"
:title="isCollapsed ? '计划任务' : ''"
class="flex items-center py-1.5 text-gray-700 transition-all duration-300 ease-in-out text-sm"
:class="[
{ 'bg-[#fb7299]/10 text-[#fb7299]': currentContent === 'scheduler' },
{ 'justify-center': isCollapsed },
isCollapsed ? 'px-2' : 'px-3 rounded-lg'
]"
>
<svg class="w-5 h-5 flex-shrink-0" :class="{ 'mr-3': !isCollapsed }" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z" />
</svg>
<span v-show="!isCollapsed" class="truncate">计划任务</span>
</router-link>
<!-- 设置 -->
<button
@click="changeContent('settings')"
:title="isCollapsed ? '设置' : ''"
class="w-full flex items-center py-1.5 text-gray-700 transition-all duration-300 ease-in-out text-sm"
:class="[
{ 'bg-[#fb7299]/10 text-[#fb7299]': currentContent === 'settings' },
{ 'justify-center': isCollapsed },
isCollapsed ? 'px-2' : 'px-3 rounded-lg'
]"
>
<svg class="w-5 h-5 flex-shrink-0" :class="{ 'mr-3': !isCollapsed }" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M10.325 4.317c.426-1.756 2.924-1.756 3.35 0a1.724 1.724 0 002.573 1.066c1.543-.94 3.31.826 2.37 2.37a1.724 1.724 0 001.065 2.572c1.756.426 1.756 2.924 0 3.35a1.724 1.724 0 00-1.066 2.573c.94 1.543-.826 3.31-2.37 2.37a1.724 1.724 0 00-2.572 1.065c-.426 1.756-2.924 1.756-3.35 0a1.724 1.724 0 00-2.573-1.066c-1.543.94-3.31-.826-2.37-2.37a1.724 1.724 0 00-1.065-2.572c-1.756-.426-1.756-2.924 0-3.35a1.724 1.724 0 001.066-2.573c-.94-1.543.826-3.31 2.37-2.37.996.608 2.296.07 2.572-1.065z" />
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z" />
</svg>
<span v-show="!isCollapsed" class="truncate">设置</span>
</button>
<!-- 登录状态显示 -->
<div
@click="handleLoginClick"
class="w-full flex items-center py-1.5 text-gray-700 transition-all duration-300 ease-in-out cursor-pointer hover:text-[#fb7299] text-sm"
:class="[
{ 'justify-center': isCollapsed },
isCollapsed ? 'px-2' : 'px-3 rounded-lg'
]"
>
<!-- 未登录时显示默认图标 -->
<svg
v-if="!isLoggedIn"
class="w-5 h-5 flex-shrink-0"
:class="{ 'mr-3': !isCollapsed }"
fill="none"
viewBox="0 0 24 24"
stroke="currentColor"
>
<path
stroke-linecap="round"
stroke-linejoin="round"
stroke-width="2"
d="M5.121 17.804A13.937 13.937 0 0112 16c2.5 0 4.847.655 6.879 1.804M15 10a3 3 0 11-6 0 3 3 0 016 0zm6 2a9 9 0 11-18 0 9 9 0 0118 0z"
/>
</svg>
<!-- 已登录时显示用户头像 -->
<div
v-else
class="w-5 h-5 flex-shrink-0 rounded-full overflow-hidden"
:class="{ 'mr-3': !isCollapsed }"
>
<img
:src="userInfo?.face"
alt="用户头像"
class="w-full h-full object-cover"
:class="{ 'blur-md': isPrivacyMode }"
onerror="this.src='/defaultAvatar.png'"
/>
</div>
<span
v-show="!isCollapsed"
class="truncate relative"
:class="{ 'text-green-500': isLoggedIn }"
>
<template v-if="isLoggedIn">
{{ isPrivacyMode ? '已登录' : (userInfo?.uname || '已登录') }}
</template>
<template v-else>
未登录
</template>
</span>
</div>
</nav>
<!-- 底部设置区域 -->
<div class="p-3 border-t border-gray-200/50">
<!-- 服务器状态和数据完整性放在一个容器中,与SQLite版本信息保持一致的边距 -->
<div v-if="!isCollapsed" class="mt-1 text-[11px] space-y-1 px-2">
<!-- 服务器状态显示 -->
<div class="flex items-center text-gray-500">
<div class="mr-1">服务器状态:</div>
<div class="flex items-center">
<span
class="w-1.5 h-1.5 rounded-full mr-1"
:class="serverStatus.isRunning ? 'bg-green-500' : 'bg-red-500'"
></span>
<span :class="serverStatus.isRunning ? 'text-green-600' : 'text-red-600'">
{{ serverStatus.isRunning ? '运行中' : '未连接' }}
</span>
</div>
</div>
<!-- 数据完整性状态 -->
<div class="flex items-center text-gray-500">
<div class="mr-1">数据完整性:</div>
<div class="flex items-center">
<span
class="w-1.5 h-1.5 rounded-full mr-1"
:class="integrityStatus.status === 'consistent' ? 'bg-green-500' :
integrityStatus.status === 'inconsistent' ? 'bg-yellow-500' :
integrityStatus.status === 'disabled' ? 'bg-gray-500' : 'bg-gray-400'"
></span>
<span
class="cursor-pointer hover:underline"
:class="integrityStatus.status === 'consistent' ? 'text-green-600' :
integrityStatus.status === 'inconsistent' ? 'text-yellow-600' :
integrityStatus.status === 'disabled' ? 'text-gray-500' : 'text-gray-400'"
@click="openDataSyncManager('integrity')"
>
{{ integrityStatus.status === 'consistent' ? '一致' :
integrityStatus.status === 'inconsistent' ? '不一致' :
integrityStatus.status === 'disabled' ? '未开启' : '未检查' }}
</span>
</div>
</div>
</div>
<!-- SQLite版本显示 -->
<div v-if="!isCollapsed" class="mt-3 text-xs space-y-1 px-2 text-[11px]">
<div class="text-gray-500">
SQLite版本: {{ sqliteVersion?.sqlite_version || '加载中...' }}
</div>
<div class="text-gray-500">
数据库大小: {{ sqliteVersion?.database_file?.size_mb?.toFixed(2) || '0' }} MB
</div>
</div>
<!-- 收缩按钮 -->
<button
@click="toggleCollapse"
:title="isCollapsed ? '展开侧边栏' : '收起侧边栏'"
class="mt-3 w-full flex items-center justify-center px-2 py-1.5 text-gray-700 hover:text-[#fb7299] transition-colors duration-200 text-sm"
>
<svg
class="w-5 h-5 flex-shrink-0 transform transition-transform duration-300"
:class="{ 'rotate-180': isCollapsed }"
fill="none"
viewBox="0 0 24 24"
stroke="currentColor"
>
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M11 19l-7-7 7-7m8 14l-7-7 7-7" />
</svg>
<span v-show="!isCollapsed" class="ml-2 truncate">收起侧边栏</span>
</button>
</div>
</div>
</div>
<!-- 右侧内容区域 -->
<div class="flex-1 border-l border-gray-200/50 transition-all duration-300">
<slot></slot>
</div>
</div>
<!-- 登录弹窗组件 -->
<LoginDialog
v-model:show="showLoginDialog"
@login-success="checkLoginStatus"
/>
</template>
<script setup>
import { ref, computed, watch, onMounted, onUnmounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { usePrivacyStore } from '@/store/privacy.js'
import { getLoginStatus, logout, getSqliteVersion, checkServerHealth, checkDataIntegrity, getIntegrityCheckConfig } from '../../api/api'
import { showNotify } from 'vant'
import { showDialog } from 'vant'
import 'vant/es/notify/style'
import 'vant/es/dialog/style'
import LoginDialog from './LoginDialog.vue'
const route = useRoute()
const router = useRouter()
const currentRoute = computed(() => route.path)
// 根据当前路由路径计算当前内容
const currentContent = computed(() => {
const path = route.path
if (path.startsWith('/search')) return 'search'
if (path.startsWith('/analytics')) return 'analytics'
if (path.startsWith('/settings')) return 'settings'
if (path.startsWith('/images')) return 'images'
if (path.startsWith('/scheduler')) return 'scheduler'
if (path.startsWith('/downloads')) return 'downloads'
if (path.startsWith('/media')) return 'media'
if (path.startsWith('/favorites')) return 'favorites'
if (path.startsWith('/bili-tools')) return 'bili-tools'
return 'history' // 默认返回历史记录
})
const props = defineProps({
showRemarks: {
type: Boolean,
default: false
}
})
const emit = defineEmits(['change-content', 'update:showRemarks'])
// 监听路由变化
watch(
() => route.path,
(path) => {
if (path === '/settings') {
currentContent.value = 'settings'
} else if (path === '/media') {
currentContent.value = 'media'
} else if (path === '/analytics') {
currentContent.value = 'analytics'
} else if (path === '/scheduler') {
currentContent.value = 'scheduler'
} else if (path === '/favorites' || path.startsWith('/favorites/')) {
currentContent.value = 'favorites'
} else if (path === '/bili-tools') {
currentContent.value = 'bili-tools'
} else if (path === '/' || path.startsWith('/page/')) {
currentContent.value = 'history'
}
}
)
// 切换内容
const changeContent = (content) => {
if (content === 'history') {
emit('change-content', content)
emit('update:showRemarks', false)
// 更新路由
if (route.path !== '/' && !route.path.startsWith('/page/')) {
router.push('/')
}
} else if (content === 'settings') {
emit('change-content', content)
emit('update:showRemarks', false)
router.push('/settings')
}
}
// 判断是否在历史记录页面(包括分页)
const isHistoryPage = computed(() => {
return currentRoute.value === '/' || currentRoute.value.startsWith('/page/')
})
// 隐私模式状态
const { isPrivacyMode } = usePrivacyStore()
// 侧边栏收缩状态
const isCollapsed = ref(false)
const toggleCollapse = () => {
isCollapsed.value = !isCollapsed.value
// 保存当前侧边栏状态
localStorage.setItem('sidebarCollapsed', isCollapsed.value.toString())
// 如果用户手动收起侧边栏,将showSidebar设置为false
if (isCollapsed.value) {
localStorage.setItem('showSidebar', 'false')
// 触发全局事件,通知设置组件更新
try {
const event = new CustomEvent('sidebar-toggle-changed', {
detail: { showSidebar: false }
})
window.dispatchEvent(event)
} catch (error) {
console.error('触发侧边栏切换事件失败:', error)
}
} else {
// 如果用户展开侧边栏,将showSidebar设置为true
localStorage.setItem('showSidebar', 'true')
// 触发全局事件,通知设置组件更新
try {
const event = new CustomEvent('sidebar-toggle-changed', {
detail: { showSidebar: true }
})
window.dispatchEvent(event)
} catch (error) {
console.error('触发侧边栏切换事件失败:', error)
}
}
}
// SQLite版本信息
const sqliteVersion = ref({
sqlite_version: '',
user_version: 0,
database_settings: {
journal_mode: '',
synchronous: 0,
legacy_format: null
},
database_file: {
exists: false,
size_bytes: 0,
size_mb: 0,
path: ''
}
})
// 登录相关状态
const isLoggedIn = ref(false)
const userInfo = ref(null)
const showLoginDialog = ref(false)
// 检查登录状态
const checkLoginStatus = async () => {
try {
const response = await getLoginStatus()
// 新的API响应格式是 {code: 0, message: "0", ttl: 1, data: {...}}
// code为0表示请求成功
if (response.data && response.data.code === 0) {
isLoggedIn.value = response.data.data.isLogin
if (isLoggedIn.value) {
userInfo.value = response.data.data
}
}
} catch (error) {
console.error('获取登录状态失败:', error)
isLoggedIn.value = false
userInfo.value = null
}
}
// 点击登录状态处理
const handleLoginClick = () => {
if (!isLoggedIn.value) {
showLoginDialog.value = true
} else {
showDialog({
title: '确认退出',
message: '确定要退出登录吗?',
showCancelButton: true,
confirmButtonText: '确认',
cancelButtonText: '取消',
confirmButtonColor: '#fb7299'
}).then(() => {
// 点击确认按钮
handleLogout()
}).catch(() => {
// 点击取消按钮,不做任何操作
})
}
}
// 处理退出登录
const handleLogout = async () => {
try {
const response = await logout()
if (response.data.status === 'success') {
showNotify({
type: 'success',
message: '已成功退出登录'
})
isLoggedIn.value = false
userInfo.value = null
// 1秒后刷新页面
setTimeout(() => {
window.location.reload()
}, 1000)
} else {
throw new Error(response.data.message || '退出登录失败')
}
} catch (error) {
console.error('退出登录失败:', error)
showNotify({
type: 'danger',
message: error.response?.status === 500 ?
'服务器错误,请稍后重试' :
`退出登录失败: ${error.message}`
})
}
}
// 获取SQLite版本
const fetchSqliteVersion = async () => {
try {
const response = await getSqliteVersion()
if (response.data.status === 'success') {
sqliteVersion.value = response.data.data
}
} catch (error) {
console.error('获取SQLite版本失败:', error)
sqliteVersion.value = null
}
}
// 服务器状态相关
const serverStatus = ref({
isRunning: false,
timestamp: '',
schedulerStatus: ''
})
// 数据完整性状态
const integrityStatus = ref({
status: 'unknown', // 'consistent', 'inconsistent', 'unknown'
difference: 0,
lastCheck: null
})
// 开始服务器健康检查
const checkServerHealthStatus = async () => {
try {
const response = await checkServerHealth()
if (response.data && response.data.status === 'running') {
serverStatus.value = {
isRunning: true,
timestamp: response.data.timestamp,
schedulerStatus: response.data.scheduler_status
}
return true
} else {
serverStatus.value.isRunning = false
console.error('服务器健康检查失败: 服务器未运行')
return false
}
} catch (error) {
console.error('服务器健康检查失败:', error)
serverStatus.value.isRunning = false
return false
}
}
// 获取数据完整性状态
const fetchIntegrityStatus = async () => {
try {
// 首先获取数据完整性校验配置
const configResponse = await getIntegrityCheckConfig()
// 检查是否启用了数据完整性校验
if (configResponse.data && configResponse.data.success) {
const checkEnabled = configResponse.data.check_on_startup
if (!checkEnabled) {
// 如果未启用数据完整性校验,显示"未开启"状态
integrityStatus.value = {
status: 'disabled',
difference: 0,
lastCheck: new Date().toISOString()
}
return
}
}
// 如果启用了数据完整性校验,获取校验结果
const response = await checkDataIntegrity('output/bilibili_history.db', 'output/history_by_date', false)
if (response.data && response.data.success) {
// 检查是否有消息提示(可能是配置禁用了校验)
if (response.data.message && response.data.message.includes('数据完整性校验已在配置中禁用')) {
integrityStatus.value = {
status: 'disabled',
difference: 0,
lastCheck: response.data.timestamp
}
} else {
integrityStatus.value = {
status: response.data.difference === 0 ? 'consistent' : 'inconsistent',
difference: response.data.difference || 0,
lastCheck: response.data.timestamp
}
}
}
} catch (error) {
console.error('获取完整性状态失败:', error)
// 出错时保持当前状态不变
}
}
// 打开数据同步管理器
const openDataSyncManager = (tab = null) => {
// 使用自定义事件触发全局弹窗
const event = new CustomEvent('open-data-sync-manager', {
detail: { tab: tab || 'integrity' }
})
window.dispatchEvent(event)
}
// 定时器引用
const healthCheckTimer = ref(null)
// 设置定期健康检查
const setupPeriodicHealthCheck = () => {
// 先清除可能存在的定时器
if (healthCheckTimer.value) {
clearInterval(healthCheckTimer.value)
}
// 每30秒检查一次服务器状态
healthCheckTimer.value = setInterval(async () => {
await checkServerHealthStatus()
}, 30000) // 30秒
}
onMounted(async () => {
// 读取侧边栏设置,默认显示
const showSidebar = localStorage.getItem('showSidebar') !== 'false'
// 如果设置为不显示侧边栏,则自动收起
if (!showSidebar) {
isCollapsed.value = true
} else {
// 否则使用上次保存的状态
isCollapsed.value = localStorage.getItem('sidebarCollapsed') === 'true'
}
// 初始时检查登录状态
checkLoginStatus()
await fetchSqliteVersion()
// 设置定期健康检查
setupPeriodicHealthCheck()
checkServerHealthStatus()
// 添加获取数据完整性状态
await fetchIntegrityStatus()
// 添加全局事件监听器,当登录状态变化时更新侧边栏的登录状态
window.addEventListener('login-status-changed', handleLoginStatusChange)
// 添加侧边栏设置变更事件监听
window.addEventListener('sidebar-setting-changed', handleSidebarSettingChange)
})
// 处理登录状态变化事件
const handleLoginStatusChange = (event) => {
console.log('侧边栏收到登录状态变化事件,正在更新登录状态...', event.detail)
// 如果事件中包含用户信息,直接使用
if (event.detail && event.detail.isLoggedIn) {
isLoggedIn.value = true
if (event.detail.userInfo) {
userInfo.value = event.detail.userInfo
console.log('从事件中获取到用户信息:', userInfo.value)
} else {
// 如果没有用户信息,则调用API获取
checkLoginStatus()
}
} else {
// 如果事件中没有登录状态信息,则调用API获取
checkLoginStatus()
}
}
// 处理侧边栏设置变更事件
const handleSidebarSettingChange = (event) => {
console.log('侧边栏收到设置变更事件', event.detail)
if (event.detail && typeof event.detail.showSidebar === 'boolean') {
// 如果设置为不显示侧边栏,则自动收起
if (!event.detail.showSidebar) {
isCollapsed.value = true
}
}
}
// 组件卸载时移除事件监听器和清除定时器
onUnmounted(() => {
window.removeEventListener('login-status-changed', handleLoginStatusChange)
window.removeEventListener('sidebar-setting-changed', handleSidebarSettingChange)
// 清除定时器
if (healthCheckTimer.value) {
clearInterval(healthCheckTimer.value)
healthCheckTimer.value = null
}
})
</script>
|
2977094657/BiliHistoryFrontend
| 7,496
|
src/components/tailwind/TaskTreeItem.vue
|
<template>
<div class="task-tree-node">
<div class="flex items-start">
<div class="flex items-center">
<div class="w-6 h-6 flex items-center justify-center">
<button
v-if="childTasks.length > 0"
@click="toggleExpanded"
class="w-5 h-5 rounded hover:bg-gray-100 flex items-center justify-center focus:outline-none"
>
<svg
class="w-4 h-4 text-gray-500 transform transition-transform duration-200"
:class="{ 'rotate-90': expanded }"
fill="none"
viewBox="0 0 24 24"
stroke="currentColor"
>
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 5l7 7-7 7" />
</svg>
</button>
</div>
<div class="flex-1 min-w-0">
<div class="bg-white border border-gray-200 rounded-lg shadow-sm p-3 hover:border-[#fb7299] transition-colors duration-200">
<div class="flex items-center justify-between">
<div class="flex items-center space-x-2">
<span class="font-medium text-sm">{{ task.config?.name || task.task_id }}</span>
<div class="flex items-center space-x-1">
<span
v-if="task.config?.schedule_type"
:class="scheduleTypeClass"
class="px-1.5 py-0.5 rounded-full text-xs"
>
{{ scheduleTypeLabel }}
</span>
<span
v-if="task.execution?.status"
:class="statusClass"
class="px-1.5 py-0.5 rounded-full text-xs"
>
{{ task.execution.status }}
</span>
</div>
</div>
<div class="flex items-center space-x-1">
<button
@click="viewDetail"
class="text-blue-600 hover:text-blue-900 text-xs px-1.5 py-0.5"
>
详情
</button>
<button
@click="editTask"
class="text-green-600 hover:text-green-900 text-xs px-1.5 py-0.5"
>
编辑
</button>
<button
@click="executeTask"
class="text-purple-600 hover:text-purple-900 text-xs px-1.5 py-0.5"
>
执行
</button>
<button
v-if="task.config?.enabled !== undefined"
@click="toggleEnabled"
:class="task.config.enabled ? 'text-orange-600 hover:text-orange-900' : 'text-teal-600 hover:text-teal-900'"
class="text-xs px-1.5 py-0.5"
>
{{ task.config.enabled ? '禁用' : '启用' }}
</button>
<button
@click="deleteTask"
class="text-red-600 hover:text-red-900 text-xs px-1.5 py-0.5"
>
删除
</button>
</div>
</div>
<div class="mt-2 text-xs text-gray-500">
<div v-if="task.execution?.last_run">上次运行: {{ task.execution.last_run }}</div>
<div v-if="task.config?.endpoint" class="mt-0.5">端点: {{ task.config.endpoint }}</div>
</div>
</div>
</div>
</div>
</div>
<div v-show="expanded && childTasks.length > 0" class="pl-6 mt-2 space-y-2 relative">
<!-- 添加垂直连接线 -->
<div class="absolute left-3 top-0 bottom-0 w-px bg-gray-200"></div>
<div v-for="childTask in childTasks" :key="getTaskId(childTask)" class="relative">
<!-- 添加水平连接线 -->
<div class="absolute left-0 top-1/2 w-3 h-px bg-gray-200"></div>
<task-tree-item
:task="childTask"
:tasks="tasks"
@view-detail="$emit('view-detail', $event)"
@edit-task="$emit('edit-task', $event)"
@execute-task="$emit('execute-task', $event)"
@delete-task="$emit('delete-task', $event)"
@toggle-enabled="$emit('toggle-enabled', $event)"
/>
</div>
</div>
</div>
</template>
<script lang="ts">
import { ref, computed, defineComponent } from 'vue'
type TaskConfig = {
name?: string;
schedule_type?: string;
schedule_time?: string;
enabled?: boolean;
endpoint?: string;
method?: string;
}
type TaskExecution = {
status?: string;
last_run?: string;
}
type Task = {
task_id: string;
config?: TaskConfig;
execution?: TaskExecution;
sub_tasks?: Task[];
success_rate?: number;
depends_on?: string[];
requires?: string[];
sequence_number?: number;
}
export default defineComponent({
name: 'TaskTreeItem',
props: {
task: {
type: Object as () => Task,
required: true
},
tasks: {
type: Array as () => Task[],
default: () => []
}
},
emits: ['view-detail', 'edit-task', 'execute-task', 'delete-task', 'toggle-enabled'],
setup(props, { emit }) {
const expanded = ref(true)
// 获取子任务,按 sequence_number 排序
const childTasks = computed(() => {
const subTasks = props.task.sub_tasks || []
return subTasks.sort((a, b) => (a.sequence_number || 0) - (b.sequence_number || 0))
})
// 计算调度类型标签
const scheduleTypeLabel = computed(() => {
const type = props.task.config?.schedule_type
return type === 'daily' ? '每日' :
type === 'chain' ? '链式' :
type === 'once' ? '一次性' :
type === 'interval' ? '间隔' : type
})
// 计算调度类型样式
const scheduleTypeClass = computed(() => {
const type = props.task.config?.schedule_type
return {
'bg-blue-100 text-blue-800': type === 'daily',
'bg-purple-100 text-purple-800': type === 'chain',
'bg-green-100 text-green-800': type === 'once',
'bg-yellow-100 text-yellow-800': type === 'interval'
}
})
// 计算状态样式
const statusClass = computed(() => {
const status = props.task.execution?.status
return {
'bg-green-100 text-green-800': status === 'success',
'bg-yellow-100 text-yellow-800': status === 'running',
'bg-red-100 text-red-800': status === 'error' || status === 'failed'
}
})
// 切换展开状态
const toggleExpanded = () => {
expanded.value = !expanded.value
}
// 查看详情
const viewDetail = () => {
emit('view-detail', props.task.task_id)
}
// 编辑任务
const editTask = () => {
emit('edit-task', props.task.task_id)
}
// 执行任务
const executeTask = () => {
emit('execute-task', props.task.task_id)
}
// 删除任务
const deleteTask = () => {
emit('delete-task', props.task.task_id)
}
// 切换启用状态
const toggleEnabled = () => {
emit('toggle-enabled', props.task.task_id, !props.task.config?.enabled)
}
// 安全地获取任务ID
const getTaskId = (task: Task | null) => {
return task?.task_id || Math.random().toString()
}
return {
expanded,
childTasks,
scheduleTypeLabel,
scheduleTypeClass,
statusClass,
toggleExpanded,
viewDetail,
editTask,
executeTask,
deleteTask,
toggleEnabled,
getTaskId
}
}
})
</script>
<style scoped>
.task-tree-node {
transition: all 0.2s ease;
}
</style>
|
2881099/FreeSql.AdminLTE
| 4,463
|
FreeSql.AdminLTE/ResponseModel/TreeNode.cs
|
//using FreeSql.Internal.CommonProvider;
//using FreeSql.Internal.Model;
//using System;
//using System.Collections.Generic;
//using System.Linq;
//using System.Linq.Expressions;
//using System.Text;
//namespace FreeSql.AdminLTE.ResponseModel
//{
// public class TopicController
// {
// public ListPage<object> List(int pageNumber, int pageSize, DynamicFilterInfo dynamicFilter)
// {
// IFreeSql fsql = null;
// var list = fsql.Select<object>().WhereDynamic(dynamicFilter).Page(pageNumber, pageSize).ToList();
// return new ListPage<object>()
// .SetOptions(new ListPageOptions
// {
// })
// .AddTableColumn()
// }
// }
// public class BaseController
// {
// }
// public class ListPage<T> where T : class
// {
// public ListPageOptions Options { get; set; }
// public Pagination Pagination { get; set; }
// public List<TableColumn> Headers { get; set; }
// public List<Func<T, object>> CellTextSelector { get; set; }
// public List<object[]> Rows { get; set; }
// public ListPage<T> SetOptions(ListPageOptions options)
// {
// this.Options = options;
// return this;
// }
// public ListPage<T> SetPagination(int pageNumber, int pageSize, int total)
// {
// this.Pagination = new Pagination { PageNumber = pageNumber, PageSize = pageSize, Total = total };
// return this;
// }
// public ListPage<T> AddTableColumn(string headerName, string heawderText, string headerClass, int width,
// string cellClass, Func<T, object> cellTextSelector)
// {
// this.Headers.Add(new TableColumn { HeaderName = headerName, HeaderText = heawderText, HeaderClass = headerClass, Width = width, CellClass = cellClass });
// this.CellTextSelector.Add(cellTextSelector);
// return this;
// }
// public ListPage<T> AddTableColumn(string text, Func<T, object> cellValueSelector) => this.AddTableColumn(text, null, null, 0, null, cellValueSelector);
// public ListPage<T> AddTableColumn(string text, int width, Func<T, object> cellValueSelector) => this.AddTableColumn(text, null, null, width, null, cellValueSelector);
// public ListPage<T> AddTableRow(T item)
// {
// this.Rows.Add(CellTextSelector.Select(a => a?.Invoke(item)).ToArray());
// return this;
// }
// }
// public class ListPageOptions
// {
// public Filter[] Filters { get; set; }
// public bool IsDynamicFilter { get; set; }
// public bool IsInsert { get; set; }
// public bool IsUpdate { get; set; }
// public bool IsDelete { get; set; }
// public bool IsBatchDelete { get; set; }
// public bool IsPage { get; set; }
// public class Filter
// {
// public string Name { get; set; }
// public string Text { get; set; }
// public DynamicFilterOperator[] Operators { get; set; }
// }
// }
// public class Pagination
// {
// public int Total { get; set; }
// public int PageNumber { get; set; } = 1;
// public int PageSize { get; set; } = 20;
// public int PageTotal => (int)Math.Ceiling(1.0 * Total / PageSize);
// }
// public class TableColumn
// {
// public string HeaderName { get; set; }
// public string HeaderText { get; set; }
// public string HeaderClass { get; set; }
// public string CellClass { get; set; }
// public int Width { get; set; }
// }
// public class TreeNode<T>
// {
// public List<TreeNode<T>> Childs { get; } = new List<TreeNode<T>>();
// public T Item { get; set; }
// }
// public class MenuTreeNodeItem
// {
// public string Id { get; set; }
// public int Level { get; set; }
// public string Icon { get; set; }
// public string Link { get; set; }
// }
// public class GridView
// {
// public List<GridViewColumn> Columns { get; } = new List<GridViewColumn>();
// }
// public class GridViewColumn
// {
// public GridViewColumnType ColumnType { get; set; }
// public string ColumnHeaderText { get; set; }
// }
// public enum GridViewColumnType { Boolean, String, DateTime, Number, Money, Button }
//}
|
294coder/Efficient-MIF
| 2,891
|
Pansharpening_Hyper_SR_Matlab_Test_Package/MF/Pyr_Dec.m
|
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Description:
% Morphological Pyramid Decomposition using Half-Gradient.
%
% Interface:
% P = Pyr_Dec(Im,textse,lev,int_meth)
%
% Inputs:
% Im: Image to decompose;
% textse: Structuring Element;
% lev: Number of decomposition levels;
% int_meth: Interpolation method.
%
% Outputs:
% P: Morphological Pyramid using Half-Gradient.
%
% References:
% [Vivone14] G. Vivone, R. Restaino, M. Dalla Mura, G. Licciardi, and J. Chanussot, Contrast and error-based fusion schemes for multispectral
% image pansharpening, IEEE Geoscience and Remote Sensing Letters, vol. 11, no. 5, pp. 930934, May 2014.
% [Vivone15] G. Vivone, L. Alparone, J. Chanussot, M. Dalla Mura, A. Garzelli, G. Licciardi, R. Restaino, and L. Wald, A Critical Comparison Among Pansharpening Algorithms,
% IEEE Transactions on Geoscience and Remote Sensing, vol. 53, no. 5, pp. 2565-2586, May 2015.
% [Restaino16] R. Restaino, G. Vivone, M. Dalla Mura, and J. Chanussot, Fusion of Multispectral and Panchromatic Images Based on Morphological Operators,
% IEEE Transactions on Image Processing, vol. 25, no. 6, pp. 2882-2895, Jun. 2016.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function P = Pyr_Dec(Im,textse,lev,int_meth)
P(:,:,:,1) = Im;
Sizes(1,:)=[size(Im,1), size(Im,2)];
imageI_new=P(:,:,:,1);
first=1;
for ii = 2 : lev
imageI_old = imageI_new;
clear imageI_new
% Half Gradient
PD = imdilate(imageI_old,textse);
PE= imerode(imageI_old,textse);
rho_minus=imageI_old-PE;
rho_plus=PD-imageI_old;
D=rho_minus-rho_plus;
PS = imageI_old -0.5*D;
% PS = 0.5*squeeze(PD+PE); %equivalently
% Downsampling
if first
for il=1:size(imageI_old,3)
imageI_new(:,:,il)=PS(2:2:end,2:2:end,il);
end
first=0;
else
for il=1:size(imageI_old,3)
imageI_new(:,:,il)=PS(1:2:end,1:2:end,il);
end
end
Sizes(ii,:)=[size(imageI_new,1) size(imageI_new,1)];
imageI_resized_old=imageI_new;
for ir=ii:-1:2,
for il=1:size(Im,3)
imageI_resized_new(:,:,il) = imresize(imageI_resized_old(:,:,il),[Sizes(ir-1,1) Sizes(ir-1,2)],int_meth);
end
imageI_resized_old=imageI_resized_new;
clear imageI_resized_new
end
if sum(isfinite(imageI_resized_old(:)))~=numel(imageI_resized_old)
P(:,:,:,1:lev) =repmat(P(:,:,:,1),1,1,1,lev);
break
else
P(:,:,:,ii) = imageI_resized_old;
end
clear imageI_resized_old
end
end
|
294coder/Efficient-MIF
| 2,081
|
Pansharpening_Hyper_SR_Matlab_Test_Package/MF/MF_HG_Pansharpen.m
|
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Description:
% Morphological Pyramid Decomposition using Half-Gradient.
%
% Interface:
% I_Fus_MF_HG = MF_HG_Pansharpen(I_MS,I_PAN,ratio)
%
% Inputs:
% I_MS: MS image upsampled at PAN scale;
% I_PAN: PAN image;
% ratio: Scale ratio between MS and PAN. Pre-condition: Integer value.
%
% Outputs:
% I_Fus_MF_HG: Morphological Half Gradient (HG) pansharpened image.
%
% Reference:
% [Restaino16] R. Restaino, G. Vivone, M. Dalla Mura, and J. Chanussot, Fusion of Multispectral and Panchromatic Images Based on Morphological Operators,
% IEEE Transactions on Image Processing, vol. 25, no. 6, pp. 2882-2895, Jun. 2016.
% [Vivone20] G. Vivone, M. Dalla Mura, A. Garzelli, R. Restaino, G. Scarpa, M.O. Ulfarsson, L. Alparone, and J. Chanussot, "A New Benchmark Based on Recent Advances in Multispectral Pansharpening: Revisiting pansharpening with classical and emerging pansharpening methods",
% IEEE Geoscience and Remote Sensing Magazine, doi: 10.1109/MGRS.2020.3019315.
% % % % % % % % % % % % %
%
% Version: 1
%
% % % % % % % % % % % % %
%
% Copyright (C) 2019
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function I_Fus_MF_HG = MF_HG_Pansharpen(I_MS,I_PAN,ratio)
imageLR = double(I_MS);
imageHR = double(I_PAN);
% Equalization
imageHR = repmat(imageHR,[1 1 size(imageLR,3)]);
for ii = 1 : size(imageLR,3)
imageHR(:,:,ii) = (imageHR(:,:,ii) - mean2(imageHR(:,:,ii))).*(std2(imageLR(:,:,ii))./std2(imageHR(:,:,ii))) + mean2(imageLR(:,:,ii));
end
% Structuring Element choice
textse= [0 1 0; 1 1 1; 0 1 0];
% Interpolation Method
int_meth='bilinear';
% Number of levels
lev=ceil(log2(ratio))+1;
% Image Construction
P = Pyr_Dec(imageHR,textse,lev,int_meth);
% Fusion
P_LP = P(:,:,:,lev);
I_Fus_MF_HG = imageLR .* (P(:,:,:,1)./(P_LP+eps));
end
|
2977094657/BiliHistoryFrontend
| 5,728
|
src/components/tailwind/SearchBar.vue
|
<template>
<div class="relative mx-auto max-w-4xl">
<!-- 搜索区域容器 -->
<div class="relative">
<!-- 搜索框容器 -->
<div class="flex w-full h-8 sm:h-10 items-center rounded-md border border-gray-300 bg-white focus-within:border-[#fb7299] transition-colors duration-200">
<!-- 搜索图标 -->
<div class="pl-2 sm:pl-3 text-gray-400">
<svg xmlns="http://www.w3.org/2000/svg" class="h-3 w-3 sm:h-4 sm:w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z" />
</svg>
</div>
<!-- 搜索类型选择器 - 替换为CustomDropdown组件 -->
<div class="h-full pl-1 sm:pl-2 flex items-center">
<CustomDropdown
v-model="searchType"
:options="searchTypeOptions"
:selected-text="searchType"
@change="onSearchTypeChange"
custom-class="h-full border-none !shadow-none !p-0 !m-0 !rounded-none !pr-1"
:min-width="180"
:use-fixed-width="false"
>
<template #trigger-content>
<span class="text-[#fb7299] text-xs sm:text-sm flex items-center whitespace-nowrap">{{ getTypeLabel(searchType) }}</span>
</template>
</CustomDropdown>
</div>
<!-- 分隔线 -->
<div class="h-4 sm:h-5 w-px bg-gray-200 mx-1"></div>
<!-- 输入框 -->
<input
v-model="searchQuery"
@keyup.enter="handleSearch"
type="search"
:placeholder="getPlaceholder"
class="h-full w-full border-none bg-transparent px-1 sm:px-2 pr-2 sm:pr-3 text-gray-700 focus:outline-none focus:ring-0 text-xs sm:text-sm leading-none"
/>
</div>
</div>
</div>
</template>
<script setup>
import { ref, onMounted, watch, computed } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { getAvailableYears } from '../../api/api.js'
import CustomDropdown from './CustomDropdown.vue'
const props = defineProps({
initialYear: {
type: Number,
default: () => new Date().getFullYear()
},
initialKeyword: {
type: String,
default: ''
},
initialSearchType: {
type: String,
default: 'all'
}
})
const emit = defineEmits(['year-change', 'search'])
const router = useRouter()
const route = useRoute()
// 搜索相关
const searchQuery = ref(props.initialKeyword)
const searchType = ref(props.initialSearchType)
// 搜索类型选项
const searchTypeOptions = [
{ value: 'all', label: '全部' },
{ value: 'title', label: '标题' },
{ value: 'author', label: 'UP主' },
{ value: 'tag', label: '分区' },
{ value: 'remark', label: '备注' }
]
// 根据选项值获取显示文本
const getTypeLabel = (value) => {
const option = searchTypeOptions.find(opt => opt.value === value)
return option ? option.label : '全部'
}
// 处理搜索类型变更
const onSearchTypeChange = (value) => {
searchType.value = value
// 如果在搜索页面且有搜索关键词,触发搜索
if (route.name === 'Search' && searchQuery.value.trim()) {
handleSearch()
}
}
// 年份相关
const selectedYear = ref(props.initialYear)
const availableYears = ref([props.initialYear])
// 根据搜索类型获取占位符文本
const getPlaceholder = computed(() => {
switch (searchType.value) {
case 'title':
return '视频标题/oid'
case 'author':
return 'UP主名称'
case 'tag':
return '分区名称'
case 'remark':
return '备注内容'
default:
return '输入关键词搜索'
}
})
// 获取可用年份列表
const fetchAvailableYears = async () => {
try {
const response = await getAvailableYears()
if (response.data.status === 'success') {
availableYears.value = response.data.data
// 如果当前选中的年份不在可用年份列表中,设置为最新的年份
if (!availableYears.value.includes(selectedYear.value)) {
selectedYear.value = availableYears.value[0]
emit('year-change', selectedYear.value)
}
}
} catch (error) {
console.error('获取可用年份失败:', error)
}
}
// 处理年份变化
const handleYearChange = () => {
emit('year-change', selectedYear.value)
}
// 处理搜索
const handleSearch = () => {
if (searchQuery.value.trim()) {
console.log('SearchBar - 执行搜索:', {
keyword: searchQuery.value.trim(),
type: searchType.value
})
if (route.name === 'Search') {
// 如果在搜索页面,发出搜索事件
emit('search', {
keyword: searchQuery.value.trim(),
type: searchType.value
})
} else {
// 修改为在当前窗口打开搜索结果页面
router.push({
name: 'Search',
params: { keyword: searchQuery.value.trim() },
query: {
type: searchType.value
}
})
searchQuery.value = ''
}
} else {
alert('请输入有效的搜索关键词')
}
}
// 监听props变化
watch(() => props.initialKeyword, (newKeyword) => {
searchQuery.value = newKeyword
})
watch(() => props.initialYear, (newYear) => {
if (newYear !== selectedYear.value) {
selectedYear.value = newYear
}
})
watch(() => props.initialSearchType, (newType) => {
if (newType !== searchType.value) {
searchType.value = newType
}
})
onMounted(async () => {
await fetchAvailableYears()
})
</script>
<style scoped>
/* 移除搜索框的默认样式 */
input[type="search"]::-webkit-search-decoration,
input[type="search"]::-webkit-search-cancel-button,
input[type="search"]::-webkit-search-results-button,
input[type="search"]::-webkit-search-results-decoration {
display: none;
}
/* 移除输入框的默认focus样式 */
input:focus {
box-shadow: none !important;
outline: none !important;
}
:deep(.custom-dropdown-trigger) {
border: none !important;
box-shadow: none !important;
background: transparent !important;
}
/* 确保下拉菜单按钮文本不会折行 */
:deep(.custom-dropdown-trigger span) {
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
</style>
|
2977094657/BiliHistoryFrontend
| 4,521
|
src/components/tailwind/CustomDropdown.vue
|
<template>
<div class="relative" :style="containerStyle">
<button
ref="triggerBtn"
@click.stop="toggleDropdown"
type="button"
:class="[
'custom-dropdown-trigger w-full py-1.5 px-2 border border-gray-300 rounded-md text-xs text-gray-800 focus:border-[#fb7299] focus:outline-none focus:ring focus:ring-[#fb7299]/20 flex items-center justify-between bg-white transition-colors duration-200',
customClass,
'whitespace-nowrap overflow-hidden'
]"
>
<slot name="trigger-content">
<span class="truncate mr-1">{{ selectedText }}</span>
</slot>
<svg class="w-3 h-3 text-[#fb7299] flex-shrink-0" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 9l-7 7-7-7" />
</svg>
</button>
<!-- 下拉菜单 -->
<div
v-if="showDropdown"
@click.stop
class="fixed z-50 mt-1 rounded-lg bg-white shadow-lg ring-1 ring-black ring-opacity-5 focus:outline-none max-w-[90vw]"
:style="dropdownStyle"
>
<div class="py-1 max-h-60 overflow-auto">
<slot>
<button
v-for="(option, index) in options"
:key="index"
@click.stop="selectOption(option.value)"
class="w-full px-2 py-1 text-xs text-left hover:bg-[#fb7299]/5 hover:text-[#fb7299] transition-colors flex items-center whitespace-nowrap"
:class="{'text-[#fb7299] bg-[#fb7299]/5 font-medium': modelValue === option.value}"
>
{{ option.label }}
</button>
</slot>
</div>
</div>
</div>
</template>
<script setup>
import { ref, onMounted, onUnmounted, watch, computed } from 'vue'
const props = defineProps({
modelValue: {
type: [String, Number],
default: ''
},
options: {
type: Array,
default: () => []
},
selectedText: {
type: String,
default: '请选择'
},
customClass: {
type: String,
default: ''
},
minWidth: {
type: Number,
default: 120
},
useFixedWidth: {
type: Boolean,
default: false
},
buttonWidth: {
type: [String, Number],
default: null
}
})
const emit = defineEmits(['update:modelValue', 'change'])
// 计算容器样式(包括宽度控制)
const containerStyle = computed(() => {
if (props.buttonWidth) {
return {
width: typeof props.buttonWidth === 'number' ? `${props.buttonWidth}px` : props.buttonWidth
}
}
return {}
})
const triggerBtn = ref(null)
const showDropdown = ref(false)
const dropdownStyle = ref({})
// 切换下拉菜单
const toggleDropdown = () => {
showDropdown.value = !showDropdown.value
if (showDropdown.value) {
// 计算位置
calculateDropdownPosition()
}
}
// 选择选项
const selectOption = (value) => {
emit('update:modelValue', value)
emit('change', value)
showDropdown.value = false
}
// 计算下拉菜单位置
const calculateDropdownPosition = () => {
setTimeout(() => {
if (triggerBtn.value) {
const rect = triggerBtn.value.getBoundingClientRect()
// 使用按钮自身的宽度或指定的最小宽度,不自动放大
const width = props.useFixedWidth ? rect.width : Math.max(rect.width, props.minWidth || 80)
// 获取视口宽度,确保菜单不会超出边界
const viewportWidth = window.innerWidth
let left = rect.left
// 如果下拉菜单右边缘超出视口,调整位置
if (left + width > viewportWidth - 10) {
left = Math.max(10, viewportWidth - width - 10)
}
dropdownStyle.value = {
top: `${rect.bottom + window.scrollY}px`,
left: `${left}px`,
width: `${width}px`,
maxWidth: viewportWidth - 20 + 'px' // 确保不会超过视口宽度
}
}
}, 0)
}
// 点击外部关闭下拉菜单
const closeDropdown = (event) => {
if (triggerBtn.value && !triggerBtn.value.contains(event.target)) {
showDropdown.value = false
}
}
// 处理窗口大小变化
const handleResize = () => {
if (showDropdown.value) {
calculateDropdownPosition()
}
}
// 处理滚动事件
const handleScroll = () => {
if (showDropdown.value) {
calculateDropdownPosition()
}
}
onMounted(() => {
document.addEventListener('click', closeDropdown)
window.addEventListener('resize', handleResize)
window.addEventListener('scroll', handleScroll)
})
onUnmounted(() => {
document.removeEventListener('click', closeDropdown)
window.removeEventListener('resize', handleResize)
window.removeEventListener('scroll', handleScroll)
})
// 监听modelValue变化
watch(() => props.modelValue, (newVal) => {
// 如果需要在值变化时做额外处理
})
</script>
<style scoped>
/* 任何自定义样式 */
</style>
|
281677160/openwrt-package
| 61,865
|
luci-app-passwall2/luasrc/passwall2/util_xray.lua
|
module("luci.passwall2.util_xray", package.seeall)
local api = require "luci.passwall2.api"
local uci = api.uci
local sys = api.sys
local jsonc = api.jsonc
local appname = api.appname
local fs = api.fs
local CACHE_PATH = api.CACHE_PATH
local new_port
local function get_new_port()
if new_port then
new_port = tonumber(sys.exec(string.format("echo -n $(/usr/share/%s/app.sh get_new_port %s tcp)", appname, new_port + 1)))
else
new_port = tonumber(sys.exec(string.format("echo -n $(/usr/share/%s/app.sh get_new_port auto tcp)", appname)))
end
return new_port
end
local function get_noise_packets()
local noises = {}
uci:foreach(appname, "xray_noise_packets", function(n)
local noise = (n.enabled == "1") and {
type = n.type,
packet = n.packet,
delay = string.find(n.delay, "-") and n.delay or tonumber(n.delay),
applyTo = n.applyTo
} or nil
table.insert(noises, noise)
end)
if #noises == 0 then noises = nil end
return noises
end
local function get_domain_excluded()
local path = string.format("/usr/share/%s/domains_excluded", appname)
local content = fs.readfile(path)
if not content then return nil end
local hosts = {}
string.gsub(content, '[^' .. "\n" .. ']+', function(w)
local s = api.trim(w)
if s == "" then return end
if s:find("#") and s:find("#") == 1 then return end
if not s:find("#") or s:find("#") ~= 1 then table.insert(hosts, s) end
end)
if #hosts == 0 then hosts = nil end
return hosts
end
function gen_outbound(flag, node, tag, proxy_table)
local result = nil
if node then
local node_id = node[".name"]
if tag == nil then
tag = node_id
end
local proxy_tag = nil
local fragment = nil
local noise = nil
local run_socks_instance = true
if proxy_table ~= nil and type(proxy_table) == "table" then
proxy_tag = proxy_table.tag or nil
fragment = proxy_table.fragment or nil
noise = proxy_table.noise or nil
run_socks_instance = proxy_table.run_socks_instance
end
if node.type ~= "Xray" then
local relay_port = node.port
new_port = get_new_port()
local config_file = string.format("%s_%s_%s.json", flag, tag, new_port)
if tag and node_id and tag ~= node_id then
config_file = string.format("%s_%s_%s_%s.json", flag, tag, node_id, new_port)
end
if run_socks_instance then
sys.call(string.format('/usr/share/%s/app.sh run_socks "%s"> /dev/null',
appname,
string.format("flag=%s node=%s bind=%s socks_port=%s config_file=%s relay_port=%s",
new_port, --flag
node_id, --node
"127.0.0.1", --bind
new_port, --socks port
config_file, --config file
(proxy_tag and relay_port) and tostring(relay_port) or "" --relay port
)
)
)
end
node = {}
node.protocol = "socks"
node.transport = "tcp"
node.address = "127.0.0.1"
node.port = new_port
node.stream_security = "none"
else
if proxy_tag then
node.proxySettings = {
tag = proxy_tag,
transportLayer = true
}
end
end
if node.type == "Xray" then
if node.tls and node.tls == "1" then
node.stream_security = "tls"
if node.reality and node.reality == "1" then
node.stream_security = "reality"
end
end
end
if node.protocol == "wireguard" and node.wireguard_reserved then
local bytes = {}
if not node.wireguard_reserved:match("[^%d,]+") then
node.wireguard_reserved:gsub("%d+", function(b)
bytes[#bytes + 1] = tonumber(b)
end)
else
local result = api.bin.b64decode(node.wireguard_reserved)
for i = 1, #result do
bytes[i] = result:byte(i)
end
end
node.wireguard_reserved = #bytes > 0 and bytes or nil
end
result = {
_id = node_id,
_flag = flag,
_flag_proxy_tag = proxy_tag,
tag = tag,
proxySettings = node.proxySettings or nil,
protocol = node.protocol,
mux = {
enabled = (node.mux == "1") and true or false,
concurrency = (node.mux == "1" and ((node.mux_concurrency) and tonumber(node.mux_concurrency) or -1)) or nil,
xudpConcurrency = (node.mux == "1" and ((node.xudp_concurrency) and tonumber(node.xudp_concurrency) or 8)) or nil
} or nil,
-- 底层传输配置
streamSettings = (node.streamSettings or node.protocol == "vmess" or node.protocol == "vless" or node.protocol == "socks" or node.protocol == "shadowsocks" or node.protocol == "trojan") and {
sockopt = {
mark = 255,
tcpMptcp = (node.tcpMptcp == "1") and true or nil,
dialerProxy = (fragment or noise) and "dialerproxy" or nil
},
network = node.transport,
security = node.stream_security,
tlsSettings = (node.stream_security == "tls") and {
serverName = node.tls_serverName,
allowInsecure = (node.tls_allowInsecure == "1") and true or false,
fingerprint = (node.type == "Xray" and node.utls == "1" and node.fingerprint and node.fingerprint ~= "") and node.fingerprint or nil,
echConfigList = (node.ech == "1") and node.ech_config or nil,
echForceQuery = (node.ech == "1") and (node.ech_ForceQuery or "none") or nil
} or nil,
realitySettings = (node.stream_security == "reality") and {
serverName = node.tls_serverName,
publicKey = node.reality_publicKey,
shortId = node.reality_shortId or "",
spiderX = node.reality_spiderX or "/",
fingerprint = (node.type == "Xray" and node.fingerprint and node.fingerprint ~= "") and node.fingerprint or "chrome",
mldsa65Verify = (node.use_mldsa65Verify == "1") and node.reality_mldsa65Verify or nil
} or nil,
rawSettings = ((node.transport == "raw" or node.transport == "tcp") and node.protocol ~= "socks" and (node.tcp_guise and node.tcp_guise ~= "none")) and {
header = {
type = node.tcp_guise,
request = (node.tcp_guise == "http") and {
path = node.tcp_guise_http_path or {"/"},
headers = {
Host = node.tcp_guise_http_host or {}
}
} or nil
}
} or nil,
kcpSettings = (node.transport == "mkcp") and {
mtu = tonumber(node.mkcp_mtu),
tti = tonumber(node.mkcp_tti),
uplinkCapacity = tonumber(node.mkcp_uplinkCapacity),
downlinkCapacity = tonumber(node.mkcp_downlinkCapacity),
congestion = (node.mkcp_congestion == "1") and true or false,
readBufferSize = tonumber(node.mkcp_readBufferSize),
writeBufferSize = tonumber(node.mkcp_writeBufferSize),
seed = (node.mkcp_seed and node.mkcp_seed ~= "") and node.mkcp_seed or nil,
header = {
type = node.mkcp_guise,
domain = node.mkcp_domain
}
} or nil,
wsSettings = (node.transport == "ws") and {
path = node.ws_path or "/",
host = node.ws_host or nil,
maxEarlyData = tonumber(node.ws_maxEarlyData) or nil,
earlyDataHeaderName = (node.ws_earlyDataHeaderName) and node.ws_earlyDataHeaderName or nil,
heartbeatPeriod = tonumber(node.ws_heartbeatPeriod) or nil
} or nil,
grpcSettings = (node.transport == "grpc") and {
serviceName = node.grpc_serviceName,
multiMode = (node.grpc_mode == "multi") and true or nil,
idle_timeout = tonumber(node.grpc_idle_timeout) or nil,
health_check_timeout = tonumber(node.grpc_health_check_timeout) or nil,
permit_without_stream = (node.grpc_permit_without_stream == "1") and true or nil,
initial_windows_size = tonumber(node.grpc_initial_windows_size) or nil
} or nil,
httpupgradeSettings = (node.transport == "httpupgrade") and {
path = node.httpupgrade_path or "/",
host = node.httpupgrade_host
} or nil,
xhttpSettings = (node.transport == "xhttp") and {
mode = node.xhttp_mode or "auto",
path = node.xhttp_path or "/",
host = node.xhttp_host,
-- 如果包含 "extra" 节,取 "extra" 内的内容,否则直接赋值给 extra
extra = node.xhttp_extra and (function()
local success, parsed = pcall(jsonc.parse, node.xhttp_extra)
if success then
return parsed.extra or parsed
else
return nil
end
end)() or nil
} or nil,
} or nil,
settings = {
vnext = (node.protocol == "vmess" or node.protocol == "vless") and {
{
address = node.address,
port = tonumber(node.port),
users = {
{
id = node.uuid,
level = 0,
security = (node.protocol == "vmess") and node.security or nil,
encryption = node.encryption or "none",
flow = (node.protocol == "vless" and node.tls == "1" and (node.transport == "raw" or node.transport == "tcp" or node.transport == "xhttp") and node.flow and node.flow ~= "") and node.flow or nil
}
}
}
} or nil,
servers = (node.protocol == "socks" or node.protocol == "http" or node.protocol == "shadowsocks" or node.protocol == "trojan") and {
{
address = node.address,
port = tonumber(node.port),
method = (node.method == "chacha20-ietf-poly1305" and "chacha20-poly1305") or
(node.method == "xchacha20-ietf-poly1305" and "xchacha20-poly1305") or
(node.method ~= "" and node.method) or nil,
ivCheck = (node.protocol == "shadowsocks") and node.iv_check == "1" or nil,
uot = (node.protocol == "shadowsocks") and node.uot == "1" or nil,
password = node.password or "",
users = (node.username and node.password) and {
{
user = node.username,
pass = node.password
}
} or nil
}
} or nil,
address = (node.protocol == "wireguard" and node.wireguard_local_address) and node.wireguard_local_address or nil,
secretKey = (node.protocol == "wireguard") and node.wireguard_secret_key or nil,
peers = (node.protocol == "wireguard") and {
{
publicKey = node.wireguard_public_key,
endpoint = node.address .. ":" .. node.port,
preSharedKey = node.wireguard_preSharedKey,
keepAlive = node.wireguard_keepAlive and tonumber(node.wireguard_keepAlive) or nil
}
} or nil,
mtu = (node.protocol == "wireguard" and node.wireguard_mtu) and tonumber(node.wireguard_mtu) or nil,
reserved = (node.protocol == "wireguard" and node.wireguard_reserved) and node.wireguard_reserved or nil
}
}
if node.protocol == "wireguard" then
result.settings.kernelMode = false
end
local alpn = {}
if node.alpn and node.alpn ~= "default" then
string.gsub(node.alpn, '[^' .. "," .. ']+', function(w)
table.insert(alpn, w)
end)
end
if alpn and #alpn > 0 then
if result.streamSettings.tlsSettings then
result.streamSettings.tlsSettings.alpn = alpn
end
end
end
return result
end
function gen_config_server(node)
local settings = nil
local routing = nil
local outbounds = {
{protocol = "freedom", tag = "direct"}, {protocol = "blackhole", tag = "blocked"}
}
if node.protocol == "vmess" or node.protocol == "vless" then
if node.uuid then
local clients = {}
for i = 1, #node.uuid do
clients[i] = {
id = node.uuid[i],
flow = (node.protocol == "vless" and node.tls == "1" and (node.transport == "raw" or node.transport == "xhttp") and node.flow and node.flow ~= "") and node.flow or nil
}
end
settings = {
clients = clients,
decryption = node.decryption or "none"
}
end
elseif node.protocol == "socks" then
settings = {
udp = ("1" == node.udp_forward) and true or false,
auth = ("1" == node.auth) and "password" or "noauth",
accounts = ("1" == node.auth) and {
{
user = node.username,
pass = node.password
}
} or nil
}
elseif node.protocol == "http" then
settings = {
allowTransparent = false,
accounts = ("1" == node.auth) and {
{
user = node.username,
pass = node.password
}
} or nil
}
node.transport = "tcp"
node.tcp_guise = "none"
elseif node.protocol == "shadowsocks" then
settings = {
method = node.method,
password = node.password,
ivCheck = ("1" == node.iv_check) and true or false,
network = node.ss_network or "TCP,UDP"
}
elseif node.protocol == "trojan" then
if node.uuid then
local clients = {}
for i = 1, #node.uuid do
clients[i] = {
password = node.uuid[i]
}
end
settings = {
clients = clients
}
end
elseif node.protocol == "dokodemo-door" then
settings = {
network = node.d_protocol,
address = node.d_address,
port = tonumber(node.d_port)
}
end
if node.fallback and node.fallback == "1" then
local fallbacks = {}
for i = 1, #node.fallback_list do
local fallbackStr = node.fallback_list[i]
if fallbackStr then
local tmp = {}
string.gsub(fallbackStr, '[^,]+', function(w)
table.insert(tmp, w)
end)
local dest = tmp[1] or ""
local path = tmp[2]
local xver = tonumber(tmp[3])
if not dest:find("%.") then
dest = tonumber(dest)
end
fallbacks[i] = {
path = path,
dest = dest,
xver = xver
}
end
end
settings.fallbacks = fallbacks
end
routing = {
domainStrategy = "IPOnDemand",
rules = {
{
ip = {"10.0.0.0/8", "172.16.0.0/12", "192.168.0.0/16"},
outboundTag = (node.accept_lan == nil or node.accept_lan == "0") and "blocked" or "direct"
}
}
}
if node.outbound_node then
local outbound = nil
if node.outbound_node == "_iface" and node.outbound_node_iface then
outbound = {
protocol = "freedom",
tag = "outbound",
streamSettings = {
sockopt = {
mark = 255,
interface = node.outbound_node_iface
}
}
}
sys.call(string.format("mkdir -p %s && touch %s/%s", api.TMP_IFACE_PATH, api.TMP_IFACE_PATH, node.outbound_node_iface))
else
local outbound_node_t = uci:get_all("passwall2", node.outbound_node)
if node.outbound_node == "_socks" or node.outbound_node == "_http" then
outbound_node_t = {
type = node.type,
protocol = node.outbound_node:gsub("_", ""),
transport = "tcp",
address = node.outbound_node_address,
port = node.outbound_node_port,
username = (node.outbound_node_username and node.outbound_node_username ~= "") and node.outbound_node_username or nil,
password = (node.outbound_node_password and node.outbound_node_password ~= "") and node.outbound_node_password or nil,
}
end
outbound = require("luci.passwall2.util_xray").gen_outbound(nil, outbound_node_t, "outbound")
end
if outbound then
table.insert(outbounds, 1, outbound)
end
end
local config = {
log = {
loglevel = ("1" == node.log) and node.loglevel or "none"
},
-- 传入连接
inbounds = {
{
listen = (node.bind_local == "1") and "127.0.0.1" or nil,
port = tonumber(node.port),
protocol = node.protocol,
settings = settings,
streamSettings = {
network = node.transport,
security = "none",
tlsSettings = ("1" == node.tls) and {
disableSystemRoot = false,
certificates = {
{
certificateFile = node.tls_certificateFile,
keyFile = node.tls_keyFile
}
},
echServerKeys = (node.ech == "1") and node.ech_key or nil
} or nil,
rawSettings = (node.transport == "raw" or node.transport == "tcp") and {
header = {
type = node.tcp_guise,
request = (node.tcp_guise == "http") and {
path = node.tcp_guise_http_path or {"/"},
headers = {
Host = node.tcp_guise_http_host or {}
}
} or nil
}
} or nil,
kcpSettings = (node.transport == "mkcp") and {
mtu = tonumber(node.mkcp_mtu),
tti = tonumber(node.mkcp_tti),
uplinkCapacity = tonumber(node.mkcp_uplinkCapacity),
downlinkCapacity = tonumber(node.mkcp_downlinkCapacity),
congestion = (node.mkcp_congestion == "1") and true or false,
readBufferSize = tonumber(node.mkcp_readBufferSize),
writeBufferSize = tonumber(node.mkcp_writeBufferSize),
seed = (node.mkcp_seed and node.mkcp_seed ~= "") and node.mkcp_seed or nil,
header = {
type = node.mkcp_guise,
domain = node.mkcp_domain
}
} or nil,
wsSettings = (node.transport == "ws") and {
host = node.ws_host or nil,
path = node.ws_path
} or nil,
grpcSettings = (node.transport == "grpc") and {
serviceName = node.grpc_serviceName
} or nil,
httpupgradeSettings = (node.transport == "httpupgrade") and {
path = node.httpupgrade_path or "/",
host = node.httpupgrade_host
} or nil,
xhttpSettings = (node.transport == "xhttp") and {
path = node.xhttp_path or "/",
host = node.xhttp_host,
maxUploadSize = node.xhttp_maxuploadsize,
maxConcurrentUploads = node.xhttp_maxconcurrentuploads
} or nil,
sockopt = {
acceptProxyProtocol = (node.acceptProxyProtocol and node.acceptProxyProtocol == "1") and true or false
}
}
}
},
-- 传出连接
outbounds = outbounds,
routing = routing
}
local alpn = {}
if node.alpn then
string.gsub(node.alpn, '[^' .. "," .. ']+', function(w)
table.insert(alpn, w)
end)
end
if alpn and #alpn > 0 then
if config.inbounds[1].streamSettings.tlsSettings then
config.inbounds[1].streamSettings.tlsSettings.alpn = alpn
end
end
if "1" == node.tls then
config.inbounds[1].streamSettings.security = "tls"
if "1" == node.reality then
config.inbounds[1].streamSettings.tlsSettings = nil
config.inbounds[1].streamSettings.security = "reality"
config.inbounds[1].streamSettings.realitySettings = {
show = false,
dest = node.reality_dest,
serverNames = node.reality_serverNames or {},
privateKey = node.reality_private_key,
shortIds = node.reality_shortId or "",
mldsa65Seed = (node.use_mldsa65Seed == "1") and node.reality_mldsa65Seed or nil
} or nil
end
end
return config
end
function gen_config(var)
local flag = var["-flag"]
local loglevel = var["-loglevel"] or "warning"
local node_id = var["-node"]
local server_host = var["-server_host"]
local server_port = var["-server_port"]
local tcp_proxy_way = var["-tcp_proxy_way"]
local redir_port = var["-redir_port"]
local local_socks_address = var["-local_socks_address"] or "0.0.0.0"
local local_socks_port = var["-local_socks_port"]
local local_socks_username = var["-local_socks_username"]
local local_socks_password = var["-local_socks_password"]
local local_http_address = var["-local_http_address"] or "0.0.0.0"
local local_http_port = var["-local_http_port"]
local local_http_username = var["-local_http_username"]
local local_http_password = var["-local_http_password"]
local dns_listen_port = var["-dns_listen_port"]
local direct_dns_udp_server = var["-direct_dns_udp_server"]
local direct_dns_udp_port = var["-direct_dns_udp_port"]
local direct_dns_query_strategy = var["-direct_dns_query_strategy"]
local direct_ipset = var["-direct_ipset"]
local direct_nftset = var["-direct_nftset"]
local remote_dns_udp_server = var["-remote_dns_udp_server"]
local remote_dns_udp_port = var["-remote_dns_udp_port"]
local remote_dns_tcp_server = var["-remote_dns_tcp_server"]
local remote_dns_tcp_port = var["-remote_dns_tcp_port"]
local remote_dns_doh_url = var["-remote_dns_doh_url"]
local remote_dns_doh_host = var["-remote_dns_doh_host"]
local remote_dns_doh_ip = var["-remote_dns_doh_ip"]
local remote_dns_doh_port = var["-remote_dns_doh_port"]
local remote_dns_fake = var["-remote_dns_fake"]
local remote_dns_query_strategy = var["-remote_dns_query_strategy"]
local remote_dns_detour = var["-remote_dns_detour"]
local dns_cache = var["-dns_cache"]
local no_run = var["-no_run"]
local dns_domain_rules = {}
local dns = nil
local fakedns = nil
local inbounds = {}
local outbounds = {}
local routing = nil
local burstObservatory = nil
local strategy = nil
local COMMON = {}
local CACHE_TEXT_FILE = CACHE_PATH .. "/cache_" .. flag .. ".txt"
local xray_settings = uci:get_all(appname, "@global_xray[0]") or {}
local node = node_id and uci:get_all(appname, node_id) or nil
local balancers = {}
local rules = {}
if local_socks_port then
local inbound = {
tag = "socks-in",
listen = local_socks_address,
port = tonumber(local_socks_port),
protocol = "socks",
settings = {auth = "noauth", udp = true},
sniffing = {
enabled = xray_settings.sniffing_override_dest == "1" or node.protocol == "_shunt"
}
}
if inbound.sniffing.enabled == true then
inbound.sniffing.destOverride = {"http", "tls", "quic"}
inbound.sniffing.routeOnly = xray_settings.sniffing_override_dest ~= "1" or nil
inbound.sniffing.domainsExcluded = xray_settings.sniffing_override_dest == "1" and get_domain_excluded() or nil
end
if local_socks_username and local_socks_password and local_socks_username ~= "" and local_socks_password ~= "" then
inbound.settings.auth = "password"
inbound.settings.accounts = {
{
user = local_socks_username,
pass = local_socks_password
}
}
end
table.insert(inbounds, inbound)
end
if local_http_port then
local inbound = {
listen = local_http_address,
port = tonumber(local_http_port),
protocol = "http",
settings = {allowTransparent = false}
}
if local_http_username and local_http_password and local_http_username ~= "" and local_http_password ~= "" then
inbound.settings.accounts = {
{
user = local_http_username,
pass = local_http_password
}
}
end
table.insert(inbounds, inbound)
end
if redir_port then
local inbound = {
port = tonumber(redir_port),
protocol = "dokodemo-door",
settings = {network = "tcp,udp", followRedirect = true},
streamSettings = {sockopt = {tproxy = "tproxy"}},
sniffing = {
enabled = xray_settings.sniffing_override_dest == "1" or node.protocol == "_shunt"
}
}
if inbound.sniffing.enabled == true then
inbound.sniffing.destOverride = {"http", "tls", "quic"}
inbound.sniffing.metadataOnly = false
inbound.sniffing.routeOnly = xray_settings.sniffing_override_dest ~= "1" or nil
inbound.sniffing.domainsExcluded = xray_settings.sniffing_override_dest == "1" and get_domain_excluded() or nil
end
if remote_dns_fake then
inbound.sniffing.enabled = true
if not inbound.sniffing.destOverride then
inbound.sniffing.destOverride = {"fakedns"}
inbound.sniffing.metadataOnly = true
else
table.insert(inbound.sniffing.destOverride, "fakedns")
inbound.sniffing.metadataOnly = false
end
end
local tcp_inbound = api.clone(inbound)
tcp_inbound.tag = "tcp_redir"
tcp_inbound.settings.network = "tcp"
tcp_inbound.streamSettings.sockopt.tproxy = tcp_proxy_way
table.insert(inbounds, tcp_inbound)
local udp_inbound = api.clone(inbound)
udp_inbound.tag = "udp_redir"
udp_inbound.settings.network = "udp"
table.insert(inbounds, udp_inbound)
end
local function get_balancer_tag(_node_id)
return "balancer-" .. _node_id
end
local function gen_loopback(outboundTag, dst_node_id)
if not outboundTag then return nil end
local inboundTag = dst_node_id and "loop-in-" .. dst_node_id or outboundTag .. "-lo"
table.insert(outbounds, {
protocol = "loopback",
tag = outboundTag,
settings = { inboundTag = inboundTag }
})
return inboundTag
end
local function gen_balancer(_node, loopback_tag)
local balancer_id = _node[".name"]
local balancer_tag = "balancer-" .. balancer_id
local loopback_dst = balancer_id -- route destination for the loopback outbound
if not loopback_tag or loopback_tag == "" then loopback_tag = balancer_id end
-- existing balancer
for _, v in ipairs(balancers) do
if v.tag == balancer_tag then
gen_loopback(loopback_tag, loopback_dst)
return balancer_tag
end
end
-- new balancer
local blc_nodes = _node.balancing_node
local valid_nodes = {}
for i = 1, #blc_nodes do
local blc_node_id = blc_nodes[i]
local blc_node_tag = "blc-" .. blc_node_id
local is_new_blc_node = true
for _, outbound in ipairs(outbounds) do
if string.sub(outbound.tag, 1, #blc_node_tag) == blc_node_tag then
is_new_blc_node = false
valid_nodes[#valid_nodes + 1] = outbound.tag
break
end
end
if is_new_blc_node then
local blc_node = uci:get_all(appname, blc_node_id)
local outbound = gen_outbound(flag, blc_node, blc_node_tag, { fragment = xray_settings.fragment == "1" or nil, noise = xray_settings.noise == "1" or nil, run_socks_instance = not no_run })
if outbound then
outbound.tag = outbound.tag .. ":" .. blc_node.remarks
table.insert(outbounds, outbound)
valid_nodes[#valid_nodes + 1] = outbound.tag
end
end
end
if #valid_nodes == 0 then return nil end
-- fallback node
local fallback_node_tag = nil
local fallback_node_id = _node.fallback_node
if not fallback_node_id or fallback_node_id == "" then fallback_node_id = nil end
if fallback_node_id then
local is_new_node = true
for _, outbound in ipairs(outbounds) do
if string.sub(outbound.tag, 1, #fallback_node_id) == fallback_node_id then
is_new_node = false
fallback_node_tag = outbound.tag
break
end
end
if is_new_node then
local fallback_node = uci:get_all(appname, fallback_node_id)
if fallback_node.protocol ~= "_balancing" then
local outbound = gen_outbound(flag, fallback_node, fallback_node_id, { fragment = xray_settings.fragment == "1" or nil, noise = xray_settings.noise == "1" or nil, run_socks_instance = not no_run })
if outbound then
outbound.tag = outbound.tag .. ":" .. fallback_node.remarks
table.insert(outbounds, outbound)
fallback_node_tag = outbound.tag
end
else
if gen_balancer(fallback_node) then
fallback_node_tag = fallback_node_id
end
end
end
end
if _node.balancingStrategy == "leastLoad" then
strategy = {
type = _node.balancingStrategy,
settings = {
expected = _node.expected and tonumber(_node.expected) and tonumber(_node.expected) or 2,
maxRTT = "1s"
}
}
else
strategy = { type = _node.balancingStrategy or "random" }
end
table.insert(balancers, {
tag = balancer_tag,
selector = valid_nodes,
fallbackTag = fallback_node_tag,
strategy = strategy
})
if _node.balancingStrategy == "leastPing" or _node.balancingStrategy == "leastLoad" or fallback_node_tag then
if not burstObservatory then
burstObservatory = {
subjectSelector = { "blc-" },
pingConfig = {
destination = _node.useCustomProbeUrl and _node.probeUrl or nil,
interval = (api.format_go_time(_node.probeInterval) ~= "0s") and api.format_go_time(_node.probeInterval) or "1m",
sampling = 3,
timeout = "5s"
}
}
end
end
local inbound_tag = gen_loopback(loopback_tag, loopback_dst)
table.insert(rules, { inboundTag = { inbound_tag }, balancerTag = balancer_tag })
return balancer_tag
end
local function set_outbound_detour(node, outbound, outbounds_table, shunt_rule_name)
if not node or not outbound or not outbounds_table then return nil end
local default_outTag = outbound.tag
local last_insert_outbound
if node.chain_proxy == "1" and node.preproxy_node then
if outbound["_flag_proxy_tag"] then
--Ignore
else
local preproxy_node = uci:get_all(appname, node.preproxy_node)
if preproxy_node then
local preproxy_outbound = gen_outbound(nil, preproxy_node)
if preproxy_outbound then
preproxy_outbound.tag = preproxy_node[".name"] .. ":" .. preproxy_node.remarks
outbound.tag = preproxy_outbound.tag .. " -> " .. outbound.tag
outbound.proxySettings = {
tag = preproxy_outbound.tag,
transportLayer = true
}
last_insert_outbound = preproxy_outbound
default_outTag = outbound.tag
end
end
end
end
if node.chain_proxy == "2" and node.to_node then
local to_node = uci:get_all(appname, node.to_node)
if to_node then
local to_outbound = gen_outbound(nil, to_node)
if to_outbound then
if shunt_rule_name then
to_outbound.tag = outbound.tag
outbound.tag = node[".name"]
else
to_outbound.tag = outbound.tag .. " -> " .. to_outbound.tag
end
to_outbound.proxySettings = {
tag = outbound.tag,
transportLayer = true
}
table.insert(outbounds_table, to_outbound)
default_outTag = to_outbound.tag
end
end
end
return default_outTag, last_insert_outbound
end
if node then
if server_host and server_port then
node.address = server_host
node.port = server_port
end
if node.protocol == "_shunt" then
local preproxy_rule_name = node.preproxy_enabled == "1" and "main" or nil
local preproxy_tag = preproxy_rule_name
local preproxy_node_id = node["main_node"]
local preproxy_outbound_tag, preproxy_balancer_tag
local preproxy_nodes
local function gen_shunt_node(rule_name, _node_id)
if not rule_name then return nil, nil end
if not _node_id then _node_id = node[rule_name] end
if _node_id == "_direct" then
return "direct", nil
elseif _node_id == "_blackhole" then
return "blackhole", nil
elseif _node_id == "_default" then
return "default", nil
elseif _node_id and _node_id:find("Socks_") then
local socks_id = _node_id:sub(1 + #"Socks_")
local socks_node = uci:get_all(appname, socks_id) or nil
local socks_tag
if socks_node then
local _node = {
type = "Xray",
protocol = "socks",
address = "127.0.0.1",
port = socks_node.port,
transport = "tcp",
stream_security = "none"
}
local outbound = gen_outbound(flag, _node, rule_name)
if outbound then
if rule_name == "default" then
table.insert(outbounds, 1, outbound)
else
table.insert(outbounds, outbound)
end
socks_tag = outbound.tag
end
end
return socks_tag, nil
elseif _node_id then
local _node = uci:get_all(appname, _node_id)
if not _node then return nil, nil end
if api.is_normal_node(_node) then
local use_proxy = preproxy_tag and node[rule_name .. "_proxy_tag"] == preproxy_rule_name and _node_id ~= preproxy_node_id
if use_proxy and preproxy_balancer_tag and preproxy_nodes[_node_id] then use_proxy = false end
local copied_outbound
for index, value in ipairs(outbounds) do
if value["_id"] == _node_id and value["_flag_proxy_tag"] == (use_proxy and preproxy_tag or nil) then
copied_outbound = api.clone(value)
break
end
end
if copied_outbound then
copied_outbound.tag = rule_name .. ":" .. _node.remarks
table.insert(outbounds, copied_outbound)
return copied_outbound.tag, nil
else
if use_proxy and _node.type ~= "Xray" then
new_port = get_new_port()
table.insert(inbounds, {
tag = "proxy_" .. rule_name,
listen = "127.0.0.1",
port = new_port,
protocol = "dokodemo-door",
settings = {network = "tcp,udp", address = _node.address, port = tonumber(_node.port)}
})
if _node.tls_serverName == nil then
_node.tls_serverName = _node.address
end
_node.address = "127.0.0.1"
_node.port = new_port
table.insert(rules, 1, {
inboundTag = {"proxy_" .. rule_name},
outboundTag = not preproxy_balancer_tag and preproxy_tag or nil,
balancerTag = preproxy_balancer_tag
})
end
local proxy_table = {
tag = use_proxy and preproxy_tag or nil,
run_socks_instance = not no_run
}
if not proxy_table.tag then
if xray_settings.fragment == "1" then
proxy_table.fragment = true
end
if xray_settings.noise == "1" then
proxy_table.noise = true
end
end
local outbound = gen_outbound(flag, _node, rule_name, proxy_table)
local outbound_tag
if outbound then
outbound.tag = outbound.tag .. ":" .. _node.remarks
outbound_tag, last_insert_outbound = set_outbound_detour(_node, outbound, outbounds, rule_name)
if rule_name == "default" then
table.insert(outbounds, 1, outbound)
else
table.insert(outbounds, outbound)
end
if last_insert_outbound then
table.insert(outbounds, last_insert_outbound)
end
end
return outbound_tag, nil
end
elseif _node.protocol == "_balancing" then
return nil, gen_balancer(_node, rule_name)
elseif _node.protocol == "_iface" then
local outbound_tag
if _node.iface then
local outbound = {
protocol = "freedom",
tag = rule_name,
streamSettings = {
sockopt = {
mark = 255,
interface = _node.iface
}
}
}
outbound_tag = outbound.tag
table.insert(outbounds, outbound)
sys.call(string.format("mkdir -p %s && touch %s/%s", api.TMP_IFACE_PATH, api.TMP_IFACE_PATH, _node.iface))
end
return outbound_tag, nil
end
end
end
if preproxy_tag and preproxy_node_id then
preproxy_outbound_tag, preproxy_balancer_tag = gen_shunt_node(preproxy_rule_name, preproxy_node_id)
if preproxy_balancer_tag then
local _node_id = preproxy_node_id
preproxy_nodes = {}
while _node_id do
_node = uci:get_all(appname, _node_id)
if not _node then break end
if _node.protocol ~= "_balancing" then
preproxy_nodes[_node_id] = true
break
end
local _blc_nodes = _node.balancing_node
for i = 1, #_blc_nodes do preproxy_nodes[_blc_nodes[i]] = true end
_node_id = _node.fallback_node
end
elseif preproxy_outbound_tag then
preproxy_tag = preproxy_outbound_tag
end
end
--default_node
local default_node_id = node.default_node or "_direct"
local default_outboundTag, default_balancerTag = gen_shunt_node("default", default_node_id)
COMMON.default_outbound_tag = default_outboundTag
COMMON.default_balancer_tag = default_balancerTag
--shunt rule
uci:foreach(appname, "shunt_rules", function(e)
local outboundTag, balancerTag = gen_shunt_node(e[".name"])
if outboundTag or balancerTag and e.remarks then
if outboundTag == "default" then
outboundTag = default_outboundTag
balancerTag = default_balancerTag
end
local protocols = nil
if e["protocol"] and e["protocol"] ~= "" then
protocols = {}
string.gsub(e["protocol"], '[^' .. " " .. ']+', function(w)
table.insert(protocols, w)
end)
end
local inboundTag = nil
if e["inbound"] and e["inbound"] ~= "" then
inboundTag = {}
if e["inbound"]:find("tproxy") then
if redir_port then
table.insert(inboundTag, "tcp_redir")
table.insert(inboundTag, "udp_redir")
end
end
if e["inbound"]:find("socks") then
if local_socks_port then
table.insert(inboundTag, "socks-in")
end
end
end
local domains = nil
if e.domain_list then
local domain_table = {
shunt_rule_name = e[".name"],
outboundTag = outboundTag,
balancerTag = balancerTag,
domain = {},
}
domains = {}
string.gsub(e.domain_list, '[^' .. "\r\n" .. ']+', function(w)
if w:find("#") == 1 then return end
if w:find("rule-set:", 1, true) == 1 or w:find("rs:") == 1 then return end
table.insert(domains, w)
table.insert(domain_table.domain, w)
end)
if outboundTag or balancerTag then
table.insert(dns_domain_rules, api.clone(domain_table))
end
if #domains == 0 then domains = nil end
end
local ip = nil
if e.ip_list then
ip = {}
string.gsub(e.ip_list, '[^' .. "\r\n" .. ']+', function(w)
if w:find("#") == 1 then return end
if w:find("rule-set:", 1, true) == 1 or w:find("rs:") == 1 then return end
table.insert(ip, w)
end)
if #ip == 0 then ip = nil end
end
local source = nil
if e.source then
source = {}
string.gsub(e.source, '[^' .. " " .. ']+', function(w)
table.insert(source, w)
end)
end
local rule = {
ruleTag = e.remarks,
inboundTag = inboundTag,
outboundTag = outboundTag,
balancerTag = balancerTag,
network = e["network"] or "tcp,udp",
source = source,
sourcePort = e["sourcePort"] ~= "" and e["sourcePort"] or nil,
port = e["port"] ~= "" and e["port"] or nil,
protocol = protocols
}
if domains then
local _rule = api.clone(rule)
_rule.ruleTag = _rule.ruleTag .. " Domains"
_rule.domains = domains
table.insert(rules, _rule)
end
if ip then
local _rule = api.clone(rule)
_rule.ruleTag = _rule.ruleTag .. " IP"
_rule.ip = ip
table.insert(rules, _rule)
end
if not domains and not ip then
table.insert(rules, rule)
end
end
end)
if default_balancerTag then
table.insert(rules, {
ruleTag = "default",
balancerTag = default_balancerTag,
network = "tcp,udp"
})
end
routing = {
domainStrategy = node.domainStrategy or "AsIs",
domainMatcher = node.domainMatcher or "hybrid",
balancers = #balancers > 0 and balancers or nil,
rules = rules
}
elseif node.protocol == "_balancing" then
if node.balancing_node then
local balancer_tag = gen_balancer(node)
if balancer_tag then
table.insert(rules, { network = "tcp,udp", balancerTag = balancer_tag })
end
routing = {
balancers = balancers,
rules = rules
}
COMMON.default_balancer_tag = balancer_tag
end
elseif node.protocol == "_iface" then
if node.iface then
local outbound = {
protocol = "freedom",
tag = node.remarks or node_id,
streamSettings = {
sockopt = {
mark = 255,
interface = node.iface
}
}
}
table.insert(outbounds, outbound)
COMMON.default_outbound_tag = outbound.tag
sys.call(string.format("mkdir -p %s && touch %s/%s", api.TMP_IFACE_PATH, api.TMP_IFACE_PATH, node.iface))
end
else
local outbound = gen_outbound(flag, node, nil, { fragment = xray_settings.fragment == "1" or nil, noise = xray_settings.noise == "1" or nil, run_socks_instance = not no_run })
if outbound then
outbound.tag = outbound.tag .. ":" .. node.remarks
COMMON.default_outbound_tag, last_insert_outbound = set_outbound_detour(node, outbound, outbounds)
table.insert(outbounds, outbound)
if last_insert_outbound then
table.insert(outbounds, last_insert_outbound)
end
routing = {
domainStrategy = "AsIs",
domainMatcher = "hybrid",
rules = {}
}
table.insert(routing.rules, {
ruleTag = "default",
outboundTag = COMMON.default_outbound_tag,
network = "tcp,udp"
})
end
end
end
if dns_listen_port then
local direct_dns_tag = "dns-in-direct"
local remote_dns_tag = "dns-in-remote"
local remote_fakedns_tag = "dns-in-remote-fakedns"
local default_dns_tag = "dns-in-default"
local dns_servers = {}
local _remote_dns_proto = "tcp"
if not routing then
routing = {
domainStrategy = "IPOnDemand",
rules = {}
}
end
dns = {
tag = "dns-global",
hosts = {},
disableCache = (dns_cache and dns_cache == "0") and true or false,
disableFallback = true,
disableFallbackIfMatch = true,
servers = {},
queryStrategy = "UseIP"
}
local dns_host = ""
if flag == "global" then
dns_host = uci:get(appname, "@global[0]", "dns_hosts") or ""
else
flag = flag:gsub("acl_", "")
local dns_hosts_mode = uci:get(appname, flag, "dns_hosts_mode") or "default"
if dns_hosts_mode == "default" then
dns_host = uci:get(appname, "@global[0]", "dns_hosts") or ""
elseif dns_hosts_mode == "disable" then
dns_host = ""
elseif dns_hosts_mode == "custom" then
dns_host = uci:get(appname, flag, "dns_hosts") or ""
end
end
if #dns_host > 0 then
string.gsub(dns_host, '[^' .. "\r\n" .. ']+', function(w)
local host = sys.exec(string.format("echo -n $(echo %s | awk -F ' ' '{print $1}')", w))
local key = sys.exec(string.format("echo -n $(echo %s | awk -F ' ' '{print $2}')", w))
if host ~= "" and key ~= "" then
dns.hosts[host] = key
end
end)
end
local _remote_dns_ip = nil
local _remote_dns = {
tag = remote_dns_tag,
queryStrategy = (remote_dns_query_strategy and remote_dns_query_strategy ~= "") and remote_dns_query_strategy or "UseIPv4"
}
if remote_dns_udp_server then
_remote_dns.address = remote_dns_udp_server
_remote_dns.port = tonumber(remote_dns_udp_port) or 53
_remote_dns_proto = "udp"
_remote_dns_ip = remote_dns_udp_server
end
if remote_dns_tcp_server then
_remote_dns.address = "tcp://" .. remote_dns_tcp_server .. ":" .. tonumber(remote_dns_tcp_port) or 53
_remote_dns.port = tonumber(remote_dns_tcp_port) or 53
_remote_dns_proto = "tcp"
_remote_dns_ip = remote_dns_tcp_server
end
if remote_dns_doh_url and remote_dns_doh_host then
if remote_dns_doh_ip and remote_dns_doh_host ~= remote_dns_doh_ip and not api.is_ip(remote_dns_doh_host) then
dns.hosts[remote_dns_doh_host] = remote_dns_doh_ip
end
_remote_dns.address = remote_dns_doh_url
_remote_dns.port = tonumber(remote_dns_doh_port) or 443
_remote_dns_ip = remote_dns_doh_ip
end
if _remote_dns.address then
table.insert(dns_servers, {
outboundTag = remote_dns_detour == "direct" and "direct" or nil,
server = _remote_dns
})
end
local _remote_fakedns = nil
if remote_dns_fake then
fakedns = {}
local fakedns4 = {
ipPool = "198.18.0.0/16",
poolSize = 65535
}
local fakedns6 = {
ipPool = "fc00::/18",
poolSize = 65535
}
if remote_dns_query_strategy == "UseIP" then
table.insert(fakedns, fakedns4)
table.insert(fakedns, fakedns6)
elseif remote_dns_query_strategy == "UseIPv4" then
table.insert(fakedns, fakedns4)
elseif remote_dns_query_strategy == "UseIPv6" then
table.insert(fakedns, fakedns6)
end
_remote_fakedns = {
tag = remote_fakedns_tag,
address = "fakedns",
}
table.insert(dns_servers, {
server = _remote_fakedns
})
end
local _direct_dns = nil
if direct_dns_udp_server then
local domain = {}
local nodes_domain_text = sys.exec('uci show passwall2 | grep ".address=" | cut -d "\'" -f 2 | grep "[a-zA-Z]$" | sort -u')
string.gsub(nodes_domain_text, '[^' .. "\r\n" .. ']+', function(w)
table.insert(domain, "full:" .. w)
end)
if #domain > 0 then
table.insert(dns_domain_rules, 1, {
shunt_rule_name = "logic-vpslist",
outboundTag = "direct",
domain = domain
})
end
_direct_dns = {
tag = direct_dns_tag,
address = direct_dns_udp_server,
port = tonumber(direct_dns_udp_port) or 53,
queryStrategy = (direct_dns_query_strategy and direct_dns_query_strategy ~= "") and direct_dns_query_strategy or "UseIP",
}
if _direct_dns.address then
table.insert(dns_servers, {
outboundTag = "direct",
server = _direct_dns
})
end
end
if dns_listen_port then
table.insert(inbounds, {
listen = "127.0.0.1",
port = tonumber(dns_listen_port),
protocol = "dokodemo-door",
tag = "dns-in",
settings = {
address = "0.0.0.0",
network = "tcp,udp"
}
})
local direct_type_dns = {
settings = {
address = direct_dns_udp_server,
port = tonumber(direct_dns_udp_port) or 53,
network = "udp",
nonIPQuery = "skip",
blockTypes = {
65
}
},
proxySettings = {
tag = "direct"
}
}
local remote_type_dns = {
settings = {
address = remote_dns_udp_server,
port = tonumber(remote_dns_udp_port) or 53,
network = _remote_dns_proto or "tcp",
nonIPQuery = "drop"
}
}
local type_dns = direct_type_dns
table.insert(outbounds, {
tag = "dns-out",
protocol = "dns",
proxySettings = type_dns.proxySettings,
settings = type_dns.settings
})
table.insert(routing.rules, 1, {
inboundTag = {
"dns-in"
},
outboundTag = "dns-out"
})
end
local default_dns_tag_name = remote_dns_tag
if (not COMMON.default_balancer_tag and not COMMON.default_outbound_tag) or COMMON.default_outbound_tag == "direct" then
default_dns_tag_name = direct_dns_tag
end
if dns_servers and #dns_servers > 0 then
-- Default DNS logic
local default_dns_server = nil
for index, value in ipairs(dns_servers) do
if not default_dns_server and value.server.tag == default_dns_tag_name then
default_dns_server = api.clone(value)
default_dns_server.server.tag = default_dns_tag
if value.server.tag == remote_dns_tag then
if remote_dns_fake then
default_dns_server.server = api.clone(_remote_fakedns)
default_dns_server.server.tag = default_dns_tag
else
default_dns_server.outboundTag = value.outboundTag or COMMON.default_outbound_tag
default_dns_server.balancerTag = COMMON.default_balancer_tag
end
end
table.insert(dns_servers, 1, default_dns_server)
break
end
end
-- Shunt rule DNS logic
if dns_domain_rules and #dns_domain_rules > 0 then
for index, value in ipairs(dns_domain_rules) do
if value.domain and (value.outboundTag or value.balancerTag) then
local dns_server = nil
local dns_outboundTag = value.outboundTag
local dns_balancerTag = value.balancerTag
if value.outboundTag == "direct" then
dns_server = api.clone(_direct_dns)
else
if remote_dns_fake then
dns_server = api.clone(_remote_fakedns)
else
dns_server = api.clone(_remote_dns)
if remote_dns_detour == "direct" then
dns_outboundTag = "direct"
dns_balancerTag = nil
end
end
end
dns_server.domains = value.domain
if value.shunt_rule_name then
dns_server.tag = "dns-in-" .. value.shunt_rule_name
end
if dns_server then
table.insert(dns_servers, {
outboundTag = dns_outboundTag,
balancerTag = dns_balancerTag,
server = dns_server
})
end
end
end
end
for i = #dns_servers, 1, -1 do
local value = dns_servers[i]
if value.server.tag ~= direct_dns_tag and value.server.tag ~= remote_dns_tag then
-- DNS rule must be at the front, prevents being matched by rules.
if (value.outboundTag or value.balancerTag) and value.server.address ~= "fakedns" then
table.insert(routing.rules, 1, {
inboundTag = {
value.server.tag
},
outboundTag = value.outboundTag,
balancerTag = value.balancerTag
})
end
if (value.server.domains and #value.server.domains > 0) or value.server.tag == default_dns_tag then
-- Only keep default DNS server or has domains DNS server.
table.insert(dns.servers, 1, value.server)
end
end
end
end
local default_rule_index = nil
for index, value in ipairs(routing.rules) do
if value.ruleTag == "default" then
default_rule_index = index
break
end
end
if default_rule_index then
local default_rule = api.clone(routing.rules[default_rule_index])
table.remove(routing.rules, default_rule_index)
table.insert(routing.rules, default_rule)
end
local dns_hosts_len = 0
for key, value in pairs(dns.hosts) do
dns_hosts_len = dns_hosts_len + 1
end
if dns_hosts_len == 0 then
dns.hosts = nil
end
local content = flag .. node_id .. jsonc.stringify(routing.rules)
if api.cacheFileCompareToLogic(CACHE_TEXT_FILE, content) == false then
--clear ipset/nftset
if direct_ipset then
string.gsub(direct_ipset, '[^' .. "," .. ']+', function(w)
sys.call("ipset -q -F " .. w)
end)
local ipset_prefix_name = "passwall2_" .. node_id .. "_"
local ipset_list = sys.exec("ipset list | grep 'Name: ' | grep '" .. ipset_prefix_name .. "' | awk '{print $2}'")
string.gsub(ipset_list, '[^' .. "\r\n" .. ']+', function(w)
sys.call("ipset -q -F " .. w)
end)
end
if direct_nftset then
string.gsub(direct_nftset, '[^' .. "," .. ']+', function(w)
local split = api.split(w, "#")
if #split > 3 then
local ip_type = split[1]
local family = split[2]
local table_name = split[3]
local set_name = split[4]
sys.call(string.format("nft flush set %s %s %s 2>/dev/null", family, table_name, set_name))
end
end)
local family = "inet"
local table_name = "passwall2"
local nftset_prefix_name = "passwall2_" .. node_id .. "_"
local nftset_list = sys.exec("nft -a list sets | grep -E '" .. nftset_prefix_name .. "' | awk -F 'set ' '{print $2}' | awk '{print $1}'")
string.gsub(nftset_list, '[^' .. "\r\n" .. ']+', function(w)
sys.call(string.format("nft flush set %s %s %s 2>/dev/null", family, table_name, w))
end)
end
end
end
if inbounds or outbounds then
local config = {
log = {
--access = string.format("/tmp/etc/%s/%s_access.log", appname, "global"),
--error = string.format("/tmp/etc/%s/%s_error.log", appname, "global"),
--dnsLog = true,
loglevel = loglevel
},
-- DNS
dns = dns,
fakedns = fakedns,
-- 传入连接
inbounds = inbounds,
-- 传出连接
outbounds = outbounds,
-- 连接观测
burstObservatory = burstObservatory,
-- 路由
routing = routing,
-- 本地策略
policy = {
levels = {
[0] = {
-- handshake = 4,
-- connIdle = 300,
-- uplinkOnly = 2,
-- downlinkOnly = 5,
bufferSize = xray_settings.buffer_size and tonumber(xray_settings.buffer_size) or nil,
statsUserUplink = false,
statsUserDownlink = false
}
},
-- system = {
-- statsInboundUplink = false,
-- statsInboundDownlink = false
-- }
}
}
if xray_settings.fragment == "1" or xray_settings.noise == "1" then
table.insert(outbounds, {
protocol = "freedom",
tag = "dialerproxy",
settings = {
domainStrategy = (direct_dns_query_strategy and direct_dns_query_strategy ~= "") and direct_dns_query_strategy or "UseIP",
fragment = (xray_settings.fragment == "1") and {
packets = (xray_settings.fragment_packets and xray_settings.fragment_packets ~= "") and xray_settings.fragment_packets,
length = (xray_settings.fragment_length and xray_settings.fragment_length ~= "") and xray_settings.fragment_length,
interval = (xray_settings.fragment_interval and xray_settings.fragment_interval ~= "") and xray_settings.fragment_interval,
maxSplit = (xray_settings.fragment_maxSplit and xray_settings.fragment_maxSplit ~= "") and xray_settings.fragment_maxSplit
} or nil,
noises = (xray_settings.noise == "1") and get_noise_packets() or nil
},
streamSettings = {
sockopt = {
mark = 255
}
}
})
end
local direct_outbound = {
protocol = "freedom",
tag = "direct",
settings = {
domainStrategy = (direct_dns_query_strategy and direct_dns_query_strategy ~= "") and direct_dns_query_strategy or "UseIP"
},
streamSettings = {
sockopt = {
mark = 255
}
}
}
if COMMON.default_outbound_tag == "direct" then
table.insert(outbounds, 1, direct_outbound)
else
table.insert(outbounds, direct_outbound)
end
local blackhole_outbound = {
protocol = "blackhole",
tag = "blackhole"
}
if COMMON.default_outbound_tag == "blackhole" then
table.insert(outbounds, 1, blackhole_outbound)
else
table.insert(outbounds, blackhole_outbound)
end
for index, value in ipairs(config.outbounds) do
if not value["_flag_proxy_tag"] and value["_id"] and value.server and value.server_port and not no_run then
sys.call(string.format("echo '%s' >> %s", value["_id"], api.TMP_PATH .. "/direct_node_list"))
end
for k, v in pairs(config.outbounds[index]) do
if k:find("_") == 1 then
config.outbounds[index][k] = nil
end
end
end
return jsonc.stringify(config, 1)
end
end
function gen_proto_config(var)
local local_socks_address = var["-local_socks_address"] or "0.0.0.0"
local local_socks_port = var["-local_socks_port"]
local local_socks_username = var["-local_socks_username"]
local local_socks_password = var["-local_socks_password"]
local local_http_address = var["-local_http_address"] or "0.0.0.0"
local local_http_port = var["-local_http_port"]
local local_http_username = var["-local_http_username"]
local local_http_password = var["-local_http_password"]
local server_proto = var["-server_proto"]
local server_address = var["-server_address"]
local server_port = var["-server_port"]
local server_username = var["-server_username"]
local server_password = var["-server_password"]
local inbounds = {}
local outbounds = {}
local routing = nil
if local_socks_address and local_socks_port then
local inbound = {
listen = local_socks_address,
port = tonumber(local_socks_port),
protocol = "socks",
settings = {
udp = true,
auth = "noauth"
}
}
if local_socks_username and local_socks_password and local_socks_username ~= "" and local_socks_password ~= "" then
inbound.settings.auth = "password"
inbound.settings.accounts = {
{
user = local_socks_username,
pass = local_socks_password
}
}
end
table.insert(inbounds, inbound)
end
if local_http_address and local_http_port then
local inbound = {
listen = local_http_address,
port = tonumber(local_http_port),
protocol = "http",
settings = {
allowTransparent = false
}
}
if local_http_username and local_http_password and local_http_username ~= "" and local_http_password ~= "" then
inbound.settings.accounts = {
{
user = local_http_username,
pass = local_http_password
}
}
end
table.insert(inbounds, inbound)
end
if server_proto ~= "nil" and server_address ~= "nil" and server_port ~= "nil" then
local outbound = {
protocol = server_proto,
streamSettings = {
network = "tcp",
security = "none"
},
settings = {
servers = {
{
address = server_address,
port = tonumber(server_port),
users = (server_username and server_password) and {
{
user = server_username,
pass = server_password
}
} or nil
}
}
}
}
if outbound then table.insert(outbounds, outbound) end
end
-- 额外传出连接
table.insert(outbounds, {
protocol = "freedom", tag = "direct", settings = {keep = ""}
})
local config = {
log = {
loglevel = "warning"
},
-- 传入连接
inbounds = inbounds,
-- 传出连接
outbounds = outbounds,
-- 路由
routing = routing
}
return jsonc.stringify(config, 1)
end
function gen_dns_config(var)
local dns_listen_port = var["-dns_listen_port"]
local dns_out_tag = var["-dns_out_tag"]
local direct_dns_udp_server = var["-direct_dns_udp_server"]
local direct_dns_udp_port = var["-direct_dns_udp_port"]
local direct_dns_tcp_server = var["-direct_dns_tcp_server"]
local direct_dns_tcp_port = var["-direct_dns_tcp_port"]
local direct_dns_doh_url = var["-direct_dns_doh_url"]
local direct_dns_doh_host = var["-direct_dns_doh_host"]
local direct_dns_doh_ip = var["-direct_dns_doh_ip"]
local direct_dns_doh_port = var["-direct_dns_doh_port"]
local direct_dns_query_strategy = var["-direct_dns_query_strategy"]
local remote_dns_udp_server = var["-remote_dns_udp_server"]
local remote_dns_udp_port = var["-remote_dns_udp_port"]
local remote_dns_tcp_server = var["-remote_dns_tcp_server"]
local remote_dns_tcp_port = var["-remote_dns_tcp_port"]
local remote_dns_doh_url = var["-remote_dns_doh_url"]
local remote_dns_doh_host = var["-remote_dns_doh_host"]
local remote_dns_doh_ip = var["-remote_dns_doh_ip"]
local remote_dns_doh_port = var["-remote_dns_doh_port"]
local remote_dns_query_strategy = var["-remote_dns_query_strategy"]
local remote_dns_detour = var["-remote_dns_detour"]
local remote_dns_client_ip = var["-remote_dns_client_ip"]
local remote_dns_outbound_socks_address = var["-remote_dns_outbound_socks_address"]
local remote_dns_outbound_socks_port = var["-remote_dns_outbound_socks_port"]
local dns_cache = var["-dns_cache"]
local loglevel = var["-loglevel"] or "warning"
local inbounds = {}
local outbounds = {}
local dns = nil
local routing = nil
if dns_listen_port then
routing = {
domainStrategy = "IPOnDemand",
rules = {}
}
dns = {
tag = "dns-global",
hosts = {},
disableCache = (dns_cache == "1") and false or true,
disableFallback = true,
disableFallbackIfMatch = true,
servers = {},
clientIp = (remote_dns_client_ip and remote_dns_client_ip ~= "") and remote_dns_client_ip or nil,
}
local other_type_dns_proto, other_type_dns_server, other_type_dns_port
if dns_out_tag == "remote" then
dns.queryStrategy = (remote_dns_query_strategy and remote_dns_query_strategy ~= "") and remote_dns_query_strategy or "UseIPv4"
if remote_dns_detour == "direct" then
dns_out_tag = "direct"
table.insert(outbounds, 1, {
tag = dns_out_tag,
protocol = "freedom",
settings = {
domainStrategy = (direct_dns_query_strategy and direct_dns_query_strategy ~= "") and direct_dns_query_strategy or "UseIP"
},
streamSettings = {
sockopt = {
mark = 255
}
}
})
else
if remote_dns_outbound_socks_address and remote_dns_outbound_socks_port then
table.insert(outbounds, 1, {
tag = dns_out_tag,
protocol = "socks",
streamSettings = {
network = "tcp",
security = "none"
},
settings = {
servers = {
{
address = remote_dns_outbound_socks_address,
port = tonumber(remote_dns_outbound_socks_port)
}
}
}
})
end
end
local _remote_dns = {
tag = "dns-in-remote"
}
if remote_dns_udp_server then
_remote_dns.address = remote_dns_udp_server
_remote_dns.port = tonumber(remote_dns_udp_port) or 53
other_type_dns_proto = "udp"
other_type_dns_server = remote_dns_udp_server
other_type_dns_port = _remote_dns.port
end
if remote_dns_tcp_server then
_remote_dns.address = "tcp://" .. remote_dns_tcp_server .. ":" .. tonumber(remote_dns_tcp_port) or 53
_remote_dns.port = tonumber(remote_dns_tcp_port) or 53
other_type_dns_proto = "tcp"
other_type_dns_server = remote_dns_tcp_server
other_type_dns_port = _remote_dns.port
end
if remote_dns_doh_url and remote_dns_doh_host then
if remote_dns_doh_ip and remote_dns_doh_host ~= remote_dns_doh_ip and not api.is_ip(remote_dns_doh_host) then
dns.hosts[remote_dns_doh_host] = remote_dns_doh_ip
end
_remote_dns.address = remote_dns_doh_url
_remote_dns.port = tonumber(remote_dns_doh_port) or 443
end
table.insert(dns.servers, _remote_dns)
elseif dns_out_tag == "direct" then
dns.queryStrategy = (direct_dns_query_strategy and direct_dns_query_strategy ~= "") and direct_dns_query_strategy or "UseIP"
table.insert(outbounds, 1, {
tag = dns_out_tag,
protocol = "freedom",
settings = {
domainStrategy = dns.queryStrategy
},
streamSettings = {
sockopt = {
mark = 255
}
}
})
local _direct_dns = {
tag = "dns-in-direct"
}
if direct_dns_udp_server then
_direct_dns.address = direct_dns_udp_server
_direct_dns.port = tonumber(direct_dns_udp_port) or 53
table.insert(routing.rules, 1, {
ip = {
direct_dns_udp_server
},
port = tonumber(direct_dns_udp_port) or 53,
network = "udp",
outboundTag = "direct"
})
other_type_dns_proto = "udp"
other_type_dns_server = direct_dns_udp_server
other_type_dns_port = _direct_dns.port
end
if direct_dns_tcp_server then
_direct_dns.address = "tcp+local://" .. direct_dns_tcp_server
_direct_dns.port = tonumber(direct_dns_tcp_port) or 53
other_type_dns_proto = "tcp"
other_type_dns_server = direct_dns_tcp_server
other_type_dns_port = _direct_dns.port
end
if direct_dns_doh_url and direct_dns_doh_host then
if direct_dns_doh_ip and direct_dns_doh_host ~= direct_dns_doh_ip and not api.is_ip(direct_dns_doh_host) then
dns.hosts[direct_dns_doh_host] = direct_dns_doh_ip
end
_direct_dns.address = direct_dns_doh_url:gsub("https://", "https+local://")
_direct_dns.port = tonumber(direct_dns_doh_port) or 443
end
table.insert(dns.servers, _direct_dns)
end
local dns_hosts_len = 0
for key, value in pairs(dns.hosts) do
dns_hosts_len = dns_hosts_len + 1
end
if dns_hosts_len == 0 then
dns.hosts = nil
end
table.insert(inbounds, {
listen = "127.0.0.1",
port = tonumber(dns_listen_port),
protocol = "dokodemo-door",
tag = "dns-in",
settings = {
address = other_type_dns_server or "1.1.1.1",
port = other_type_dns_port or 53,
network = "tcp,udp"
}
})
table.insert(outbounds, {
tag = "dns-out",
protocol = "dns",
proxySettings = {
tag = dns_out_tag
},
settings = {
address = other_type_dns_server or "1.1.1.1",
port = other_type_dns_port or 53,
network = other_type_dns_proto or "tcp",
nonIPQuery = "drop"
}
})
table.insert(routing.rules, 1, {
inboundTag = {
"dns-in"
},
outboundTag = "dns-out"
})
table.insert(routing.rules, {
inboundTag = {
"dns-global"
},
outboundTag = dns_out_tag
})
end
if inbounds or outbounds then
local config = {
log = {
--dnsLog = true,
loglevel = loglevel
},
-- DNS
dns = dns,
-- 传入连接
inbounds = inbounds,
-- 传出连接
outbounds = outbounds,
-- 路由
routing = routing
}
return jsonc.stringify(config, 1)
end
end
_G.gen_config = gen_config
_G.gen_proto_config = gen_proto_config
_G.gen_dns_config = gen_dns_config
if arg[1] then
local func =_G[arg[1]]
if func then
print(func(api.get_function_args(arg)))
end
end
|
294coder/Efficient-MIF
| 1,526
|
Pansharpening_Hyper_SR_Matlab_Test_Package/Quality_Indices/ERGAS.m
|
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Description:
% Erreur Relative Globale Adimensionnelle de Synthse (ERGAS).
%
% Interface:
% ERGAS_index = ERGAS(I1,I2,ratio)
%
% Inputs:
% I1: First multispectral image;
% I2: Second multispectral image;
% ratio: Scale ratio between MS and PAN. Pre-condition: Integer value.
%
% Outputs:
% ERGAS_index: ERGAS index.
% References:
% [Ranchin00] T. Ranchin and L. Wald, Fusion of high spatial and spectral resolution images: the ARSIS concept and its implementation,
% Photogrammetric Engineering and Remote Sensing, vol. 66, no. 1, pp. 4961, January 2000.
% [Vivone20] G. Vivone, M. Dalla Mura, A. Garzelli, R. Restaino, G. Scarpa, M.O. Ulfarsson, L. Alparone, and J. Chanussot, "A New Benchmark Based on Recent Advances in Multispectral Pansharpening: Revisiting pansharpening with classical and emerging pansharpening methods",
% IEEE Geoscience and Remote Sensing Magazine, doi: 10.1109/MGRS.2020.3019315.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function ERGAS_index = ERGAS(I1,I2,ratio)
I1 = double(I1);
I2 = double(I2);
Err=I1-I2;
ERGAS_index=0;
for iLR=1:size(Err,3),
ERGAS_index = ERGAS_index+mean2(Err(:,:,iLR).^2)/(mean2((I1(:,:,iLR))))^2;
end
ERGAS_index = (100/ratio) * sqrt((1/size(Err,3)) * ERGAS_index);
end
|
2977094657/BiliHistoryFrontend
| 67,006
|
src/components/tailwind/HistoryContent.vue
|
<template>
<div class="transition-all duration-300 ease-in-out">
<!-- 年度总结横幅 -->
<div class="mt-1 mb-3 sm:hidden">
<router-link
to="/analytics"
class="flex h-10 items-center justify-between px-2 bg-gradient-to-r from-[#fb7299] to-[#FF9966] text-white"
>
<div class="flex items-center space-x-2">
<svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
d="M9 19v-6a2 2 0 00-2-2H5a2 2 0 00-2 2v6a2 2 0 002 2h2a2 2 0 002-2zm0 0V9a2 2 0 012-2h2a2 2 0 012 2v10m-6 0a2 2 0 002 2h2a2 2 0 002-2m0 0V5a2 2 0 012-2h2a2 2 0 012 2v14a2 2 0 01-2 2h-2a2 2 0 01-2-2z" />
</svg>
<span class="text-sm">点击查看年度总结</span>
</div>
<svg class="w-4 h-4 animate-bounce-x" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 5l7 7-7 7" />
</svg>
</router-link>
</div>
<!-- 加载状态 -->
<div v-if="isLoading" class="flex flex-col items-center justify-center py-16 bg-white rounded-lg">
<div class="w-16 h-16 border-4 border-[#fb7299] border-t-transparent rounded-full animate-spin mb-4"></div>
<h3 class="text-xl font-medium text-gray-600 mb-2">加载中</h3>
<p class="text-gray-500">正在获取历史记录数据...</p>
</div>
<!-- 登录状态空状态 -->
<div v-else-if="!isLoggedIn" class="flex flex-col items-center justify-center py-16 bg-white rounded-lg shadow-sm">
<svg class="w-24 h-24 text-gray-300 mb-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.5"
d="M15 7a2 2 0 012 2m4 0a6 6 0 01-7.743 5.743L11 17H9v2H7v2H4a1 1 0 01-1-1v-2.586a1 1 0 01.293-.707l5.964-5.964A6 6 0 1121 9z" />
</svg>
<h3 class="text-xl font-medium text-gray-600 mb-2">请先登录</h3>
<p class="text-gray-500 mb-6">登录B站账号后才能查看您的历史记录</p>
<button
class="px-4 py-2 bg-[#fb7299] text-white rounded-md hover:bg-[#fb7299]/90 transition-colors duration-200 flex items-center space-x-2"
@click="openLoginDialog">
<svg class="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
d="M11 16l-4-4m0 0l4-4m-4 4h14m-5 4v1a3 3 0 01-3 3H6a3 3 0 01-3-3V7a3 3 0 013-3h7a3 3 0 013 3v1" />
</svg>
<span>点击登录</span>
</button>
</div>
<!-- 数据为空状态 -->
<div v-else-if="isLoggedIn && records.length === 0"
class="flex flex-col items-center justify-center py-16 bg-white rounded-lg">
<svg class="w-24 h-24 text-gray-300 mb-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.5"
d="M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z" />
</svg>
<h3 class="text-xl font-medium text-gray-600 mb-2">暂无历史记录</h3>
<p class="text-gray-500 mb-6">点击下方按钮从B站获取您的历史记录</p>
<button
class="px-4 py-2 bg-[#fb7299] text-white rounded-md hover:bg-[#fb7299]/90 transition-colors duration-200 flex items-center space-x-2"
@click="refreshData">
<svg class="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15" />
</svg>
<span>获取历史记录</span>
</button>
</div>
<!-- 视频记录列表 -->
<div v-else class="overflow-hidden">
<transition name="float" mode="out-in">
<!-- 网格布局(仅PC端) -->
<div v-if="layout === 'grid'"
class="hidden sm:grid grid-cols-2 md:grid-cols-3 lg:grid-cols-4 xl:grid-cols-5 gap-4 px-4 mx-auto transition-all duration-300 ease-in-out transform-gpu"
style="max-width: 1152px;" key="grid-layout">
<template v-for="(record, index) in records" :key="`grid-${record.id}-${record.view_at}`">
<!-- 日期分割线和视频数量 -->
<div v-if="shouldShowDivider(index)" class="col-span-full relative py-1">
<div>
<div class="relative">
<div class="absolute inset-0 flex items-center" aria-hidden="true">
<div class="w-full border-t border-gray-300" />
</div>
<div class="relative flex items-center justify-between">
<div class="bg-white pr-3 flex items-center space-x-2">
<!-- 添加当天记录的勾选框 -->
<div v-if="isBatchMode"
class="flex items-center justify-center cursor-pointer"
@click.stop="toggleDaySelection(record.view_at)">
<div class="w-5 h-5 rounded border-2 flex items-center justify-center"
:class="isDaySelected(record.view_at) ? 'bg-[#fb7299] border-[#fb7299]' : 'border-gray-300 bg-white'">
<svg v-if="isDaySelected(record.view_at)" class="w-3 h-3 text-white" fill="none"
viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="3" d="M5 13l4 4L19 7" />
</svg>
</div>
</div>
<span class="lm:text-xs">
{{ formatDividerDate(record.view_at) }}
</span>
</div>
<div class="bg-white pl-3">
<span class="lm:text-xs text-[#FF6699]">
{{ getDailyStatsForDate(record.view_at) }}条数据 · 总时长 {{ formatDailyWatchTime(record.view_at) }}
</span>
</div>
</div>
</div>
</div>
</div>
<!-- 网格布局的视频卡片 -->
<div
class="bg-white/50 backdrop-blur-sm rounded-lg overflow-hidden border border-gray-200/50 hover:border-[#FF6699] hover:shadow-md transition-all duration-200 relative group"
:class="{ 'ring-2 ring-[#fb7299]': selectedRecords.has(`${record.bvid}_${record.view_at}`), 'cursor-pointer': isBatchMode }"
@click="isBatchMode ? toggleRecordSelection(record) : null">
<!-- 多选框 -->
<div v-if="isBatchMode"
class="absolute top-2 left-2 z-10">
<div class="w-5 h-5 rounded border-2 flex items-center justify-center"
:class="selectedRecords.has(`${record.bvid}_${record.view_at}`) ? 'bg-[#fb7299] border-[#fb7299]' : 'border-white bg-black/20'">
<svg v-if="selectedRecords.has(`${record.bvid}_${record.view_at}`)" class="w-3 h-3 text-white"
fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="3" d="M5 13l4 4L19 7" />
</svg>
</div>
</div>
<!-- 封面图片 -->
<div class="relative aspect-video" :class="{ 'cursor-pointer': !isBatchMode }"
@click="!isBatchMode ? handleVideoClick(record) : null">
<!-- 下载状态标识 -->
<div v-if="isVideoDownloaded(record.cid) && record.business === 'archive'"
class="absolute left-0 top-0 z-20">
<div
class="bg-gradient-to-r from-green-500 to-green-400 text-white font-semibold px-2 py-0.5 text-xs flex items-center space-x-1.5 rounded-br-md shadow-md">
<svg class="w-3 h-3" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
d="M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-4l-4 4m0 0l-4-4m4 4V4" />
</svg>
<span>已下载</span>
</div>
</div>
<!-- 收藏状态标识 - 不对直播类型显示 -->
<div
v-if="isVideoFavorited(parseInt(record.aid || record.avid || (record.business === 'archive' ? record.oid : 0), 10)) && record.business !== 'live'"
class="absolute right-0 top-0 z-20">
<div
class="bg-gradient-to-r from-amber-500 to-yellow-400 text-white font-semibold px-2 py-0.5 text-xs flex items-center space-x-1.5 rounded-bl-md shadow-md">
<svg class="w-3 h-3" fill="currentColor" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
d="M5 5a2 2 0 012-2h10a2 2 0 012 2v16l-7-3.5L5 21V5z" />
</svg>
<span>已收藏</span>
</div>
</div>
<!-- 按钮组 -->
<div v-if="!isBatchMode"
class="absolute right-2 top-2 z-20 hidden group-hover:flex flex-row items-center space-x-2">
<!-- 收藏按钮 - 不对直播类型显示 -->
<div v-if="record.business !== 'live'"
class="flex items-center justify-center w-7 h-7 bg-[#7d7c75]/60 backdrop-blur-sm hover:bg-[#7d7c75]/80 rounded-md cursor-pointer transition-all duration-200"
@click.stop.prevent="handleFavoriteGrid(record)">
<svg class="w-4 h-4"
:class="isVideoFavorited(parseInt(record.aid || record.avid || (record.business === 'archive' ? record.oid : 0), 10)) ? 'text-yellow-400' : 'text-white'"
:fill="isVideoFavorited(parseInt(record.aid || record.avid || (record.business === 'archive' ? record.oid : 0), 10)) ? 'currentColor' : 'none'"
viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
d="M5 5a2 2 0 012-2h10a2 2 0 012 2v16l-7-3.5L5 21V5z" />
</svg>
</div>
<!-- 下载按钮 - 只对视频类型显示 -->
<div v-if="record.business === 'archive'"
class="flex items-center justify-center w-7 h-7 bg-[#7d7c75]/60 backdrop-blur-sm hover:bg-[#7d7c75]/80 rounded-md cursor-pointer transition-all duration-200"
@click.stop.prevent="handleDownloadGrid(record)">
<svg class="w-4 h-4 text-white" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
d="M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-4l-4 4m0 0l-4-4m4 4V4" />
</svg>
</div>
<!-- 详情按钮 - 只对普通视频类型显示 -->
<div v-if="record.business === 'archive'"
class="flex items-center justify-center w-7 h-7 bg-[#7d7c75]/60 backdrop-blur-sm hover:bg-[#7d7c75]/80 rounded-md cursor-pointer transition-all duration-200"
@click.stop="openVideoDetail(record)">
<svg class="w-4 h-4 text-white" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
d="M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
</svg>
</div>
<!-- 删除按钮 -->
<div
class="flex items-center justify-center w-7 h-7 bg-[#7d7c75]/60 backdrop-blur-sm hover:bg-[#7d7c75]/80 rounded-md cursor-pointer transition-all duration-200"
@click.stop="handleDelete(record)">
<svg class="w-4 h-4 text-white" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16" />
</svg>
</div>
</div>
<img
:src="normalizeImageUrl(record.cover || record.covers?.[0])"
class="w-full h-full object-cover transition-all duration-300"
:class="{ 'blur-md': isPrivacyMode }"
alt=""
/>
<!-- 视频进度条 -->
<div
v-if="record.business !== 'article-list' && record.business !== 'article' && record.business !== 'live'"
class="absolute bottom-0 left-0 w-full">
<div
class="absolute bottom-1 right-1 rounded bg-black/50 px-1 py-1 text-[10px] font-semibold text-white">
<span>{{ formatDuration(record.progress) }}</span>
<span>/</span>
<span>{{ formatDuration(record.duration) }}</span>
</div>
<div class="absolute bottom-0 left-0 h-0.5 w-full bg-black">
<div class="h-full bg-[#FF6699]"
:style="{ width: getProgressWidth(record.progress, record.duration) }">
</div>
</div>
</div>
<!-- 右上角的类型角标 -->
<div
v-if="record.badge"
class="absolute right-1 top-1 rounded bg-[#FF6699] px-1 py-0.5 text-[10px] text-white"
>
{{ record.badge }}
</div>
</div>
<!-- 视频信息 -->
<div class="p-3 flex flex-col space-y-1">
<!-- 标题 - 单行显示 -->
<div class="line-clamp-1 text-sm text-gray-900"
v-html="isPrivacyMode ? '******' : highlightText(record.title)"
:class="{ 'blur-sm': isPrivacyMode, 'cursor-pointer': !isBatchMode }"
@click="!isBatchMode ? handleVideoClick(record) : null">
</div>
<!-- 分区标签 - 单行显示 -->
<div class="text-xs text-gray-500 truncate flex items-center space-x-1">
<span class="inline-flex items-center rounded-md bg-[#f1f2f3] px-2 py-1 text-xs text-[#71767d]">
{{ record.business === 'archive' ? record.tag_name : getBusinessType(record.business) }}
</span>
<span v-if="record.business === 'archive'" class="text-gray-400">·</span>
<span v-if="record.business === 'archive' && record.name" class="text-[#71767d]">{{ record.name
}}</span>
</div>
<!-- UP主和时间信息 - 单行显示 -->
<div class="flex items-center justify-between text-xs text-gray-600">
<div class="flex items-center space-x-2 min-w-0 flex-1">
<img v-if="record.business !== 'cheese' && record.business !== 'pgc'"
:src="normalizeImageUrl(record.author_face)"
:class="{ 'blur-md': isPrivacyMode, 'cursor-pointer': !isBatchMode }"
class="w-4 h-4 rounded-full flex-shrink-0"
@click="!isBatchMode ? handleAuthorClick(record) : null"
:title="isPrivacyMode ? '隐私模式已开启' : `访问 ${record.author_name} 的个人空间`"
/>
<span v-html="isPrivacyMode ? '******' : highlightText(record.author_name)"
:class="{ 'blur-sm': isPrivacyMode, 'cursor-pointer': !isBatchMode }"
class="hover:text-[#fb7299] transition-colors duration-200 truncate"
@click="!isBatchMode ? handleAuthorClick(record) : null">
</span>
</div>
<div class="flex items-center space-x-2 flex-shrink-0">
<img v-if="record.dt === 1 || record.dt === 3 || record.dt === 5 || record.dt === 7"
src="/Mobile.svg"
alt="Mobile"
class="h-4 w-4"
/>
<img v-else-if="record.dt === 2 || record.dt === 33"
src="/PC.svg"
alt="PC"
class="h-4 w-4"
/>
<img v-else-if="record.dt === 4 || record.dt === 6"
src="/Pad.svg"
alt="Pad"
class="h-4 w-4"
/>
<span>{{ formatTimestamp(record.view_at) }}</span>
</div>
</div>
</div>
</div>
</template>
</div>
<!-- 列表布局(移动端始终显示,PC端在list模式下显示) -->
<div v-else :class="{'sm:hidden': layout === 'grid'}"
class="transition-all duration-300 ease-in-out transform-gpu" key="list-layout">
<template v-for="(record, index) in records" :key="`list-${record.id}-${record.view_at}`">
<!-- 日期分割线和视频数量 -->
<div v-if="shouldShowDivider(index)" class="relative py-1 max-w-4xl mx-auto">
<div class="px-2">
<div class="relative">
<div class="absolute inset-0 flex items-center" aria-hidden="true">
<div class="w-full border-t border-gray-300" />
</div>
<div class="relative flex items-center justify-between">
<div class="bg-white pr-3 flex items-center space-x-2">
<!-- 添加当天记录的勾选框 -->
<div v-if="isBatchMode"
class="flex items-center justify-center cursor-pointer"
@click.stop="toggleDaySelection(record.view_at)">
<div class="w-5 h-5 rounded border-2 flex items-center justify-center"
:class="isDaySelected(record.view_at) ? 'bg-[#fb7299] border-[#fb7299]' : 'border-gray-300 bg-white'">
<svg v-if="isDaySelected(record.view_at)" class="w-3 h-3 text-white" fill="none"
viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="3" d="M5 13l4 4L19 7" />
</svg>
</div>
</div>
<span class="lm:text-xs">
{{ formatDividerDate(record.view_at) }}
</span>
</div>
<div class="bg-white pl-3">
<span class="lm:text-xs text-[#FF6699]">
{{ getDailyStatsForDate(record.view_at) }}条数据 · 总时长 {{ formatDailyWatchTime(record.view_at) }}
</span>
</div>
</div>
</div>
</div>
</div>
<VideoRecord
:record="record"
:is-batch-mode="isBatchMode"
:is-selected="selectedRecords.has(`${record.bvid}_${record.view_at}`)"
:remark-data="remarkData"
:is-downloaded="isVideoDownloaded(record.cid)"
:is-video-favorited="isVideoFavorited(parseInt(record.aid || record.avid || (record.business === 'archive' ? record.oid : 0), 10))"
@toggle-selection="toggleRecordSelection"
@refresh-data="fetchHistoryByDateRange"
@remark-updated="handleRemarkUpdate"
@favorite="handleFavorite"
/>
</template>
</div>
</transition>
</div>
<!-- 日期选择日历 -->
<van-calendar
:show-confirm="false"
title="选择日期区间"
switch-mode="year-month"
:show="show"
:style="{ height: '65%' }"
type="range"
@confirm="onConfirm"
@update:show="(val) => emit('update:show', val)"
/>
<!-- 批量操作按钮区域 -->
<div v-if="isBatchMode && selectedRecords.size > 0"
class="fixed bottom-4 left-1/2 transform -translate-x-1/2 z-50 w-[90vw] max-w-[1200px]">
<div class="flex flex-col space-y-2 w-full">
<!-- 删除模式切换按钮 -->
<div class="flex justify-center mb-1">
<!-- 已移除本地/远程收藏模式切换 -->
</div>
<div class="flex flex-wrap gap-3 justify-center w-full mt-2">
<!-- 批量删除按钮 -->
<button
@click="handleBatchDelete"
class="w-28 py-2 bg-red-500 text-white rounded-lg shadow-md hover:bg-red-600 transition-all duration-200 flex items-center justify-center space-x-1.5 text-sm focus:outline-none focus:ring-2 focus:ring-red-400 focus:ring-opacity-50"
>
<svg class="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16" />
</svg>
<span>删除({{ selectedRecords.size }})</span>
</button>
<!-- 批量下载按钮 - 始终显示 -->
<button
@click="handleBatchDownload"
class="w-28 py-2 bg-green-500 text-white rounded-lg shadow-md hover:bg-green-600 transition-all duration-200 flex items-center justify-center space-x-1.5 text-sm focus:outline-none focus:ring-2 focus:ring-green-400 focus:ring-opacity-50"
>
<svg class="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
d="M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-4l-4 4m0 0l-4-4m4 4V4" />
</svg>
<span>下载({{ selectedRecords.size }})</span>
</button>
<!-- 批量收藏按钮 - 仅在有未收藏的视频时显示 -->
<button
v-if="!isAllFavorited && unfavoritedCount > 0"
@click="handleBatchFavorite"
class="w-28 py-2 bg-[#fb7299] text-white rounded-lg shadow-md hover:bg-[#fb7299]/90 transition-all duration-200 flex items-center justify-center space-x-1.5 text-sm focus:outline-none focus:ring-2 focus:ring-pink-400 focus:ring-opacity-50"
>
<svg class="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
d="M5 5a2 2 0 012-2h10a2 2 0 012 2v16l-7-3.5L5 21V5z" />
</svg>
<span>收藏({{ unfavoritedCount }})</span>
</button>
<!-- 批量取消收藏按钮 - 仅在有已收藏的视频时显示 -->
<button
v-if="hasFavoritedVideos"
@click="handleBatchUnfavorite"
class="w-28 py-2 bg-orange-500 text-white rounded-lg shadow-md hover:bg-orange-600 transition-all duration-200 flex items-center justify-center space-x-1.5 text-sm focus:outline-none focus:ring-2 focus:ring-orange-400 focus:ring-opacity-50"
>
<svg class="w-4 h-4" fill="currentColor" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12" />
</svg>
<span>取消收藏({{ favoritedCount }})</span>
</button>
<!-- 复制链接按钮 - 始终显示 -->
<button
@click="handleCopyLinks"
class="w-28 py-2 bg-blue-500 text-white rounded-lg shadow-md hover:bg-blue-600 transition-all duration-200 flex items-center justify-center space-x-1.5 text-sm focus:outline-none focus:ring-2 focus:ring-blue-400 focus:ring-opacity-50"
>
<svg class="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
d="M8 5H6a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2v-1M8 5a2 2 0 002 2h2a2 2 0 002-2M8 5a2 2 0 012-2h2a2 2 0 012 2m0 0h2a2 2 0 012 2v3m2 4H10m0 0l3-3m-3 3l3 3" />
</svg>
<span>复制链接({{ selectedRecords.size }})</span>
</button>
</div>
</div>
</div>
</div>
<!-- 视频详情对话框 -->
<Teleport to="body">
<VideoDetailDialog
:modelValue="showDetailDialog"
@update:modelValue="showDetailDialog = $event"
:video="selectedRecord"
:remarkData="remarkData"
@remark-updated="handleRemarkUpdate"
/>
</Teleport>
<!-- 下载弹窗 -->
<Teleport to="body">
<DownloadDialog
v-model:show="showDownloadDialog"
:video-info="{
title: selectedRecord?.title || '',
author: selectedRecord?.author_name || '',
bvid: selectedRecord?.bvid || '',
cover: selectedRecord?.cover || selectedRecord?.covers?.[0] || '',
cid: selectedRecord?.cid || ''
}"
:is-batch-download="isBatchDownload"
:batch-videos="batchVideos"
v-model:currentVideoIndex="currentVideoIndex"
@download-complete="handleDownloadComplete"
/>
</Teleport>
<!-- 收藏夹选择对话框 -->
<Teleport to="body">
<FavoriteDialog
v-model="showFavoriteDialog"
:video-info="favoriteVideoInfo"
@favorite-done="handleFavoriteDone"
/>
</Teleport>
<!-- 登录对话框 -->
<Teleport to="body">
<LoginDialog
v-model:show="showLoginDialog"
@login-success="handleLoginSuccess"
/>
</Teleport>
</template>
<style scoped>
@keyframes bounce-x {
0%, 100% {
transform: translateX(0);
}
50% {
transform: translateX(25%);
}
}
.animate-bounce-x {
animation: bounce-x 1s infinite;
}
.float-enter-active,
.float-leave-active {
transition: all 0.3s ease;
}
.float-enter-from {
opacity: 0;
transform: translateY(20px);
}
.float-leave-to {
opacity: 0;
transform: translateY(-20px);
}
</style>
<script setup>
import { ref, computed, onMounted, watch } from 'vue'
import {
getBiliHistory2024,
getMainCategories,
getDailyStats,
batchDeleteHistory,
batchGetRemarks,
getLoginStatus,
updateBiliHistoryRealtime,
checkVideoDownload,
batchCheckFavoriteStatus,
favoriteResource,
localBatchFavoriteResource,
batchDeleteBilibiliHistory,
deleteBilibiliHistory,
} from '@/api/api.js'
import { showNotify, showDialog } from 'vant'
import 'vant/es/dialog/style'
import VideoRecord from './VideoRecord.vue'
import { usePrivacyStore } from '@/store/privacy.js'
import VideoDetailDialog from './VideoDetailDialog.vue'
import LoginDialog from './LoginDialog.vue'
import DownloadDialog from './DownloadDialog.vue'
import FavoriteDialog from './FavoriteDialog.vue'
import { openInBrowser } from '@/utils/openUrl.js'
import { normalizeImageUrl } from '@/utils/imageUrl.js'
const { isPrivacyMode } = usePrivacyStore()
const props = defineProps({
selectedYear: {
type: Number,
default: new Date().getFullYear(),
},
page: {
type: Number,
default: 1,
},
show: {
type: Boolean,
default: false,
},
showBottom: {
type: Boolean,
default: false,
},
layout: {
type: String,
default: 'list',
},
searchKeyword: {
type: String,
default: '',
},
date: {
type: String,
default: '',
},
category: {
type: String,
default: '',
},
business: {
type: String,
default: '',
},
isBatchMode: {
type: Boolean,
default: false,
},
pageSize: {
type: Number,
default: 30,
},
})
const emit = defineEmits([
'update:total-pages',
'update:total',
'update:date',
'update:category',
'update:show',
'update:showBottom',
'update:pageSize',
])
// 状态变量
const records = ref([])
const total = ref(0)
const sortOrder = ref(0)
const size = ref(props.pageSize)
const remarkData = ref({}) // 存储备注数据
const downloadedVideos = ref(new Set()) // 存储已下载视频的CID集合
const favoriteStatus = ref({}) // 存储视频收藏状态信息
const date = ref('')
const dateRange = ref('')
const tagName = ref('')
const mainCategory = ref('')
const mainCategories = ref([])
// 每日统计数据
const dailyStats = ref({})
// 批量删除相关
const selectedRecords = ref(new Set())
// 在data区域添加
const selectedRecord = ref(null)
const showDetailDialog = ref(false)
const showDownloadDialog = ref(false)
const showFavoriteDialog = ref(false)
const favoriteVideoInfo = ref(null) // 用于存储收藏相关的视频信息
// 登录相关
const isLoggedIn = ref(false)
const isLoading = ref(false)
const showLoginDialog = ref(false)
// 选择/取消选择记录
const toggleRecordSelection = (record) => {
const key = `${record.bvid}_${record.view_at}`
if (selectedRecords.value.has(key)) {
selectedRecords.value.delete(key)
} else {
selectedRecords.value.add(key)
}
}
// 批量删除选中的记录
const handleBatchDelete = async () => {
if (selectedRecords.value.size === 0) {
showNotify({
type: 'warning',
message: '请先选择要删除的记录',
})
return
}
try {
// 检查是否需要同步删除B站历史记录
const syncDeleteToBilibili = localStorage.getItem('syncDeleteToBilibili') === 'true'
// 根据是否同步删除B站历史记录,显示不同的确认信息
await showDialog({
title: '确认删除',
message: syncDeleteToBilibili
? `确定要删除选中的 ${selectedRecords.value.size} 条记录吗?此操作将同时删除B站服务器上的历史记录,不可恢复。`
: `确定要删除选中的 ${selectedRecords.value.size} 条记录吗?此操作不可恢复。`,
showCancelButton: true,
confirmButtonText: '确认删除',
cancelButtonText: '取消',
confirmButtonColor: '#fb7299',
})
// 从记录中找到对应的完整信息
const items = Array.from(selectedRecords.value).map(key => {
const [bvid, view_at] = key.split('_')
return {
bvid,
view_at: parseInt(view_at),
}
})
if (syncDeleteToBilibili) {
// 构建B站历史记录删除请求的items
const biliItems = items.map(item => {
// 查找对应的完整记录以获取业务类型
const record = records.value.find(r => r.bvid === item.bvid && r.view_at === item.view_at)
if (!record) return null
// 根据业务类型构建kid
const business = record.business || 'archive'
let kid
switch (business) {
case 'archive':
// 使用oid而不是bvid
kid = `${business}_${record.oid}`
break
case 'live':
kid = `${business}_${record.oid}`
break
case 'article':
kid = `${business}_${record.oid}`
break
case 'pgc':
kid = `${business}_${record.oid || record.ssid}`
break
case 'article-list':
kid = `${business}_${record.oid || record.rlid}`
break
default:
kid = `${business}_${record.oid || record.bvid}`
break
}
if (!kid) {
return null
}
return {
kid,
sync_to_bilibili: true,
}
}).filter(item => item !== null)
if (biliItems.length > 0) {
try {
// 调用B站历史记录删除API
const biliResponse = await batchDeleteBilibiliHistory(biliItems)
if (biliResponse.data.status === 'success' || biliResponse.data.status === 'partial_success') {
console.log('B站历史记录删除成功或部分成功:', biliResponse.data)
} else {
console.error('B站历史记录删除失败:', biliResponse.data)
throw new Error(biliResponse.data.message || '删除B站历史记录失败')
}
} catch (error) {
console.error('B站历史记录删除失败:', error)
// 即使B站删除失败,也继续删除本地记录
}
}
}
// 删除本地记录
const response = await batchDeleteHistory(items)
if (response.data.status === 'success') {
showNotify({
type: 'success',
message: response.data.message + (syncDeleteToBilibili ? ',并已同步删除B站历史记录' : ''),
})
selectedRecords.value.clear()
await fetchHistoryByDateRange()
} else {
throw new Error(response.data.message || '删除失败')
}
} catch (error) {
if (error.toString().includes('cancel')) return
showNotify({
type: 'danger',
message: error.response?.data?.detail || error.message || '删除失败',
})
}
}
// 监听批量模式变化
watch(() => props.isBatchMode, (newVal) => {
if (!newVal) {
selectedRecords.value.clear()
}
})
// 计算属性用于显示当前选中的分类
computed(() => {
return mainCategory.value || tagName.value || '全部分区'
})
// 获取主分区列表
const fetchMainCategories = async () => {
try {
const response = await getMainCategories()
if (response.data.status === 'success') {
mainCategories.value = response.data.data.map((cat) => cat.name)
}
} catch (error) {
console.error('Error fetching main categories:', error)
}
}
// 辅助函数:格式化日期
const formatDate = (date) => `${date.getMonth() + 1}/${date.getDate()}`
const formatDateWithYear = (date) => `${date.getFullYear()}/${date.getMonth() + 1}/${date.getDate()}`
const formatDateForAPI = (date) => {
const year = date.getFullYear()
const month = String(date.getMonth() + 1).padStart(2, '0')
const day = String(date.getDate()).padStart(2, '0')
return `${year}${month}${day}`
}
// 处理日期区间确认
const onConfirm = (values) => {
const [start, end] = values
emit('update:show', false)
const startYear = start.getFullYear()
const endYear = end.getFullYear()
let dateText
if (startYear === props.selectedYear && endYear === props.selectedYear) {
dateText = `${formatDate(start)} - ${formatDate(end)}`
} else {
dateText = `${formatDateWithYear(start)} - ${formatDateWithYear(end)}`
}
emit('update:date', dateText)
dateRange.value = `${formatDateForAPI(start)}-${formatDateForAPI(end)}`
fetchHistoryByDateRange()
}
// 批量检查视频下载状态
const batchCheckDownloadStatus = async () => {
try {
if (records.value.length === 0) return
// 筛选出视频类型的记录
const videoRecords = records.value.filter(record => record.business === 'archive')
if (videoRecords.length === 0) return
// 获取所有视频的CID
const cids = videoRecords.map(record => record.cid).filter(cid => cid)
if (cids.length === 0) return
const response = await checkVideoDownload(cids)
if (response.data && response.data.status === 'success') {
// 清空已有集合
downloadedVideos.value.clear()
// 处理返回结果,将已下载视频的CID添加到集合中
const results = response.data.results || {}
// 遍历results对象的每个键值对
Object.entries(results).forEach(([cid, info]) => {
if (info.downloaded) {
downloadedVideos.value.add(cid.toString())
}
})
}
} catch (error) {
console.error('批量检查下载状态失败:', error)
}
}
// 检查视频是否已下载
const isVideoDownloaded = (cid) => {
return cid && downloadedVideos.value.has(cid.toString())
}
// 检查视频是否已收藏
const isVideoFavorited = (oid) => {
if (!oid) return false
// 确保oid是字符串类型,方便比较
const oidStr = String(oid)
// 检查是否在收藏状态中
return Object.keys(favoriteStatus.value).some(key => {
return String(key) === oidStr && favoriteStatus.value[key].is_favorited
})
}
// 获取视频被收藏到的收藏夹
const getVideoFavoriteFolders = (oid) => {
if (!oid) return []
// 确保oid是字符串类型,方便比较
const oidStr = String(oid)
// 查找匹配的收藏状态
for (const key in favoriteStatus.value) {
if (String(key) === oidStr) {
return favoriteStatus.value[key].favorite_folders || []
}
}
return []
}
// 批量检查视频收藏状态
const batchCheckFavorites = async () => {
try {
if (records.value.length === 0) return
// 筛选出视频类型的记录
const videoRecords = records.value.filter(record => record.business === 'archive')
if (videoRecords.length === 0) return
// 获取所有视频的avid
const oids = videoRecords.map(record => {
// 使用 aid 或 avid 或 (oid 如果 business 是 archive)
const id = record.aid || record.avid || (record.business === 'archive' ? record.oid : null)
// 确保ID是数字类型
return id ? parseInt(id, 10) : null
}).filter(oid => oid !== null && !isNaN(oid))
if (oids.length === 0) return
console.log('批量检查视频收藏状态:', oids)
const response = await batchCheckFavoriteStatus({ oids }) // 直接传递数组
if (response.data && response.data.status === 'success') {
// 清空已有状态
favoriteStatus.value = {}
// 处理返回结果
const results = response.data.data.results || []
results.forEach(item => {
favoriteStatus.value[item.oid] = {
is_favorited: item.is_favorited,
favorite_folders: item.favorite_folders || [],
}
})
console.log('收藏状态数据:', favoriteStatus.value)
}
} catch (error) {
console.error('批量检查收藏状态失败:', error)
}
}
// 数据获取函数
const fetchHistoryByDateRange = async () => {
try {
isLoading.value = true
records.value = []
const response = await getBiliHistory2024(
props.page,
size.value,
sortOrder.value,
tagName.value,
mainCategory.value,
dateRange.value || '',
localStorage.getItem('useLocalImages') === 'true',
props.business,
)
if (response.data && response.data.data) {
total.value = response.data.data.total
records.value = response.data.data.records
emit('update:total-pages', Math.ceil(response.data.data.total / size.value))
emit('update:total', response.data.data.total)
// 批量获取备注
if (records.value.length > 0) {
const batchRecords = records.value.map(record => ({
bvid: record.bvid,
view_at: record.view_at,
}))
const remarksResponse = await batchGetRemarks(batchRecords)
if (remarksResponse.data.status === 'success') {
remarkData.value = remarksResponse.data.data
}
// 批量检查下载状态
await batchCheckDownloadStatus()
// 批量检查收藏状态
await batchCheckFavorites()
}
}
} catch (error) {
console.error('数据获取失败:', error)
records.value = []
total.value = 0
emit('update:total-pages', 0)
emit('update:total', 0)
} finally {
isLoading.value = false
}
}
// 监听年份和页码变化
watch(
() => [props.selectedYear, props.page],
() => {
fetchHistoryByDateRange()
},
)
// 监听 pageSize 变化
watch(
() => props.pageSize,
(newSize) => {
size.value = newSize
// 保存到 localStorage
localStorage.setItem('pageSize', newSize.toString())
fetchHistoryByDateRange()
},
)
// 监听父组件的 date 变化
watch(
() => props.date,
(newDate) => {
if (!newDate) {
dateRange.value = ''
fetchHistoryByDateRange()
} else {
// 解析日期区间格式 "YYYY/MM/DD 至 YYYY/MM/DD"
const dates = newDate.split(' 至 ')
if (dates.length === 2) {
const startParts = dates[0].split('/')
const endParts = dates[1].split('/')
if (startParts.length === 3 && endParts.length === 3) {
const startDate = `${startParts[0]}${startParts[1].padStart(2, '0')}${startParts[2].padStart(2, '0')}`
const endDate = `${endParts[0]}${endParts[1].padStart(2, '0')}${endParts[2].padStart(2, '0')}`
dateRange.value = `${startDate}-${endDate}`
fetchHistoryByDateRange()
}
}
}
},
)
// 监听父组件的 category 变化
watch(
() => props.category,
(newCategory) => {
if (!newCategory) {
tagName.value = ''
mainCategory.value = ''
} else {
// 根据分区名称判断是主分区还是子分区
// 由于我们无法确定是主分区还是子分区,所以统一赋值给mainCategory
mainCategory.value = newCategory
tagName.value = ''
}
// 这里会触发数据获取
fetchHistoryByDateRange()
},
)
// 监听父组件的 business 变化
watch(
() => props.business,
() => {
fetchHistoryByDateRange()
},
)
// 获取每日统计数据
const fetchDailyStats = async (timestamp) => {
if (!timestamp) return
try {
const date = new Date(timestamp * 1000)
const year = date.getFullYear()
const month = String(date.getMonth() + 1).padStart(2, '0')
const day = String(date.getDate()).padStart(2, '0')
const dateStr = `${month}${day}`
// 如果已经有这个日期的数据,就不重复获取
const dateKey = `${year}-${month}-${day}`
if (dailyStats.value[dateKey]) return
const response = await getDailyStats(dateStr, year)
if (response.data.status === 'success') {
dailyStats.value[dateKey] = response.data.data
}
} catch (error) {
console.error('获取每日统计数据失败:', error)
}
}
// 监听记录变化,获取所有不同日期的统计数据
watch(() => records.value, (newRecords) => {
if (newRecords && newRecords.length > 0) {
// 获取所有不同日期的时间戳
const uniqueDates = new Set()
newRecords.forEach(record => {
const date = new Date(record.view_at * 1000)
const dateKey = `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`
if (!uniqueDates.has(dateKey)) {
uniqueDates.add(dateKey)
fetchDailyStats(record.view_at)
}
})
} else {
dailyStats.value = {}
}
}, { deep: true })
// 获取指定日期的统计数据
const getDailyStatsForDate = (timestamp) => {
const date = new Date(timestamp * 1000)
const month = String(date.getMonth() + 1).padStart(2, '0')
const day = String(date.getDate()).padStart(2, '0')
const dateKey = `${date.getFullYear()}-${month}-${day}`
return dailyStats.value[dateKey]?.total_count || 0
}
// 获取指定日期的总观看时长(秒)
const getDailyWatchSecondsForDate = (timestamp) => {
const date = new Date(timestamp * 1000)
const month = String(date.getMonth() + 1).padStart(2, '0')
const day = String(date.getDate()).padStart(2, '0')
const dateKey = `${date.getFullYear()}-${month}-${day}`
return dailyStats.value[dateKey]?.total_watch_seconds || 0
}
// 将秒格式化为中文时长(如 1小时23分45秒)
const formatHMS = (seconds) => {
const total = Math.max(0, Math.floor(seconds || 0))
const h = Math.floor(total / 3600)
const m = Math.floor((total % 3600) / 60)
const s = total % 60
if (h > 0) {
return `${h}小时${String(m).padStart(2, '0')}分${String(s).padStart(2, '0')}秒`
}
if (m > 0) {
return `${m}分${String(s).padStart(2, '0')}秒`
}
return `${s}秒`
}
// 获取指定日期的总时长(格式化)
const formatDailyWatchTime = (timestamp) => {
return formatHMS(getDailyWatchSecondsForDate(timestamp))
}
// 打开登录对话框
const openLoginDialog = () => {
showLoginDialog.value = true
}
// 处理登录成功
const handleLoginSuccess = async (userData) => {
try {
// 如果登录对话框传递了用户数据,直接使用
if (userData && userData.isLogin) {
isLoggedIn.value = userData.isLogin
// 触发全局事件,通知侧边栏更新登录状态,并传递用户信息
window.dispatchEvent(new CustomEvent('login-status-changed', {
detail: {
isLoggedIn: true,
userInfo: userData,
},
}))
} else {
// 如果没有传递用户数据,则调用API获取
const response = await getLoginStatus()
if (response.data && response.data.code === 0) {
isLoggedIn.value = response.data.data.isLogin
// 触发全局事件,通知侧边栏更新登录状态,并传递用户信息
window.dispatchEvent(new CustomEvent('login-status-changed', {
detail: {
isLoggedIn: true,
userInfo: response.data.data,
},
}))
}
}
// 刷新历史记录数据
if (isLoggedIn.value) {
fetchHistoryByDateRange()
}
} catch (error) {
console.error('登录成功后获取状态失败:', error)
}
}
// 检查登录状态
const checkLoginStatus = async () => {
try {
const response = await getLoginStatus()
isLoggedIn.value = response.data && response.data.code === 0 && response.data.data.isLogin
} catch (error) {
console.error('获取登录状态失败:', error)
isLoggedIn.value = false
}
}
// 刷新数据
const refreshData = async () => {
try {
isLoading.value = true
showNotify({ type: 'success', message: '正在从B站获取历史记录...' })
const syncDeleted = localStorage.getItem('syncDeleted') === 'true'
const response = await updateBiliHistoryRealtime(syncDeleted)
if (response.data.status === 'success') {
showNotify({ type: 'success', message: response.data.message || '数据获取成功' })
fetchHistoryByDateRange()
} else {
throw new Error(response.data.message || '获取失败')
}
} catch (error) {
console.error('刷新数据失败:', error)
showNotify({
type: 'danger',
message: error.response?.data?.message || error.message || '获取历史记录失败',
})
} finally {
isLoading.value = false
}
}
onMounted(async () => {
isLoading.value = true
try {
await checkLoginStatus()
await fetchMainCategories()
if (isLoggedIn.value) {
await fetchHistoryByDateRange()
} else {
isLoading.value = false
}
} catch (error) {
console.error('初始化失败:', error)
isLoading.value = false
}
})
// 暴露方法给父组件
defineExpose({
fetchHistoryByDateRange,
refreshData,
checkLoginStatus,
})
// 格式化分割线日期
const formatDividerDate = (timestamp) => {
const date = new Date(timestamp * 1000)
const currentYear = new Date().getFullYear()
const year = date.getFullYear()
const month = date.getMonth() + 1
const day = date.getDate()
if (year === currentYear) {
return `${month}月${day}日`
} else {
return `${year}年${month}月${day}日`
}
}
// 判断是否需要显示分割线
const shouldShowDivider = (index) => {
if (index === 0) return true
const currentDate = new Date(records.value[index].view_at * 1000)
const prevDate = new Date(records.value[index - 1].view_at * 1000)
return currentDate.getDate() !== prevDate.getDate() ||
currentDate.getMonth() !== prevDate.getMonth() ||
currentDate.getFullYear() !== prevDate.getFullYear()
}
// 处理视频点击
const handleVideoClick = async (record) => {
let url = ''
switch (record.business) {
case 'archive':
url = `https://www.bilibili.com/video/${record.bvid}`
break
case 'article':
url = `https://www.bilibili.com/read/cv${record.oid}`
break
case 'article-list':
url = `https://www.bilibili.com/read/readlist/rl${record.oid}`
break
case 'live':
url = `https://live.bilibili.com/${record.oid}`
break
case 'pgc':
url = record.uri || `https://www.bilibili.com/bangumi/play/ep${record.epid}`
break
case 'cheese':
url = record.uri || `https://www.bilibili.com/cheese/play/ep${record.epid}`
break
default:
console.warn('未知的业务类型:', record.business)
return
}
if (url) {
await openInBrowser(url)
}
}
// 处理UP主点击
const handleAuthorClick = async (record) => {
const url = `https://space.bilibili.com/${record.author_mid}`
await openInBrowser(url)
}
// 格式化时长
const formatDuration = (seconds) => {
if (seconds === -1) return '已看完'
const minutes = String(Math.floor(seconds / 60)).padStart(2, '0')
const secs = String(seconds % 60).padStart(2, '0')
return `${minutes}:${secs}`
}
// 获取业务类型
const getBusinessType = (business) => {
const businessTypes = {
archive: '稿件',
cheese: '课堂',
pgc: '电影',
live: '直播',
'article-list': '专栏',
article: '专栏',
}
return businessTypes[business] || '其他类型'
}
// 获取进度条宽度
const getProgressWidth = (progress, duration) => {
if (progress === -1) return '100%'
if (duration === 0) return '0%'
return `${(progress / duration) * 100}%`
}
// 格式化时间戳
const formatTimestamp = (timestamp) => {
if (!timestamp) {
console.warn('Invalid timestamp:', timestamp)
return '时间未知'
}
try {
const date = new Date(timestamp * 1000)
const now = new Date()
if (isNaN(date.getTime())) {
console.warn('Invalid date from timestamp:', timestamp)
return '时间未知'
}
const isToday = now.toDateString() === date.toDateString()
const isYesterday =
new Date(now.setDate(now.getDate() - 1)).toDateString() === date.toDateString()
const timeString = date.toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' })
if (isToday) {
return timeString
} else if (isYesterday) {
return `昨天 ${timeString}`
} else if (now.getFullYear() === date.getFullYear()) {
return `${date.getMonth() + 1}-${date.getDate()} ${timeString}`
} else {
return `${date.getFullYear()}-${date.getMonth() + 1}-${date.getDate()} ${timeString}`
}
} catch (error) {
console.error('Error formatting timestamp:', error)
return '时间未知'
}
}
// 高亮显示匹配的文本
const highlightText = (text) => {
if (!props.searchKeyword || !text) return text
const regex = new RegExp(props.searchKeyword, 'gi')
return text.replace(regex, match => `<span class="text-[#FF6699]">${match}</span>`)
}
// 处理删除记录
const handleDelete = async (record) => {
try {
// 检查是否需要同步删除B站历史记录
const syncDeleteToBilibili = localStorage.getItem('syncDeleteToBilibili') === 'true'
await showDialog({
title: '确认删除',
message: syncDeleteToBilibili
? '确定要删除这条记录吗?此操作将同时删除B站服务器上的历史记录,不可恢复。'
: '确定要删除这条记录吗?此操作不可恢复。',
showCancelButton: true,
confirmButtonText: '确认删除',
cancelButtonText: '取消',
confirmButtonColor: '#fb7299',
})
// 如果需要同步删除B站历史记录
if (syncDeleteToBilibili) {
// 构建B站历史记录删除请求
const business = record.business || 'archive'
let kid = ''
switch (business) {
case 'archive':
// 使用oid而不是bvid
kid = `${business}_${record.oid}`
break
case 'live':
kid = `${business}_${record.oid}`
break
case 'article':
kid = `${business}_${record.oid}`
break
case 'pgc':
kid = `${business}_${record.oid || record.ssid}`
break
case 'article-list':
kid = `${business}_${record.oid || record.rlid}`
break
default:
kid = `${business}_${record.oid || record.bvid}`
break
}
if (kid) {
try {
// 调用B站历史记录删除API
const biliResponse = await deleteBilibiliHistory(kid, true)
if (biliResponse.data.status === 'success') {
console.log('B站历史记录删除成功:', biliResponse.data)
} else {
console.error('B站历史记录删除失败:', biliResponse.data)
// 即使B站删除失败,也继续删除本地记录
}
} catch (error) {
console.error('B站历史记录删除失败:', error)
// 即使B站删除失败,也继续删除本地记录
}
}
}
const response = await batchDeleteHistory([{
bvid: record.bvid,
view_at: record.view_at,
}])
if (response.data.status === 'success') {
showNotify({
type: 'success',
message: response.data.message + (syncDeleteToBilibili ? ',并已同步删除B站历史记录' : ''),
})
fetchHistoryByDateRange()
} else {
throw new Error(response.data.message || '删除失败')
}
} catch (error) {
if (error.toString().includes('cancel')) return
showNotify({
type: 'danger',
message: error.response?.data?.detail || error.message || '删除失败',
})
}
}
// 判断某一天是否被全部选中
const isDaySelected = (timestamp) => {
const date = new Date(timestamp * 1000)
const dayStart = new Date(date.getFullYear(), date.getMonth(), date.getDate()).getTime() / 1000
const dayEnd = new Date(date.getFullYear(), date.getMonth(), date.getDate() + 1).getTime() / 1000 - 1
const dayRecords = records.value.filter(record =>
record.view_at >= dayStart && record.view_at <= dayEnd,
)
return dayRecords.every(record =>
selectedRecords.value.has(`${record.bvid}_${record.view_at}`),
)
}
// 切换某一天的所有记录的选中状态
const toggleDaySelection = (timestamp) => {
const date = new Date(timestamp * 1000)
const dayStart = new Date(date.getFullYear(), date.getMonth(), date.getDate()).getTime() / 1000
const dayEnd = new Date(date.getFullYear(), date.getMonth(), date.getDate() + 1).getTime() / 1000 - 1
const dayRecords = records.value.filter(record =>
record.view_at >= dayStart && record.view_at <= dayEnd,
)
const allSelected = isDaySelected(timestamp)
dayRecords.forEach(record => {
const key = `${record.bvid}_${record.view_at}`
if (allSelected) {
selectedRecords.value.delete(key)
} else {
selectedRecords.value.add(key)
}
})
}
// 处理备注更新
const handleRemarkUpdate = (data) => {
const key = `${data.bvid}_${data.view_at}`
remarkData.value[key] = {
bvid: data.bvid,
view_at: data.view_at,
remark: data.remark,
remark_time: data.remark_time,
}
}
// 添加打开详情对话框的方法
const openVideoDetail = (record) => {
selectedRecord.value = record
showDetailDialog.value = true
}
// 处理网格视图下载按钮点击
const handleDownloadGrid = (record) => {
console.log('handleDownloadGrid - 处理网格视图下载按钮点击')
selectedRecord.value = record
// 确保设置为单个视频下载模式,而非批量下载
isBatchDownload.value = false
showDownloadDialog.value = true
}
// 批量下载视频列表
const batchVideos = ref([])
const isBatchDownload = ref(false)
const currentVideoIndex = ref(0)
// 批量下载处理函数
const handleBatchDownload = async () => {
if (selectedRecords.value.size === 0) {
showNotify({
type: 'warning',
message: '请先选择要下载的记录',
})
return
}
try {
// 从选中的记录中提取视频信息
const videoRecords = [...selectedRecords.value].map(key => {
const [bvid, timestamp] = key.split('_')
return records.value.find(r => r.bvid === bvid && String(r.view_at) === timestamp)
}).filter(record => record && record.business === 'archive') // 过滤掉未找到的记录和非视频记录
if (videoRecords.length === 0) {
showNotify({
type: 'warning',
message: '选中的记录中没有有效的视频',
})
return
}
// 准备批量下载的视频列表
batchVideos.value = videoRecords.map(record => ({
bvid: record.bvid,
cid: record.cid,
title: record.title,
author: record.author_name,
cover: record.cover,
}))
// 设置批量下载模式
isBatchDownload.value = true
currentVideoIndex.value = 0
// 显示下载对话框
if (batchVideos.value.length > 0) {
// 设置第一个视频作为当前下载视频
const firstVideo = batchVideos.value[0]
selectedRecord.value = {
title: firstVideo.title,
author_name: firstVideo.author,
bvid: firstVideo.bvid,
cover: firstVideo.cover,
cid: firstVideo.cid,
}
showDownloadDialog.value = true
}
} catch (error) {
console.error('批量下载准备失败:', error)
showNotify({
type: 'danger',
message: '批量下载准备失败: ' + (error.message || '未知错误'),
})
}
}
// 处理下载完成
const handleDownloadComplete = async () => {
// 下载完成后重新检查下载状态
await batchCheckDownloadStatus()
}
// 调试函数,在控制台显示所有视频的CID和下载状态
// 处理收藏按钮点击(网格布局)
const handleFavoriteGrid = (record) => {
// 获取视频ID,适配不同的属性名(aid或avid)
let videoId = record.aid || record.avid || (record.business === 'archive' ? record.oid : null)
if (videoId) {
videoId = parseInt(videoId, 10)
}
if (!videoId || isNaN(videoId)) {
showNotify({ type: 'warning', message: '无法识别视频ID' })
return
}
// 检查是否已收藏
if (isVideoFavorited(videoId)) {
// 如果已收藏,提示是否取消收藏
showDialog({
title: '取消收藏',
message: '确定要取消收藏该视频吗?',
showCancelButton: true,
}).then(async () => {
// 获取视频的收藏夹列表
const folders = getVideoFavoriteFolders(videoId)
if (folders.length > 0) {
// 获取收藏夹ID
const folderIds = folders.map(folder => folder.media_id)
try {
// 发送取消收藏请求
const response = await favoriteResource({
rid: videoId,
del_media_ids: folderIds.join(','),
})
// 如果远程操作成功,同步本地数据库(不提示用户)
if (response.data.status === 'success') {
try {
await localBatchFavoriteResource({
rids: videoId.toString(),
del_media_ids: folderIds.join(','),
operation_type: 'local', // 只在本地操作
})
} catch (syncError) {
console.error('本地同步取消收藏失败,但不影响用户体验:', syncError)
}
// 更新收藏状态
favoriteStatus.value[videoId] = {
is_favorited: false,
favorite_folders: [],
}
showNotify({ type: 'success', message: '已取消收藏' })
// 刷新收藏状态
await batchCheckFavorites()
} else {
throw new Error(response.data.message || '取消收藏失败')
}
} catch (error) {
console.error('取消收藏失败:', error)
showNotify({ type: 'danger', message: '取消收藏失败: ' + (error.message || '未知错误') })
}
}
}).catch(() => {
// 取消操作,不做任何处理
})
} else {
// 如果未收藏,打开收藏夹选择对话框
showFavoriteDialog.value = true
favoriteVideoInfo.value = record
}
}
// 处理收藏夹选择对话框
const handleFavoriteDone = async (result) => {
console.log('handleFavoriteDone - 处理收藏完成', result)
if (result && result.success) {
if (result.isBatch) {
// 批量收藏完成
showNotify({ type: 'success', message: `批量收藏完成,已添加${result.videoInfo.selectedCount}个视频到收藏夹` })
// 更新收藏状态
if (result.videoInfo.batchIds) {
const videoIds = result.videoInfo.batchIds.split(',').map(id => parseInt(id.trim(), 10)).filter(id => !isNaN(id))
// 为每个视频ID更新收藏状态
videoIds.forEach(videoId => {
favoriteStatus.value[videoId] = {
is_favorited: true,
favorite_folders: result.folders.map(folderId => ({
media_id: folderId,
title: '收藏夹',
})),
}
})
// 取消批量模式并清空选择
selectedRecords.value.clear()
// 刷新收藏状态
await batchCheckFavorites()
}
} else {
// 单个视频收藏完成
showNotify({ type: 'success', message: '收藏成功' })
// 更新收藏状态
let videoId = result.videoInfo.aid || result.videoInfo.avid ||
(result.videoInfo.business === 'archive' ? result.videoInfo.oid : null)
if (videoId) {
// 确保ID是整数
videoId = parseInt(videoId, 10)
if (!isNaN(videoId)) {
// 设置为已收藏状态
favoriteStatus.value[videoId] = {
is_favorited: true,
favorite_folders: result.folders.map(folderId => ({
media_id: folderId,
title: '收藏夹', // 由于API返回的是ID列表,我们不知道具体名称,所以用通用名称
})),
}
// 重新获取精确的收藏夹信息
await batchCheckFavorites()
}
}
}
}
}
// 批量收藏选中的记录
const handleBatchFavorite = async () => {
if (selectedRecords.value.size === 0) {
showNotify({
type: 'warning',
message: '请先选择要收藏的记录',
})
return
}
// 从选中的记录中提取视频ID
const videoRecords = [...selectedRecords.value].map(key => {
const [bvid, timestamp] = key.split('_')
return records.value.find(r => r.bvid === bvid && String(r.view_at) === timestamp)
}).filter(record => record) // 过滤掉未找到的记录
// 提取视频ID
const oids = videoRecords.map(record => {
const id = record.aid || record.avid || (record.business === 'archive' ? record.oid : null)
return id ? parseInt(id, 10) : null
}).filter(oid => oid !== null && !isNaN(oid))
if (oids.length === 0) {
showNotify({
type: 'warning',
message: '选中的记录中没有有效的视频ID',
})
return
}
// 打开收藏夹选择对话框
showFavoriteDialog.value = true
favoriteVideoInfo.value = {
isBatch: true,
batchIds: oids.join(','),
selectedCount: oids.length,
}
}
// 计算选中记录中已收藏的数量
const hasFavoritedVideos = computed(() => {
return favoritedCount.value > 0
})
const favoritedCount = computed(() => {
if (selectedRecords.value.size === 0) return 0
let count = 0
selectedRecords.value.forEach(key => {
const [bvid, timestamp] = key.split('_')
const record = records.value.find(r => r.bvid === bvid && String(r.view_at) === timestamp)
if (record) {
const videoId = record.aid || record.avid || (record.business === 'archive' ? record.oid : null)
if (videoId && isVideoFavorited(parseInt(videoId, 10))) {
count++
}
}
})
return count
})
// 计算选中记录中未收藏的数量
const unfavoritedCount = computed(() => {
if (selectedRecords.value.size === 0) return 0
return selectedRecords.value.size - favoritedCount.value
})
// 检查是否所有选中的记录都已收藏
const isAllFavorited = computed(() => {
return selectedRecords.value.size > 0 && favoritedCount.value === selectedRecords.value.size
})
// 检查是否所有选中的记录都未收藏
computed(() => {
return selectedRecords.value.size > 0 && unfavoritedCount.value === selectedRecords.value.size
})
// 复制选中视频的链接到剪贴板
const handleCopyLinks = async () => {
if (selectedRecords.value.size === 0) {
showNotify({
type: 'warning',
message: '请先选择要复制链接的记录',
})
return
}
try {
// 从选中的记录中提取视频信息
const videoRecords = [...selectedRecords.value].map(key => {
const [bvid, timestamp] = key.split('_')
return records.value.find(r => r.bvid === bvid && String(r.view_at) === timestamp)
}).filter(record => record) // 过滤掉未找到的记录
// 生成链接列表
const links = videoRecords.map(record => {
let url = ''
switch (record.business) {
case 'archive':
url = `https://www.bilibili.com/video/${record.bvid}`
break
case 'article':
url = `https://www.bilibili.com/read/cv${record.oid}`
break
case 'article-list':
url = `https://www.bilibili.com/read/readlist/rl${record.oid}`
break
case 'live':
url = `https://live.bilibili.com/${record.oid}`
break
case 'pgc':
url = record.uri || `https://www.bilibili.com/bangumi/play/ep${record.epid}`
break
case 'cheese':
url = record.uri || `https://www.bilibili.com/cheese/play/ep${record.epid}`
break
default:
console.warn('未知的业务类型:', record.business)
return null
}
return url
}).filter(url => url) // 过滤掉无效的URL
// 复制到剪贴板
if (links.length > 0) {
await copyToClipboard(links.join('\n'))
showNotify({
type: 'success',
message: `已复制 ${links.length} 个链接到剪贴板`,
})
} else {
showNotify({
type: 'warning',
message: '没有找到有效的链接',
})
}
} catch (error) {
console.error('复制链接失败:', error)
showNotify({
type: 'danger',
message: '复制链接失败: ' + (error.message || '未知错误'),
})
}
}
// 复制到剪贴板函数
const copyToClipboard = async (text) => {
try {
await navigator.clipboard.writeText(text)
return true
} catch (err) {
console.error('复制失败:', err)
throw new Error('复制到剪贴板失败,请检查浏览器权限')
}
}
// 批量取消收藏选中的记录
const handleBatchUnfavorite = async () => {
if (selectedRecords.value.size === 0) {
showNotify({
type: 'warning',
message: '请先选择要取消收藏的记录',
})
return
}
try {
// 确认取消收藏
await showDialog({
title: '确认取消收藏',
message: `确定要取消${favoritedCount.value}个视频的收藏吗?`,
showCancelButton: true,
})
// 从选中的记录中提取视频ID
const videoRecords = [...selectedRecords.value].map(key => {
const [bvid, timestamp] = key.split('_')
return records.value.find(r => r.bvid === bvid && String(r.view_at) === timestamp)
}).filter(record => record) // 过滤掉未找到的记录
// 过滤出已收藏的视频
const favoritedRecords = videoRecords.filter(record => {
const videoId = record.aid || record.avid || (record.business === 'archive' ? record.oid : null)
return videoId && isVideoFavorited(parseInt(videoId, 10))
})
if (favoritedRecords.length === 0) {
showNotify({
type: 'warning',
message: '选中的记录中不包含已收藏的视频',
})
return
}
// 提取视频ID
const videoIds = favoritedRecords.map(record => {
const id = record.aid || record.avid || (record.business === 'archive' ? record.oid : null)
return id ? parseInt(id, 10) : null
}).filter(id => id !== null && !isNaN(id))
if (videoIds.length === 0) {
showNotify({
type: 'warning',
message: '无法获取有效的视频ID',
})
return
}
// 获取每个视频的收藏夹列表和执行取消收藏操作
let results
// 获取每个视频的收藏夹列表
const unfavoritePromises = videoIds.map(async videoId => {
const folders = getVideoFavoriteFolders(videoId)
if (folders.length > 0) {
// 获取收藏夹ID
const folderIds = folders.map(folder => folder.media_id)
// 发送取消收藏请求
const response = await favoriteResource({
rid: videoId,
del_media_ids: folderIds.join(','),
})
// 如果远程操作成功,同步本地数据库(不提示用户)
if (response.data.status === 'success') {
try {
await localBatchFavoriteResource({
rids: videoId.toString(),
del_media_ids: folderIds.join(','),
operation_type: 'local', // 只在本地操作
})
} catch (syncError) {
console.error('本地同步取消收藏失败,但不影响用户体验:', syncError)
}
}
return { videoId, success: response.data.status === 'success' }
}
return { videoId, success: false, reason: '没有找到收藏夹' }
})
results = await Promise.all(unfavoritePromises)
const successCount = results.filter(r => r.success).length
if (successCount > 0) {
showNotify({
type: 'success',
message: `成功取消${successCount}个视频的收藏`,
})
// 更新收藏状态
results.forEach(result => {
if (result.success) {
favoriteStatus.value[result.videoId] = {
is_favorited: false,
favorite_folders: [],
}
}
})
// 刷新收藏状态
await batchCheckFavorites()
// 取消选择
selectedRecords.value.clear()
} else {
showNotify({
type: 'danger',
message: '取消收藏失败',
})
}
} catch (error) {
if (error.toString().includes('cancel')) return
console.error('批量取消收藏失败:', error)
showNotify({
type: 'danger',
message: '批量取消收藏失败: ' + (error.message || '未知错误'),
})
}
}
// 处理收藏按钮点击(列表布局)
const handleFavorite = (record) => {
// 获取视频ID,适配不同的属性名(aid或avid)
const videoId = record.aid || record.avid || (record.business === 'archive' ? record.oid : null)
if (!videoId) {
showNotify({ type: 'warning', message: '无法识别视频ID' })
return
}
// 检查是否已收藏
const parsedVideoId = parseInt(videoId, 10)
if (isVideoFavorited(parsedVideoId)) {
// 如果已收藏,提示是否取消收藏
showDialog({
title: '取消收藏',
message: '确定要取消收藏该视频吗?',
showCancelButton: true,
}).then(async () => {
// 获取视频的收藏夹列表
const folders = getVideoFavoriteFolders(parsedVideoId)
if (folders.length > 0) {
// 获取收藏夹ID
const folderIds = folders.map(folder => folder.media_id)
try {
// 发送取消收藏请求
const response = await favoriteResource({
rid: parsedVideoId,
del_media_ids: folderIds.join(','),
})
// 如果远程操作成功,同步本地数据库(不提示用户)
if (response.data.status === 'success') {
try {
await localBatchFavoriteResource({
rids: parsedVideoId.toString(),
del_media_ids: folderIds.join(','),
operation_type: 'local', // 只在本地操作
})
} catch (syncError) {
console.error('本地同步取消收藏失败,但不影响用户体验:', syncError)
}
// 更新收藏状态
favoriteStatus.value[parsedVideoId] = {
is_favorited: false,
favorite_folders: [],
}
showNotify({ type: 'success', message: '已取消收藏' })
// 刷新收藏状态
await batchCheckFavorites()
} else {
throw new Error(response.data.message || '取消收藏失败')
}
} catch (error) {
console.error('取消收藏失败:', error)
showNotify({ type: 'danger', message: '取消收藏失败: ' + (error.message || '未知错误') })
}
}
}).catch(() => {
// 取消操作,不做任何处理
})
} else {
// 如果未收藏,打开收藏夹选择对话框
showFavoriteDialog.value = true
favoriteVideoInfo.value = record
}
}
</script>
|
2977094657/BiliHistoryFrontend
| 16,626
|
src/components/tailwind/FilterDropdown.vue
|
<template>
<div class="relative">
<!-- 筛选头部 - 所有元素在同一行 -->
<div class="flex items-center justify-between flex-wrap py-2 px-3">
<!-- 条目类型快速切换区域 -->
<div class="flex flex-1 flex-wrap gap-1 sm:gap-2">
<button
v-for="(label, type) in businessTypeMap"
:key="type"
class="px-2 sm:px-3 py-1 sm:py-1.5 text-xs rounded-md border transition-colors duration-200"
:class="business === type ? 'border-[#fb7299] bg-[#fb7299]/10 text-[#fb7299]' : 'border-gray-300 text-gray-700 hover:border-[#fb7299]/50'"
@click="selectBusiness(type)"
>
{{ label }}
</button>
</div>
<!-- 右侧操作区 -->
<div class="flex items-center space-x-2 sm:space-x-3 ml-1 sm:ml-2">
<!-- 每页显示条数设置 -->
<div class="flex items-center text-xs text-gray-500">
<span class="mr-1">每页</span>
<input
type="number"
:value="pageSize"
@input="handlePageSizeChange"
@blur="handlePageSizeBlur"
min="10"
max="100"
class="w-12 h-6 rounded border border-gray-200 px-1 text-center text-gray-700 transition-colors [appearance:textfield] hover:border-[#fb7299] focus:border-[#fb7299] focus:outline-none focus:ring-1 focus:ring-[#fb7299]/30 [&::-webkit-inner-spin-button]:appearance-none [&::-webkit-outer-spin-button]:appearance-none"
/>
<span class="ml-1">条</span>
</div>
<!-- 总视频数显示 -->
<div class="text-xs text-gray-500 ">
总视频数: <span class="text-[#FF6699] font-medium">{{ total }}</span>
</div>
<!-- 筛选图标按钮 -->
<button
@click="showFilterPopup = true"
class="p-1 sm:p-1.5 rounded-md hover:bg-gray-100 transition-colors duration-200"
>
<svg class="w-4 h-4 sm:w-5 sm:h-5 text-gray-600 " fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
d="M3 4a1 1 0 011-1h16a1 1 0 011 1v2.586a1 1 0 01-.293.707l-6.414 6.414a1 1 0 00-.293.707V17l-4 4v-6.586a1 1 0 00-.293-.707L3.293 7.293A1 1 0 013 6.586V4z" />
</svg>
</button>
</div>
</div>
<!-- 底部弹出式筛选栏 -->
<VanPopup
v-model:show="showFilterPopup"
position="bottom"
round
:z-index="2000"
get-container="body"
teleport="body"
:style="{ height: '70%' }"
class="overflow-hidden"
>
<div class="p-3 sm:p-4 h-full flex flex-col">
<div class="flex-1 overflow-y-auto">
<!-- 条目类型筛选 -->
<div class="mb-4 sm:mb-6">
<div class="flex items-center mb-2">
<h4 class="text-sm font-medium text-gray-700 ">条目类型</h4>
<div class="flex items-center ml-2 flex-1">
<span
class="text-xs sm:text-sm text-[#fb7299] font-medium truncate max-w-[80%]">{{ businessLabel || '全部'
}}</span>
<button
v-if="business"
@click="clearBusiness"
class="ml-1 sm:ml-2 p-1 rounded-full hover:bg-gray-100"
>
<svg class="w-3 h-3 sm:w-4 sm:h-4 text-gray-500" fill="none" viewBox="0 0 24 24"
stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12" />
</svg>
</button>
</div>
</div>
<div class="grid grid-cols-3 gap-1.5 sm:gap-2">
<div
v-for="(label, type) in businessTypeMap"
:key="type"
class="flex items-center p-1.5 sm:p-2 rounded-lg cursor-pointer border"
:class="business === type ? 'border-[#fb7299] bg-[#fb7299]/5' : 'border-gray-200 hover:border-[#fb7299]/50'"
@click="selectBusinessFromPopup(type)"
>
<div class="flex-1">
<div class="text-xs font-medium truncate">{{ label }}</div>
</div>
<div v-if="business === type" class="text-[#fb7299]">
<svg class="w-3 h-3 sm:w-4 sm:h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 13l4 4L19 7" />
</svg>
</div>
</div>
</div>
</div>
<!-- 日期筛选 -->
<div class="mb-4 sm:mb-6">
<div class="flex items-center mb-2">
<h4 class="text-sm font-medium text-gray-700 ">日期区间</h4>
<div class="flex items-center ml-2 flex-1">
<span class="text-xs sm:text-sm text-[#fb7299] font-medium truncate max-w-[80%]">{{ date || '全部'
}}</span>
<button
v-if="date"
@click="clearDate"
class="ml-1 sm:ml-2 p-1 rounded-full hover:bg-gray-100"
>
<svg class="w-3 h-3 sm:w-4 sm:h-4 text-gray-500" fill="none" viewBox="0 0 24 24"
stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12" />
</svg>
</button>
</div>
</div>
<div class="flex items-center space-x-2">
<div class="relative flex-1">
<input
type="date"
v-model="startDate"
@change="onDateChange"
class="w-full p-1.5 sm:p-2 text-xs sm:text-sm border border-gray-300 rounded-md focus:outline-none focus:ring-1 focus:ring-[#fb7299] focus:border-[#fb7299] cursor-pointer"
:max="endDate || undefined"
/>
<label class="absolute -top-1.5 left-2 text-[10px] bg-white px-1 text-gray-500">开始日期</label>
</div>
<span class="text-gray-400">至</span>
<div class="relative flex-1">
<input
type="date"
v-model="endDate"
@change="onDateChange"
class="w-full p-1.5 sm:p-2 text-xs sm:text-sm border border-gray-300 rounded-md focus:outline-none focus:ring-1 focus:ring-[#fb7299] focus:border-[#fb7299] cursor-pointer"
:min="startDate || undefined"
/>
<label class="absolute -top-1.5 left-2 text-[10px] bg-white px-1 text-gray-500">结束日期</label>
</div>
</div>
</div>
<!-- 视频分区筛选 -->
<div>
<div class="flex items-center mb-2">
<h4 class="text-sm font-medium text-gray-700 ">视频分区</h4>
<div class="flex items-center ml-2 flex-1">
<span class="text-xs sm:text-sm text-[#fb7299] font-medium truncate max-w-[80%]">{{ category || '全部'
}}</span>
<button
v-if="category"
@click="clearCategory"
class="ml-1 sm:ml-2 p-1 rounded-full hover:bg-gray-100"
>
<svg class="w-3 h-3 sm:w-4 sm:h-4 text-gray-500" fill="none" viewBox="0 0 24 24"
stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12" />
</svg>
</button>
</div>
</div>
<!-- 分区选择器 -->
<div class="border border-gray-300 rounded-md overflow-hidden">
<!-- 主分区选择 -->
<div class="flex h-48 sm:h-56">
<div class="w-1/3 border-r border-gray-300 overflow-y-auto">
<div
v-for="(category, index) in videoCategories"
:key="category.text"
class="p-1.5 sm:p-2 text-xs sm:text-sm cursor-pointer transition-colors duration-200 truncate"
:class="activeMainCategory === index ? 'bg-[#fb7299]/10 text-[#fb7299] font-medium' : 'hover:bg-gray-100'"
@click="activeMainCategory = index"
>
{{ category.text }}
</div>
</div>
<!-- 子分区选择 -->
<div class="w-2/3 overflow-y-auto">
<div class="grid grid-cols-2 gap-1.5 sm:gap-2 p-1 sm:p-2">
<!-- 主分区选项 -->
<div
class="p-1 sm:p-2 text-xs sm:text-sm border rounded-md cursor-pointer transition-colors duration-200 truncate"
:class="category === videoCategories[activeMainCategory]?.text ? 'border-[#fb7299] bg-[#fb7299]/10 text-[#fb7299]' : 'border-gray-300 hover:bg-gray-100'"
@click="selectVideoCategory({text: videoCategories[activeMainCategory]?.text, type: 'main'})"
>
{{ videoCategories[activeMainCategory]?.text || '全部' }}
</div>
<!-- 子分区选项 -->
<div
v-for="subCategory in videoCategories[activeMainCategory]?.children"
:key="subCategory.id"
class="p-1 sm:p-2 text-xs sm:text-sm border rounded-md cursor-pointer transition-colors duration-200 truncate"
:class="category === subCategory.text ? 'border-[#fb7299] bg-[#fb7299]/10 text-[#fb7299]' : 'border-gray-300 hover:bg-gray-100'"
@click="selectVideoCategory(subCategory)"
>
{{ subCategory.text }}
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</VanPopup>
</div>
</template>
<script setup>
import { ref, watch, onMounted } from 'vue'
import { showNotify, Popup as VanPopup } from 'vant'
import 'vant/es/popup/style'
import 'vant/es/notify/style'
const props = defineProps({
business: {
type: String,
default: '',
},
businessLabel: {
type: String,
default: '',
},
date: {
type: String,
default: '',
},
category: {
type: String,
default: '',
},
total: {
type: Number,
default: 0,
},
pageSize: {
type: Number,
default: 30,
},
})
const emit = defineEmits([
'update:business',
'update:businessLabel',
'update:date',
'update:category',
'update:pageSize',
'refresh-data',
])
// 底部弹出筛选栏的显示状态
const showFilterPopup = ref(false)
// 日期选择相关
const startDate = ref('')
const endDate = ref('')
// 视频分区选择相关
const videoCategories = ref([])
const activeMainCategory = ref(0)
// 获取视频分类
const fetchVideoCategories = async () => {
try {
const { getVideoCategories } = await import('../../api/api.js')
const response = await getVideoCategories()
if (response.data.status === 'success') {
videoCategories.value = response.data.data.map((category) => ({
text: category.name,
type: 'main',
children: category.sub_categories.map((sub) => ({
text: sub.name,
id: sub.tid,
type: 'sub',
})),
}))
}
} catch (error) {
console.error('获取视频分类失败:', error)
}
}
// 选择视频分区
const selectVideoCategory = (item) => {
const isMainName = videoCategories.value.some(cat =>
cat.text === item.text && item.type === 'main',
)
let categoryText = ''
if (item.type === 'main' || (item.type === 'sub' && isMainName)) {
categoryText = item.text
} else if (item.type === 'sub') {
categoryText = item.text
}
// 打印日志,帮助调试
console.log('选择分区:', {
item,
categoryText,
isMainName,
})
// 先更新分类,然后重置页码
emit('update:category', categoryText)
// 重置页码到第一页,而不是触发实时更新
emit('update:page', 1)
showNotify({
type: 'success',
message: `已筛选分区: ${categoryText || '全部'}`,
duration: 1000,
})
}
// 监听日期属性变化,解析为开始和结束日期
watch(() => props.date, (newDate) => {
if (newDate) {
const dates = newDate.split(' 至 ')
if (dates.length === 2) {
startDate.value = formatDateForInput(dates[0])
endDate.value = formatDateForInput(dates[1])
}
} else {
startDate.value = ''
endDate.value = ''
}
}, { immediate: true })
// 格式化日期为输入框格式 (YYYY-MM-DD)
const formatDateForInput = (dateStr) => {
try {
const parts = dateStr.split('/')
if (parts.length === 3) {
return `${parts[0]}-${parts[1].padStart(2, '0')}-${parts[2].padStart(2, '0')}`
}
return ''
} catch (e) {
return ''
}
}
// 格式化日期为显示格式 (YYYY/MM/DD)
const formatDateForDisplay = (dateStr) => {
try {
const date = new Date(dateStr)
if (isNaN(date.getTime())) return ''
return `${date.getFullYear()}/${(date.getMonth() + 1).toString().padStart(2, '0')}/${date.getDate().toString().padStart(2, '0')}`
} catch (e) {
console.error('日期格式化错误:', e)
return ''
}
}
// 业务类型映射表
const businessTypeMap = {
'': '全部',
'archive': '普通视频',
'pgc': '番剧',
'live': '直播',
'article': '文章',
'article-list': '文集',
}
// 选择业务类型(快速切换区域)
const selectBusiness = (type) => {
emit('update:business', type)
emit('update:businessLabel', businessTypeMap[type])
// 移除实时更新触发,改为只更新当前数据
emit('update:page', 1) // 重置页码到第一页
showNotify({
type: 'success',
message: `已切换到${businessTypeMap[type]}`,
duration: 1000,
})
}
// 从弹出窗口选择业务类型
const selectBusinessFromPopup = (type) => {
emit('update:business', type)
emit('update:businessLabel', businessTypeMap[type])
// 移除实时更新触发,改为只更新当前数据
emit('update:page', 1) // 重置页码到第一页
showNotify({
type: 'success',
message: `已切换到${businessTypeMap[type]}`,
duration: 1000,
})
}
// 应用日期筛选
const applyDateFilter = () => {
if (startDate.value && endDate.value) {
const formattedStartDate = formatDateForDisplay(startDate.value)
const formattedEndDate = formatDateForDisplay(endDate.value)
if (formattedStartDate && formattedEndDate) {
const dateRange = `${formattedStartDate} 至 ${formattedEndDate}`
console.log('设置日期区间:', dateRange)
emit('update:date', dateRange)
emit('update:page', 1) // 重置页码到第一页,而不是触发实时更新
showNotify({
type: 'success',
message: `已筛选日期: ${dateRange}`,
duration: 1000,
})
} else {
showNotify({
type: 'warning',
message: '日期格式无效',
duration: 2000,
})
}
} else if (!startDate.value && !endDate.value) {
// 如果两个日期都为空,清除筛选
emit('update:date', '')
emit('update:page', 1) // 重置页码到第一页,而不是触发实时更新
} else {
// 如果只有一个日期,显示提示
showNotify({
type: 'warning',
message: '请同时设置开始和结束日期',
duration: 2000,
})
}
}
// 处理日期变化
const onDateChange = () => {
applyDateFilter()
}
// 清除分区
const clearCategory = () => {
console.log('清除分区筛选')
// 先更新分类,然后重置页码
emit('update:category', '')
emit('update:page', 1) // 重置页码到第一页,而不是触发实时更新
showNotify({
type: 'success',
message: '已清除分区筛选',
duration: 1000,
})
}
// 清除日期
const clearDate = () => {
console.log('清除日期筛选')
// 先更新日期,然后重置页码
emit('update:date', '')
emit('update:page', 1) // 重置页码到第一页,而不是触发实时更新
showNotify({
type: 'success',
message: '已清除日期筛选',
duration: 1000,
})
}
// 清除业务类型
const clearBusiness = () => {
console.log('清除业务类型筛选')
// 先更新业务类型,然后重置页码
emit('update:business', '')
emit('update:businessLabel', '')
emit('update:page', 1) // 重置页码到第一页,而不是触发实时更新
showNotify({
type: 'success',
message: '已清除业务类型筛选',
duration: 1000,
})
}
// 处理每页条数变化
const handlePageSizeChange = (event) => {
const value = parseInt(event.target.value)
if (!isNaN(value) && value >= 10 && value <= 100) {
emit('update:pageSize', value)
}
}
// 处理输入框失焦
const handlePageSizeBlur = (event) => {
let value = parseInt(event.target.value)
if (isNaN(value) || value < 10) {
value = 10
} else if (value > 100) {
value = 100
}
emit('update:pageSize', value)
// 不调用 refresh-data,因为 pageSize 的 watch 会自动触发 fetchHistoryByDateRange
}
// 组件挂载时获取视频分类
onMounted(() => {
fetchVideoCategories()
})
</script>
<style scoped>
/* 可以添加自定义样式 */
/* 确保日期输入框在移动设备上正常工作 */
input[type="date"] {
-webkit-appearance: none;
appearance: none;
position: relative;
}
input[type="date"]::-webkit-calendar-picker-indicator {
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
width: 100%;
height: 100%;
opacity: 0;
cursor: pointer;
}
</style>
|
294coder/Efficient-MIF
| 3,471
|
Pansharpening_Hyper_SR_Matlab_Test_Package/Quality_Indices/D_s.m
|
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Description:
% Quality with No Reference (QNR). Spatial distortion index.
%
% Interface:
% D_s_index = D_s(I_F,I_MS,I_MS_LR,I_PAN,ratio,S,q)
%
% Inputs:
% I_F: Pansharpened image;
% I_MS: MS image resampled to panchromatic scale;
% I_MS_LR: Original MS image;
% I_PAN: Panchromatic image;
% ratio: Scale ratio between MS and PAN. Pre-condition: Integer value;
% S: Block size (optional); Default value: 32;
% q: Exponent value (optional); Default value: q = 1.
%
% Outputs:
% D_s_index: D_s index.
%
% References:
% [Alparone08] L. Alparone, B. Aiazzi, S. Baronti, A. Garzelli, F. Nencini, and M. Selva, "Multispectral and panchromatic data fusion assessment without reference,"
% Photogrammetric Engineering and Remote Sensing, vol. 74, no. 2, pp. 193200, February 2008.
% [Vivone14] G. Vivone, L. Alparone, J. Chanussot, M. Dalla Mura, A. Garzelli, G. Licciardi, R. Restaino, and L. Wald, A Critical Comparison Among Pansharpening Algorithms,
% IEEE Transaction on Geoscience and Remote Sensing, 2014. (Accepted)
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function D_s_index = D_s(I_F,I_MS,I_MS_LR,I_PAN,ratio,S,q)
flag_orig_paper = 0; % if 0, Toolbox 1.0, otherwise, original QNR paper
if (size(I_F) ~= size(I_MS))
error('The two images must have the same dimensions')
end
[N, M, Nb] = size(I_F);
if (rem(N,S) ~= 0)
error('number of rows must be multiple of the block size')
end
if (rem(M,S) ~= 0)
error('number of columns must be multiple of the block size')
end
if flag_orig_paper == 0
%%%%%%% Opt. 1 (as toolbox 1.0)
pan_filt = interp23tap(imresize(I_PAN,1./ratio),ratio);
else
%%%%%%% Opt. 2 (as paper QNR)
pan_filt = imresize(I_PAN,1./ratio);
end
D_s_index = 0;
for i = 1:Nb
band1 = I_F(:,:,i);
band2 = I_PAN;
fun_uqi = @(bs) uqi(bs.data,...
band2(bs.location(1):bs.location(1)+S-1,...
bs.location(2):bs.location(2)+S-1));
Qmap_high = blockproc(band1,[S S],fun_uqi);
Q_high = mean2(Qmap_high);
if flag_orig_paper == 0
%%%%%%% Opt. 1 (as toolbox 1.0)
band1 = I_MS(:,:,i);
band2 = pan_filt;
fun_uqi = @(bs) uqi(bs.data,...
band2(bs.location(1):bs.location(1)+S-1,...
bs.location(2):bs.location(2)+S-1));
Qmap_low = blockproc(band1,[S S],fun_uqi);
else
%%%%%%% Opt. 2 (as paper QNR)
band1 = I_MS_LR(:,:,i);
band2 = pan_filt;
fun_uqi = @(bs) uqi(bs.data,...
band2(bs.location(1):bs.location(1)+S/ratio-1,...
bs.location(2):bs.location(2)+S/ratio-1));
Qmap_low = blockproc(band1,[S/ratio S/ratio],fun_uqi);
end
Q_low = mean2(Qmap_low);
D_s_index = D_s_index + abs(Q_high-Q_low)^q;
end
D_s_index = (D_s_index/Nb)^(1/q);
end
%%%%%%% Q-index on x and y images
function Q = uqi(x,y)
x = double(x(:));
y = double(y(:));
mx = mean(x);
my = mean(y);
C = cov(x,y);
Q = 4 * C(1,2) * mx * my / (C(1,1)+C(2,2)) / (mx^2 + my^2);
end
|
294coder/Efficient-MIF
| 1,675
|
Pansharpening_Hyper_SR_Matlab_Test_Package/Quality_Indices/SAM.m
|
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Description:
% Spectral Angle Mapper (SAM).
%
% Interface:
% [SAM_index,SAM_map] = SAM(I1,I2)
%
% Inputs:
% I1: First multispectral image;
% I2: Second multispectral image.
%
% Outputs:
% SAM_index: SAM index;
% SAM_map: Image of SAM values.
%
% References:
% [Yuhas92] R. H. Yuhas, A. F. H. Goetz, and J. W. Boardman, "Discrimination among semi-arid landscape endmembers using the Spectral Angle Mapper (SAM) algorithm,"
% in Proceeding Summaries 3rd Annual JPL Airborne Geoscience Workshop, 1992, pp. 147149.
% [Vivone20] G. Vivone, M. Dalla Mura, A. Garzelli, R. Restaino, G. Scarpa, M.O. Ulfarsson, L. Alparone, and J. Chanussot, "A New Benchmark Based on Recent Advances in Multispectral Pansharpening: Revisiting pansharpening with classical and emerging pansharpening methods",
% IEEE Geoscience and Remote Sensing Magazine, doi: 10.1109/MGRS.2020.3019315.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [SAM_index,SAM_map] = SAM(I1,I2)
[M,N,~] = size(I2);
prod_scal = dot(I1,I2,3);
norm_orig = dot(I1,I1,3);
norm_fusa = dot(I2,I2,3);
prod_norm = sqrt(norm_orig.*norm_fusa);
prod_map = prod_norm;
prod_map(prod_map==0)=eps;
SAM_map = acos(prod_scal./prod_map);
prod_scal = reshape(prod_scal,M*N,1);
prod_norm = reshape(prod_norm, M*N,1);
z=find(prod_norm==0);
prod_scal(z)=[];prod_norm(z)=[];
angolo = sum(sum(acos(prod_scal./prod_norm)))/(size(prod_norm,1));
SAM_index = real(angolo)*180/pi;
end
|
294coder/Efficient-MIF
| 6,165
|
Pansharpening_Hyper_SR_Matlab_Test_Package/Quality_Indices/ssim.m
|
function [mssim, ssim_map] = ssim(img1, img2, K, window, L)
% ========================================================================
% SSIM Index with automatic downsampling, Version 1.0
% Copyright(c) 2009 Zhou Wang
% All Rights Reserved.
%
% ----------------------------------------------------------------------
% Permission to use, copy, or modify this software and its documentation
% for educational and research purposes only and without fee is hereby
% granted, provided that this copyright notice and the original authors'
% names appear on all copies and supporting documentation. This program
% shall not be used, rewritten, or adapted as the basis of a commercial
% software or hardware product without first obtaining permission of the
% authors. The authors make no representations about the suitability of
% this software for any purpose. It is provided "as is" without express
% or implied warranty.
%----------------------------------------------------------------------
%
% This is an implementation of the algorithm for calculating the
% Structural SIMilarity (SSIM) index between two images
%
% Please refer to the following paper and the website with suggested usage
%
% Z. Wang, A. C. Bovik, H. R. Sheikh, and E. P. Simoncelli, "Image
% quality assessment: From error visibility to structural similarity,"
% IEEE Transactios on Image Processing, vol. 13, no. 4, pp. 600-612,
% Apr. 2004.
%
% http://www.ece.uwaterloo.ca/~z70wang/research/ssim/
%
% Note: This program is different from ssim_index.m, where no automatic
% downsampling is performed. (downsampling was done in the above paper
% and was described as suggested usage in the above website.)
%
% Kindly report any suggestions or corrections to [email protected]
%
%----------------------------------------------------------------------
%
%Input : (1) img1: the first image being compared
% (2) img2: the second image being compared
% (3) K: constants in the SSIM index formula (see the above
% reference). defualt value: K = [0.01 0.03]
% (4) window: local window for statistics (see the above
% reference). default widnow is Gaussian given by
% window = fspecial('gaussian', 11, 1.5);
% (5) L: dynamic range of the images. default: L = 255
%
%Output: (1) mssim: the mean SSIM index value between 2 images.
% If one of the images being compared is regarded as
% perfect quality, then mssim can be considered as the
% quality measure of the other image.
% If img1 = img2, then mssim = 1.
% (2) ssim_map: the SSIM index map of the test image. The map
% has a smaller size than the input images. The actual size
% depends on the window size and the downsampling factor.
%
%Basic Usage:
% Given 2 test images img1 and img2, whose dynamic range is 0-255
%
% [mssim, ssim_map] = ssim(img1, img2);
%
%Advanced Usage:
% User defined parameters. For example
%
% K = [0.05 0.05];
% window = ones(8);
% L = 100;
% [mssim, ssim_map] = ssim(img1, img2, K, window, L);
%
%Visualize the results:
%
% mssim %Gives the mssim value
% imshow(max(0, ssim_map).^4) %Shows the SSIM index map
%========================================================================
if (nargin < 2 || nargin > 5)
mssim = -Inf;
ssim_map = -Inf;
return;
end
if (size(img1) ~= size(img2))
mssim = -Inf;
ssim_map = -Inf;
return;
end
[M N] = size(img1);
if (nargin == 2)
if ((M < 11) || (N < 11))
mssim = -Inf;
ssim_map = -Inf;
return
end
window = fspecial('gaussian', 11, 1.5); %
K(1) = 0.01; % default settings
K(2) = 0.03; %
L = 255; %
end
if (nargin == 3)
if ((M < 11) || (N < 11))
mssim = -Inf;
ssim_map = -Inf;
return
end
window = fspecial('gaussian', 11, 1.5);
L = 255;
if (length(K) == 2)
if (K(1) < 0 || K(2) < 0)
mssim = -Inf;
ssim_map = -Inf;
return;
end
else
mssim = -Inf;
ssim_map = -Inf;
return;
end
end
if (nargin == 4)
[H W] = size(window);
if ((H*W) < 4 || (H > M) || (W > N))
mssim = -Inf;
ssim_map = -Inf;
return
end
L = 255;
if (length(K) == 2)
if (K(1) < 0 || K(2) < 0)
mssim = -Inf;
ssim_map = -Inf;
return;
end
else
mssim = -Inf;
ssim_map = -Inf;
return;
end
end
if (nargin == 5)
[H W] = size(window);
if ((H*W) < 4 || (H > M) || (W > N))
mssim = -Inf;
ssim_map = -Inf;
return
end
if (length(K) == 2)
if (K(1) < 0 || K(2) < 0)
mssim = -Inf;
ssim_map = -Inf;
return;
end
else
mssim = -Inf;
ssim_map = -Inf;
return;
end
end
img1 = double(img1);
img2 = double(img2);
% automatic downsampling
f = max(1,round(min(M,N)/256));
%downsampling by f
%use a simple low-pass filter
if(f>1)
lpf = ones(f,f);
lpf = lpf/sum(lpf(:));
img1 = imfilter(img1,lpf,'symmetric','same');
img2 = imfilter(img2,lpf,'symmetric','same');
img1 = img1(1:f:end,1:f:end);
img2 = img2(1:f:end,1:f:end);
end
C1 = (K(1)*L)^2;
C2 = (K(2)*L)^2;
window = window/sum(sum(window));
mu1 = filter2(window, img1, 'valid');
mu2 = filter2(window, img2, 'valid');
mu1_sq = mu1.*mu1;
mu2_sq = mu2.*mu2;
mu1_mu2 = mu1.*mu2;
sigma1_sq = filter2(window, img1.*img1, 'valid') - mu1_sq;
sigma2_sq = filter2(window, img2.*img2, 'valid') - mu2_sq;
sigma12 = filter2(window, img1.*img2, 'valid') - mu1_mu2;
if (C1 > 0 && C2 > 0)
ssim_map = ((2*mu1_mu2 + C1).*(2*sigma12 + C2))./((mu1_sq + mu2_sq + C1).*(sigma1_sq + sigma2_sq + C2));
else
numerator1 = 2*mu1_mu2 + C1;
numerator2 = 2*sigma12 + C2;
denominator1 = mu1_sq + mu2_sq + C1;
denominator2 = sigma1_sq + sigma2_sq + C2;
ssim_map = ones(size(mu1));
index = (denominator1.*denominator2 > 0);
ssim_map(index) = (numerator1(index).*numerator2(index))./(denominator1(index).*denominator2(index));
index = (denominator1 ~= 0) & (denominator2 == 0);
ssim_map(index) = numerator1(index)./denominator1(index);
end
mssim = mean2(ssim_map);
return
|
2881099/FreeSql.AdminLTE
| 25,287
|
FreeSql.AdminLTE.Preview/Template/TemplateEngin.cs
|
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
namespace FreeSql.Template
{
public class TemplateEngin : IDisposable {
public interface ITemplateOutput {
/// <summary>
///
/// </summary>
/// <param name="tOuTpUt">返回内容</param>
/// <param name="oPtIoNs">渲染对象</param>
/// <param name="rEfErErFiLeNaMe">当前文件路径</param>
/// <param name="tEmPlAtEsEnDeR"></param>
/// <returns></returns>
TemplateReturnInfo OuTpUt(StringBuilder tOuTpUt, IDictionary oPtIoNs, string rEfErErFiLeNaMe, TemplateEngin tEmPlAtEsEnDeR);
}
public class TemplateReturnInfo {
public Dictionary<string, int[]> Blocks;
public StringBuilder Sb;
}
public delegate bool TemplateIf(object exp);
public delegate void TemplatePrint(params object[] parms);
private static int _view = 0;
private static Regex _reg = new Regex(@"\{(\$TEMPLATE__CODE|\/\$TEMPLATE__CODE|import\s+|module\s+|extends\s+|block\s+|include\s+|for\s+|if\s+|#|\/for|elseif|else|\/if|\/block|\/module)([^\}]*)\}", RegexOptions.Compiled);
private static Regex _reg_forin = new Regex(@"^([\w_]+)\s*,?\s*([\w_]+)?\s+in\s+(.+)", RegexOptions.Compiled);
private static Regex _reg_foron = new Regex(@"^([\w_]+)\s*,?\s*([\w_]+)?,?\s*([\w_]+)?\s+on\s+(.+)", RegexOptions.Compiled);
private static Regex _reg_forab = new Regex(@"^([\w_]+)\s+([^,]+)\s*,\s*(.+)", RegexOptions.Compiled);
private static Regex _reg_miss = new Regex(@"\{\/?miss\}", RegexOptions.Compiled);
private static Regex _reg_code = new Regex(@"(\{%|%\})", RegexOptions.Compiled);
private static Regex _reg_syntax = new Regex(@"<(\w+)\s+@(if|for|else)\s*=""([^""]*)""", RegexOptions.Compiled);
private static Regex _reg_htmltag = new Regex(@"<\/?\w+[^>]*>", RegexOptions.Compiled);
private static Regex _reg_blank = new Regex(@"\s+", RegexOptions.Compiled);
private static Regex _reg_complie_undefined = new Regex(@"(当前上下文中不存在名称)?“(\w+)”", RegexOptions.Compiled);
private Dictionary<string, ITemplateOutput> _cache = new Dictionary<string, ITemplateOutput>();
private object _cache_lock = new object();
private string _viewDir;
private string[] _usings;
private FileSystemWatcher _fsw = new FileSystemWatcher();
public TemplateEngin(string viewDir, params string[] usings) {
_viewDir = Utils.TranslateUrl(viewDir);
_usings = usings;
_fsw = new FileSystemWatcher(_viewDir);
_fsw.IncludeSubdirectories = true;
_fsw.Changed += ViewDirChange;
_fsw.Renamed += ViewDirChange;
_fsw.EnableRaisingEvents = true;
}
public void Dispose() {
_fsw.Dispose();
}
void ViewDirChange(object sender, FileSystemEventArgs e) {
string filename = e.FullPath.ToLower();
lock (_cache_lock) {
_cache.Remove(filename);
}
}
public TemplateReturnInfo RenderFile2(StringBuilder sb, IDictionary options, string filename, string refererFilename) {
if (filename[0] == '/' || string.IsNullOrEmpty(refererFilename)) refererFilename = _viewDir;
//else refererFilename = Path.GetDirectoryName(refererFilename);
string filename2 = Utils.TranslateUrl(filename, refererFilename);
Console.WriteLine(filename2);
ITemplateOutput tpl;
if (_cache.TryGetValue(filename2, out tpl) == false) {
string tplcode = File.Exists(filename2) == false ? string.Concat("文件不存在 ", filename) : Utils.ReadTextFile(filename2);
tpl = Parser(tplcode, _usings, options);
lock (_cache_lock) {
if (_cache.ContainsKey(filename2) == false) {
_cache.Add(filename2, tpl);
}
}
}
try {
return tpl.OuTpUt(sb, options, filename2, this);
} catch (Exception ex) {
TemplateReturnInfo ret = sb == null ?
new TemplateReturnInfo { Sb = new StringBuilder(), Blocks = new Dictionary<string, int[]>() } :
new TemplateReturnInfo { Sb = sb, Blocks = new Dictionary<string, int[]>() };
ret.Sb.Append(refererFilename);
ret.Sb.Append(" -> ");
ret.Sb.Append(filename);
ret.Sb.Append("\r\n");
ret.Sb.Append(ex.Message);
ret.Sb.Append("\r\n");
ret.Sb.Append(ex.StackTrace);
return ret;
}
}
public string RenderFile(string filename, IDictionary options) {
TemplateReturnInfo ret = this.RenderFile2(null, options, filename, null);
return ret.Sb.ToString();
}
private static ITemplateOutput Parser(string tplcode, string[] usings, IDictionary options) {
int view = Interlocked.Increment(ref _view);
StringBuilder sb = new StringBuilder();
IDictionary options_copy = new Hashtable();
foreach (DictionaryEntry options_de in options) options_copy[options_de.Key] = options_de.Value;
sb.AppendFormat(@"
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;{1}
//namespace TplDynamicCodeGenerate {{
public class TplDynamicCodeGenerate_view{0} : FreeSql.Template.TemplateEngin.ITemplateOutput {{
public FreeSql.Template.TemplateEngin.TemplateReturnInfo OuTpUt(StringBuilder tOuTpUt, IDictionary oPtIoNs, string rEfErErFiLeNaMe, FreeSql.Template.TemplateEngin tEmPlAtEsEnDeR) {{
FreeSql.Template.TemplateEngin.TemplateReturnInfo rTn = tOuTpUt == null ?
new FreeSql.Template.TemplateEngin.TemplateReturnInfo {{ Sb = (tOuTpUt = new StringBuilder()), Blocks = new Dictionary<string, int[]>() }} :
new FreeSql.Template.TemplateEngin.TemplateReturnInfo {{ Sb = tOuTpUt, Blocks = new Dictionary<string, int[]>() }};
Dictionary<string, int[]> TPL__blocks = rTn.Blocks;
Stack<int[]> TPL__blocks_stack = new Stack<int[]>();
int[] TPL__blocks_stack_peek;
List<IDictionary> TPL__forc = new List<IDictionary>();
Func<IDictionary> pRoCeSsOpTiOnS = new Func<IDictionary>(delegate () {{
IDictionary nEwoPtIoNs = new Hashtable();
foreach (DictionaryEntry oPtIoNs_dE in oPtIoNs)
nEwoPtIoNs[oPtIoNs_dE.Key] = oPtIoNs_dE.Value;
foreach (IDictionary TPL__forc_dIc in TPL__forc)
foreach (DictionaryEntry TPL__forc_dIc_dE in TPL__forc_dIc)
nEwoPtIoNs[TPL__forc_dIc_dE.Key] = TPL__forc_dIc_dE.Value;
return nEwoPtIoNs;
}});
FreeSql.Template.TemplateEngin.TemplateIf tPlIf = delegate(object exp) {{
if (exp is bool) return (bool)exp;
if (exp == null) return false;
if (exp is int && (int)exp == 0) return false;
if (exp is string && (string)exp == string.Empty) return false;
if (exp is long && (long)exp == 0) return false;
if (exp is short && (short)exp == 0) return false;
if (exp is byte && (byte)exp == 0) return false;
if (exp is double && (double)exp == 0) return false;
if (exp is float && (float)exp == 0) return false;
if (exp is decimal && (decimal)exp == 0) return false;
return true;
}};
FreeSql.Template.TemplateEngin.TemplatePrint print = delegate(object[] pArMs) {{
if (pArMs == null || pArMs.Length == 0) return;
foreach (object pArMs_A in pArMs) if (pArMs_A != null) tOuTpUt.Append(pArMs_A);
}};
FreeSql.Template.TemplateEngin.TemplatePrint Print = print;", view, usings?.Any() == true ? $"\r\nusing {string.Join(";\r\nusing ", usings)};" : "");
#region {miss}...{/miss}块内容将不被解析
string[] tmp_content_arr = _reg_miss.Split(tplcode);
if (tmp_content_arr.Length > 1) {
sb.AppendFormat(@"
string[] TPL__MISS = new string[{0}];", Math.Ceiling(1.0 * (tmp_content_arr.Length - 1) / 2));
int miss_len = -1;
for (int a = 1; a < tmp_content_arr.Length; a += 2) {
sb.Append(string.Concat(@"
TPL__MISS[", ++miss_len, @"] = """, Utils.GetConstString(tmp_content_arr[a]), @""";"));
tmp_content_arr[a] = string.Concat("{#TPL__MISS[", miss_len, "]}");
}
tplcode = string.Join("", tmp_content_arr);
}
#endregion
#region 扩展语法如 <div @if="表达式"></div>
tplcode = htmlSyntax(tplcode, 3); //<div @if="c#表达式" @for="index 1,100"></div>
//处理 {% %} 块 c#代码
tmp_content_arr = _reg_code.Split(tplcode);
if (tmp_content_arr.Length == 1) {
tplcode = Utils.GetConstString(tplcode)
.Replace("{%", "{$TEMPLATE__CODE}")
.Replace("%}", "{/$TEMPLATE__CODE}");
} else {
tmp_content_arr[0] = Utils.GetConstString(tmp_content_arr[0]);
for (int a = 1; a < tmp_content_arr.Length; a += 4) {
tmp_content_arr[a] = "{$TEMPLATE__CODE}";
tmp_content_arr[a + 2] = "{/$TEMPLATE__CODE}";
tmp_content_arr[a + 3] = Utils.GetConstString(tmp_content_arr[a + 3]);
}
tplcode = string.Join("", tmp_content_arr);
}
#endregion
sb.Append(@"
tOuTpUt.Append(""");
string error = null;
int tpl_tmpid = 0;
int forc_i = 0;
string extends = null;
Stack<string> codeTree = new Stack<string>();
Stack<string> forEndRepl = new Stack<string>();
sb.Append(_reg.Replace(tplcode, delegate (Match m) {
string _0 = m.Groups[0].Value;
if (!string.IsNullOrEmpty(error)) return _0;
string _1 = m.Groups[1].Value.Trim(' ', '\t');
string _2 = m.Groups[2].Value
.Replace("\\\\", "\\")
.Replace("\\\"", "\"");
_2 = Utils.ReplaceSingleQuote(_2);
switch (_1) {
#region $TEMPLATE__CODE--------------------------------------------------
case "$TEMPLATE__CODE":
codeTree.Push(_1);
return @""");
";
case "/$TEMPLATE__CODE":
string pop = codeTree.Pop();
if (pop != "$TEMPLATE__CODE") {
codeTree.Push(pop);
error = "编译出错,{% 与 %} 并没有配对";
return _0;
}
return @"
tOuTpUt.Append(""";
#endregion
case "include":
return string.Format(@""");
tEmPlAtEsEnDeR.RenderFile2(tOuTpUt, pRoCeSsOpTiOnS(), ""{0}"", rEfErErFiLeNaMe);
tOuTpUt.Append(""", _2);
case "import":
return _0;
case "module":
return _0;
case "/module":
return _0;
case "extends":
//{extends ../inc/layout.html}
if (string.IsNullOrEmpty(extends) == false) return _0;
extends = _2;
return string.Empty;
case "block":
codeTree.Push("block");
return string.Format(@""");
TPL__blocks_stack_peek = new int[] {{ tOuTpUt.Length, 0 }};
TPL__blocks_stack.Push(TPL__blocks_stack_peek);
TPL__blocks.Add(""{0}"", TPL__blocks_stack_peek);
tOuTpUt.Append(""", _2.Trim(' ', '\t'));
case "/block":
codeTreeEnd(codeTree, "block");
return @""");
TPL__blocks_stack_peek = TPL__blocks_stack.Pop();
TPL__blocks_stack_peek[1] = tOuTpUt.Length - TPL__blocks_stack_peek[0];
tOuTpUt.Append(""";
#region ##---------------------------------------------------------
case "#":
if (_2[0] == '#')
return string.Format(@""");
try {{ Print({0}); }} catch {{ }}
tOuTpUt.Append(""", _2.Substring(1));
return string.Format(@""");
Print({0});
tOuTpUt.Append(""", _2);
#endregion
#region for--------------------------------------------------------
case "for":
forc_i++;
int cur_tpl_tmpid = tpl_tmpid;
string sb_endRepl = string.Empty;
StringBuilder sbfor = new StringBuilder();
sbfor.Append(@""");");
Match mfor = _reg_forin.Match(_2);
if (mfor.Success) {
string mfor1 = mfor.Groups[1].Value.Trim(' ', '\t');
string mfor2 = mfor.Groups[2].Value.Trim(' ', '\t');
sbfor.AppendFormat(@"
//new Action(delegate () {{
IDictionary TPL__tmp{0} = new Hashtable();
TPL__forc.Add(TPL__tmp{0});
var TPL__tmp{1} = {3};
var TPL__tmp{2} = {4};", ++tpl_tmpid, ++tpl_tmpid, ++tpl_tmpid, mfor.Groups[3].Value, mfor1);
sb_endRepl = string.Concat(sb_endRepl, string.Format(@"
{0} = TPL__tmp{1};", mfor1, cur_tpl_tmpid + 3));
if (options_copy.Contains(mfor1) == false) options_copy[mfor1] = null;
if (!string.IsNullOrEmpty(mfor2)) {
sbfor.AppendFormat(@"
var TPL__tmp{1} = {0};
{0} = 0;", mfor2, ++tpl_tmpid);
sb_endRepl = string.Concat(sb_endRepl, string.Format(@"
{0} = TPL__tmp{1};", mfor2, tpl_tmpid));
if (options_copy.Contains(mfor2) == false) options_copy[mfor2] = null;
}
sbfor.AppendFormat(@"
if (TPL__tmp{1} != null)
foreach (var TPL__tmp{0} in TPL__tmp{1}) {{", ++tpl_tmpid, cur_tpl_tmpid + 2);
if (!string.IsNullOrEmpty(mfor2))
sbfor.AppendFormat(@"
TPL__tmp{1}[""{0}""] = ++ {0};", mfor2, cur_tpl_tmpid + 1);
sbfor.AppendFormat(@"
TPL__tmp{1}[""{0}""] = TPL__tmp{2};
{0} = TPL__tmp{2};
tOuTpUt.Append(""", mfor1, cur_tpl_tmpid + 1, tpl_tmpid);
codeTree.Push("for");
forEndRepl.Push(sb_endRepl);
return sbfor.ToString();
}
mfor = _reg_foron.Match(_2);
if (mfor.Success) {
string mfor1 = mfor.Groups[1].Value.Trim(' ', '\t');
string mfor2 = mfor.Groups[2].Value.Trim(' ', '\t');
string mfor3 = mfor.Groups[3].Value.Trim(' ', '\t');
sbfor.AppendFormat(@"
//new Action(delegate () {{
IDictionary TPL__tmp{0} = new Hashtable();
TPL__forc.Add(TPL__tmp{0});
var TPL__tmp{1} = {3};
var TPL__tmp{2} = {4};", ++tpl_tmpid, ++tpl_tmpid, ++tpl_tmpid, mfor.Groups[4].Value, mfor1);
sb_endRepl = string.Concat(sb_endRepl, string.Format(@"
{0} = TPL__tmp{1};", mfor1, cur_tpl_tmpid + 3));
if (options_copy.Contains(mfor1) == false) options_copy[mfor1] = null;
if (!string.IsNullOrEmpty(mfor2)) {
sbfor.AppendFormat(@"
var TPL__tmp{1} = {0};", mfor2, ++tpl_tmpid);
sb_endRepl = string.Concat(sb_endRepl, string.Format(@"
{0} = TPL__tmp{1};", mfor2, tpl_tmpid));
if (options_copy.Contains(mfor2) == false) options_copy[mfor2] = null;
}
if (!string.IsNullOrEmpty(mfor3)) {
sbfor.AppendFormat(@"
var TPL__tmp{1} = {0};
{0} = 0;", mfor3, ++tpl_tmpid);
sb_endRepl = string.Concat(sb_endRepl, string.Format(@"
{0} = TPL__tmp{1};", mfor3, tpl_tmpid));
if (options_copy.Contains(mfor3) == false) options_copy[mfor3] = null;
}
sbfor.AppendFormat(@"
if (TPL__tmp{2} != null)
foreach (DictionaryEntry TPL__tmp{1} in TPL__tmp{2}) {{
{0} = TPL__tmp{1}.Key;
TPL__tmp{3}[""{0}""] = {0};", mfor1, ++tpl_tmpid, cur_tpl_tmpid + 2, cur_tpl_tmpid + 1);
if (!string.IsNullOrEmpty(mfor2))
sbfor.AppendFormat(@"
{0} = TPL__tmp{1}.Value;
TPL__tmp{2}[""{0}""] = {0};", mfor2, tpl_tmpid, cur_tpl_tmpid + 1);
if (!string.IsNullOrEmpty(mfor3))
sbfor.AppendFormat(@"
TPL__tmp{1}[""{0}""] = ++ {0};", mfor3, cur_tpl_tmpid + 1);
sbfor.AppendFormat(@"
tOuTpUt.Append(""");
codeTree.Push("for");
forEndRepl.Push(sb_endRepl);
return sbfor.ToString();
}
mfor = _reg_forab.Match(_2);
if (mfor.Success) {
string mfor1 = mfor.Groups[1].Value.Trim(' ', '\t');
sbfor.AppendFormat(@"
//new Action(delegate () {{
IDictionary TPL__tmp{0} = new Hashtable();
TPL__forc.Add(TPL__tmp{0});
var TPL__tmp{1} = {5};
{5} = {3} - 1;
if ({5} == null) {5} = 0;
var TPL__tmp{2} = {4} + 1;
while (++{5} < TPL__tmp{2}) {{
TPL__tmp{0}[""{5}""] = {5};
tOuTpUt.Append(""", ++tpl_tmpid, ++tpl_tmpid, ++tpl_tmpid, mfor.Groups[2].Value, mfor.Groups[3].Value, mfor1);
sb_endRepl = string.Concat(sb_endRepl, string.Format(@"
{0} = TPL__tmp{1};", mfor1, cur_tpl_tmpid + 1));
if (options_copy.Contains(mfor1) == false) options_copy[mfor1] = null;
codeTree.Push("for");
forEndRepl.Push(sb_endRepl);
return sbfor.ToString();
}
return _0;
case "/for":
if (--forc_i < 0) return _0;
codeTreeEnd(codeTree, "for");
return string.Format(@""");
}}{0}
TPL__forc.RemoveAt(TPL__forc.Count - 1);
//}})();
tOuTpUt.Append(""", forEndRepl.Pop());
#endregion
#region if---------------------------------------------------------
case "if":
codeTree.Push("if");
return string.Format(@""");
if ({1}tPlIf({0})) {{
tOuTpUt.Append(""", _2[0] == '!' ? _2.Substring(1) : _2, _2[0] == '!' ? '!' : ' ');
case "elseif":
codeTreeEnd(codeTree, "if");
codeTree.Push("if");
return string.Format(@""");
}} else if ({1}tPlIf({0})) {{
tOuTpUt.Append(""", _2[0] == '!' ? _2.Substring(1) : _2, _2[0] == '!' ? '!' : ' ');
case "else":
codeTreeEnd(codeTree, "if");
codeTree.Push("if");
return @""");
} else {
tOuTpUt.Append(""";
case "/if":
codeTreeEnd(codeTree, "if");
return @""");
}
tOuTpUt.Append(""";
#endregion
}
return _0;
}));
sb.Append(@""");");
if (string.IsNullOrEmpty(extends) == false) {
sb.AppendFormat(@"
FreeSql.Template.TemplateEngin.TemplateReturnInfo eXtEnDs_ReT = tEmPlAtEsEnDeR.RenderFile2(null, pRoCeSsOpTiOnS(), ""{0}"", rEfErErFiLeNaMe);
string rTn_Sb_string = rTn.Sb.ToString();
foreach(string eXtEnDs_ReT_blocks_key in eXtEnDs_ReT.Blocks.Keys) {{
if (rTn.Blocks.ContainsKey(eXtEnDs_ReT_blocks_key)) {{
int[] eXtEnDs_ReT_blocks_value = eXtEnDs_ReT.Blocks[eXtEnDs_ReT_blocks_key];
eXtEnDs_ReT.Sb.Remove(eXtEnDs_ReT_blocks_value[0], eXtEnDs_ReT_blocks_value[1]);
int[] rTn_blocks_value = rTn.Blocks[eXtEnDs_ReT_blocks_key];
eXtEnDs_ReT.Sb.Insert(eXtEnDs_ReT_blocks_value[0], rTn_Sb_string.Substring(rTn_blocks_value[0], rTn_blocks_value[1]));
foreach(string eXtEnDs_ReT_blocks_keyb in eXtEnDs_ReT.Blocks.Keys) {{
if (eXtEnDs_ReT_blocks_keyb == eXtEnDs_ReT_blocks_key) continue;
int[] eXtEnDs_ReT_blocks_valueb = eXtEnDs_ReT.Blocks[eXtEnDs_ReT_blocks_keyb];
if (eXtEnDs_ReT_blocks_valueb[0] >= eXtEnDs_ReT_blocks_value[0])
eXtEnDs_ReT_blocks_valueb[0] = eXtEnDs_ReT_blocks_valueb[0] - eXtEnDs_ReT_blocks_value[1] + rTn_blocks_value[1];
}}
eXtEnDs_ReT_blocks_value[1] = rTn_blocks_value[1];
}}
}}
return eXtEnDs_ReT;
", extends);
} else {
sb.Append(@"
return rTn;");
}
sb.Append(@"
}
}
//}
");
var str = "FreeSql.Template.TemplateEngin.TemplatePrint Print = print;";
int dim_idx = sb.ToString().IndexOf(str) + str.Length;
foreach (string dic_name in options_copy.Keys) {
sb.Insert(dim_idx, string.Format(@"
dynamic {0} = oPtIoNs[""{0}""];", dic_name));
}
//Console.WriteLine(sb.ToString());
return Complie(sb.ToString(), @"TplDynamicCodeGenerate_view" + view);
}
private static string codeTreeEnd(Stack<string> codeTree, string tag) {
string ret = string.Empty;
Stack<int> pop = new Stack<int>();
foreach (string ct in codeTree) {
if (ct == "import" ||
ct == "include") {
pop.Push(1);
} else if (ct == tag) {
pop.Push(2);
break;
} else {
if (string.IsNullOrEmpty(tag) == false) pop.Clear();
break;
}
}
if (pop.Count == 0 && string.IsNullOrEmpty(tag) == false)
return string.Concat("语法错误,{", tag, "} {/", tag, "} 并没配对");
while (pop.Count > 0 && pop.Pop() > 0) codeTree.Pop();
return ret;
}
#region htmlSyntax
private static string htmlSyntax(string tplcode, int num) {
while (num-- > 0) {
string[] arr = _reg_syntax.Split(tplcode);
if (arr.Length == 1) break;
for (int a = 1; a < arr.Length; a += 4) {
string tag = string.Concat('<', arr[a]);
string end = string.Concat("</", arr[a], '>');
int fc = 1;
for (int b = a; fc > 0 && b < arr.Length; b += 4) {
if (b > a && arr[a].ToLower() == arr[b].ToLower()) fc++;
int bpos = 0;
while (true) {
int fa = arr[b + 3].IndexOf(tag, bpos);
int fb = arr[b + 3].IndexOf(end, bpos);
if (b == a) {
var z = arr[b + 3].IndexOf("/>");
if ((fb == -1 || z < fb) && z != -1) {
var y = arr[b + 3].Substring(0, z + 2);
if (_reg_htmltag.IsMatch(y) == false)
fb = z - end.Length + 2;
}
}
if (fa == -1 && fb == -1) break;
if (fa != -1 && (fa < fb || fb == -1)) {
fc++;
bpos = fa + tag.Length;
continue;
}
if (fb != -1) fc--;
if (fc <= 0) {
var a1 = arr[a + 1];
var end3 = string.Concat("{/", a1, "}");
if (a1.ToLower() == "else") {
if (_reg_blank.Replace(arr[a - 4 + 3], "").EndsWith("{/if}", StringComparison.CurrentCultureIgnoreCase) == true) {
var idx = arr[a - 4 + 3].IndexOf("{/if}");
arr[a - 4 + 3] = string.Concat(arr[a - 4 + 3].Substring(0, idx), arr[a - 4 + 3].Substring(idx + 5));
//如果 @else="有条件内容",则变换成 elseif 条件内容
if (_reg_blank.Replace(arr[a + 2], "").Length > 0) a1 = "elseif";
end3 = "{/if}";
} else {
arr[a] = string.Concat("指令 @", arr[a + 1], "='", arr[a + 2], "' 没紧接着 if/else 指令之后,无效. <", arr[a]);
arr[a + 1] = arr[a + 2] = string.Empty;
}
}
if (arr[a + 1].Length > 0) {
if (_reg_blank.Replace(arr[a + 2], "").Length > 0 || a1.ToLower() == "else") {
arr[b + 3] = string.Concat(arr[b + 3].Substring(0, fb + end.Length), end3, arr[b + 3].Substring(fb + end.Length));
arr[a] = string.Concat("{", a1, " ", arr[a + 2], "}<", arr[a]);
arr[a + 1] = arr[a + 2] = string.Empty;
} else {
arr[a] = string.Concat('<', arr[a]);
arr[a + 1] = arr[a + 2] = string.Empty;
}
}
break;
}
bpos = fb + end.Length;
}
}
if (fc > 0) {
arr[a] = string.Concat("不严谨的html格式,请检查 ", arr[a], " 的结束标签, @", arr[a + 1], "='", arr[a + 2], "' 指令无效. <", arr[a]);
arr[a + 1] = arr[a + 2] = string.Empty;
}
}
if (arr.Length > 0) tplcode = string.Join(string.Empty, arr);
}
return tplcode;
}
#endregion
#region Complie
private static ITemplateOutput Complie(string cscode, string typename) {
var assemly = _compiler.Value.CompileCode(cscode);
var type = assemly.DefinedTypes.Where(a => a.FullName.EndsWith(typename)).FirstOrDefault();
return Activator.CreateInstance(type) as ITemplateOutput;
}
internal static Lazy<CSScriptLib.RoslynEvaluator> _compiler = new Lazy<CSScriptLib.RoslynEvaluator>(() => {
//var dlls = Directory.GetFiles(Directory.GetParent(Type.GetType("IFreeSql, FreeSql").Assembly.Location).FullName, "*.dll");
var compiler = new CSScriptLib.RoslynEvaluator();
compiler.DisableReferencingFromCode = false;
//compiler.DebugBuild = true;
//foreach (var dll in dlls) {
// Console.WriteLine(dll);
// var ass = Assembly.LoadFile(dll);
// compiler.ReferenceAssembly(ass);
//}
compiler
.ReferenceAssemblyOf<IFreeSql>()
.ReferenceDomainAssemblies();
return compiler;
});
#endregion
#region Utils
public class Utils {
public static string ReplaceSingleQuote(object exp) {
//将 ' 转换成 "
string exp2 = string.Concat(exp);
int quote_pos = -1;
while (true) {
int first_pos = quote_pos = exp2.IndexOf('\'', quote_pos + 1);
if (quote_pos == -1) break;
while (true) {
quote_pos = exp2.IndexOf('\'', quote_pos + 1);
if (quote_pos == -1) break;
int r_cout = 0;
for (int p = 1; true; p++) {
if (exp2[quote_pos - p] == '\\') r_cout++;
else break;
}
if (r_cout % 2 == 0/* && quote_pos - first_pos > 2*/) {
string str1 = exp2.Substring(0, first_pos);
string str2 = exp2.Substring(first_pos + 1, quote_pos - first_pos - 1);
string str3 = exp2.Substring(quote_pos + 1);
string str4 = str2.Replace("\"", "\\\"");
quote_pos += str4.Length - str2.Length;
exp2 = string.Concat(str1, "\"", str4, "\"", str3);
break;
}
}
if (quote_pos == -1) break;
}
return exp2;
}
public static string GetConstString(object obj) {
return string.Concat(obj)
.Replace("\\", "\\\\")
.Replace("\"", "\\\"")
.Replace("\r", "\\r")
.Replace("\n", "\\n");
}
public static string ReadTextFile(string path) {
byte[] bytes = ReadFile(path);
return Encoding.UTF8.GetString(bytes).TrimStart((char)65279);
}
public static byte[] ReadFile(string path) {
if (File.Exists(path)) {
string destFileName = Path.GetTempFileName();
File.Copy(path, destFileName, true);
int read = 0;
byte[] data = new byte[1024];
using (MemoryStream ms = new MemoryStream()) {
using (FileStream fs = new FileStream(destFileName, FileMode.OpenOrCreate, FileAccess.Read)) {
do {
read = fs.Read(data, 0, data.Length);
if (read <= 0) break;
ms.Write(data, 0, read);
} while (true);
}
File.Delete(destFileName);
data = ms.ToArray();
}
return data;
}
return new byte[] { };
}
public static string TranslateUrl(string url) {
return TranslateUrl(url, null);
}
public static string TranslateUrl(string url, string baseDir) {
if (string.IsNullOrEmpty(baseDir))
{
baseDir = AppContext.BaseDirectory + "/";
if (url.StartsWith(AppContext.BaseDirectory)) url = url.Substring(AppContext.BaseDirectory.Length).TrimStart('/');
}
if (string.IsNullOrEmpty(url)) return Path.GetDirectoryName(baseDir);
if (url.StartsWith("~/")) url = url.Substring(1);
if (url.StartsWith("/")) return Path.GetFullPath(Path.Combine(Path.GetDirectoryName(baseDir), url.TrimStart('/')));
if (url.StartsWith("\\")) return Path.GetFullPath(Path.Combine(Path.GetDirectoryName(baseDir), url.TrimStart('\\')));
if (url.IndexOf(":\\") != -1) return url;
return Path.GetFullPath(Path.Combine(Path.GetDirectoryName(baseDir), url));
}
}
#endregion
}
}
|
294coder/Efficient-MIF
| 2,035
|
Pansharpening_Hyper_SR_Matlab_Test_Package/Quality_Indices/SCC.m
|
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Description:
% spatial Correlation Coefficient (sCC).
%
% Interface:
% [sCC,SCCMap] = SCC(I_F,I_GT)
%
% Inputs:
% I_F: Fused image;
% I_GT: Ground-truth image.
%
% Outputs:
% sCC: spatial correlation coefficient;
% SCCMap: Image of sCC values.
%
% Reference:
% [Vivone15] G. Vivone, L. Alparone, J. Chanussot, M. Dalla Mura, A. Garzelli, G. Licciardi, R. Restaino, and L. Wald, A Critical Comparison Among Pansharpening Algorithms,
% IEEE Transaction on Geoscience and Remote Sensing, vol. 53, no. 5, pp. 2565-2586, May 2015.
% [Vivone20] G. Vivone, M. Dalla Mura, A. Garzelli, R. Restaino, G. Scarpa, M.O. Ulfarsson, L. Alparone, and J. Chanussot, "A New Benchmark Based on Recent Advances in Multispectral Pansharpening: Revisiting pansharpening with classical and emerging pansharpening methods",
% IEEE Geoscience and Remote Sensing Magazine, doi: 10.1109/MGRS.2020.3019315.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [sCC,SCCMap]=SCC(I_F,I_GT)
Im_Lap_F = zeros(size(I_F,1)-2,size(I_F,2)-2,size(I_F,3));
for idim=1:size(I_F,3)
Im_Lap_F_y= imfilter(I_F(2:end-1,2:end-1,idim),fspecial('sobel'));
Im_Lap_F_x= imfilter(I_F(2:end-1,2:end-1,idim),fspecial('sobel')');
Im_Lap_F(:,:,idim) = sqrt(Im_Lap_F_y.^2+Im_Lap_F_x.^2);
end
Im_Lap_GT = zeros(size(I_GT,1)-2,size(I_GT,2)-2,size(I_GT,3));
for idim=1:size(I_GT,3)
Im_Lap_GT_y= imfilter(I_GT(2:end-1,2:end-1,idim),fspecial('sobel'));
Im_Lap_GT_x= imfilter(I_GT(2:end-1,2:end-1,idim),fspecial('sobel')');
Im_Lap_GT(:,:,idim) = sqrt(Im_Lap_GT_y.^2+Im_Lap_GT_x.^2);
end
sCC=sum(sum(sum(Im_Lap_F.*Im_Lap_GT)));
sCC = sCC/sqrt(sum(Im_Lap_F(:).^2));
sCC = sCC/sqrt(sum(Im_Lap_GT(:).^2));
SCCMap=sum(Im_Lap_F.*Im_Lap_GT,3)/sqrt(sum(Im_Lap_GT(:).^2))...
/sqrt(sum(Im_Lap_GT(:).^2));
end
|
294coder/Efficient-MIF
| 3,286
|
Pansharpening_Hyper_SR_Matlab_Test_Package/Quality_Indices/D_lambda.m
|
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Description:
% Quality with No Reference (QNR). Spectral distortion index.
%
% Interface:
% D_lambda_index = D_lambda(I_F,I_MS,I_MS_LR,S,ratio,p)
%
% Inputs:
% I_F: Pansharpened image;
% I_MS: MS image resampled to panchromatic scale;
% I_MS_LR: Original MS image;
% S: Block size (optional); Default value: 32;
% ratio: Resolution ratio;
% p: Exponent value (optional); Default value: p = 1.
%
% Outputs:
% D_lambda_index: D_lambda index.
%
% References:
% [Alparone08] L. Alparone, B. Aiazzi, S. Baronti, A. Garzelli, F. Nencini, and M. Selva, "Multispectral and panchromatic data fusion assessment without reference,"
% Photogrammetric Engineering and Remote Sensing, vol. 74, no. 2, pp. 193200, February 2008.
% [Vivone14] G. Vivone, L. Alparone, J. Chanussot, M. Dalla Mura, A. Garzelli, G. Licciardi, R. Restaino, and L. Wald, A Critical Comparison Among Pansharpening Algorithms,
% IEEE Transaction on Geoscience and Remote Sensing, 2014. (Accepted)
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function D_lambda_index = D_lambda(I_F,I_MS,I_MS_LR,S,ratio,p)
flag_orig_paper = 0; % if 0, Toolbox 1.0, otherwise, original QNR paper
if (size(I_F) ~= size(I_MS))
error('The two input images must have the same dimensions')
end
[N,M,Nb] = size(I_F);
if (rem(N,S) ~= 0)
error('The number of rows must be multiple of the block size')
end
if (rem(M,S) ~= 0)
error('The number of columns must be multiple of the block size')
end
D_lambda_index = 0;
for i = 1:Nb-1
for j = i+1:Nb
if flag_orig_paper == 0
%%%%%%% Opt. 1 (as toolbox 1.0)
band1 = I_MS(:,:,i);
band2 = I_MS(:,:,j);
fun_uqi = @(bs) uqi(bs.data,...
band2(bs.location(1):bs.location(1)+S-1,...
bs.location(2):bs.location(2)+S-1));
Qmap_exp = blockproc(band1,[S S],fun_uqi);
else
%%%%%%% Opt. 2 (as paper QNR)
band1 = I_MS_LR(:,:,i);
band2 = I_MS_LR(:,:,j);
fun_uqi = @(bs) uqi(bs.data,...
band2(bs.location(1):bs.location(1)+S/ratio-1,...
bs.location(2):bs.location(2)+S/ratio-1));
Qmap_exp = blockproc(band1,[S/ratio S/ratio],fun_uqi);
end
Q_exp = mean2(Qmap_exp);
band1 = I_F(:,:,i);
band2 = I_F(:,:,j);
fun_uqi = @(bs) uqi(bs.data,...
band2(bs.location(1):bs.location(1)+S-1,...
bs.location(2):bs.location(2)+S-1));
Qmap_fused = blockproc(band1,[S S],fun_uqi);
Q_fused = mean2(Qmap_fused);
D_lambda_index = D_lambda_index + abs(Q_fused-Q_exp)^p;
end
end
s = ((Nb^2)-Nb)/2;
D_lambda_index = (D_lambda_index/s)^(1/p);
end
%%%%%%% Q-index on x and y images
function Q = uqi(x,y)
x = double(x(:));
y = double(y(:));
mx = mean(x);
my = mean(y);
C = cov(x,y);
Q = 4 * C(1,2) * mx * my / (C(1,1)+C(2,2)) / (mx^2 + my^2);
end
|
294coder/Efficient-MIF
| 4,063
|
Pansharpening_Hyper_SR_Matlab_Test_Package/Quality_Indices/img_qi.m
|
function [quality, quality_map] = img_qi(img1, img2, block_size)
%========================================================================
%
%Copyright (c) 2001 The University of Texas at Austin
%All Rights Reserved.
%
%This program is free software; you can redistribute it and/or modify
%it under the terms of the GNU General Public License as published by
%the Free Software Foundation; either version 2 of the License, or
%(at your option) any later version.
%
%This program is distributed in the hope that it will be useful,
%but WITHOUT ANY WARRANTY; without even the implied warranty of
%MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
%GNU General Public License for more details.
%
%The GNU Public License is available in the file LICENSE, or you
%can write to the Free Software Foundation, Inc., 59 Temple Place -
%Suite 330, Boston, MA 02111-1307, USA, or you can find it on the
%World Wide Web at http://www.fsf.org.
%
%Author : Zhou Wang
%Version : 1.0
%
%The authors are with the Laboratory for Image and Video Engineering
%(LIVE), Department of Electrical and Computer Engineering, The
%University of Texas at Austin, Austin, TX.
%
%Kindly report any suggestions or corrections to [email protected]
%
%Acknowledgement:
%The author would like to thank Mr. Umesh Rajashekar, the Matlab master
%in our lab, for spending his precious time and giving his kind help
%on writing this program. Without his help, this program would not
%achieve its current efficiency.
%
%========================================================================
%
%This is an efficient implementation of the algorithm for calculating
%the universal image quality index proposed by Zhou Wang and Alan C.
%Bovik. Please refer to the paper "A Universal Image Quality Index"
%by Zhou Wang and Alan C. Bovik, published in IEEE Signal Processing
%Letters, 2001. In order to run this function, you must have Matlab's
%Image Processing Toobox.
%
%Input : an original image and a test image of the same size
%Output: (1) an overall quality index of the test image, with a value
% range of [-1, 1].
% (2) a quality map of the test image. The map has a smaller
% size than the input images. The actual size is
% img_size - BLOCK_SIZE + 1.
%
%Usage:
%
%1. Load the original and the test images into two matrices
% (say img1 and img2)
%
%2. Run this function in one of the two ways:
%
% % Choice 1 (suggested):
% [qi qi_map] = img_qi(img1, img2);
%
% % Choice 2:
% [qi qi_map] = img_qi(img1, img2, BLOCK_SIZE);
%
% The default BLOCK_SIZE is 8 (Choice 1). Otherwise, you can specify
% it by yourself (Choice 2).
%
%3. See the results:
%
% qi %Gives the over quality index.
% imshow((qi_map+1)/2) %Shows the quality map as an image.
%
%========================================================================
if (nargin == 1 | nargin > 3)
quality = -Inf;
quality_map = -1*ones(size(img1));
return;
end
if (size(img1) ~= size(img2))
quality = -Inf;
quality_map = -1*ones(size(img1));
return;
end
if (nargin == 2)
block_size = 8;
end
N = block_size.^2;
sum2_filter = ones(block_size);
img1_sq = img1.*img1;
img2_sq = img2.*img2;
img12 = img1.*img2;
img1_sum = filter2(sum2_filter, img1, 'valid');
img2_sum = filter2(sum2_filter, img2, 'valid');
img1_sq_sum = filter2(sum2_filter, img1_sq, 'valid');
img2_sq_sum = filter2(sum2_filter, img2_sq, 'valid');
img12_sum = filter2(sum2_filter, img12, 'valid');
img12_sum_mul = img1_sum.*img2_sum;
img12_sq_sum_mul = img1_sum.*img1_sum + img2_sum.*img2_sum;
numerator = 4*(N*img12_sum - img12_sum_mul).*img12_sum_mul;
denominator1 = N*(img1_sq_sum + img2_sq_sum) - img12_sq_sum_mul;
denominator = denominator1.*img12_sq_sum_mul;
quality_map = ones(size(denominator));
index = (denominator1 == 0) & (img12_sq_sum_mul ~= 0);
quality_map(index) = 2*img12_sum_mul(index)./img12_sq_sum_mul(index);
index = (denominator ~= 0);
quality_map(index) = numerator(index)./denominator(index);
quality = mean2(quality_map);
|
294coder/Efficient-MIF
| 1,318
|
Pansharpening_Hyper_SR_Matlab_Test_Package/Quality_Indices/Q.m
|
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Description:
% Q/SSIM averaged on all bands.
%
% Interface:
% Q_avg = Q(I1,I2,L)
%
% Inputs:
% I1: First multispectral image;
% I2: Second multispectral image;
% L: Radiometric resolution.
%
% Outputs:
% Q_avg: Q index averaged on all bands.
%
% References:
% [Wang02] Z. Wang and A. C. Bovik, A universal image quality index, IEEE Signal Processing Letters, vol. 9, no. 3, pp. 8184, March 2002.
% [Vivone20] G. Vivone, M. Dalla Mura, A. Garzelli, R. Restaino, G. Scarpa, M.O. Ulfarsson, L. Alparone, and J. Chanussot, "A New Benchmark Based on Recent Advances in Multispectral Pansharpening: Revisiting pansharpening with classical and emerging pansharpening methods",
% IEEE Geoscience and Remote Sensing Magazine, doi: 10.1109/MGRS.2020.3019315.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function Q_avg = Q(I1,I2,L)
Q_orig = zeros(1,size(I1,3));
for idim=1:size(I1,3),
% Q_orig(idim) = ssim(I_GT(:,:,idim),I1U(:,:,idim), [0.01 0.03],fspecial('gaussian', 11, 1.5), L);
Q_orig(idim) = img_qi(I1(:,:,idim),I2(:,:,idim), 32);
end
Q_avg = mean(Q_orig);
end
|
2881099/FreeSql.AdminLTE
| 3,701
|
FreeSql.AdminLTE.Preview/Template/TemplateGenerator.cs
|
using FreeSql.DatabaseModel;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
namespace FreeSql.Template
{
public class TemplateGenerator {
public void Build(IDbFirst dbfirst, string templateDirectory, string outputDirectory, params string[] database) {
if (dbfirst == null) throw new ArgumentException("dbfirst 参数不能为 null");
if (string.IsNullOrEmpty(templateDirectory) || Directory.Exists(templateDirectory) == false) throw new ArgumentException("templateDirectory 目录不存在");
if (string.IsNullOrEmpty(templateDirectory)) throw new ArgumentException("outputDirectory 不能为 null");
if (database == null || database.Any() == false) throw new ArgumentException("database 参数不能为空");
if (Directory.Exists(outputDirectory) == false) Directory.CreateDirectory(outputDirectory);
templateDirectory = new DirectoryInfo(templateDirectory).FullName;
outputDirectory = new DirectoryInfo(outputDirectory).FullName;
if (templateDirectory.IndexOf(outputDirectory, StringComparison.CurrentCultureIgnoreCase) != -1) throw new ArgumentException("outputDirectory 目录不能设置在 templateDirectory 目录内");
var tables = dbfirst.GetTablesByDatabase(database);
var tpl = new TemplateEngin(templateDirectory, "FreeSql", "FreeSql.DatabaseModel");
BuildEachDirectory(templateDirectory, outputDirectory, tpl, dbfirst, tables);
tpl.Dispose();
}
void BuildEachDirectory(string templateDirectory, string outputDirectory, TemplateEngin tpl, IDbFirst dbfirst, List<DbTableInfo> tables) {
if (Directory.Exists(outputDirectory) == false) Directory.CreateDirectory(outputDirectory);
var files = Directory.GetFiles(templateDirectory);
foreach (var file in files) {
var fi = new FileInfo(file);
if (string.Compare(fi.Extension, ".FreeSql", true) == 0) {
var outputExtension = "." + fi.Name.Split('.')[1];
if (fi.Name.StartsWith("for-table.")) {
foreach (var table in tables) {
var result = tpl.RenderFile(file, new Dictionary<string, object>() { { "table", table }, { "dbfirst", dbfirst } });
if (result.EndsWith("return;")) continue;
var outputName = table.Name + outputExtension;
var mcls = Regex.Match(result, @"\s+class\s+(\w+)");
if (mcls.Success) outputName = mcls.Groups[1].Value + outputExtension;
var outputStream = Encoding.UTF8.GetBytes(result);
var fullname = outputDirectory + "/" + outputName;
if (File.Exists(fullname)) File.Delete(fullname);
using (var outfs = File.Open(fullname, FileMode.OpenOrCreate, FileAccess.Write)) {
outfs.Write(outputStream, 0, outputStream.Length);
outfs.Close();
}
}
continue;
} else {
var result = tpl.RenderFile(file, new Dictionary<string, object>() { { "tables", tables }, { "dbfirst", dbfirst } });
var outputName = fi.Name;
var mcls = Regex.Match(result, @"\s+class\s+(\w+)");
if (mcls.Success) outputName = mcls.Groups[1].Value + outputExtension;
var outputStream = Encoding.UTF8.GetBytes(result);
var fullname = outputDirectory + "/" + outputName;
if (File.Exists(fullname)) File.Delete(fullname);
using (var outfs = File.Open(fullname, FileMode.OpenOrCreate, FileAccess.Write)) {
outfs.Write(outputStream, 0, outputStream.Length);
outfs.Close();
}
}
}
File.Copy(file, outputDirectory + file.Replace(templateDirectory, ""), true);
}
var dirs = Directory.GetDirectories(templateDirectory);
foreach(var dir in dirs) {
BuildEachDirectory(dir, outputDirectory + dir.Replace(templateDirectory, ""), tpl, dbfirst, tables);
}
}
}
}
|
2977094657/BiliHistoryFrontend
| 7,515
|
src/components/tailwind/FavoriteDialog.vue
|
<template>
<van-dialog
v-model:show="visible"
:title="title"
:width="350"
class="favorite-dialog"
show-cancel-button
:confirm-button-text="confirmText"
:cancel-button-text="cancelText"
@confirm="handleConfirm"
@cancel="handleCancel"
>
<div class="p-5">
<div v-if="loading" class="flex justify-center py-4">
<div class="inline-flex items-center">
<svg class="animate-spin -ml-1 mr-3 h-5 w-5 text-[#fb7299]" fill="none" viewBox="0 0 24 24">
<circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
<path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
</svg>
<span>加载中...</span>
</div>
</div>
<div v-else-if="favorites.length === 0" class="text-center py-4">
<p class="text-gray-500">暂无收藏夹</p>
<div class="mt-3">
<button
class="px-3 py-1.5 text-sm bg-[#fb7299] text-white rounded-md hover:bg-[#fb7299]/90 transition-colors"
@click="openLoginDialog"
>
登录账号
</button>
</div>
</div>
<div v-else>
<div v-if="videoInfo" class="mb-3">
<p class="text-sm text-gray-700 truncate">
<span v-if="videoInfo.isBatch">批量收藏:{{ videoInfo.selectedCount }}个视频</span>
<span v-else>收藏视频:{{ videoInfo.title }}</span>
</p>
</div>
<div class="max-h-60 overflow-y-auto pr-2 space-y-2">
<div
v-for="folder in favorites"
:key="folder.id"
class="flex items-center p-2 rounded-md hover:bg-gray-100 transition-colors"
>
<input
type="checkbox"
:id="`folder-${folder.id}`"
:value="folder.id"
v-model="selectedFolders"
class="w-4 h-4 text-[#fb7299] border-gray-300 rounded focus:ring-[#fb7299]"
/>
<label :for="`folder-${folder.id}`" class="ml-2 flex-1 cursor-pointer">
<div class="flex items-center">
<span class="text-sm font-medium text-gray-700">{{ folder.title }}</span>
<span class="ml-1 text-xs text-gray-500">({{ folder.media_count }})</span>
</div>
</label>
</div>
</div>
</div>
</div>
</van-dialog>
<!-- 登录对话框 -->
<Teleport to="body">
<LoginDialog
v-model:show="showLoginDialog"
@login-success="handleLoginSuccess"
/>
</Teleport>
</template>
<script setup>
import { ref, defineProps, defineEmits, computed, watch, onMounted } from 'vue'
import { getCreatedFavoriteFolders, favoriteResource, batchFavoriteResource, localBatchFavoriteResource } from '../../api/api.js'
import { showNotify } from 'vant'
import LoginDialog from './LoginDialog.vue'
const props = defineProps({
modelValue: {
type: Boolean,
default: false
},
videoInfo: {
type: Object,
default: () => ({})
}
})
const emit = defineEmits(['update:modelValue', 'favoriteDone'])
// 对话框状态
const visible = computed({
get: () => props.modelValue,
set: (val) => emit('update:modelValue', val)
})
// 组件数据
const loading = ref(false)
const favorites = ref([])
const selectedFolders = ref([])
const showLoginDialog = ref(false)
const isLoggedIn = ref(false)
// 对话框文本
const title = computed(() => '选择收藏夹')
const confirmText = computed(() => '确认收藏')
const cancelText = computed(() => '取消')
// 加载收藏夹列表
const loadFavorites = async () => {
loading.value = true
try {
const response = await getCreatedFavoriteFolders()
if (response.data.status === 'success') {
favorites.value = response.data.data.list || []
isLoggedIn.value = true
} else {
// 没有权限或未登录
isLoggedIn.value = false
favorites.value = []
}
} catch (error) {
console.error('获取收藏夹列表失败:', error)
showNotify({ type: 'danger', message: '获取收藏夹列表失败' })
} finally {
loading.value = false
}
}
// 处理确认按钮
const handleConfirm = async () => {
if (selectedFolders.value.length === 0) {
showNotify({ type: 'warning', message: '请至少选择一个收藏夹' })
return
}
loading.value = true
try {
let response;
// 判断是批量收藏还是单个收藏
if (props.videoInfo.isBatch && props.videoInfo.batchIds) {
// 批量收藏
const requestParams = {
rids: props.videoInfo.batchIds,
add_media_ids: selectedFolders.value.join(',')
};
// 先远程操作,然后本地同步
response = await batchFavoriteResource(requestParams);
// 成功后进行本地同步(不展示给用户)
if (response.data.status === 'success') {
try {
await localBatchFavoriteResource({
rids: props.videoInfo.batchIds,
add_media_ids: selectedFolders.value.join(','),
operation_type: 'local' // 只在本地操作,不需要再同步远程
});
} catch (syncError) {
console.error('本地同步失败,但不影响用户体验:', syncError);
}
showNotify({ type: 'success', message: `成功收藏${props.videoInfo.selectedCount}个视频` });
emit('favoriteDone', {
success: true,
videoInfo: props.videoInfo,
folders: selectedFolders.value,
isBatch: true
});
visible.value = false;
} else {
throw new Error(response.data.message || '批量收藏失败');
}
} else {
// 单个视频收藏
// 获取视频ID,适配不同的属性名(aid或avid)
const videoId = props.videoInfo?.aid || props.videoInfo?.avid || (props.videoInfo?.business === 'archive' ? props.videoInfo?.oid : null);
if (!props.videoInfo || !videoId) {
showNotify({ type: 'warning', message: '视频信息不完整,无法收藏' });
return;
}
// 先远程操作
response = await favoriteResource({
rid: videoId,
add_media_ids: selectedFolders.value.join(',')
});
if (response.data.status === 'success') {
// 成功后进行本地同步(不展示给用户)
try {
await localBatchFavoriteResource({
rids: videoId.toString(),
add_media_ids: selectedFolders.value.join(','),
operation_type: 'local' // 只在本地操作,不需要再同步远程
});
} catch (syncError) {
console.error('本地同步失败,但不影响用户体验:', syncError);
}
showNotify({ type: 'success', message: '收藏成功' });
emit('favoriteDone', {
success: true,
videoInfo: props.videoInfo,
folders: selectedFolders.value
});
visible.value = false;
} else {
throw new Error(response.data.message || '收藏失败');
}
}
} catch (error) {
console.error('收藏视频失败:', error);
showNotify({ type: 'danger', message: '收藏失败: ' + (error.message || '未知错误') });
} finally {
loading.value = false;
}
}
// 处理取消按钮
const handleCancel = () => {
visible.value = false
}
// 打开登录对话框
const openLoginDialog = () => {
showLoginDialog.value = true
}
// 登录成功回调
const handleLoginSuccess = () => {
showNotify({ type: 'success', message: '登录成功' })
loadFavorites()
}
// 监听对话框显示状态变化
watch(() => visible.value, (newVal) => {
if (newVal) {
selectedFolders.value = []
loadFavorites()
}
})
onMounted(() => {
if (visible.value) {
loadFavorites()
}
})
</script>
<style scoped>
.favorite-dialog {
border-radius: 8px;
overflow: hidden;
}
</style>
|
2977094657/BiliHistoryFrontend
| 31,610
|
src/components/tailwind/VideoRecord.vue
|
<template>
<!-- 每条记录的容器 -->
<div
class="mx-auto max-w-2xl cursor-pointer border-b border-gray-200 transition-all duration-200 ease-in-out sm:px-4 lg:max-w-4xl lg:px-0 relative"
:class="{
'group': !showDownloadDialog,
'border-[#fb7299] bg-[#fff9fb] ring-1 ring-[#fb7299]/20': isBatchMode && isSelected,
'hover:border-[#fb7299] hover:bg-[#f5f5f5] hover:shadow-md': !isBatchMode || !isSelected
}"
@click="handleClick"
>
<!-- 内层容器 -->
<div class="p-2">
<!-- 当类型为文章或文集时,图片铺满整行,标题在上方 -->
<div v-if="record.business === 'article-list' || record.business === 'article'">
<!-- 标题在封面图片上方 -->
<div class="mb-2">
<div
class="line-clamp-2 text-gray-900 lm:text-sm lg:font-semibold"
v-html="isPrivacyMode ? '******' : highlightedTitle"
:class="{ 'blur-sm': isPrivacyMode }"
></div>
</div>
<!-- 封面图片,铺满整行 -->
<div class="relative h-28 w-full overflow-hidden rounded-lg">
<!-- 删除按钮 -->
<div v-if="!isBatchMode"
class="absolute right-0 top-0 z-20 hidden group-hover:flex flex-row items-center justify-end pt-1 pr-1">
<div class="flex items-center justify-end space-x-2">
<!-- 下载按钮 - 只对视频类型显示 -->
<div v-if="record.business === 'archive'"
class="flex items-center justify-center w-7 h-7 bg-[#7d7c75]/60 backdrop-blur-sm hover:bg-[#7d7c75]/80 rounded-md cursor-pointer transition-all duration-200"
@click.stop.prevent="handleDownload"
title="下载视频">
<svg class="w-4 h-4 text-white" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-4l-4 4m0 0l-4-4m4 4V4" />
</svg>
</div>
<!-- 收藏按钮 - 不对直播类型显示 -->
<div v-if="record.business !== 'live'"
class="flex items-center justify-center w-7 h-7 bg-[#7d7c75]/60 backdrop-blur-sm hover:bg-[#7d7c75]/80 rounded-md cursor-pointer transition-all duration-200"
@click.stop.prevent="handleFavorite"
title="收藏视频">
<svg class="w-4 h-4" :class="isVideoFavorited ? 'text-yellow-400' : 'text-white'" :fill="isVideoFavorited ? 'currentColor' : 'none'" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 5a2 2 0 012-2h10a2 2 0 012 2v16l-7-3.5L5 21V5z" />
</svg>
</div>
<!-- 删除按钮 -->
<div class="flex items-center justify-center w-7 h-7 bg-[#7d7c75]/60 backdrop-blur-sm hover:bg-[#7d7c75]/80 rounded-md cursor-pointer transition-all duration-200"
@click.stop="handleDelete"
title="删除记录">
<svg class="w-4 h-4 text-white" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16" />
</svg>
</div>
<!-- 详情按钮 - 只对普通视频类型显示 -->
<div v-if="record.business === 'archive'"
class="flex items-center justify-center w-7 h-7 bg-[#7d7c75]/60 backdrop-blur-sm hover:bg-[#7d7c75]/80 rounded-md cursor-pointer transition-all duration-200"
@click.stop="showDetailDialog = true"
title="查看详情">
<svg class="w-4 h-4 text-white" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
</svg>
</div>
</div>
</div>
<!-- 多选框 -->
<div v-if="isBatchMode"
class="absolute left-2 top-2 z-10"
@click.stop="$emit('toggle-selection', record)">
<div class="w-5 h-5 rounded border-2 flex items-center justify-center"
:class="isSelected ? 'bg-[#fb7299] border-[#fb7299]' : 'border-white bg-black/20'">
<svg v-if="isSelected" class="w-3 h-3 text-white" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="3" d="M5 13l4 4L19 7" />
</svg>
</div>
</div>
<!-- 批量模式下的收藏状态图标 - 不对直播类型显示 -->
<div v-if="isBatchMode && record.business !== 'live'"
class="absolute right-2 top-2 z-10">
<div class="flex items-center justify-center w-6 h-6 rounded-full bg-black/40 backdrop-blur-sm">
<svg class="w-4 h-4" :class="isVideoFavorited ? 'text-yellow-400' : 'text-white'" :fill="isVideoFavorited ? 'currentColor' : 'none'" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 5a2 2 0 012-2h10a2 2 0 012 2v16l-7-3.5L5 21V5z" />
</svg>
</div>
</div>
<!-- 已下载标识 -->
<div v-if="isDownloaded && record.business === 'archive'"
class="absolute left-0 top-0 z-10">
<div class="bg-gradient-to-r from-[#fb7299] to-[#fc9b7a] text-white font-semibold px-2 py-0.5 text-xs flex items-center space-x-1.5 rounded-br-md shadow-md">
<svg class="w-3 h-3" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-4l-4 4m0 0l-4-4m4 4V4" />
</svg>
<span>已下载</span>
</div>
</div>
<!-- 收藏状态标识 - 不对直播类型显示 -->
<div v-if="isVideoFavorited && record.business !== 'live'"
class="absolute right-0 top-0 z-10">
<div class="bg-gradient-to-r from-amber-500 to-yellow-400 text-white font-semibold px-2 py-0.5 text-xs flex items-center space-x-1.5 rounded-bl-md shadow-md">
<svg class="w-3 h-3" fill="currentColor" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 5a2 2 0 012-2h10a2 2 0 012 2v16l-7-3.5L5 21V5z" />
</svg>
<span>已收藏</span>
</div>
</div>
<img
:src="normalizeImageUrl(record.cover || record.covers[0])"
class="h-full w-full object-cover transition-all duration-300"
:class="{ 'blur-md': isPrivacyMode }"
alt=""
/>
<!-- 右上角的类型角标 -->
<div
v-if="record.badge"
class="absolute right-1 top-1 rounded bg-[#FF6699] px-1 py-0.5 text-[10px] font-semibold text-white"
>
{{ record.badge }}
</div>
</div>
<!-- 文章类型:作者信息、观看设备、时间放在封面图片下方 -->
<div class="mt-2 flex items-center justify-between text-sm text-[#99a2aa] lm:text-xs">
<!-- 左侧:仅当类型不是剧集或课程时,显示作者头像和名字 -->
<div
v-if="record.business !== 'cheese' && record.business !== 'pgc'"
class="flex items-center space-x-2"
@click.stop
>
<img
:src="normalizeImageUrl(record.author_face)"
alt="author"
class="h-4 w-4 cursor-pointer rounded-full transition-all duration-300 hover:scale-110 lg:h-8 lg:w-8"
:class="{ 'blur-md': isPrivacyMode }"
@click="handleAuthorClick"
:title="isPrivacyMode ? '隐私模式已开启' : `访问 ${record.author_name} 的个人空间`"
/>
<p
class="cursor-pointer transition-colors hover:text-[#FF6699]"
@click="handleAuthorClick"
:title="isPrivacyMode ? '隐私模式已开启' : `访问 ${record.author_name} 的个人空间`"
v-html="isPrivacyMode ? '******' : highlightedAuthorName"
></p>
</div>
<!-- 右侧:设备和时间信息 -->
<div class="flex items-center space-x-2">
<img
v-if="record.dt === 1 || record.dt === 3 || record.dt === 5 || record.dt === 7"
src="/Mobile.svg"
alt="Mobile"
class="h-4 w-4 lg:h-8 lg:w-8"
/>
<img
v-else-if="record.dt === 2 || record.dt === 33"
src="/PC.svg"
alt="PC"
class="h-4 w-4 lg:h-8 lg:w-8"
/>
<img
v-else-if="record.dt === 4 || record.dt === 6"
src="/Pad.svg"
alt="Pad"
class="h-4 w-4 lg:h-8 lg:w-8"
/>
<p v-else>未知设备</p>
<!-- 显示时间 -->
<span>{{ formatTimestamp(record.view_at) }}</span>
</div>
</div>
</div>
<!-- 其他类型的展示方式 -->
<div v-else class="flex space-x-2">
<!-- 封面图片区域 -->
<div class="relative h-20 w-32 overflow-hidden rounded-lg sm:h-28 sm:w-40">
<!-- 多选框 -->
<div v-if="isBatchMode"
class="absolute left-2 top-2 z-10"
@click.stop="$emit('toggle-selection', record)">
<div class="w-5 h-5 rounded border-2 flex items-center justify-center"
:class="isSelected ? 'bg-[#fb7299] border-[#fb7299]' : 'border-white bg-black/20'">
<svg v-if="isSelected" class="w-3 h-3 text-white" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="3" d="M5 13l4 4L19 7" />
</svg>
</div>
</div>
<!-- 批量模式下的收藏状态图标 - 不对直播类型显示 -->
<div v-if="isBatchMode && record.business !== 'live'"
class="absolute right-2 top-2 z-10">
<div class="flex items-center justify-center w-6 h-6 rounded-full bg-black/40 backdrop-blur-sm">
<svg class="w-4 h-4" :class="isVideoFavorited ? 'text-yellow-400' : 'text-white'" :fill="isVideoFavorited ? 'currentColor' : 'none'" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 5a2 2 0 012-2h10a2 2 0 012 2v16l-7-3.5L5 21V5z" />
</svg>
</div>
</div>
<!-- 已下载标识 -->
<div v-if="isDownloaded && record.business === 'archive'"
class="absolute left-0 top-0 z-10">
<div class="bg-gradient-to-r from-[#fb7299] to-[#fc9b7a] text-white font-semibold px-2 py-0.5 text-xs flex items-center space-x-1.5 rounded-br-md shadow-md">
<svg class="w-3 h-3" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-4l-4 4m0 0l-4-4m4 4V4" />
</svg>
<span>已下载</span>
</div>
</div>
<!-- 收藏状态标识 - 不对直播类型显示 -->
<div v-if="isVideoFavorited && record.business !== 'live'"
class="absolute right-0 top-0 z-10">
<div class="bg-gradient-to-r from-amber-500 to-yellow-400 text-white font-semibold px-2 py-0.5 text-xs flex items-center space-x-1.5 rounded-bl-md shadow-md">
<svg class="w-3 h-3" fill="currentColor" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 5a2 2 0 012-2h10a2 2 0 012 2v16l-7-3.5L5 21V5z" />
</svg>
<span>已收藏</span>
</div>
</div>
<img
v-if="record.cover"
:src="normalizeImageUrl(record.cover)"
class="h-full w-full object-cover transition-all duration-300"
:class="{ 'blur-md': isPrivacyMode }"
alt=""
/>
<div v-else>
<div v-for="(cover, index) in record.covers" :key="index" class="mb-1">
<img
:src="normalizeImageUrl(cover)"
class="h-full w-full object-cover transition-all duration-300"
:class="{ 'blur-md': isPrivacyMode }"
alt=""
/>
</div>
</div>
<!-- 右上角的类型角标 -->
<div
v-if="record.badge"
class="absolute right-1 top-1 rounded bg-[#FF6699] px-1 py-0.5 text-[10px] font-semibold text-white"
>
{{ record.badge }}
</div>
<!-- 右下角的时间进度角标和进度条,仅当不是文章时显示 -->
<div
v-if="
record.business !== 'article-list' &&
record.business !== 'article' &&
record.business !== 'live'
"
>
<div
class="absolute bottom-1 right-1 rounded bg-black/50 px-1 py-1 text-[10px] font-semibold text-white"
>
<span>{{ formatDuration(record.progress) }}</span>
<span>/</span>
<span>{{ formatDuration(record.duration) }}</span>
</div>
<div class="absolute bottom-0 left-0 h-0.5 w-full bg-black">
<div
class="h-full bg-[#FF6699]"
:style="{ width: getProgressWidth(record.progress, record.duration) }"
></div>
</div>
</div>
</div>
<!-- 右侧内容区域 -->
<div class="ml-2 flex flex-1 flex-col justify-between lm:text-sm lg:font-semibold relative">
<!-- 删除按钮 -->
<div v-if="!isBatchMode"
class="absolute right-0 top-0 z-20 hidden group-hover:flex flex-row items-center justify-end pt-1 pr-1">
<div class="flex items-center justify-end space-x-2">
<!-- 下载按钮 - 只对视频类型显示 -->
<div v-if="record.business === 'archive'"
class="flex items-center justify-center w-7 h-7 bg-[#7d7c75]/60 backdrop-blur-sm hover:bg-[#7d7c75]/80 rounded-md cursor-pointer transition-all duration-200"
@click.stop.prevent="handleDownload"
title="下载视频">
<svg class="w-4 h-4 text-white" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-4l-4 4m0 0l-4-4m4 4V4" />
</svg>
</div>
<!-- 收藏按钮 - 不对直播类型显示 -->
<div v-if="record.business !== 'live'"
class="flex items-center justify-center w-7 h-7 bg-[#7d7c75]/60 backdrop-blur-sm hover:bg-[#7d7c75]/80 rounded-md cursor-pointer transition-all duration-200"
@click.stop.prevent="handleFavorite"
title="收藏视频">
<svg class="w-4 h-4" :class="isVideoFavorited ? 'text-yellow-400' : 'text-white'" :fill="isVideoFavorited ? 'currentColor' : 'none'" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 5a2 2 0 012-2h10a2 2 0 012 2v16l-7-3.5L5 21V5z" />
</svg>
</div>
<!-- 删除按钮 -->
<div class="flex items-center justify-center w-7 h-7 bg-[#7d7c75]/60 backdrop-blur-sm hover:bg-[#7d7c75]/80 rounded-md cursor-pointer transition-all duration-200"
@click.stop="handleDelete"
title="删除记录">
<svg class="w-4 h-4 text-white" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16" />
</svg>
</div>
<!-- 详情按钮 - 只对普通视频类型显示 -->
<div v-if="record.business === 'archive'"
class="flex items-center justify-center w-7 h-7 bg-[#7d7c75]/60 backdrop-blur-sm hover:bg-[#7d7c75]/80 rounded-md cursor-pointer transition-all duration-200"
@click.stop="showDetailDialog = true"
title="查看详情">
<svg class="w-4 h-4 text-white" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
</svg>
</div>
</div>
</div>
<div class="items-center justify-between lg:flex">
<div
class="line-clamp-2 text-gray-900 lm:text-sm lg:font-semibold"
v-html="isPrivacyMode ? '******' : highlightedTitle"
:class="{ 'blur-sm': isPrivacyMode }"
></div>
</div>
<div class="flex items-center space-x-2">
<span
v-if="record.business !== 'pgc'"
class="inline-flex items-center rounded-md bg-[#f1f2f3] px-2 py-1 text-xs text-[#71767d]"
>
{{ record.tag_name }}
</span>
<!-- 备注输入框 -->
<div class="flex-1 relative group" @click.stop>
<div class="flex items-center space-x-1">
<span class="text-xs text-[#fb7299]">备注:</span>
<input
type="text"
v-model="remarkContent"
@focus="handleRemarkFocus"
@blur="handleRemarkBlur"
placeholder="添加备注..."
:disabled="isPrivacyMode"
class="flex-1 px-2 py-1 text-xs text-[#fb7299] bg-[#f8f8f8] rounded border-0 border-b border-transparent hover:border-gray-200 focus:border-[#fb7299] focus:ring-0 transition-colors duration-200 placeholder-[#fb7299]/50"
:class="{ 'blur-sm': isPrivacyMode }"
/>
<span v-if="remarkTime" class="text-xs text-gray-400">{{ formatRemarkTime(remarkTime) }}</span>
</div>
<div v-if="!remarkContent && !isPrivacyMode" class="absolute right-2 top-1/2 -translate-y-1/2 hidden group-hover:block">
<svg class="w-3 h-3 text-[#fb7299]" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z" />
</svg>
</div>
</div>
</div>
<div class="flex items-end justify-between text-sm text-[#99a2aa] lm:text-xs">
<!-- PGC内容显示long_title -->
<div v-if="record.business === 'pgc'" class="flex items-center space-x-2">
<p class="text-[#99a2aa]">{{ record.long_title }}</p>
</div>
<!-- 非PGC内容显示UP主信息 -->
<div v-else class="flex items-center space-x-2" @click.stop>
<img
:src="normalizeImageUrl(record.author_face)"
alt="author"
class="h-5 w-5 cursor-pointer rounded-full transition-all duration-300 hover:scale-110 lg:h-8 lg:w-8"
:class="{ 'blur-md': isPrivacyMode }"
@click="handleAuthorClick"
:title="isPrivacyMode ? '隐私模式已开启' : `访问 ${record.author_name} 的个人空间`"
/>
<p
class="cursor-pointer transition-colors hover:text-[#FF6699]"
@click="handleAuthorClick"
:title="isPrivacyMode ? '隐私模式已开启' : `访问 ${record.author_name} 的个人空间`"
v-html="isPrivacyMode ? '******' : highlightedAuthorName"
></p>
</div>
<div class="flex items-center space-x-2">
<img
v-if="record.dt === 1 || record.dt === 3 || record.dt === 5 || record.dt === 7"
src="/Mobile.svg"
alt="Mobile"
class="h-4 w-4 lg:h-8 lg:w-8"
/>
<img
v-else-if="record.dt === 2 || record.dt === 33"
src="/PC.svg"
alt="PC"
class="h-4 w-4 lg:h-8 lg:w-8"
/>
<img
v-else-if="record.dt === 4 || record.dt === 6"
src="/Pad.svg"
alt="Pad"
class="h-4 w-4 lg:h-8 lg:w-8"
/>
<p v-else>未知设备</p>
<!-- 显示时间 -->
<span>{{ formatTimestamp(record.view_at) }}</span>
</div>
</div>
</div>
</div>
</div>
<!-- 下载弹窗 -->
<Teleport to="body">
<DownloadDialog
v-model:show="showDownloadDialog"
:video-info="{
title: record.title,
author: record.author_name,
bvid: record.bvid,
cover: record.cover || record.covers?.[0],
cid: record.cid
}"
:is-batch-download="false"
/>
</Teleport>
<!-- 视频详情对话框 -->
<Teleport to="body">
<VideoDetailDialog
:modelValue="showDetailDialog"
@update:modelValue="showDetailDialog = $event"
:video="record"
:remarkData="remarkData"
@remark-updated="$emit('remark-updated', $event)"
/>
</Teleport>
</div>
</template>
<script setup>
import { computed, ref, onMounted, watch } from 'vue'
import { usePrivacyStore } from '../../store/privacy'
import { showDialog, showNotify } from 'vant'
import { batchDeleteHistory, updateVideoRemark, deleteBilibiliHistory } from '../../api/api'
import 'vant/es/dialog/style'
import 'vant/es/popup/style'
import 'vant/es/field/style'
import DownloadDialog from './DownloadDialog.vue'
import VideoDetailDialog from './VideoDetailDialog.vue'
import { openInBrowser } from '@/utils/openUrl.js'
import { normalizeImageUrl } from '@/utils/imageUrl.js'
const { isPrivacyMode } = usePrivacyStore()
const props = defineProps({
record: {
type: Object,
required: true
},
searchKeyword: {
type: String,
default: ''
},
searchType: {
type: String,
default: 'title'
},
isBatchMode: {
type: Boolean,
default: false
},
isSelected: {
type: Boolean,
default: false
},
remarkData: {
type: Object,
default: () => ({})
},
isDownloaded: {
type: Boolean,
default: false
},
isVideoFavorited: {
type: Boolean,
default: false
}
})
const emit = defineEmits([
'toggle-selection',
'refresh-data',
'remark-updated',
'favorite'
])
const remarkContent = ref('')
const originalRemark = ref('') // 用于存储原始备注内容
const remarkTime = ref(null)
const showDetailDialog = ref(false)
// 高亮显示匹配的文本
const highlightText = (text) => {
if (!props.searchKeyword || !text) return text
// 将搜索关键词按空格分割成数组
const keywords = props.searchKeyword.split(/\s+/).filter(k => k)
let highlightedText = text
// 对每个关键词进行高亮处理
keywords.forEach(keyword => {
const regex = new RegExp(keyword.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'), 'gi')
highlightedText = highlightedText.replace(regex, match => `<span class="text-[#FF6699]">${match}</span>`)
})
return highlightedText
}
// 获取高亮后的标题
const highlightedTitle = computed(() => {
if (!props.searchKeyword) return props.record.title
if (props.searchType === 'all' || props.searchType === 'title') {
return highlightText(props.record.title)
}
return props.record.title
})
// 获取高亮后的作者名称
const highlightedAuthorName = computed(() => {
if (!props.searchKeyword) return props.record.author_name
if (props.searchType === 'all' || props.searchType === 'author') {
return highlightText(props.record.author_name)
}
return props.record.author_name
})
// 处理点击事件
const handleClick = () => {
if (props.isBatchMode) {
emit('toggle-selection', props.record)
} else {
handleContentClick()
}
}
// 处理内容点击事件
const handleContentClick = async () => {
let url = ''
switch (props.record.business) {
case 'archive':
url = `https://www.bilibili.com/video/${props.record.bvid}`
break
case 'article':
url = `https://www.bilibili.com/read/cv${props.record.oid}`
break
case 'article-list':
url = `https://www.bilibili.com/read/readlist/rl${props.record.oid}`
break
case 'live':
url = `https://live.bilibili.com/${props.record.oid}`
break
case 'pgc':
url = props.record.uri || `https://www.bilibili.com/bangumi/play/ep${props.record.epid}`
break
case 'cheese':
url = props.record.uri || `https://www.bilibili.com/cheese/play/ep${props.record.epid}`
break
default:
console.warn('未知的业务类型:', props.record.business)
return
}
if (url) {
await openInBrowser(url)
}
}
// 处理UP主点击事件
const handleAuthorClick = async () => {
const url = `https://space.bilibili.com/${props.record.author_mid}`
await openInBrowser(url)
}
// 修改时间戳显示相关的代码
const formatTimestamp = (timestamp) => {
// 检查 timestamp 是否有效
if (!timestamp) {
console.warn('Invalid timestamp:', timestamp)
return '时间未知'
}
try {
// 将秒级时间戳转换为毫秒级
const date = new Date(timestamp * 1000)
const now = new Date()
// 检查日期是否有效
if (isNaN(date.getTime())) {
console.warn('Invalid date from timestamp:', timestamp)
return '时间未知'
}
const isToday = now.toDateString() === date.toDateString()
const isYesterday =
new Date(now.setDate(now.getDate() - 1)).toDateString() === date.toDateString()
const timeString = date.toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' })
if (isToday) {
return timeString
} else if (isYesterday) {
return `昨天 ${timeString}`
} else if (now.getFullYear() === date.getFullYear()) {
return `${date.getMonth() + 1}-${date.getDate()} ${timeString}`
} else {
return `${date.getFullYear()}-${date.getMonth() + 1}-${date.getDate()} ${timeString}`
}
} catch (error) {
console.error('Error formatting timestamp:', error)
return '时间未知'
}
}
const formatDuration = (seconds) => {
if (seconds === -1) return '已看完'
const minutes = String(Math.floor(seconds / 60)).padStart(2, '0')
const secs = String(seconds % 60).padStart(2, '0')
return `${minutes}:${secs}`
}
const getProgressWidth = (progress, duration) => {
if (progress === -1) return '100%'
if (duration === 0) return '0%'
return `${(progress / duration) * 100}%`
}
// 处理删除事件
const handleDelete = async () => {
try {
// 检查是否需要同步删除B站历史记录
const syncDeleteToBilibili = localStorage.getItem('syncDeleteToBilibili') === 'true'
// 根据是否同步删除B站历史记录,显示不同的确认信息
await showDialog({
title: '确认删除',
message: syncDeleteToBilibili
? '确定要删除这条记录吗?此操作将同时删除B站服务器上的历史记录,不可恢复。'
: '确定要删除这条记录吗?此操作不可恢复。',
showCancelButton: true,
confirmButtonText: '确认删除',
cancelButtonText: '取消',
confirmButtonColor: '#fb7299'
})
if (syncDeleteToBilibili) {
try {
// 构建kid
let kid = ''
const business = props.record.business || 'archive'
// 根据业务类型构建kid
switch (business) {
case 'archive':
// 使用oid而不是bvid
kid = `${business}_${props.record.oid}`
break
case 'live':
kid = `${business}_${props.record.oid}`
break
case 'article':
kid = `${business}_${props.record.oid}`
break
case 'pgc':
kid = `${business}_${props.record.oid || props.record.ssid}`
break
case 'article-list':
kid = `${business}_${props.record.oid || props.record.rlid}`
break
default:
kid = `${business}_${props.record.oid || props.record.bvid}`
break
}
if (kid) {
// 调用B站历史记录删除API
const biliResponse = await deleteBilibiliHistory(kid, true)
if (biliResponse.data.status === 'success') {
console.log('B站历史记录删除成功:', biliResponse.data)
} else {
console.error('B站历史记录删除失败:', biliResponse.data)
throw new Error(biliResponse.data.message || '删除B站历史记录失败')
}
}
} catch (error) {
console.error('B站历史记录删除失败:', error)
// 即使B站删除失败,也继续删除本地记录
}
}
// 删除本地记录
const response = await batchDeleteHistory([{
bvid: props.record.bvid,
view_at: props.record.view_at
}])
if (response.data.status === 'success') {
showNotify({
type: 'success',
message: response.data.message + (syncDeleteToBilibili ? ',并已同步删除B站历史记录' : '')
})
emit('refresh-data')
} else {
throw new Error(response.data.message || '删除失败')
}
} catch (error) {
if (error.toString().includes('cancel')) return
showNotify({
type: 'danger',
message: error.response?.data?.detail || error.message || '删除失败'
})
}
}
// 格式化备注时间
const formatRemarkTime = (timestamp) => {
if (!timestamp) return ''
const date = new Date(timestamp * 1000)
return date.toLocaleString('zh-CN', {
month: '2-digit',
day: '2-digit',
hour: '2-digit',
minute: '2-digit'
})
}
// 修改初始化备注内容的方法
const initRemark = () => {
const key = `${props.record.bvid}_${props.record.view_at}`
const data = props.remarkData[key]
if (data) {
remarkContent.value = data.remark || ''
remarkTime.value = data.remark_time || null
originalRemark.value = remarkContent.value // 保存原始值
} else {
remarkContent.value = ''
remarkTime.value = null
originalRemark.value = ''
}
}
// 修改备注更新方法
const handleRemarkBlur = async () => {
// 如果内容没有变化,不发送请求
if (remarkContent.value === originalRemark.value) {
return
}
try {
const response = await updateVideoRemark(
props.record.bvid,
props.record.view_at,
remarkContent.value
)
if (response.data.status === 'success') {
if (remarkContent.value) { // 只在有内容时显示提示
showNotify({
type: 'success',
message: '备注已保存'
})
}
originalRemark.value = remarkContent.value // 更新原始值
remarkTime.value = response.data.data.remark_time // 更新备注时间
// 通知父组件备注已更新
emit('remark-updated', {
bvid: props.record.bvid,
view_at: props.record.view_at,
remark: remarkContent.value,
remark_time: response.data.data.remark_time
})
}
} catch (error) {
showNotify({
type: 'danger',
message: `保存备注失败:${error.message}`
})
remarkContent.value = originalRemark.value // 恢复原始值
}
}
// 组件挂载时初始化备注
onMounted(() => {
initRemark()
})
// 监听 remarkData 的变化
watch(() => props.remarkData, () => {
initRemark()
}, { deep: true })
// 下载弹窗状态
const showDownloadDialog = ref(false)
// 处理下载按钮点击
const handleDownload = () => {
showDownloadDialog.value = true
}
// 处理收藏按钮点击
const handleFavorite = () => {
// 触发父组件的favorite事件
emit('favorite', props.record)
}
</script>
<style scoped>
.line-clamp-2 {
display: -webkit-box;
-webkit-box-orient: vertical;
-webkit-line-clamp: 1;
line-clamp: 1;
overflow: hidden;
text-overflow: ellipsis;
}
/* 可以添加一些额外的悬停效果样式 */
.hover\:scale-110:hover {
transform: scale(1.1);
}
.hover\:text-\[\#FF6699\]:hover {
color: #ff6699;
}
/* 添加 group-hover 相关样式 */
.group:hover .group-hover\:flex {
display: flex;
}
</style>
|
2977094657/BiliHistoryFrontend
| 5,688
|
src/components/tailwind/UserVideos.vue
|
<template>
<div class="transition-all duration-300 ease-in-out">
<!-- 加载状态 -->
<div v-if="isLoading" class="flex flex-col items-center justify-center py-16 bg-white rounded-lg">
<div class="w-16 h-16 border-4 border-[#fb7299] border-t-transparent rounded-full animate-spin mb-4"></div>
<h3 class="text-xl font-medium text-gray-600 mb-2">加载中</h3>
<p class="text-gray-500">正在获取视频列表...</p>
</div>
<!-- 视频列表为空状态 -->
<div v-else-if="videos.length === 0" class="flex flex-col items-center justify-center py-16 bg-white rounded-lg">
<svg class="w-24 h-24 text-gray-300 mb-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.5"
d="M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z" />
</svg>
<h3 class="text-xl font-medium text-gray-600 mb-2">暂无视频</h3>
<p class="text-gray-500">该用户还没有发布任何视频</p>
</div>
<!-- 视频列表 -->
<div v-else class="overflow-hidden">
<div
class="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-4 xl:grid-cols-5 gap-4 px-4 mx-auto transition-all duration-300 ease-in-out transform-gpu"
style="max-width: 1152px;">
<div v-for="video in videos" :key="video.aid"
class="bg-white/50 backdrop-blur-sm rounded-lg overflow-hidden border border-gray-200/50 hover:border-[#FF6699] hover:shadow-md transition-all duration-200 relative group">
<!-- 封面图片 -->
<div class="relative aspect-video cursor-pointer" @click="handleVideoClick(video)">
<img
:src="video.pic"
class="w-full h-full object-cover transition-all duration-300"
alt=""
/>
<!-- 视频时长 -->
<div class="absolute bottom-1 right-1 rounded bg-black/50 px-1 py-1 text-[10px] font-semibold text-white">
{{ video.length }}
</div>
</div>
<!-- 视频信息 -->
<div class="p-3 flex flex-col space-y-1">
<!-- 标题 -->
<div class="line-clamp-1 text-sm text-gray-900 cursor-pointer" @click="handleVideoClick(video)">
{{ video.title }}
</div>
<!-- 播放量和评论数 -->
<div class="text-xs text-gray-500 flex items-center space-x-2">
<span class="flex items-center">
<svg class="w-3 h-3 mr-1" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z" />
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
d="M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z" />
</svg>
{{ formatNumber(video.play) }}
</span>
<span class="flex items-center">
<svg class="w-3 h-3 mr-1" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
d="M8 12h.01M12 12h.01M16 12h.01M21 12c0 4.418-4.03 8-9 8a9.863 9.863 0 01-4.255-.949L3 20l1.395-3.72C3.512 15.042 3 13.574 3 12c0-4.418 4.03-8 9-8s9 3.582 9 8z" />
</svg>
{{ formatNumber(video.comment) }}
</span>
</div>
<!-- 发布时间 -->
<div class="text-xs text-gray-500">
{{ formatTimestamp(video.created) }}
</div>
</div>
</div>
</div>
<!-- 分页 -->
<div class="mt-4 flex justify-center">
<Pagination
:current-page="currentPage"
:total-pages="totalPages"
@page-change="handlePageChange"
/>
</div>
</div>
</div>
</template>
<script>
import { ref, onMounted, watch } from 'vue'
import { getUserVideos } from '@/api/api'
import Pagination from './Pagination.vue'
import { openInBrowser } from '@/utils/openUrl.js'
export default {
name: 'UserVideos',
components: {
Pagination,
},
props: {
mid: {
type: [String, Number],
required: true,
},
},
setup(props) {
const videos = ref([])
const isLoading = ref(false)
const currentPage = ref(1)
const totalPages = ref(1)
const pageSize = 30
const fetchVideos = async () => {
isLoading.value = true
try {
const response = await getUserVideos({
mid: props.mid,
pn: currentPage.value,
ps: pageSize,
})
if (response.data.status === 'success') {
videos.value = response.data.data.list.vlist
totalPages.value = Math.ceil(response.data.data.page.count / pageSize)
}
} catch (error) {
console.error('获取用户视频列表失败:', error)
} finally {
isLoading.value = false
}
}
const handlePageChange = (page) => {
currentPage.value = page
fetchVideos()
}
const handleVideoClick = async (video) => {
await openInBrowser(`https://www.bilibili.com/video/${video.bvid}`)
}
const formatNumber = (num) => {
if (num >= 10000) {
return (num / 10000).toFixed(1) + '万'
}
return num.toString()
}
const formatTimestamp = (timestamp) => {
const date = new Date(timestamp * 1000)
return date.toLocaleDateString('zh-CN', {
year: 'numeric',
month: '2-digit',
day: '2-digit',
})
}
watch(() => props.mid, () => {
currentPage.value = 1
fetchVideos()
})
onMounted(() => {
fetchVideos()
})
return {
videos,
isLoading,
currentPage,
totalPages,
handlePageChange,
handleVideoClick,
formatNumber,
formatTimestamp,
}
},
}
</script>
|
294coder/Efficient-MIF
| 2,443
|
Pansharpening_Hyper_SR_Matlab_Test_Package/Quality_Indices/HQNR.m
|
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Description:
% Hybrid Quality with No Reference (HQNR) index.
%
% Interface:
% [HQNR_value,Dl,Ds] = HQNR(ps_ms,ms,msexp,pan,S,sensor,ratio)
%
% Inputs:
% ps_ms: Pansharpened image;
% ms: Original MS image;
% msexp: MS image resampled to panchromatic scale;
% pan: Panchromatic image;
% S: Block size (optional); Default value: 32;
% sensor: String for type of sensor (e.g. 'WV2','IKONOS');
% ratio: Scale ratio between MS and PAN. Pre-condition: Integer value.
%
% Outputs:
% HQNR_value: QNR index;
% Dl: D_lambda index;
% Ds: D_s index.
%
% References:
% [Alparone08] L. Alparone, B. Aiazzi, S. Baronti, A. Garzelli, F. Nencini, and M. Selva, "Multispectral and panchromatic data fusion assessment without reference,"
% Photogrammetric Engineering and Remote Sensing, vol. 74, no. 2, pp. 193200, February 2008.
% [Khan09] M. M. Khan, L. Alparone, and J. Chanussot, "Pansharpening quality assessment using the modulation transfer functions of instruments",
% IEEE Trans. Geosci. Remote Sens., vol. 11, no. 47, pp. 38803891, Nov. 2009.
% [Aiazzi14] B. Aiazzi, L. Alparone, S. Baronti, R. Carl, A. Garzelli, and L. Santurri,
% "Full scale assessment of pansharpening methods and data products",
% in SPIE Remote Sensing, pp. 924 402 924 402, 2014.
% [Vivone20] G. Vivone, M. Dalla Mura, A. Garzelli, R. Restaino, G. Scarpa, M.O. Ulfarsson, L. Alparone, and J. Chanussot, "A New Benchmark Based on Recent Advances in Multispectral Pansharpening: Revisiting pansharpening with classical and emerging pansharpening methods",
% IEEE Geoscience and Remote Sensing Magazine, doi: 10.1109/MGRS.2020.3019315.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [HQNR_value,Dl,Ds] = HQNR(ps_ms,ms,msexp,pan,S,sensor,ratio)
Dl = D_lambda_K(ps_ms,msexp,ratio,sensor,S);
Ds = D_s(ps_ms,msexp,ms,pan,ratio,S,1);
HQNR_value = (1-Dl)*(1-Ds);
end
|
294coder/Efficient-MIF
| 1,658
|
Pansharpening_Hyper_SR_Matlab_Test_Package/Quality_Indices/onions_quality.m
|
%%%%%%%%%%%%%% Q2n aux. function
function q = onions_quality(dat1,dat2,size1)
dat1=double(dat1);
dat2=double(dat2);
dat2=cat(3,dat2(:,:,1),-dat2(:,:,2:end));
[~,~,N3]=size(dat1);
size2=size1;
% Block normalization
for i=1:N3
[a1,s,t]=norm_blocco(squeeze(dat1(:,:,i)));
dat1(:,:,i)=a1;
clear a1
if s==0
if i==1
dat2(:,:,i)=dat2(:,:,i)-s+1;
else
dat2(:,:,i)=-(-dat2(:,:,i)-s+1);
end
else
if i==1
dat2(:,:,i)=((dat2(:,:,i)-s)/t)+1;
else
dat2(:,:,i)=-(((-dat2(:,:,i)-s)/t)+1);
end
end
end
m1=zeros(1,N3);
m2=zeros(1,N3);
mod_q1m=0;
mod_q2m=0;
mod_q1=zeros(size1,size2);
mod_q2=zeros(size1,size2);
for i=1:N3
m1(i)=mean2(squeeze(dat1(:,:,i)));
m2(i)=mean2(squeeze(dat2(:,:,i)));
mod_q1m=mod_q1m+(m1(i)^2);
mod_q2m=mod_q2m+(m2(i)^2);
mod_q1=mod_q1+((squeeze(dat1(:,:,i))).^2);
mod_q2=mod_q2+((squeeze(dat2(:,:,i))).^2);
end
mod_q1m=sqrt(mod_q1m);
mod_q2m=sqrt(mod_q2m);
mod_q1=sqrt(mod_q1);
mod_q2=sqrt(mod_q2);
termine2 = (mod_q1m*mod_q2m);
termine4 = ((mod_q1m^2)+(mod_q2m^2));
int1=(size1*size2)/((size1*size2)-1)*mean2(mod_q1.^2);
int2=(size1*size2)/((size1*size2)-1)*mean2(mod_q2.^2);
termine3=int1+int2-(size1*size2)/((size1*size2)-1)*((mod_q1m^2)+(mod_q2m^2));
mean_bias=2*termine2/termine4;
if termine3==0
q=zeros(1,1,N3);
q(:,:,N3)=mean_bias;
else
cbm=2/termine3;
qu=onion_mult2D(dat1,dat2);
qm=onion_mult(m1,m2);
qv=zeros(1,N3);
for i=1:N3
qv(i)=(size1*size2)/((size1*size2)-1)*mean2(squeeze(qu(:,:,i)));
end
q=qv-(size1*size2)/((size1*size2)-1)*qm;
q=q*mean_bias*cbm;
end
end
|
294coder/Efficient-MIF
| 2,442
|
Pansharpening_Hyper_SR_Matlab_Test_Package/Quality_Indices/QNR.m
|
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Description:
% Quality with No Reference (QNR) index.
%
% Interface:
% [QNR_index,D_lambda_index,D_s_index] = QNR(I_F,I_MS,I_MS_LR,I_PAN,ratio,S,p,q,alpha,beta)
%
% Inputs:
% I_F: Pansharpened image;
% I_MS: MS image resampled to panchromatic scale;
% I_MS_LR: Original MS image;
% I_PAN: Panchromatic image;
% ratio: Scale ratio between MS and PAN. Pre-condition: Integer value;
% S: Block size (optional); Default value: 32;
% p, q, alpha, beta: Exponent values (optional); Default values: p = q = alpha = beta = 1.
%
% Outputs:
% QNR_index: QNR index;
% D_lambda_index: D_lambda index;
% D_s_index: D_s index.
%
% References:
% [Alparone08] L. Alparone, B. Aiazzi, S. Baronti, A. Garzelli, F. Nencini, and M. Selva, "Multispectral and panchromatic data fusion assessment without reference,"
% Photogrammetric Engineering and Remote Sensing, vol. 74, no. 2, pp. 193200, February 2008.
% [Vivone15] G. Vivone, L. Alparone, J. Chanussot, M. Dalla Mura, A. Garzelli, G. Licciardi, R. Restaino, and L. Wald, A Critical Comparison Among Pansharpening Algorithms,
% IEEE Transactions on Geoscience and Remote Sensing, vol. 53, no. 5, pp. 25652586, May 2015.
% [Vivone20] G. Vivone, M. Dalla Mura, A. Garzelli, R. Restaino, G. Scarpa, M.O. Ulfarsson, L. Alparone, and J. Chanussot, "A New Benchmark Based on Recent Advances in Multispectral Pansharpening: Revisiting pansharpening with classical and emerging pansharpening methods",
% IEEE Geoscience and Remote Sensing Magazine, doi: 10.1109/MGRS.2020.3019315.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [QNR_index,D_lambda_index,D_s_index] = QNR(I_F,I_MS,I_MS_LR,I_PAN,ratio,S,p,q,alpha,beta)
if nargin < 11, beta=1; end
if nargin < 10, alpha=1; end
if nargin < 9, q=1; end
if nargin < 8, p=1; end
if nargin < 7, S=32; end
D_lambda_index = D_lambda(I_F,I_MS,I_MS_LR,S,ratio,p);
D_s_index = D_s(I_F,I_MS,I_MS_LR,I_PAN,ratio,S,q);
QNR_index = (1-D_lambda_index)^alpha * (1-D_s_index)^beta;
end
|
2977094657/BiliHistoryFrontend
| 55,333
|
src/components/tailwind/DownloadDialog.vue
|
<!-- 视频下载弹窗 -->
<template>
<!-- 将通知容器放置在最外层,确保z-index最高 -->
<Teleport to="body">
<div class="notification-container fixed top-0 left-0 right-0 z-[999999]"></div>
</Teleport>
<Teleport to="body">
<div v-if="show" class="fixed inset-0 z-[9999] flex items-center justify-center">
<!-- 遮罩层 -->
<div class="fixed inset-0 bg-black/60 backdrop-blur-sm" @click="handleClose"></div>
<!-- 弹窗内容 -->
<div
class="relative bg-white dark:bg-gray-800 rounded-lg shadow-xl w-[96vw] max-w-5xl h-[95vh] z-10 overflow-hidden flex flex-col">
<!-- 关闭按钮 -->
<button
@click="handleClose"
class="absolute right-4 top-4 text-gray-400 hover:text-gray-500 dark:hover:text-gray-300 z-20 p-1 rounded-full hover:bg-gray-100 dark:hover:bg-gray-700 transition-colors"
>
<svg class="w-5 h-5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12" />
</svg>
</button>
<!-- 页眉区域:包含Yutto致谢和FFmpeg状态 -->
<div
class="px-6 py-3 flex items-center justify-between bg-gray-50 dark:bg-gray-800 border-b border-gray-200 dark:border-gray-700">
<div class="flex items-center space-x-3">
<img src="https://yutto.nyakku.moe/logo-mini.svg" alt="Yutto Logo" class="w-6 h-6">
<div class="flex flex-col">
<p class="text-xs text-gray-700 dark:text-gray-300">下载功能通过 <a href="https://yutto.nyakku.moe/"
target="_blank"
class="text-[#fb7299] hover:text-[#fb7299]/80 font-medium">Yutto</a>
实现</p>
<p class="text-xs text-gray-500 dark:text-gray-400">感谢 Yutto 开发团队的开源贡献</p>
</div>
</div>
<!-- FFmpeg 状态 -->
<div v-if="ffmpegStatus" class="flex-shrink-0">
<div v-if="ffmpegStatus.installed"
class="flex items-center space-x-1 p-1.5 bg-green-50 dark:bg-green-900/30 text-green-700 dark:text-green-400 rounded-lg text-xs">
<svg class="w-4 h-4 flex-shrink-0" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 13l4 4L19 7" />
</svg>
<div>
<p class="font-medium">FFmpeg 已安装</p>
<p class="text-xs">{{ ffmpegStatus.version }}</p>
</div>
</div>
<div v-else class="group relative">
<div class="flex flex-col space-y-1">
<div
class="flex items-center space-x-1 p-1.5 bg-red-50 dark:bg-red-900/30 text-red-700 dark:text-red-400 rounded-lg text-xs">
<svg class="w-4 h-4 flex-shrink-0" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z" />
</svg>
<p class="font-medium">FFmpeg 未安装</p>
</div>
<div class="text-xs text-gray-600 dark:text-gray-400">
<p>
<a
href="https://yutto.nyakku.moe/guide/quick-start#ffmpeg-%E4%B8%8B%E8%BD%BD%E4%B8%8E%E9%85%8D%E7%BD%AE"
target="_blank"
class="text-[#fb7299] hover:text-[#fb7299]/80">
点击查看Yutto说明 →
</a>
</p>
</div>
</div>
<div class="hidden group-hover:block hover:block absolute right-0 top-full h-2 w-full"></div>
<div
class="hidden group-hover:block hover:block absolute right-0 top-[calc(100%+0.5rem)] w-[500px] p-3 bg-white dark:bg-gray-800 rounded-lg shadow-lg border border-gray-200 dark:border-gray-700 z-30 text-xs">
<p class="font-medium text-gray-900 dark:text-gray-100 mb-2">安装指南:</p>
<div v-if="ffmpegStatus?.install_guide" class="space-y-1 whitespace-pre-wrap">
<div v-for="(line, index) in installGuideLines" :key="index" class="flex items-start space-x-1">
<template v-if="isCommand(line)">
<div class="flex-1 bg-gray-50 dark:bg-gray-900 p-1.5 rounded break-all">
<code class="text-gray-700 dark:text-gray-300">{{ getCommandContent(line) }}</code>
</div>
<button @click="copyToClipboard(getCommandContent(line))"
class="text-[#fb7299] hover:text-[#fb7299]/80 p-1 rounded-md hover:bg-[#fb7299]/10 flex-shrink-0"
title="点击复制命令">
<svg class="w-3 h-3" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
d="M8 5H6a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2v-1M8 5a2 2 0 002 2h2a2 2 0 002-2M8 5a2 2 0 012-2h2a2 2 0 012 2m0 0h2a2 2 0 012 2v3m2 4H10m0 0l3-3m-3 3l3 3" />
</svg>
</button>
</template>
<template v-else>
<p class="text-gray-600 dark:text-gray-400 break-all">{{ line }}</p>
</template>
</div>
</div>
</div>
</div>
</div>
</div>
<!-- 主内容区域 -->
<div class="flex-1 overflow-y-auto">
<div class="px-6 pt-3 pb-4">
<!-- 标题 -->
<div class="mb-2">
<h3 class="text-lg font-semibold text-gray-900 dark:text-gray-100">
{{ getDownloadTitle() }}
</h3>
<p v-if="downloadStarted" class="text-sm text-gray-500 dark:text-gray-400">
{{ isDownloading ? '正在下载:' : (downloadError ? '下载出错:' : '下载完成:') }} {{ currentVideoTitle }}
</p>
<p v-else class="text-sm text-gray-500 dark:text-gray-400">
{{ videoInfo.title }}
</p>
<!-- 收藏夹视频总数 -->
<p v-if="isFavoriteFolder" class="text-sm text-gray-500 dark:text-gray-400 mt-1">
共 {{ favoritePageInfo.totalCount || props.videoInfo.total_videos || favoriteVideos.length }}
个视频,当前进度:{{ currentVideoIndex + 1
}}/{{ favoritePageInfo.totalCount || props.videoInfo.total_videos || favoriteVideos.length }}
</p>
<!-- 批量下载视频总数 -->
<p v-if="props.isBatchDownload" class="text-sm text-gray-500 dark:text-gray-400 mt-1">
共 {{ props.batchVideos.length }} 个视频,当前进度:{{ props.currentVideoIndex + 1
}}/{{ props.batchVideos.length }}
</p>
</div>
<!-- 视频信息 -->
<div class="bg-white dark:bg-gray-800 rounded-lg border border-gray-200 dark:border-gray-700 p-4 mb-4">
<div class="flex items-start space-x-4">
<div class="w-32 h-20 flex-shrink-0 overflow-hidden rounded-lg">
<img :src="normalizeImageUrl(currentVideoCover)" :alt="currentVideoTitle"
class="w-full h-full object-cover transition-transform hover:scale-105">
</div>
<div class="flex-1 min-w-0">
<p v-if="!isFavoriteFolder" class="text-xs text-gray-500 dark:text-gray-400 mt-0.5">
UP主:{{ props.isBatchDownload ? currentVideoAuthor : props.videoInfo.author || '未知' }}</p>
<p v-if="!isFavoriteFolder" class="text-xs text-gray-500 dark:text-gray-400 mt-0.5">
BV号:{{ props.isBatchDownload ? currentVideoBvid : props.videoInfo.bvid || '未知' }}</p>
<!-- 基础下载选项 -->
<div class="flex flex-wrap gap-4 items-center mt-3">
<label class="flex items-center space-x-2 cursor-pointer select-none">
<input
type="checkbox"
v-model="downloadCover"
class="w-4 h-4 text-[#fb7299] border-gray-300 rounded focus:ring-[#fb7299]"
>
<span class="text-sm text-gray-700 dark:text-gray-300">下载并合成视频封面</span>
</label>
<label class="flex items-center space-x-2 cursor-pointer select-none">
<input
type="checkbox"
v-model="onlyAudio"
class="w-4 h-4 text-[#fb7299] border-gray-300 rounded focus:ring-[#fb7299]"
>
<span class="text-sm text-gray-700 dark:text-gray-300">仅下载音频</span>
</label>
</div>
</div>
</div>
</div>
<!-- 高级选项切换按钮 -->
<div v-if="!showAdvancedOptions" class="mb-2">
<button
@click="showAdvancedOptions = true"
class="w-full flex items-center justify-center py-2.5 px-4 text-sm bg-white border border-gray-200 rounded-lg hover:bg-gray-50 /50 transition-colors group shadow-sm"
>
<div class="flex items-center space-x-3">
<svg class="w-5 h-5 text-[#fb7299]" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
d="M10.325 4.317c.426-1.756 2.924-1.756 3.35 0a1.724 1.724 0 002.573 1.066c1.543-.94 3.31.826 2.37 2.37a1.724 1.724 0 001.065 2.572c1.756.426 1.756 2.924 0 3.35a1.724 1.724 0 00-1.066 2.573c.94 1.543-.826 3.31-2.37 2.37a1.724 1.724 0 00-2.572 1.065c-.426 1.756-2.924 1.756-3.35 0a1.724 1.724 0 00-2.573-1.066c-1.543.94-3.31-.826-2.37-2.37a1.724 1.724 0 00-1.065-2.572c-1.756-.426-1.756-2.924 0-3.35a1.724 1.724 0 001.066-2.573c-.94-1.543.826-3.31 2.37-2.37.996.608 2.296.07 2.572-1.065z" />
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
d="M15 12a3 3 0 11-6 0 3 3 0 016 0z" />
</svg>
<span class="font-medium text-gray-700 ">高级下载选项</span>
<div class="flex-grow"></div>
<div class="flex items-center space-x-1 text-xs text-[#fb7299]">
<span>展开</span>
<svg class="w-4 h-4 transform transition-transform group-hover:translate-y-0.5 duration-300"
fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 9l-7 7-7-7" />
</svg>
</div>
</div>
</button>
</div>
<!-- 高级下载选项区域 -->
<div
class="bg-white rounded-lg border border-gray-200 mb-2 overflow-hidden shadow-sm transition-all duration-300"
:class="{
'max-h-[1000px] opacity-100': showAdvancedOptions,
'max-h-0 opacity-0 border-0': !showAdvancedOptions
}"
>
<!-- 高级选项标题 -->
<div class="bg-gray-50 /50 p-3 flex justify-between items-center border-b border-gray-200 ">
<div class="flex items-center space-x-2">
<svg class="w-4 h-4 text-[#fb7299]" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
d="M10.325 4.317c.426-1.756 2.924-1.756 3.35 0a1.724 1.724 0 002.573 1.066c1.543-.94 3.31.826 2.37 2.37a1.724 1.724 0 001.065 2.572c1.756.426 1.756 2.924 0 3.35a1.724 1.724 0 00-1.066 2.573c.94 1.543-.826 3.31-2.37 2.37a1.724 1.724 0 00-2.572 1.065c-.426 1.756-2.924 1.756-3.35 0a1.724 1.724 0 00-2.573-1.066c-1.543.94-3.31-.826-2.37-2.37a1.724 1.724 0 00-1.065-2.572c-1.756-.426-1.756-2.924 0-3.35a1.724 1.724 0 001.066-2.573c-.94-1.543.826-3.31 2.37-2.37.996.608 2.296.07 2.572-1.065z" />
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
d="M15 12a3 3 0 11-6 0 3 3 0 016 0z" />
</svg>
<h4 class="text-sm font-medium text-gray-800 ">高级下载选项</h4>
</div>
<!-- 隐藏按钮 -->
<button
@click="showAdvancedOptions = false"
class="flex items-center space-x-1 px-2.5 py-1.5 rounded-md text-xs text-gray-600 hover:bg-gray-100 hover:text-[#fb7299] transition-all duration-200 group"
>
<span>收起选项</span>
<svg class="w-4 h-4 transition-transform group-hover:-translate-y-0.5 duration-300" fill="none"
viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 15l7-7 7 7" />
</svg>
</button>
</div>
<div class="p-3">
<!-- 基础参数区块 -->
<div class="mb-3">
<h5 class="text-xs font-semibold text-gray-700 mb-2 uppercase tracking-wide flex items-center">
<svg class="w-3 h-3 mr-1 text-[#fb7299]" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
d="M5 3v4M3 5h4M6 17v4m-2-2h4m5-16l2.286 6.857L21 12l-5.714 2.143L13 21l-2.286-6.857L5 12l5.714-2.143L13 3z" />
</svg>
视频和音频质量
</h5>
<div class="grid grid-cols-1 md:grid-cols-3 gap-3">
<!-- 视频清晰度 -->
<div>
<label class="block text-xs text-gray-600 mb-1">视频清晰度</label>
<CustomDropdown
v-model="advancedOptions.video_quality"
:options="videoQualityOptions"
:selected-text="getVideoQualityText(advancedOptions.video_quality)"
custom-class="w-full text-xs"
/>
<div class="text-xs text-gray-500 mt-1 text-[10px]">
yutto会尽可能满足清晰度要求,如不存在会自动调节
</div>
</div>
<!-- 音频码率 -->
<div>
<label class="block text-xs text-gray-600 mb-1">音频码率</label>
<CustomDropdown
v-model="advancedOptions.audio_quality"
:options="audioQualityOptions"
:selected-text="getAudioQualityText(advancedOptions.audio_quality)"
custom-class="w-full text-xs"
/>
</div>
<!-- 输出格式 -->
<div>
<label class="block text-xs text-gray-600 mb-1">输出格式</label>
<CustomDropdown
v-model="advancedOptions.output_format"
:options="outputFormatOptions"
:selected-text="getOutputFormatText(advancedOptions.output_format)"
custom-class="w-full text-xs"
/>
</div>
</div>
</div>
<!-- 编码参数区块 -->
<div class="mb-3">
<h5 class="text-xs font-semibold text-gray-700 mb-2 uppercase tracking-wide flex items-center">
<svg class="w-3 h-3 mr-1 text-[#fb7299]" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
d="M10 20l4-16m4 4l4 4-4 4M6 16l-4-4 4-4" />
</svg>
编码选项
</h5>
<div class="grid grid-cols-1 md:grid-cols-2 gap-3">
<!-- 视频编码 -->
<div>
<label class="block text-xs text-gray-600 mb-1">视频编码</label>
<CustomDropdown
v-model="advancedOptions.vcodec"
:options="vcodecOptions"
:selected-text="getVcodecText(advancedOptions.vcodec)"
custom-class="w-full text-xs"
/>
</div>
<!-- 音频编码 -->
<div>
<label class="block text-xs text-gray-600 mb-1">音频编码</label>
<CustomDropdown
v-model="advancedOptions.acodec"
:options="acodecOptions"
:selected-text="getAcodecText(advancedOptions.acodec)"
custom-class="w-full text-xs"
/>
</div>
</div>
</div>
<!-- 资源选项区块 -->
<div>
<h5 class="text-xs font-semibold text-gray-700 mb-2 uppercase tracking-wide flex items-center">
<svg class="w-3 h-3 mr-1 text-[#fb7299]" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
d="M19 11H5m14 0a2 2 0 012 2v6a2 2 0 01-2 2H5a2 2 0 01-2-2v-6a2 2 0 012-2m14 0V9a2 2 0 00-2-2M5 11V9a2 2 0 012-2m0 0V5a2 2 0 012-2h6a2 2 0 012 2v2M7 7h10" />
</svg>
资源选择
</h5>
<div class="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 gap-3">
<!-- 第一行 -->
<label class="flex items-center space-x-2 cursor-pointer select-none">
<input
type="checkbox"
v-model="advancedOptions.video_only"
class="w-4 h-4 text-[#fb7299] border-gray-300 rounded focus:ring-[#fb7299]"
:disabled="onlyAudio"
>
<span class="text-xs text-gray-700 ">仅下载视频流</span>
</label>
<label class="flex items-center space-x-2 cursor-pointer select-none">
<input
type="checkbox"
v-model="advancedOptions.no_danmaku"
class="w-4 h-4 text-[#fb7299] border-gray-300 rounded focus:ring-[#fb7299]"
:disabled="advancedOptions.danmaku_only"
>
<span class="text-xs text-gray-700 ">不生成弹幕</span>
</label>
<label class="flex items-center space-x-2 cursor-pointer select-none">
<input
type="checkbox"
v-model="advancedOptions.danmaku_only"
class="w-4 h-4 text-[#fb7299] border-gray-300 rounded focus:ring-[#fb7299]"
:disabled="advancedOptions.no_danmaku"
>
<span class="text-xs text-gray-700 ">仅生成弹幕</span>
</label>
<label class="flex items-center space-x-2 cursor-pointer select-none">
<input
type="checkbox"
v-model="advancedOptions.no_subtitle"
class="w-4 h-4 text-[#fb7299] border-gray-300 rounded focus:ring-[#fb7299]"
:disabled="advancedOptions.subtitle_only"
>
<span class="text-xs text-gray-700 ">不生成字幕</span>
</label>
<!-- 第二行 -->
<label class="flex items-center space-x-2 cursor-pointer select-none">
<input
type="checkbox"
v-model="advancedOptions.subtitle_only"
class="w-4 h-4 text-[#fb7299] border-gray-300 rounded focus:ring-[#fb7299]"
:disabled="advancedOptions.no_subtitle"
>
<span class="text-xs text-gray-700 ">仅生成字幕</span>
</label>
<label class="flex items-center space-x-2 cursor-pointer select-none">
<input
type="checkbox"
v-model="advancedOptions.with_metadata"
class="w-4 h-4 text-[#fb7299] border-gray-300 rounded focus:ring-[#fb7299]"
:disabled="advancedOptions.metadata_only"
>
<span class="text-xs text-gray-700 ">生成元数据</span>
</label>
<label class="flex items-center space-x-2 cursor-pointer select-none">
<input
type="checkbox"
v-model="advancedOptions.metadata_only"
class="w-4 h-4 text-[#fb7299] border-gray-300 rounded focus:ring-[#fb7299]"
:disabled="advancedOptions.with_metadata"
>
<span class="text-xs text-gray-700 ">仅生成元数据</span>
</label>
<label class="flex items-center space-x-2 cursor-pointer select-none">
<input
type="checkbox"
v-model="advancedOptions.no_cover"
class="w-4 h-4 text-[#fb7299] border-gray-300 rounded focus:ring-[#fb7299]"
:disabled="!downloadCover || advancedOptions.save_cover || advancedOptions.cover_only"
>
<span class="text-xs text-gray-700 ">不生成封面</span>
</label>
<!-- 第三行 -->
<label class="flex items-center space-x-2 cursor-pointer select-none">
<input
type="checkbox"
v-model="advancedOptions.save_cover"
class="w-4 h-4 text-[#fb7299] border-gray-300 rounded focus:ring-[#fb7299]"
:disabled="!downloadCover || advancedOptions.cover_only || advancedOptions.no_cover"
>
<span class="text-xs text-gray-700 ">单独保存封面</span>
</label>
<label class="flex items-center space-x-2 cursor-pointer select-none">
<input
type="checkbox"
v-model="advancedOptions.cover_only"
class="w-4 h-4 text-[#fb7299] border-gray-300 rounded focus:ring-[#fb7299]"
:disabled="!downloadCover || advancedOptions.save_cover || advancedOptions.no_cover"
>
<span class="text-xs text-gray-700 ">仅生成封面</span>
</label>
<label class="flex items-center space-x-2 cursor-pointer select-none">
<input
type="checkbox"
v-model="advancedOptions.no_chapter_info"
class="w-4 h-4 text-[#fb7299] border-gray-300 rounded focus:ring-[#fb7299]"
>
<span class="text-xs text-gray-700 ">不生成章节</span>
</label>
</div>
</div>
</div>
</div>
<!-- 下载日志 -->
<div
class="w-full bg-gray-50 rounded-lg p-2 pb-0 font-mono text-[11px] overflow-y-auto border border-gray-200 "
:class="showAdvancedOptions ? 'h-[calc(100vh-588px)] min-h-[130px]' : 'h-[calc(100vh-418px)] min-h-[180px]'"
ref="logContainer">
<div v-if="!downloadStarted" class="text-gray-500 flex items-center justify-center h-full">
<div class="text-center">
<svg class="w-8 h-8 mx-auto mb-0 text-gray-400 " fill="none" viewBox="0 0 24 24"
stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.5"
d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z" />
</svg>
<p>点击下方按钮开始下载...</p>
</div>
</div>
<div v-else>
<div v-for="(log, index) in downloadLogs" :key="index" class="whitespace-pre break-all leading-5 py-0.5 last:pb-0"
:class="{
'text-gray-600 ': !log.includes('ERROR') && !log.includes('下载完成') && !log.includes('WARN'),
'text-red-500 ': log.includes('ERROR'),
'text-green-500 ': log.includes('下载完成'),
'text-yellow-500 dark:text-yellow-400': log.includes('WARN'),
}">{{ log }}
</div>
</div>
</div>
</div>
</div>
<!-- 页脚区域:状态和按钮 -->
<div class="bg-gray-50 border-t border-gray-200 py-2 px-6 flex items-center justify-between">
<div class="text-xs font-medium" :class="{
'text-gray-500 ': !downloadStarted,
'text-red-500 ': downloadError,
'text-green-500 ': !isDownloading && downloadStarted && !downloadError,
'text-[#fb7299]': isDownloading
}">
{{ downloadStatus }}
</div>
<div class="flex space-x-3">
<button
@click="handleClose"
class="px-3 py-1.5 text-xs font-medium text-gray-700 bg-white border border-gray-300 rounded-md hover:bg-gray-50 transition-colors"
:disabled="isDownloading"
>
{{ isDownloading ? '下载中...' : '关闭' }}
</button>
<button
v-if="!downloadStarted || downloadError"
@click="startDownload"
class="px-3 py-1.5 text-xs font-medium text-white bg-[#fb7299] rounded-md hover:bg-[#fb7299]/90 disabled:opacity-50 transition-colors"
:disabled="isDownloading"
>
{{ downloadError ? '重试' : '开始下载' }}
</button>
</div>
</div>
</div>
</div>
</Teleport>
</template>
<script setup>
import { ref, computed, watch, onUnmounted, nextTick } from 'vue'
import {
downloadVideo,
checkFFmpeg,
downloadFavorites,
getFavoriteContents,
downloadUserVideos,
batchDownloadVideos,
downloadCollection,
} from '@/api/api.js'
import { showNotify } from 'vant'
import 'vant/es/notify/style'
import CustomDropdown from '@/components/tailwind/CustomDropdown.vue'
import { normalizeImageUrl } from '@/utils/imageUrl.js'
defineOptions({
name: 'DownloadDialog',
})
const props = defineProps({
show: {
type: Boolean,
default: false,
},
videoInfo: {
type: Object,
required: true,
default: () => ({
title: '',
author: '',
bvid: '',
cover: '',
cid: 0,
}),
},
// 当为 true 时,弹窗打开时默认勾选“仅下载音频”
defaultOnlyAudio: {
type: Boolean,
default: false,
},
// 添加 UP 主视频列表参数
upUserVideos: {
type: Array,
default: () => [],
},
// 批量下载参数
isBatchDownload: {
type: Boolean,
default: false,
},
batchVideos: {
type: Array,
default: () => [],
},
// 当前下载的视频索引
currentVideoIndex: {
type: Number,
default: 0,
},
})
const emit = defineEmits(['update:show', 'download-complete', 'update:currentVideoIndex'])
// 下载相关状态
const downloadStarted = ref(false)
const isDownloading = ref(false)
const downloadError = ref(false)
const downloadLogs = ref([])
// 控制高级选项的显示状态
const showAdvancedOptions = ref(false)
// 下载状态文本
const downloadStatus = computed(() => {
if (!downloadStarted.value) return '准备就绪'
if (downloadError.value) return '下载出错'
if (isDownloading.value) return '下载中...'
return '下载完成'
})
// 获取下载标题
const getDownloadTitle = () => {
if (props.videoInfo.is_collection_download) {
return '下载合集'
} else if (props.isBatchDownload) {
return '批量下载视频'
} else if (isFavoriteFolder.value) {
return '下载收藏夹'
} else {
return '下载视频'
}
}
// 日志容器引用
const logContainer = ref(null)
// FFmpeg 状态
const ffmpegStatus = ref(null)
// 检查 FFmpeg 安装状态
const checkFFmpegStatus = async () => {
try {
const response = await checkFFmpeg()
if (response.data) {
ffmpegStatus.value = {
installed: response.data.status === 'success',
version: response.data.version,
path: response.data.path,
os_info: response.data.os_info,
install_guide: response.data.install_guide,
}
}
} catch (error) {
console.error('检查 FFmpeg 失败:', error)
}
}
// 下载封面选项
const downloadCover = ref(true)
// 仅下载音频选项
const onlyAudio = ref(false)
// 高级选项
const advancedOptions = ref({
// 基础参数
video_quality: null,
audio_quality: null,
vcodec: null,
acodec: null,
download_vcodec_priority: null,
output_format: null,
output_format_audio_only: null,
// 资源选择参数
video_only: false,
danmaku_only: false,
no_danmaku: false,
subtitle_only: false,
no_subtitle: false,
with_metadata: false,
metadata_only: false,
no_cover: false,
save_cover: false,
cover_only: false,
no_chapter_info: false,
})
// 当前正在下载的视频信息
const currentVideoTitle = ref('')
const currentVideoCover = ref('')
const currentVideoAuthor = ref('')
const currentVideoBvid = ref('')
const videoTitles = ref([]) // 存储所有检测到的视频标题
// 存储收藏夹中所有视频信息
const favoriteVideos = ref([])
// 当前正在下载的视频索引
const currentVideoIndex = ref(-1)
// 收藏夹的页码信息
const favoritePageInfo = ref({
page: 1,
pageSize: 40,
totalCount: 0,
totalPage: 0,
hasMore: false,
})
// 加载收藏夹内容状态
const loadingFavorites = ref(false)
// 是否是收藏夹
const isFavoriteFolder = computed(() => {
return !!props.videoInfo.is_favorite_folder
})
// 预加载收藏夹所有视频
const preloadFavoriteVideos = async () => {
if (!isFavoriteFolder.value || !props.videoInfo.fid) return
try {
loadingFavorites.value = true
downloadLogs.value.push('INFO 正在获取收藏夹内容,请稍候...')
// 先获取基本信息,确定总视频数
try {
const initialResponse = await getFavoriteContents({
media_id: props.videoInfo.fid,
pn: 1,
ps: 1, // 只获取一个视频,主要是为了拿到总数
})
if (initialResponse.data && initialResponse.data.status === 'success' && initialResponse.data.data) {
// 更新总数信息
favoritePageInfo.value.totalCount = initialResponse.data.data.total || props.videoInfo.total_videos || 0
favoritePageInfo.value.totalPage = Math.ceil(favoritePageInfo.value.totalCount / 40)
console.log('收藏夹总视频数:', favoritePageInfo.value.totalCount)
console.log('总页数:', favoritePageInfo.value.totalPage)
downloadLogs.value.push(`INFO 收藏夹共有 ${favoritePageInfo.value.totalCount} 个视频,开始获取视频信息`)
}
} catch (error) {
console.error('获取收藏夹基本信息失败:', error)
}
// 如果仍然没有总数信息,使用props中的值
if (!favoritePageInfo.value.totalCount) {
favoritePageInfo.value.totalCount = props.videoInfo.total_videos || 0
favoritePageInfo.value.totalPage = Math.ceil(favoritePageInfo.value.totalCount / 40)
}
let allVideos = []
let page = 1
let maxPages = Math.min(favoritePageInfo.value.totalPage || 5, 10) // 最多获取10页,避免过多请求
let hasMore = page <= maxPages
// 如果视频总数超过200个,提示用户
if (favoritePageInfo.value.totalCount > 200) {
downloadLogs.value.push(`WARN 收藏夹视频数量较多(${favoritePageInfo.value.totalCount}个),将只预加载部分视频信息`)
downloadLogs.value.push('INFO 下载过程中会自动更新视频信息')
}
while (hasMore) {
try {
downloadLogs.value.push(`INFO 正在获取第${page}页视频信息...`)
const response = await getFavoriteContents({
media_id: props.videoInfo.fid,
pn: page,
ps: 40, // 每页40条
})
if (response.data && response.data.status === 'success' && response.data.data) {
const data = response.data.data
// 更新总视频数,避免后续请求
if (page === 1 && data.total) {
favoritePageInfo.value.totalCount = data.total
favoritePageInfo.value.totalPage = Math.ceil(data.total / (data.pagesize || 40))
}
if (data.medias && Array.isArray(data.medias)) {
// 合并结果
const newVideos = data.medias.map(item => ({
title: item.title || '',
cover: item.cover || '',
bvid: item.bvid || '',
cid: item.cid || 0,
author: item.upper?.name || '',
avid: item.id || 0,
}))
allVideos = allVideos.concat(newVideos)
// 更新日志,显示当前进度
downloadLogs.value.push(`INFO 已获取 ${allVideos.length}/${favoritePageInfo.value.totalCount} 个视频信息`)
}
// 判断是否还有更多页
page++
hasMore = page <= maxPages && page <= favoritePageInfo.value.totalPage
// 大型收藏夹时,避免请求过多页面
if (page > 5 && favoritePageInfo.value.totalCount > 200) {
downloadLogs.value.push(`INFO 已获取前${page - 1}页视频信息,剩余信息将在下载过程中更新`)
hasMore = false
}
// 休眠一段时间,避免触发API限制
if (hasMore) {
await new Promise(resolve => setTimeout(resolve, 500))
}
} else {
downloadLogs.value.push('ERROR 获取收藏夹内容失败,将使用实时日志更新视频信息')
hasMore = false
}
} catch (error) {
console.error(`获取收藏夹内容第${page}页失败:`, error)
downloadLogs.value.push(`ERROR 获取第${page}页内容失败,可能触发了API限制`)
hasMore = false
}
}
favoriteVideos.value = allVideos
if (allVideos.length < favoritePageInfo.value.totalCount) {
downloadLogs.value.push(`INFO 已预加载 ${allVideos.length}/${favoritePageInfo.value.totalCount} 个视频信息,剩余视频将在下载过程中更新`)
} else {
downloadLogs.value.push(`INFO 收藏夹内容获取完成,共 ${allVideos.length} 个视频`)
}
} catch (error) {
console.error('加载收藏夹内容失败:', error)
downloadLogs.value.push('ERROR 获取收藏夹内容失败,将使用实时日志更新视频信息')
} finally {
loadingFavorites.value = false
}
}
// 监听日志变化,提取视频顺序索引
watch(() => downloadLogs.value, async (logs) => {
if (!logs || logs.length === 0) return
// 获取最新的日志信息
const latestLog = logs[logs.length - 1]
console.log('处理新日志:', latestLog)
// 检查是否是下载完成信息
if (latestLog === '下载完成') {
console.log('收藏夹下载全部完成')
// 确保显示最后一个视频
if (isFavoriteFolder.value && favoriteVideos.value.length > 0) {
currentVideoIndex.value = favoriteVideos.value.length - 1
const lastVideo = favoriteVideos.value[currentVideoIndex.value]
currentVideoTitle.value = lastVideo.title
currentVideoCover.value = lastVideo.cover || ''
}
return
}
// 检查是否为视频序号信息 [n/total]
const indexMatch = latestLog.match(/\[(\d+)\/(\d+)\]/)
if (indexMatch) {
const index = parseInt(indexMatch[1], 10) - 1 // 索引从0开始
const total = parseInt(indexMatch[2], 10)
console.log(`检测到视频索引: ${index + 1}/${total}`)
// 提取完整的视频标题
const titleMatch = latestLog.match(/\[(\d+)\/(\d+)\]\s+(.+)/)
if (titleMatch) {
const videoTitle = titleMatch[3].trim()
console.log('检测到视频标题:', videoTitle)
currentVideoTitle.value = videoTitle
// 更新索引和封面
if (isFavoriteFolder.value && favoriteVideos.value.length > 0) {
if (index >= 0 && index < favoriteVideos.value.length) {
currentVideoIndex.value = index
const videoInfo = favoriteVideos.value[index]
if (videoInfo && videoInfo.cover) {
currentVideoCover.value = videoInfo.cover
}
}
} else {
// 搜索封面
trySearchCover(videoTitle)
}
}
return
}
// 检查是否为"开始处理视频"
const processingMatch = latestLog.match(/INFO\s+开始处理视频\s+(.+)/)
if (processingMatch) {
const videoTitle = processingMatch[1].trim()
console.log('检测到开始处理视频:', videoTitle)
// 更新当前视频标题
currentVideoTitle.value = videoTitle
// 查找匹配的视频
if (isFavoriteFolder.value && favoriteVideos.value.length > 0) {
const videoIndex = favoriteVideos.value.findIndex(v => v.title === videoTitle)
if (videoIndex >= 0) {
currentVideoIndex.value = videoIndex
const videoInfo = favoriteVideos.value[videoIndex]
if (videoInfo && videoInfo.cover) {
currentVideoCover.value = videoInfo.cover
}
} else {
// 没找到匹配的视频,尝试搜索封面
trySearchCover(videoTitle)
}
} else {
// 没有预加载数据,搜索封面
trySearchCover(videoTitle)
}
return
}
// 检查是否为"合并完成"
if (latestLog.includes('INFO 合并完成!')) {
console.log('检测到视频合并完成')
// 预测下一个视频
const nextIndex = currentVideoIndex.value + 1
if (isFavoriteFolder.value && favoriteVideos.value.length > 0 && nextIndex < favoriteVideos.value.length) {
// 等待短暂时间,看是否会有新的视频标题出现
setTimeout(() => {
// 再次检查最新的几条日志
const recentLogs = downloadLogs.value.slice(-5).join('\n')
// 如果没有新的视频标题信息,则主动切换到下一个视频
if (!recentLogs.includes('[') || !recentLogs.includes('/')) {
console.log(`准备切换到下一个视频, 索引: ${nextIndex + 1}/${favoriteVideos.value.length}`)
currentVideoIndex.value = nextIndex
const nextVideo = favoriteVideos.value[nextIndex]
if (nextVideo) {
currentVideoTitle.value = nextVideo.title
currentVideoCover.value = nextVideo.cover || props.videoInfo.cover
}
}
}, 300)
}
return
}
// 检查是否为"下载完成!"
if (latestLog.includes('INFO 下载完成!')) {
console.log('检测到视频下载完成')
// 这里不做处理,等待"合并完成"的消息
return
}
}, { deep: true })
// 辅助函数:尝试搜索视频封面
const trySearchCover = async (videoTitle) => {
if (!videoTitle) return
// 此函数不再实际执行搜索操作,只记录日志
console.log('UP主投稿模式-图片加载失败,使用原始封面:', currentVideoCover.value)
}
// 监听 show 变化
watch(() => props.show, async (isVisible) => {
if (isVisible) {
// 输出调试信息
console.log('DownloadDialog 弹窗打开,接收到的视频信息:', JSON.stringify(props.videoInfo, null, 2))
// 初始化
currentVideoTitle.value = props.videoInfo.title
currentVideoCover.value = props.videoInfo.pic || props.videoInfo.cover
currentVideoAuthor.value = props.videoInfo.author || ''
currentVideoBvid.value = props.videoInfo.bvid || ''
console.log('设置封面图片路径:', currentVideoCover.value)
videoTitles.value = []
currentVideoIndex.value = -1
favoriteVideos.value = []
// 如果是收藏夹,预加载收藏夹内容
if (isFavoriteFolder.value && props.videoInfo.fid) {
await preloadFavoriteVideos()
}
// 在弹窗打开时检查 FFmpeg
checkFFmpegStatus()
// 根据传入的默认开关设置仅下载音频
if (props.defaultOnlyAudio) {
onlyAudio.value = true
}
}
})
// 重置状态
const resetState = () => {
downloadStarted.value = false
isDownloading.value = false
downloadError.value = false
downloadLogs.value = []
currentVideoTitle.value = props.videoInfo.title
currentVideoCover.value = props.videoInfo.pic || props.videoInfo.cover
currentVideoAuthor.value = props.videoInfo.author || ''
currentVideoBvid.value = props.videoInfo.bvid || ''
videoTitles.value = []
currentVideoIndex.value = -1
favoriteVideos.value = []
// 重置高级选项的显示状态
showAdvancedOptions.value = true
// 重置高级选项
advancedOptions.value = {
// 基础参数
video_quality: null,
audio_quality: null,
vcodec: null,
acodec: null,
download_vcodec_priority: null,
output_format: null,
output_format_audio_only: null,
// 资源选择参数
video_only: false,
danmaku_only: false,
no_danmaku: false,
subtitle_only: false,
no_subtitle: false,
with_metadata: false,
metadata_only: false,
no_cover: false,
save_cover: false,
cover_only: false,
no_chapter_info: false,
}
}
// 显示下载完成通知
const showDownloadCompleteNotify = () => {
showNotify({
type: 'success',
message: '下载已完成',
position: 'top',
duration: 2000,
teleport: '.notification-container',
})
}
// 开始下载
const startDownload = async () => {
try {
// 如果 FFmpeg 未安装,显示错误提示
if (ffmpegStatus.value && !ffmpegStatus.value.installed) {
downloadLogs.value.push('ERROR: FFmpeg 未安装,请先安装 FFmpeg')
downloadError.value = true
return
}
// 重置状态
downloadStarted.value = true
isDownloading.value = true
downloadError.value = false
downloadLogs.value = []
// 隐藏高级选项,让日志显示在更靠上的位置
showAdvancedOptions.value = false
// 首次显示正在使用预加载的视频
if (isFavoriteFolder.value && favoriteVideos.value.length > 0) {
downloadLogs.value.push(`INFO 将使用预加载的 ${favoriteVideos.value.length} 个视频信息进行下载`)
// 立即设置第一个视频的信息
currentVideoIndex.value = 0
const firstVideo = favoriteVideos.value[0]
if (firstVideo) {
currentVideoTitle.value = firstVideo.title
currentVideoCover.value = firstVideo.cover || props.videoInfo.cover
}
} else {
// 设置当前视频信息
currentVideoTitle.value = props.videoInfo.title
currentVideoCover.value = props.videoInfo.pic || props.videoInfo.cover
}
// 检查是否是用户视频下载请求
if (props.videoInfo.is_user_videos) {
// 使用传入的UP主视频列表
if (props.upUserVideos && props.upUserVideos.length > 0) {
console.log('使用预加载的UP主视频列表:', props.upUserVideos.length)
favoriteVideos.value = props.upUserVideos.map(video => ({
title: video.title || '',
cover: video.pic || '',
bvid: video.bvid || '',
author: video.author || '',
}))
}
// 发起用户视频下载请求并处理实时消息
await downloadUserVideos({
user_id: props.videoInfo.user_id,
download_cover: downloadCover.value,
only_audio: onlyAudio.value,
// 添加高级选项
...advancedOptions.value,
}, (content) => {
console.log('收到用户视频下载消息:', content)
downloadLogs.value.push(content)
// 检查是否为视频标题信息 [n/5] 视频标题
const upVideoTitleMatch = content.match(/\[(\d+)\/(\d+)\]\s+(.+)/)
if (upVideoTitleMatch) {
const index = parseInt(upVideoTitleMatch[1], 10) - 1 // 索引从0开始
const total = parseInt(upVideoTitleMatch[2], 10)
const videoTitle = upVideoTitleMatch[3].trim()
console.log('检测到UP主视频标题:', videoTitle, `${index + 1}/${total}`)
currentVideoTitle.value = videoTitle
// 尝试从预加载的视频列表中找到匹配的视频以获取封面
if (favoriteVideos.value.length > 0) {
// 尝试使用索引直接获取
if (index >= 0 && index < favoriteVideos.value.length) {
const matchedVideo = favoriteVideos.value[index]
if (matchedVideo && matchedVideo.cover) {
console.log('找到匹配视频:', matchedVideo.title)
console.log('更新视频封面:', matchedVideo.cover)
currentVideoCover.value = matchedVideo.cover
currentVideoIndex.value = index
}
} else {
// 如果索引无效,尝试通过标题匹配
const videoByTitle = favoriteVideos.value.find(v => v.title === videoTitle)
if (videoByTitle && videoByTitle.cover) {
console.log('通过标题找到匹配视频:', videoByTitle.title)
console.log('更新视频封面:', videoByTitle.cover)
currentVideoCover.value = videoByTitle.cover
currentVideoIndex.value = favoriteVideos.value.indexOf(videoByTitle)
}
}
}
}
// 检查是否为"开始处理视频"
const processingMatch = content.match(/INFO\s+开始处理视频\s+(.+)/)
if (processingMatch) {
const videoTitle = processingMatch[1].trim()
console.log('检测到开始处理UP主视频:', videoTitle)
currentVideoTitle.value = videoTitle
// 尝试从预加载的视频列表中找到匹配的视频以获取封面
if (favoriteVideos.value.length > 0) {
const videoByTitle = favoriteVideos.value.find(v => v.title === videoTitle)
if (videoByTitle && videoByTitle.cover) {
console.log('根据处理信息找到匹配视频:', videoByTitle.title)
console.log('更新视频封面:', videoByTitle.cover)
currentVideoCover.value = videoByTitle.cover
currentVideoIndex.value = favoriteVideos.value.indexOf(videoByTitle)
}
}
}
// 检查下载状态
if (content.includes('下载完成') && !content.includes('INFO')) {
isDownloading.value = false
// 显示下载完成通知
showDownloadCompleteNotify()
emit('download-complete')
} else if (content.includes('ERROR')) {
downloadError.value = true
isDownloading.value = false
}
// 自动滚动到底部
nextTick(() => {
scrollToBottom()
})
})
}
// 检查是否是收藏夹下载请求
else if (props.videoInfo.is_favorite_folder) {
// 发起收藏夹下载请求并处理实时消息
await downloadFavorites({
user_id: props.videoInfo.user_id,
fid: props.videoInfo.fid,
download_cover: downloadCover.value,
only_audio: onlyAudio.value,
// 添加高级选项
...advancedOptions.value,
}, (content) => {
console.log('收到收藏夹下载消息:', content)
downloadLogs.value.push(content)
// 检查下载状态
if (content.includes('下载完成') && !content.includes('INFO')) {
isDownloading.value = false
// 显示下载完成通知
showDownloadCompleteNotify()
emit('download-complete')
} else if (content.includes('ERROR')) {
downloadError.value = true
isDownloading.value = false
}
// 自动滚动到底部
nextTick(() => {
scrollToBottom()
})
})
} else if (props.isBatchDownload && props.batchVideos.length > 0) {
// 批量下载多个视频
downloadLogs.value.push(`INFO 开始批量下载,共 ${props.batchVideos.length} 个视频`)
// 设置初始视频信息
if (props.batchVideos.length > 0 && props.currentVideoIndex < props.batchVideos.length) {
const currentVideo = props.batchVideos[props.currentVideoIndex]
currentVideoTitle.value = currentVideo.title || currentVideo.bvid
currentVideoCover.value = currentVideo.cover || props.videoInfo.cover
currentVideoAuthor.value = currentVideo.author || props.videoInfo.author || ''
currentVideoBvid.value = currentVideo.bvid || props.videoInfo.bvid || ''
}
// 发起批量下载请求
await batchDownloadVideos({
videos: props.batchVideos,
download_cover: downloadCover.value,
only_audio: onlyAudio.value,
// 添加高级选项
...advancedOptions.value,
}, (content) => {
console.log('收到批量下载消息:', content)
downloadLogs.value.push(content)
// 检查是否包含当前下载的视频信息
const currentVideoMatch = content.match(/正在下载第\s+(\d+)\/(\d+)\s+个视频:\s+(.+)/)
if (currentVideoMatch) {
const index = parseInt(currentVideoMatch[1], 10) - 1
const total = parseInt(currentVideoMatch[2], 10)
const title = currentVideoMatch[3].trim()
console.log(`正在下载第 ${index + 1}/${total} 个视频: ${title}`)
// 更新当前视频信息
if (index >= 0 && index < props.batchVideos.length) {
currentVideoIndex.value = index
currentVideoTitle.value = title
const video = props.batchVideos[index]
if (video) {
if (video.cover) {
currentVideoCover.value = video.cover
}
if (video.author) {
currentVideoAuthor.value = video.author
}
if (video.bvid) {
currentVideoBvid.value = video.bvid
}
}
// 通知父组件当前视频索引已更新
emit('update:currentVideoIndex', index)
}
}
// 检查下载状态
if (content.includes('批量下载完成') || (content.includes('下载完成') && !content.includes('INFO'))) {
isDownloading.value = false
// 显示下载完成通知
showDownloadCompleteNotify()
emit('download-complete')
} else if (content.includes('ERROR')) {
downloadError.value = true
isDownloading.value = false
}
// 自动滚动到底部
nextTick(() => {
scrollToBottom()
})
})
} else if (props.videoInfo.is_collection_download) {
// 合集下载
console.log('开始合集下载:', props.videoInfo)
await downloadCollection({
url: props.videoInfo.original_url,
cid: props.videoInfo.cid,
download_cover: downloadCover.value,
only_audio: onlyAudio.value,
// 添加高级选项
...advancedOptions.value,
}, (content) => {
console.log('收到合集下载消息:', content)
downloadLogs.value.push(content)
// 检查下载状态
if (content.includes('下载完成')) {
isDownloading.value = false
// 显示下载完成通知
showDownloadCompleteNotify()
emit('download-complete')
} else if (content.includes('ERROR')) {
downloadError.value = true
isDownloading.value = false
}
// 自动滚动到底部
nextTick(() => {
scrollToBottom()
})
})
} else {
// 发起单个视频下载请求并处理实时消息
await downloadVideo(
props.videoInfo.bvid,
null,
(content) => {
console.log('收到消息:', content)
downloadLogs.value.push(content)
// 检查下载状态
if (content.includes('下载完成')) {
isDownloading.value = false
// 显示下载完成通知
showDownloadCompleteNotify()
emit('download-complete')
} else if (content.includes('ERROR')) {
downloadError.value = true
isDownloading.value = false
}
// 自动滚动到底部
nextTick(() => {
scrollToBottom()
})
},
downloadCover.value,
onlyAudio.value,
props.videoInfo.cid,
// 添加高级选项
advancedOptions.value,
)
}
} catch (error) {
console.error('下载失败:', error)
downloadError.value = true
isDownloading.value = false
const errorLines = error.message.split('\n')
for (const line of errorLines) {
downloadLogs.value.push(`ERROR: ${line}`)
}
}
}
// 滚动到底部的优化实现
const scrollToBottom = () => {
if (logContainer.value) {
logContainer.value.scrollTop = logContainer.value.scrollHeight
}
}
// 监听日志变化
watch(() => downloadLogs.value.length, () => {
nextTick(() => {
scrollToBottom()
})
})
// 处理关闭弹窗
const handleClose = () => {
if (isDownloading.value) {
if (!confirm('下载正在进行中,确定要关闭吗?')) {
return
}
}
// 如果下载已完成且没有错误,触发下载完成事件
if (downloadStarted.value && !isDownloading.value && !downloadError.value) {
emit('download-complete')
}
emit('update:show', false)
// 重置状态
resetState()
}
// 监听show变化
watch(() => props.show, (newVal) => {
if (!newVal) {
handleClose()
} else {
// 在弹窗打开时检查 FFmpeg
checkFFmpegStatus()
// 初始化当前视频标题和封面
currentVideoTitle.value = props.videoInfo.title
currentVideoCover.value = props.videoInfo.pic || props.videoInfo.cover
}
})
// 组件卸载时清理
onUnmounted(() => {
// 重置状态
resetState()
})
// 复制到剪贴板函数
const copyToClipboard = async (text) => {
try {
await navigator.clipboard.writeText(text)
showNotify({
type: 'success',
message: '命令已复制到剪贴板',
position: 'top',
duration: 2000,
teleport: '.notification-container',
})
} catch (err) {
console.error('复制失败:', err)
showNotify({
type: 'danger',
message: '复制失败,请手动复制',
position: 'top',
duration: 2000,
teleport: '.notification-container',
})
}
}
// 处理安装指南的行
const installGuideLines = computed(() => {
if (!ffmpegStatus.value?.install_guide) return []
return ffmpegStatus.value.install_guide.split('\n').filter(line => line.trim())
})
// 判断是否为命令行
const isCommand = (line) => {
return line.trim().startsWith('yum') ||
line.trim().startsWith('sudo') ||
line.trim().startsWith('apt') ||
line.trim().startsWith('brew')
}
// 获取命令内容
const getCommandContent = (line) => {
return line.trim()
}
// 下拉菜单选项定义
const videoQualityOptions = [
{ label: '默认', value: null },
{ label: '127: 8K 超高清', value: '127' },
{ label: '126: 杜比视界', value: '126' },
{ label: '125: HDR 真彩', value: '125' },
{ label: '120: 4K 超清', value: '120' },
{ label: '116: 1080P 60帧', value: '116' },
{ label: '112: 1080P 高码率', value: '112' },
{ label: '100: 智能修复', value: '100' },
{ label: '80: 1080P 高清', value: '80' },
{ label: '74: 720P 60帧', value: '74' },
{ label: '64: 720P 高清', value: '64' },
{ label: '32: 480P 清晰', value: '32' },
{ label: '16: 360P 流畅', value: '16' },
]
const audioQualityOptions = [
{ label: '默认', value: null },
{ label: '30251: Hi-Res', value: '30251' },
{ label: '30255: 杜比音效', value: '30255' },
{ label: '30250: 杜比全景声', value: '30250' },
{ label: '30280: 320kbps', value: '30280' },
{ label: '30232: 128kbps', value: '30232' },
{ label: '30216: 64kbps', value: '30216' },
]
const vcodecOptions = [
{ label: '默认 (avc:copy)', value: null },
{ label: '下载AVC(H.264):直接复制', value: 'avc:copy' },
{ label: '下载HEVC(H.265):直接复制', value: 'hevc:copy' },
{ label: '下载AV1:直接复制', value: 'av1:copy' },
{ label: '下载AVC(H.264):转码为H.264', value: 'avc:h264' },
{ label: '下载HEVC(H.265):转码为H.265', value: 'hevc:hevc' },
{ label: '下载AV1:转码为AV1', value: 'av1:av1' },
]
const acodecOptions = [
{ label: '默认 (mp4a:copy)', value: null },
{ label: '下载MP4A:直接复制', value: 'mp4a:copy' },
{ label: '下载MP4A:转码为AAC', value: 'mp4a:aac' },
{ label: '下载MP4A:转码为MP3', value: 'mp4a:mp3' },
{ label: '下载MP4A:转码为FLAC', value: 'mp4a:flac' },
]
const outputFormatOptions = [
{ label: '默认', value: null },
{ label: '自动推断', value: 'infer' },
{ label: 'MP4', value: 'mp4' },
{ label: 'MKV', value: 'mkv' },
{ label: 'MOV', value: 'mov' },
]
const audioOutputFormatOptions = [
{ label: '默认', value: null },
{ label: '自动推断', value: 'infer' },
{ label: 'M4A', value: 'm4a' },
{ label: 'AAC', value: 'aac' },
{ label: 'MP3', value: 'mp3' },
{ label: 'FLAC', value: 'flac' },
]
// 获取选项文本的方法
const getVideoQualityText = (value) => {
const option = videoQualityOptions.find(opt => opt.value === value)
return option ? option.label : '默认'
}
const getAudioQualityText = (value) => {
const option = audioQualityOptions.find(opt => opt.value === value)
return option ? option.label : '默认'
}
const getVcodecText = (value) => {
const option = vcodecOptions.find(opt => opt.value === value)
return option ? option.label : '默认'
}
const getAcodecText = (value) => {
const option = acodecOptions.find(opt => opt.value === value)
return option ? option.label : '默认'
}
const getOutputFormatText = (value) => {
const option = outputFormatOptions.find(opt => opt.value === value)
return option ? option.label : '默认'
}
const getAudioOutputFormatText = (value) => {
const option = audioOutputFormatOptions.find(opt => opt.value === value)
return option ? option.label : '默认'
}
</script>
<style scoped>
/* 当弹窗显示时禁用页面滚动 */
:global(body) {
overflow: hidden;
}
</style>
|
294coder/Efficient-MIF
| 3,047
|
Pansharpening_Hyper_SR_Matlab_Test_Package/Quality_Indices/q2n.m
|
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Description:
% Q2n index.
%
% Interface:
% [Q2n_index, Q2n_index_map] = q2n(I_GT, I_F, Q_blocks_size, Q_shift)
%
% Inputs:
% I_GT: Ground-Truth image;
% I_F: Fused Image;
% Q_blocks_size: Block size of the Q-index locally applied;
% Q_shift: Block shift of the Q-index locally applied.
%
% Outputs:
% Q2n_index: Q2n index;
% Q2n_index_map: Map of Q2n values.
%
% References:
% [Garzelli09] A. Garzelli and F. Nencini, "Hypercomplex quality assessment of multi/hyper-spectral images,"
% IEEE Geoscience and Remote Sensing Letters, vol. 6, no. 4, pp. 662665, October 2009.
% [Vivone20] G. Vivone, M. Dalla Mura, A. Garzelli, R. Restaino, G. Scarpa, M.O. Ulfarsson, L. Alparone, and J. Chanussot, "A New Benchmark Based on Recent Advances in Multispectral Pansharpening: Revisiting pansharpening with classical and emerging pansharpening methods",
% IEEE Geoscience and Remote Sensing Magazine, doi: 10.1109/MGRS.2020.3019315.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [Q2n_index, Q2n_index_map] = q2n(I_GT, I_F, Q_blocks_size, Q_shift)
[N1,N2,N3]=size(I_GT);
size2=Q_blocks_size;
stepx=ceil(N1/Q_shift);
stepy=ceil(N2/Q_shift);
if stepy<=0
stepy=1;
stepx=1;
end
est1=(stepx-1)*Q_shift+Q_blocks_size-N1;
est2=(stepy-1)*Q_shift+Q_blocks_size-N2;
if sum([(est1~=0),(est2~=0)])>0
refref=[];
fusfus=[];
for i=1:N3
a1=squeeze(I_GT(:,:,1));
ia1=zeros(N1+est1,N2+est2);
ia1(1:N1,1:N2)=a1;
ia1(:,N2+1:N2+est2)=ia1(:,N2:-1:N2-est2+1);
ia1(N1+1:N1+est1,:)=ia1(N1:-1:N1-est1+1,:);
refref=cat(3,refref,ia1);
if i<N3
I_GT=I_GT(:,:,2:end);
end
end
I_GT=refref;
clear refref
for i=1:N3
a2=squeeze(I_F(:,:,1));
ia2=zeros(N1+est1,N2+est2);
ia2(1:N1,1:N2)=a2;
ia2(:,N2+1:N2+est2)=ia2(:,N2:-1:N2-est2+1);
ia2(N1+1:N1+est1,:)=ia2(N1:-1:N1-est1+1,:);
fusfus=cat(3,fusfus,ia2);
if i<N3
I_F=I_F(:,:,2:end);
end
end
I_F=fusfus;
clear fusfus a1 a2 ia1 ia2
end
I_F=uint16(I_F);
I_GT=uint16(I_GT);
[N1,N2,N3]=size(I_GT);
if ((ceil(log2(N3)))-log2(N3))~=0
Ndif=(2^(ceil(log2(N3))))-N3;
dif=zeros(N1,N2,Ndif);
dif=uint16(dif);
I_GT=cat(3,I_GT,dif);
I_F=cat(3,I_F,dif);
end
[~,~,N3]=size(I_GT);
valori=zeros(stepx,stepy,N3);
for j=1:stepx
for i=1:stepy
o=onions_quality(I_GT(((j-1)*Q_shift)+1:((j-1)*Q_shift)+Q_blocks_size,((i-1)*Q_shift)+1:((i-1)*Q_shift)+size2,:),I_F(((j-1)*Q_shift)+1:((j-1)*Q_shift)+Q_blocks_size,((i-1)*Q_shift)+1:((i-1)*Q_shift)+size2,:),Q_blocks_size);
valori(j,i,:)=o;
end
end
Q2n_index_map=sqrt(sum((valori.^2),3));
Q2n_index=mean2(Q2n_index_map);
end
|
2977094657/BiliHistoryFrontend
| 1,538
|
src/components/tailwind/SimpleSearchBar.vue
|
<template>
<div class="relative">
<div class="flex h-9 items-center rounded-md border border-gray-300 bg-white focus-within:border-[#fb7299] transition-colors duration-200">
<!-- 搜索图标 -->
<div class="pl-3 text-gray-400">
<svg xmlns="http://www.w3.org/2000/svg" class="h-3.5 w-3.5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z" />
</svg>
</div>
<!-- 输入框 -->
<input
:value="modelValue"
@input="$emit('update:modelValue', $event.target.value)"
type="search"
:placeholder="placeholder"
class="h-full w-full border-none bg-transparent px-2 pr-3 text-gray-700 focus:outline-none focus:ring-0 text-xs leading-none"
@keyup.enter="$emit('search')"
@search="$emit('search')"
/>
</div>
</div>
</template>
<script setup>
defineProps({
modelValue: {
type: String,
default: ''
},
placeholder: {
type: String,
default: '输入关键词搜索...'
}
})
defineEmits(['update:modelValue', 'search'])
</script>
<style scoped>
/* 移除搜索框的默认样式 */
input[type="search"]::-webkit-search-decoration,
input[type="search"]::-webkit-search-cancel-button,
input[type="search"]::-webkit-search-results-button,
input[type="search"]::-webkit-search-results-decoration {
display: none;
}
/* 移除输入框的默认focus样式 */
input:focus {
box-shadow: none !important;
outline: none !important;
}
</style>
|
281677160/openwrt-package
| 27,315
|
luci-app-passwall2/luasrc/controller/passwall2.lua
|
-- Copyright (C) 2022-2025 xiaorouji
module("luci.controller.passwall2", package.seeall)
local api = require "luci.passwall2.api"
local appname = api.appname -- not available
local uci = api.uci -- in funtion index()
local http = require "luci.http"
local util = require "luci.util"
local i18n = require "luci.i18n"
local fs = api.fs
local jsonStringify = luci.jsonc.stringify
function index()
if not nixio.fs.access("/etc/config/passwall2") then
if nixio.fs.access("/usr/share/passwall2/0_default_config") then
luci.sys.call('cp -f /usr/share/passwall2/0_default_config /etc/config/passwall2')
else return end
end
local api = require "luci.passwall2.api"
local appname = api.appname -- global definitions not available
local uci = api.uci -- in function index()
entry({"admin", "services", appname}).dependent = true
entry({"admin", "services", appname, "reset_config"}, call("reset_config")).leaf = true
entry({"admin", "services", appname, "show"}, call("show_menu")).leaf = true
entry({"admin", "services", appname, "hide"}, call("hide_menu")).leaf = true
local e
if uci:get(appname, "@global[0]", "hide_from_luci") ~= "1" then
e = entry({"admin", "services", appname}, alias("admin", "services", appname, "settings"), _("PassWall 2"), 0)
else
e = entry({"admin", "services", appname}, alias("admin", "services", appname, "settings"), nil, 0)
end
e.dependent = true
e.acl_depends = { "luci-app-passwall2" }
--[[ Client ]]
entry({"admin", "services", appname, "settings"}, cbi(appname .. "/client/global"), _("Basic Settings"), 1).dependent = true
entry({"admin", "services", appname, "node_list"}, cbi(appname .. "/client/node_list"), _("Node List"), 2).dependent = true
entry({"admin", "services", appname, "node_subscribe"}, cbi(appname .. "/client/node_subscribe"), _("Node Subscribe"), 3).dependent = true
entry({"admin", "services", appname, "other"}, cbi(appname .. "/client/other", {autoapply = true}), _("Other Settings"), 92).leaf = true
if nixio.fs.access("/usr/sbin/haproxy") then
entry({"admin", "services", appname, "haproxy"}, cbi(appname .. "/client/haproxy"), _("Load Balancing"), 93).leaf = true
end
entry({"admin", "services", appname, "app_update"}, cbi(appname .. "/client/app_update"), _("App Update"), 95).leaf = true
entry({"admin", "services", appname, "rule"}, cbi(appname .. "/client/rule"), _("Rule Manage"), 96).leaf = true
entry({"admin", "services", appname, "geoview"}, form(appname .. "/client/geoview"), _("Geo View"), 97).leaf = true
entry({"admin", "services", appname, "node_subscribe_config"}, cbi(appname .. "/client/node_subscribe_config")).leaf = true
entry({"admin", "services", appname, "node_config"}, cbi(appname .. "/client/node_config")).leaf = true
entry({"admin", "services", appname, "shunt_rules"}, cbi(appname .. "/client/shunt_rules")).leaf = true
entry({"admin", "services", appname, "socks_config"}, cbi(appname .. "/client/socks_config")).leaf = true
entry({"admin", "services", appname, "acl"}, cbi(appname .. "/client/acl"), _("Access control"), 98).leaf = true
entry({"admin", "services", appname, "acl_config"}, cbi(appname .. "/client/acl_config")).leaf = true
entry({"admin", "services", appname, "log"}, form(appname .. "/client/log"), _("Watch Logs"), 999).leaf = true
--[[ Server ]]
entry({"admin", "services", appname, "server"}, cbi(appname .. "/server/index"), _("Server-Side"), 99).leaf = true
entry({"admin", "services", appname, "server_user"}, cbi(appname .. "/server/user")).leaf = true
--[[ API ]]
entry({"admin", "services", appname, "server_user_status"}, call("server_user_status")).leaf = true
entry({"admin", "services", appname, "server_user_log"}, call("server_user_log")).leaf = true
entry({"admin", "services", appname, "server_get_log"}, call("server_get_log")).leaf = true
entry({"admin", "services", appname, "server_clear_log"}, call("server_clear_log")).leaf = true
entry({"admin", "services", appname, "link_add_node"}, call("link_add_node")).leaf = true
entry({"admin", "services", appname, "socks_autoswitch_add_node"}, call("socks_autoswitch_add_node")).leaf = true
entry({"admin", "services", appname, "socks_autoswitch_remove_node"}, call("socks_autoswitch_remove_node")).leaf = true
entry({"admin", "services", appname, "gen_client_config"}, call("gen_client_config")).leaf = true
entry({"admin", "services", appname, "get_now_use_node"}, call("get_now_use_node")).leaf = true
entry({"admin", "services", appname, "get_redir_log"}, call("get_redir_log")).leaf = true
entry({"admin", "services", appname, "get_socks_log"}, call("get_socks_log")).leaf = true
entry({"admin", "services", appname, "get_log"}, call("get_log")).leaf = true
entry({"admin", "services", appname, "clear_log"}, call("clear_log")).leaf = true
entry({"admin", "services", appname, "index_status"}, call("index_status")).leaf = true
entry({"admin", "services", appname, "haproxy_status"}, call("haproxy_status")).leaf = true
entry({"admin", "services", appname, "socks_status"}, call("socks_status")).leaf = true
entry({"admin", "services", appname, "connect_status"}, call("connect_status")).leaf = true
entry({"admin", "services", appname, "ping_node"}, call("ping_node")).leaf = true
entry({"admin", "services", appname, "urltest_node"}, call("urltest_node")).leaf = true
entry({"admin", "services", appname, "set_node"}, call("set_node")).leaf = true
entry({"admin", "services", appname, "copy_node"}, call("copy_node")).leaf = true
entry({"admin", "services", appname, "clear_all_nodes"}, call("clear_all_nodes")).leaf = true
entry({"admin", "services", appname, "delete_select_nodes"}, call("delete_select_nodes")).leaf = true
entry({"admin", "services", appname, "update_rules"}, call("update_rules")).leaf = true
entry({"admin", "services", appname, "subscribe_del_node"}, call("subscribe_del_node")).leaf = true
entry({"admin", "services", appname, "subscribe_del_all"}, call("subscribe_del_all")).leaf = true
entry({"admin", "services", appname, "subscribe_manual"}, call("subscribe_manual")).leaf = true
entry({"admin", "services", appname, "subscribe_manual_all"}, call("subscribe_manual_all")).leaf = true
--[[Components update]]
entry({"admin", "services", appname, "check_passwall2"}, call("app_check")).leaf = true
local coms = require "luci.passwall2.com"
local com
for com, _ in pairs(coms) do
entry({"admin", "services", appname, "check_" .. com}, call("com_check", com)).leaf = true
entry({"admin", "services", appname, "update_" .. com}, call("com_update", com)).leaf = true
end
--[[Backup]]
entry({"admin", "services", appname, "create_backup"}, call("create_backup")).leaf = true
entry({"admin", "services", appname, "restore_backup"}, call("restore_backup")).leaf = true
--[[geoview]]
entry({"admin", "services", appname, "geo_view"}, call("geo_view")).leaf = true
end
local function http_write_json(content)
http.prepare_content("application/json")
http.write(jsonStringify(content or {code = 1}))
end
function reset_config()
luci.sys.call('/etc/init.d/passwall2 stop')
luci.sys.call('[ -f "/usr/share/passwall2/0_default_config" ] && cp -f /usr/share/passwall2/0_default_config /etc/config/passwall2')
http.redirect(api.url())
end
function show_menu()
api.sh_uci_del(appname, "@global[0]", "hide_from_luci", true)
luci.sys.call("rm -rf /tmp/luci-*")
luci.sys.call("/etc/init.d/rpcd restart >/dev/null")
http.redirect(api.url())
end
function hide_menu()
api.sh_uci_set(appname, "@global[0]", "hide_from_luci", "1", true)
luci.sys.call("rm -rf /tmp/luci-*")
luci.sys.call("/etc/init.d/rpcd restart >/dev/null")
http.redirect(luci.dispatcher.build_url("admin", "status", "overview"))
end
function link_add_node()
-- 分片接收以突破uhttpd的限制
local tmp_file = "/tmp/links.conf"
local chunk = http.formvalue("chunk")
local chunk_index = tonumber(http.formvalue("chunk_index"))
local total_chunks = tonumber(http.formvalue("total_chunks"))
if chunk and chunk_index ~= nil and total_chunks ~= nil then
-- 按顺序拼接到文件
local mode = "a"
if chunk_index == 0 then
mode = "w"
end
local f = io.open(tmp_file, mode)
if f then
f:write(chunk)
f:close()
end
-- 如果是最后一片,才执行
if chunk_index + 1 == total_chunks then
luci.sys.call("lua /usr/share/passwall2/subscribe.lua add log")
end
end
end
function socks_autoswitch_add_node()
local id = http.formvalue("id")
local key = http.formvalue("key")
if id and id ~= "" and key and key ~= "" then
uci:set(appname, id, "enable_autoswitch", "1")
local new_list = uci:get(appname, id, "autoswitch_backup_node") or {}
for i = #new_list, 1, -1 do
if (uci:get(appname, new_list[i], "remarks") or ""):find(key) then
table.remove(new_list, i)
end
end
for k, e in ipairs(api.get_valid_nodes()) do
if e.node_type == "normal" and e["remark"]:find(key) then
table.insert(new_list, e.id)
end
end
uci:set_list(appname, id, "autoswitch_backup_node", new_list)
api.uci_save(uci, appname)
end
http.redirect(api.url("socks_config", id))
end
function socks_autoswitch_remove_node()
local id = http.formvalue("id")
local key = http.formvalue("key")
if id and id ~= "" and key and key ~= "" then
uci:set(appname, id, "enable_autoswitch", "1")
local new_list = uci:get(appname, id, "autoswitch_backup_node") or {}
for i = #new_list, 1, -1 do
if (uci:get(appname, new_list[i], "remarks") or ""):find(key) then
table.remove(new_list, i)
end
end
uci:set_list(appname, id, "autoswitch_backup_node", new_list)
api.uci_save(uci, appname)
end
http.redirect(api.url("socks_config", id))
end
function gen_client_config()
local id = http.formvalue("id")
local config_file = api.TMP_PATH .. "/config_" .. id
luci.sys.call(string.format("/usr/share/passwall2/app.sh run_socks flag=config_%s node=%s bind=127.0.0.1 socks_port=1080 config_file=%s no_run=1", id, id, config_file))
if nixio.fs.access(config_file) then
http.prepare_content("application/json")
http.write(luci.sys.exec("cat " .. config_file))
luci.sys.call("rm -f " .. config_file)
else
http.redirect(api.url("node_list"))
end
end
function get_now_use_node()
local e = {}
local node = api.get_cache_var("ACL_GLOBAL_node")
if node then
e["global"] = node
end
http_write_json(e)
end
function get_redir_log()
local id = http.formvalue("id")
local name = http.formvalue("name")
local file_path = "/tmp/etc/passwall2/acl/" .. id .. "/" .. name .. ".log"
if nixio.fs.access(file_path) then
local content = luci.sys.exec("tail -n 19999 '" .. file_path .. "'")
content = content:gsub("\n", "<br />")
http.write(content)
else
http.write(string.format("<script>alert('%s');window.close();</script>", i18n.translate("Not enabled log")))
end
end
function get_socks_log()
local name = http.formvalue("name")
local path = "/tmp/etc/passwall2/SOCKS_" .. name .. ".log"
if nixio.fs.access(path) then
local content = luci.sys.exec("tail -n 5000 ".. path)
content = content:gsub("\n", "<br />")
http.write(content)
else
http.write(string.format("<script>alert('%s');window.close();</script>", i18n.translate("Not enabled log")))
end
end
function get_log()
-- luci.sys.exec("[ -f /tmp/log/passwall2.log ] && sed '1!G;h;$!d' /tmp/log/passwall2.log > /tmp/log/passwall2_show.log")
http.write(luci.sys.exec("[ -f '/tmp/log/passwall2.log' ] && cat /tmp/log/passwall2.log"))
end
function clear_log()
luci.sys.call("echo '' > /tmp/log/passwall2.log")
end
function index_status()
local e = {}
e["global_status"] = luci.sys.call("/bin/busybox top -bn1 | grep -v 'grep' | grep '/tmp/etc/passwall2/bin/' | grep 'default' | grep 'global' >/dev/null") == 0
http_write_json(e)
end
function haproxy_status()
local e = luci.sys.call(string.format("/bin/busybox top -bn1 | grep -v grep | grep '%s/bin/' | grep haproxy >/dev/null", appname)) == 0
http_write_json(e)
end
function socks_status()
local e = {}
local index = http.formvalue("index")
local id = http.formvalue("id")
e.index = index
e.socks_status = luci.sys.call(string.format("/bin/busybox top -bn1 | grep -v -E 'grep|acl/|acl_' | grep '%s/bin/' | grep '%s' | grep 'SOCKS_' > /dev/null", appname, id)) == 0
local use_http = uci:get(appname, id, "http_port") or 0
e.use_http = 0
if tonumber(use_http) > 0 then
e.use_http = 1
e.http_status = luci.sys.call(string.format("/bin/busybox top -bn1 | grep -v -E 'grep|acl/|acl_' | grep '%s/bin/' | grep '%s' | grep -E 'HTTP_|HTTP2SOCKS' > /dev/null", appname, id)) == 0
end
http_write_json(e)
end
function connect_status()
local e = {}
e.use_time = ""
local url = http.formvalue("url")
local result = luci.sys.exec('curl --connect-timeout 3 -o /dev/null -I -sk -w "%{http_code}:%{time_appconnect}" ' .. url)
local code = tonumber(luci.sys.exec("echo -n '" .. result .. "' | awk -F ':' '{print $1}'") or "0")
if code ~= 0 then
local use_time = luci.sys.exec("echo -n '" .. result .. "' | awk -F ':' '{print $2}'")
if use_time:find("%.") then
e.use_time = string.format("%.2f", use_time * 1000)
else
e.use_time = string.format("%.2f", use_time / 1000)
end
e.ping_type = "curl"
end
http_write_json(e)
end
function ping_node()
local index = http.formvalue("index")
local address = http.formvalue("address")
local port = http.formvalue("port")
local type = http.formvalue("type") or "icmp"
local e = {}
e.index = index
if type == "tcping" and luci.sys.exec("echo -n $(command -v tcping)") ~= "" then
if api.is_ipv6(address) then
address = api.get_ipv6_only(address)
end
e.ping = luci.sys.exec(string.format("echo -n $(tcping -q -c 1 -i 1 -t 2 -p %s %s 2>&1 | grep -o 'time=[0-9]*' | awk -F '=' '{print $2}') 2>/dev/null", port, address))
else
e.ping = luci.sys.exec("echo -n $(ping -c 1 -W 1 %q 2>&1 | grep -o 'time=[0-9]*' | awk -F '=' '{print $2}') 2>/dev/null" % address)
end
http_write_json(e)
end
function urltest_node()
local index = http.formvalue("index")
local id = http.formvalue("id")
local e = {}
e.index = index
local result = luci.sys.exec(string.format("/usr/share/passwall2/test.sh url_test_node %s %s", id, "urltest_node"))
local code = tonumber(luci.sys.exec("echo -n '" .. result .. "' | awk -F ':' '{print $1}'") or "0")
if code ~= 0 then
local use_time = luci.sys.exec("echo -n '" .. result .. "' | awk -F ':' '{print $2}'")
if use_time:find("%.") then
e.use_time = string.format("%.2f", use_time * 1000)
else
e.use_time = string.format("%.2f", use_time / 1000)
end
end
http_write_json(e)
end
function set_node()
local type = http.formvalue("type")
local config = http.formvalue("config")
local section = http.formvalue("section")
uci:set(appname, type, config, section)
api.uci_save(uci, appname, true, true)
http.redirect(api.url("log"))
end
function copy_node()
local section = http.formvalue("section")
local uuid = api.gen_short_uuid()
uci:section(appname, "nodes", uuid)
for k, v in pairs(uci:get_all(appname, section)) do
local filter = k:find("%.")
if filter and filter == 1 then
else
xpcall(function()
uci:set(appname, uuid, k, v)
end,
function(e)
end)
end
end
uci:delete(appname, uuid, "add_from")
uci:set(appname, uuid, "add_mode", 1)
api.uci_save(uci, appname)
http.redirect(api.url("node_config", uuid))
end
function clear_all_nodes()
uci:set(appname, '@global[0]', "enabled", "0")
uci:set(appname, '@global[0]', "socks_enabled", "0")
uci:set(appname, '@haproxy_config[0]', "balancing_enable", "0")
uci:delete(appname, '@global[0]', "node")
uci:foreach(appname, "socks", function(t)
uci:delete(appname, t[".name"])
uci:set_list(appname, t[".name"], "autoswitch_backup_node", {})
end)
uci:foreach(appname, "haproxy_config", function(t)
uci:delete(appname, t[".name"])
end)
uci:foreach(appname, "acl_rule", function(t)
uci:delete(appname, t[".name"], "node")
end)
uci:foreach(appname, "nodes", function(node)
uci:delete(appname, node['.name'])
end)
uci:foreach(appname, "subscribe_list", function(t)
uci:delete(appname, t[".name"], "md5")
uci:delete(appname, t[".name"], "chain_proxy")
uci:delete(appname, t[".name"], "preproxy_node")
uci:delete(appname, t[".name"], "to_node")
end)
api.uci_save(uci, appname, true, true)
end
function delete_select_nodes()
local ids = http.formvalue("ids")
string.gsub(ids, '[^' .. "," .. ']+', function(w)
if (uci:get(appname, "@global[0]", "node") or "") == w then
uci:delete(appname, '@global[0]', "node")
end
uci:foreach(appname, "socks", function(t)
if t["node"] == w then
uci:delete(appname, t[".name"])
end
local auto_switch_node_list = uci:get(appname, t[".name"], "autoswitch_backup_node") or {}
for i = #auto_switch_node_list, 1, -1 do
if w == auto_switch_node_list[i] then
table.remove(auto_switch_node_list, i)
end
end
uci:set_list(appname, t[".name"], "autoswitch_backup_node", auto_switch_node_list)
end)
uci:foreach(appname, "haproxy_config", function(t)
if t["lbss"] == w then
uci:delete(appname, t[".name"])
end
end)
uci:foreach(appname, "acl_rule", function(t)
if t["node"] == w then
uci:delete(appname, t[".name"], "node")
end
end)
uci:foreach(appname, "nodes", function(t)
if t["preproxy_node"] == w then
uci:delete(appname, t[".name"], "preproxy_node")
uci:delete(appname, t[".name"], "chain_proxy")
end
if t["to_node"] == w then
uci:delete(appname, t[".name"], "to_node")
uci:delete(appname, t[".name"], "chain_proxy")
end
local list_name = t["urltest_node"] and "urltest_node" or (t["balancing_node"] and "balancing_node")
if list_name then
local nodes = uci:get_list(appname, t[".name"], list_name)
if nodes then
local changed = false
local new_nodes = {}
for _, node in ipairs(nodes) do
if node ~= w then
table.insert(new_nodes, node)
else
changed = true
end
end
if changed then
uci:set_list(appname, t[".name"], list_name, new_nodes)
end
end
end
if t["fallback_node"] == w then
uci:delete(appname, t[".name"], "fallback_node")
end
end)
uci:foreach(appname, "subscribe_list", function(t)
if t["preproxy_node"] == w then
uci:delete(appname, t[".name"], "preproxy_node")
uci:delete(appname, t[".name"], "chain_proxy")
end
if t["to_node"] == w then
uci:delete(appname, t[".name"], "to_node")
uci:delete(appname, t[".name"], "chain_proxy")
end
end)
if (uci:get(appname, w, "add_mode") or "0") == "2" then
local add_from = uci:get(appname, w, "add_from") or ""
if add_from ~= "" then
uci:foreach(appname, "subscribe_list", function(t)
if t["remark"] == add_from then
uci:delete(appname, t[".name"], "md5")
end
end)
end
end
uci:delete(appname, w)
end)
api.uci_save(uci, appname, true, true)
end
function update_rules()
local update = http.formvalue("update")
luci.sys.call("lua /usr/share/passwall2/rule_update.lua log '" .. update .. "' > /dev/null 2>&1 &")
http_write_json()
end
function server_user_status()
local e = {}
e.index = http.formvalue("index")
e.status = luci.sys.call(string.format("/bin/busybox top -bn1 | grep -v 'grep' | grep '%s/bin/' | grep -i '%s' >/dev/null", appname .. "_server", http.formvalue("id"))) == 0
http_write_json(e)
end
function server_user_log()
local id = http.formvalue("id")
if nixio.fs.access("/tmp/etc/passwall2_server/" .. id .. ".log") then
local content = luci.sys.exec("cat /tmp/etc/passwall2_server/" .. id .. ".log")
content = content:gsub("\n", "<br />")
http.write(content)
else
http.write(string.format("<script>alert('%s');window.close();</script>", i18n.translate("Not enabled log")))
end
end
function server_get_log()
http.write(luci.sys.exec("[ -f '/tmp/log/passwall2_server.log' ] && cat /tmp/log/passwall2_server.log"))
end
function server_clear_log()
luci.sys.call("echo '' > /tmp/log/passwall2_server.log")
end
function app_check()
local json = api.to_check_self()
http_write_json(json)
end
function com_check(comname)
local json = api.to_check("", comname)
http_write_json(json)
end
function com_update(comname)
local json = nil
local task = http.formvalue("task")
if task == "extract" then
json = api.to_extract(comname, http.formvalue("file"), http.formvalue("subfix"))
elseif task == "move" then
json = api.to_move(comname, http.formvalue("file"))
else
json = api.to_download(comname, http.formvalue("url"), http.formvalue("size"))
end
http_write_json(json)
end
local backup_files = {
"/etc/config/passwall2",
"/etc/config/passwall2_server",
"/usr/share/passwall2/domains_excluded"
}
function create_backup()
local date = os.date("%y%m%d%H%M")
local tar_file = "/tmp/passwall2-" .. date .. "-backup.tar.gz"
fs.remove(tar_file)
local cmd = "tar -czf " .. tar_file .. " " .. table.concat(backup_files, " ")
api.sys.call(cmd)
http.header("Content-Disposition", "attachment; filename=passwall2-" .. date .. "-backup.tar.gz")
http.header("X-Backup-Filename", "passwall2-" .. date .. "-backup.tar.gz")
http.prepare_content("application/octet-stream")
http.write(fs.readfile(tar_file))
fs.remove(tar_file)
end
function restore_backup()
local result = { status = "error", message = "unknown error" }
local ok, err = pcall(function()
local filename = http.formvalue("filename")
local chunk = http.formvalue("chunk")
local chunk_index = tonumber(http.formvalue("chunk_index") or "-1")
local total_chunks = tonumber(http.formvalue("total_chunks") or "-1")
if not filename then
result = { status = "error", message = "Missing filename" }
return
end
if not chunk then
result = { status = "error", message = "Missing chunk data" }
return
end
local file_path = "/tmp/" .. filename
local decoded = nixio.bin.b64decode(chunk)
if not decoded then
result = { status = "error", message = "Base64 decode failed" }
return
end
local fp = io.open(file_path, "a+")
if not fp then
result = { status = "error", message = "Failed to open file: " .. file_path }
return
end
fp:write(decoded)
fp:close()
if chunk_index + 1 == total_chunks then
api.sys.call("echo '' > /tmp/log/passwall2.log")
api.log(" * PassWall2 配置文件上传成功…")
local temp_dir = '/tmp/passwall2_bak'
api.sys.call("mkdir -p " .. temp_dir)
if api.sys.call("tar -xzf " .. file_path .. " -C " .. temp_dir) == 0 then
for _, backup_file in ipairs(backup_files) do
local temp_file = temp_dir .. backup_file
if fs.access(temp_file) then
api.sys.call("cp -f " .. temp_file .. " " .. backup_file)
end
end
api.log(" * PassWall2 配置还原成功…")
api.log(" * 重启 PassWall2 服务中…\n")
luci.sys.call('/etc/init.d/passwall2 restart > /dev/null 2>&1 &')
luci.sys.call('/etc/init.d/passwall2_server restart > /dev/null 2>&1 &')
result = { status = "success", message = "Upload completed", path = file_path }
else
api.log(" * PassWall2 配置文件解压失败,请重试!")
result = { status = "error", message = "Decompression failed" }
end
api.sys.call("rm -rf " .. temp_dir)
fs.remove(file_path)
else
result = { status = "success", message = "Chunk received" }
end
end)
if not ok then
result = { status = "error", message = tostring(err) }
end
http_write_json(result)
end
function geo_view()
local action = luci.http.formvalue("action")
local value = luci.http.formvalue("value")
if not value or value == "" then
http.prepare_content("text/plain")
http.write(i18n.translate("Please enter query content!"))
return
end
local geo_dir = (uci:get(appname, "@global_rules[0]", "v2ray_location_asset") or "/usr/share/v2ray/"):match("^(.*)/")
local geosite_path = geo_dir .. "/geosite.dat"
local geoip_path = geo_dir .. "/geoip.dat"
local geo_type, file_path, cmd
local geo_string = ""
if action == "lookup" then
if api.datatypes.ipaddr(value) or api.datatypes.ip6addr(value) then
geo_type, file_path = "geoip", geoip_path
else
geo_type, file_path = "geosite", geosite_path
end
cmd = string.format("geoview -type %s -action lookup -input '%s' -value '%s' -lowmem=true", geo_type, file_path, value)
geo_string = luci.sys.exec(cmd):lower()
if geo_string ~= "" then
local lines = {}
for line in geo_string:gmatch("([^\n]*)\n?") do
if line ~= "" then
table.insert(lines, geo_type .. ":" .. line)
end
end
geo_string = table.concat(lines, "\n")
end
elseif action == "extract" then
local prefix, list = value:match("^(geoip:)(.*)$")
if not prefix then
prefix, list = value:match("^(geosite:)(.*)$")
end
if prefix and list and list ~= "" then
geo_type = prefix:sub(1, -2)
file_path = (geo_type == "geoip") and geoip_path or geosite_path
cmd = string.format("geoview -type %s -action extract -input '%s' -list '%s' -lowmem=true", geo_type, file_path, list)
geo_string = luci.sys.exec(cmd)
end
end
http.prepare_content("text/plain")
if geo_string and geo_string ~="" then
http.write(geo_string)
else
http.write(i18n.translate("No results were found!"))
end
end
function subscribe_del_node()
local remark = http.formvalue("remark")
if remark and remark ~= "" then
luci.sys.call("lua /usr/share/" .. appname .. "/subscribe.lua truncate " .. luci.util.shellquote(remark) .. " > /dev/null 2>&1")
end
http.status(200, "OK")
end
function subscribe_del_all()
luci.sys.call("lua /usr/share/" .. appname .. "/subscribe.lua truncate > /dev/null 2>&1")
http.status(200, "OK")
end
function subscribe_manual()
local section = http.formvalue("section") or ""
local current_url = http.formvalue("url") or ""
if section == "" or current_url == "" then
http_write_json({ success = false, msg = "Missing section or URL, skip." })
return
end
local uci_url = api.sh_uci_get(appname, section, "url")
if not uci_url or uci_url == "" then
http_write_json({ success = false, msg = i18n.translate("Please save and apply before manually subscribing.") })
return
end
if uci_url ~= current_url then
api.sh_uci_set(appname, section, "url", current_url, true)
end
luci.sys.call("lua /usr/share/" .. appname .. "/subscribe.lua start " .. section .. " manual >/dev/null 2>&1 &")
http_write_json({ success = true, msg = "Subscribe triggered." })
end
function subscribe_manual_all()
local sections = http.formvalue("sections") or ""
local urls = http.formvalue("urls") or ""
if sections == "" or urls == "" then
http_write_json({ success = false, msg = "Missing section or URL, skip." })
return
end
local section_list = util.split(sections, ",")
local url_list = util.split(urls, ",")
-- 检查是否存在未保存配置
for i, section in ipairs(section_list) do
local uci_url = api.sh_uci_get(appname, section, "url")
if not uci_url or uci_url == "" then
http_write_json({ success = false, msg = i18n.translate("Please save and apply before manually subscribing.") })
return
end
end
-- 保存有变动的url
for i, section in ipairs(section_list) do
local current_url = url_list[i] or ""
local uci_url = api.sh_uci_get(appname, section, "url")
if current_url ~= "" and uci_url ~= current_url then
api.sh_uci_set(appname, section, "url", current_url, true)
end
end
luci.sys.call("lua /usr/share/" .. appname .. "/subscribe.lua start all manual >/dev/null 2>&1 &")
http_write_json({ success = true, msg = "Subscribe triggered." })
end
|
2881099/FreeSql.AdminLTE
| 4,389
|
Examples/net60_preview/Startup.cs
|
using FreeSql;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Routing;
using Microsoft.AspNetCore.Routing;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using net60_preview.Entitys;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
namespace net60_preview
{
public class Startup
{
public Startup(IConfiguration configuration, ILoggerFactory loggerFactory)
{
Configuration = configuration;
Fsql = new FreeSql.FreeSqlBuilder()
.UseConnectionString(FreeSql.DataType.Sqlite, @"Data Source=|DataDirectory|/document.db;Pooling=true;Max Pool Size=10")
.UseAutoSyncStructure(true)
.UseMonitorCommand(cmd => Console.WriteLine(cmd.CommandText + "\r\n"))
.Build();
}
public IConfiguration Configuration { get; }
public static IFreeSql Fsql { get; private set; }
public void ConfigureServices(IServiceCollection services)
{
services.AddControllersWithViews();
services.AddSingleton(Fsql);
}
public void Configure(IApplicationBuilder app)
{
app.UseHttpMethodOverride(new HttpMethodOverrideOptions { FormFieldName = "X-Http-Method-Override" });
app.UseDeveloperExceptionPage();
app.UseRouting();
app.UseEndpoints(a => a.MapControllers());
app.UseDefaultFiles();
app.UseStaticFiles();
//可以配置子目录访问,如:/testadmin/
app.UseFreeAdminLtePreview("/",
typeof(Song),
typeof(Tag),
typeof(User),
typeof(UserImage)
);
}
void TestRoute()
{
var controllers = typeof(Startup).Assembly.GetTypes().Where(a => typeof(Controller).IsAssignableFrom(a)).ToArray();
var routes = controllers.Select(a =>
{
var tb = Fsql.CodeFirst.GetTableByEntity(a);
var name = string.IsNullOrWhiteSpace(tb.Comment) ? a.Name : tb.Comment;
var controller = a.Name.EndsWith("Controller") ? a.Name.Remove(a.Name.Length - 10) : a.Name;
var path = a.GetCustomAttribute<RouteAttribute>()?.Template.Replace("[controller]", controller) ?? $"/controller";
var route = new AdminRoute
{
Name = name,
Path = path,
Create_time = DateTime.Now,
Extdata = JsonConvert.SerializeObject(new { icon = "org_tree_page", path = "/authuser", name = "sysadmin_authuser", component = "@/view/sysadmin/authuser-page.vue" }),
Childs = a.GetMethods().Select(m =>
{
HttpMethodAttribute httpmethod = m.GetCustomAttribute<HttpGetAttribute>();
if (httpmethod == null) httpmethod = m.GetCustomAttribute<HttpPostAttribute>();
if (httpmethod == null) httpmethod = m.GetCustomAttribute<HttpPutAttribute>();
if (httpmethod == null) httpmethod = m.GetCustomAttribute<HttpDeleteAttribute>();
if (httpmethod != null) return new AdminRoute
{
Name = LocalGetMethodName(httpmethod.Name),
Path = $"{httpmethod.HttpMethods.FirstOrDefault()} {path}/{httpmethod.Template}",
Create_time = DateTime.Now,
};
return null;
}).Where(a => a != null).ToList()
};
return route;
}).ToList();
string LocalGetMethodName(string name)
{
switch (name)
{
case "": return "列表";
case "add": return "添加";
case "edit": return "编辑";
case "del": return "添加";
}
return name;
}
}
}
public interface ISoftDelete
{
bool IsDeleted { get; set; }
}
}
|
294coder/Efficient-MIF
| 1,501
|
Pansharpening_Hyper_SR_Matlab_Test_Package/Quality_Indices/D_lambda_K.m
|
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Description:
% Spectral distortion index of the Hybrid Quality with No Reference (HQNR).
%
% Interface:
% Dl = D_lambda_K(fused,ms,ratio,sensor,S)
%
% Inputs:
% fused: Pansharpened image;
% msexp: MS image resampled to panchromatic scale;
% sensor: Type of sensor;
% ratio: Resolution ratio;
% S: Block size (optional); Default value: 32.
%
% Outputs:
% Dl: D_lambda index.
%
% Reference:
% [Khan09] M. M. Khan, L. Alparone, and J. Chanussot, "Pansharpening quality assessment using the modulation transfer functions of instruments,"
% IEEE Transactions on Geoscience and Remote Sensing, vol. 47, no. 11, pp. 3880-3891, 2009.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function Dl = D_lambda_K(fused,msexp,ratio,sensor,S)
if (size(fused,1) ~= size(msexp,1) || size(fused,2) ~= size(msexp,2))
error('The two images must have the same dimensions')
end
[N,M,~] = size(fused);
if (rem(N,S) ~= 0)
error('number of rows must be multiple of the block size')
end
if (rem(M,S) ~= 0)
error('number of columns must be multiple of the block size')
end
fused_degraded = MTF(fused,sensor,ratio);
[Q2n_index,~] = q2n(msexp,fused_degraded,S,S);
Dl = 1-Q2n_index;
end
|
294coder/Efficient-MIF
| 4,411
|
Pansharpening_Hyper_SR_Matlab_Test_Package/FE-HPM/FE.m
|
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Description:
% FE estimates the estraction detail filter via deconvolution.
%
% Interface:
% PSF_l = FE(I_MS,I_PAN,ratio,tap,lambda,mu,th,num_iter,filtername)
%
% Inputs:
% I_MS: MS image upsampled at PAN scale;
% I_PAN: PAN image;
% ratio: Scale ratio between MS and PAN. Pre-condition: Integer value.
% tap: Filter support;
% lambda: Coefficient for weighting the energy regularization term;
% mu: Coefficient for weighting the derivative regularization terms;
% th: Threshold on the kernel (it cuts to 0 values below threshold);
% num_iter: Max number of iteration (at least 3; not sensitive);
% filtername: Kind of derivative (default: 'Basic')
%
% Output:
% PSF_l: Estimated point spread function.
%
% Reference:
% [Vivone15] G. Vivone, M. Simoes, M. Dalla Mura, R. Restaino, J. Bioucas-Dias, G. A. Licciardi, and J. Chanussot, "Pansharpening based on semiblind deconvolution",
% IEEE Transactions on Geoscience and Remote Sensing, vol. 53, no. 4, pp. 1997-2010, 2015.
% [Vivone20] G. Vivone, M. Dalla Mura, A. Garzelli, R. Restaino, G. Scarpa, M.O. Ulfarsson, L. Alparone, and J. Chanussot, "A New Benchmark Based on Recent Advances in Multispectral Pansharpening: Revisiting pansharpening with classical and emerging pansharpening methods",
% IEEE Geoscience and Remote Sensing Magazine, doi: 10.1109/MGRS.2020.3019315.
% % % % % % % % % % % % %
%
% Version: 1
%
% % % % % % % % % % % % %
%
% Copyright (C) 2019
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function PSF_l = FE(I_MS,I_PAN,ratio,tap,lambda,mu,th,num_iter,filtername)
if rem(tap,2) == 0
sum_tap = 0;
else
sum_tap = 1;
end
tap = floor(tap/2);
[R_SIZE,C_SIZE] = size(I_PAN);
switch filtername
case 'Naive2'
gv = zeros(2,1);
gv(1,1) = -1;
gv(2,1) = 1;
gh = zeros(1,2);
gh(1,1) = -1;
gh(1,2) = 1;
case 'Naive3'
gv = zeros(3,1);
gv(1,1) = -1;
gv(3,1) = 1;
gh = zeros(1,3);
gh(1,1) = -1;
gh(1,3) = 1;
case 'Basic'
gv = zeros(2,2);
gv(1,:) = -1;
gv(2,:) = 1;
gh = zeros(2,2);
gh(:,1) = -1;
gh(:,2) = 1;
case 'Prewitt'
gv = zeros(3,3);
gv(1,:) = -1;
gv(3,:) = 1;
gh = zeros(3,3);
gh(:,1) = -1;
gh(:,3) = 1;
case 'Sobel'
gv = zeros(3,3);
gv(1,1) = -1;gv(1,2) = -2;gv(1,3) = -1;
gv(3,1) = +1;gv(3,2) = +2;gv(3,3) = +1;
gh = zeros(3,3);
gh(1,1) = -1;gh(2,1) = -2;gh(3,1) = -1;
gh(1,3) = +1;gh(2,3) = +2;gh(3,3) = +1;
otherwise
gv = zeros(2,2);
gv(1,:) = -1;
gv(2,:) = 1;
gh = zeros(2,2);
gh(:,1) = -1;
gh(:,2) = 1;
end
gvf = fft2(gv,R_SIZE,C_SIZE);
ghf = fft2(gh,R_SIZE,C_SIZE);
gvfc = conj(gvf);
ghfc = conj(ghf);
gvf2 = gvfc .* gvf;
ghf2 = ghfc .* ghf;
gf2sum = gvf2 + ghf2;
H_E = double(I_PAN);
for jj = 1 : num_iter
%%% Filter PAN to estimate alpha set
if jj == 1
PAN_LP = LPfilter(H_E,ratio);
else
PAN_LP = imfilter(H_E,PSF_l,'replicate');
end
%%% Estimate alpha
alpha(1,1,:) = estimation_alpha(cat(3,I_MS,ones(size(I_MS,1),size(I_MS,2))),PAN_LP,'global');
It_E = sum(cat(3,I_MS,ones(size(I_MS,1),size(I_MS,2))) .* repmat(alpha,[size(I_MS,1) size(I_MS,2) 1]),3);
%%% Edge taper
H_E = edgetaper(H_E,ones(tap,tap)./((tap)^2));
It_E = edgetaper(It_E,ones(tap,tap)./((tap)^2));
%%% Filter Estimation
PSF = real(fftshift(ifft2(conj(fft2(H_E)).* fft2(It_E)./(abs(fft2(H_E)).^2 + lambda + mu * gf2sum ))));
%%% Thresholding
PSF(PSF < th) = 0;
%%% Cut using the support dimension and center
[~, maxIndex] = max(PSF(:));
[rm, cm] = ind2sub(size(PSF), maxIndex);
PSF_l = PSF(rm - tap : rm + tap - 1 + sum_tap, cm - tap : cm + tap - 1 + sum_tap);
PSF_l = PSF_l ./ sum(PSF_l(:));
end
end
|
2977094657/BiliHistoryFrontend
| 3,851
|
src/components/tailwind/Pagination.vue
|
<template>
<div class="mx-auto mb-5 mt-8 max-w-4xl lm:text-xs">
<div class="flex justify-between items-center space-x-4 lm:mx-5">
<button
@click="handlePageChange(currentPage - 1)"
:disabled="currentPage === 1"
class="flex items-center text-gray-500 hover:text-[#fb7299] disabled:opacity-40 disabled:cursor-not-allowed transition-colors px-3 py-2"
>
<svg class="w-5 h-5 mr-1" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 19l-7-7 7-7" />
</svg>
<span class="hidden sm:inline">上一页</span>
</button>
<div class="flex items-center text-gray-700 lm:text-xs">
<div class="relative mx-1 inline-block">
<input
ref="pageInput"
type="number"
v-model="currentPageInput"
@keyup.enter="handleJumpPage"
@blur="handleJumpPage"
@focus="handleFocus"
min="1"
:max="totalPages"
class="h-8 w-12 rounded border border-gray-200 px-2 text-center text-gray-700 transition-colors [appearance:textfield] hover:border-[#fb7299] focus:border-[#fb7299] focus:outline-none focus:ring-1 focus:ring-[#fb7299]/30 lm:h-6 lm:w-10 lm:text-xs [&::-webkit-inner-spin-button]:appearance-none [&::-webkit-outer-spin-button]:appearance-none"
/>
</div>
<span class="text-gray-500 mx-1">/ {{ totalPages }}</span>
</div>
<button
@click="handlePageChange(currentPage + 1)"
:disabled="currentPage === totalPages"
class="flex items-center text-gray-500 hover:text-[#fb7299] disabled:opacity-40 disabled:cursor-not-allowed transition-colors px-3 py-2"
>
<span class="hidden sm:inline">下一页</span>
<svg class="w-5 h-5 ml-1" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 5l7 7-7 7" />
</svg>
</button>
</div>
</div>
</template>
<script setup>
import { ref, watch } from 'vue'
import { useRouter, useRoute } from 'vue-router'
const props = defineProps({
currentPage: {
type: Number,
required: true,
},
totalPages: {
type: Number,
required: true,
},
// 是否使用路由导航(首页使用,搜索页不使用)
useRouting: {
type: Boolean,
default: false,
},
})
const emit = defineEmits(['page-change'])
const router = useRouter()
const route = useRoute()
const currentPageInput = ref(props.currentPage.toString())
// 监听 props 变化更新输入框
watch(
() => props.currentPage,
(newPage) => {
currentPageInput.value = newPage.toString()
}
)
// 处理页码变化
const handlePageChange = (newPage) => {
if (newPage >= 1 && newPage <= props.totalPages) {
if (props.useRouting) {
// 检查当前是否在搜索页面
if (route.name && (route.name === 'Search' || route.name === 'SearchPage')) {
// 搜索页面的路由导航
if (newPage === 1) {
router.push(`/search/${route.params.keyword}`)
} else {
router.push(`/search/${route.params.keyword}/page/${newPage}`)
}
} else {
// 首页的路由导航
if (newPage === 1) {
router.push('/')
} else {
router.push(`/page/${newPage}`)
}
}
} else {
emit('page-change', newPage)
}
}
}
// 处理输入框获得焦点
const handleFocus = (event) => {
event.target.select()
}
// 处理跳转
const handleJumpPage = () => {
const targetPage = parseInt(currentPageInput.value)
if (!isNaN(targetPage) && targetPage >= 1 && targetPage <= props.totalPages) {
if (targetPage !== props.currentPage) {
handlePageChange(targetPage)
}
} else {
currentPageInput.value = props.currentPage.toString()
}
}
</script>
<style scoped>
button {
transition: color 0.3s ease;
}
</style>
|
2977094657/BiliHistoryFrontend
| 27,829
|
src/components/tailwind/page/SchedulerTasks.vue
|
<template>
<div class="min-h-screen bg-gray-50/30">
<div class="py-4">
<div class="max-w-7xl mx-auto px-3">
<!-- 任务列表包装层 - 添加相对定位以便放置新建按钮 -->
<div class="relative mb-6">
<!-- 任务列表 -->
<div v-if="loading" class="flex justify-center items-center py-20">
<div class="animate-spin rounded-full h-12 w-12 border-t-2 border-b-2 border-[#fb7299]"></div>
</div>
<div v-else-if="tasks.length === 0" class="bg-white border border-gray-200 rounded-lg p-6 text-center">
<!-- 在空状态页面添加标题和新建按钮 -->
<div class="flex justify-between items-center mb-6">
<h3 class="text-base font-medium text-gray-900">计划任务</h3>
<button
@click="openCreateTaskModal"
class="text-[#fb7299] hover:text-[#fb7299]/80 transition-colors text-sm font-medium"
>
新建任务
</button>
</div>
<svg class="mx-auto h-12 w-12 text-gray-400" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2" />
</svg>
<h3 class="mt-2 text-sm font-medium text-gray-900">暂无计划任务</h3>
<p class="mt-1 text-sm text-gray-500">点击"新建任务"按钮创建您的第一个计划任务</p>
</div>
<div v-else class="bg-white border border-gray-200 rounded-lg overflow-hidden">
<!-- 添加表格标题 -->
<div class="px-4 py-3 flex justify-between items-center border-b border-gray-200">
<h3 class="text-base font-medium text-gray-900">计划任务</h3>
<button
@click="openCreateTaskModal"
class="text-[#fb7299] hover:text-[#fb7299]/80 transition-colors text-sm font-medium"
>
新建任务
</button>
</div>
<div class="overflow-x-auto">
<table class="min-w-full divide-y divide-gray-200">
<thead class="bg-gray-50">
<tr>
<th scope="col" class="px-4 py-2 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">任务ID</th>
<th scope="col" class="px-4 py-2 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">名称</th>
<th scope="col" class="px-4 py-2 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">调度类型</th>
<th scope="col" class="px-4 py-2 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">调度时间</th>
<th scope="col" class="px-4 py-2 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">成功率</th>
<th scope="col" class="px-4 py-2 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">最后执行</th>
<th scope="col" class="px-4 py-2 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">状态</th>
<th scope="col" class="px-4 py-2 text-right text-xs font-medium text-gray-500 uppercase tracking-wider">
<!-- 移除这里的新建任务按钮,因为已经添加到标题中 -->
操作
</th>
</tr>
</thead>
<tbody class="bg-white divide-y divide-gray-200">
<template v-for="task in tasks" :key="task.task_id">
<!-- 主任务行 -->
<tr class="hover:bg-gray-50 border-t-2 border-gray-100">
<td class="px-4 py-3 whitespace-nowrap text-xs font-medium text-gray-900">
<div class="flex items-center space-x-1">
<button
v-if="task.sub_tasks && task.sub_tasks.length > 0"
@click="task.isExpanded = !task.isExpanded"
class="p-0.5 rounded hover:bg-gray-200 transition-colors"
>
<svg
class="w-3.5 h-3.5 text-gray-500 transform transition-transform"
:class="{'rotate-90': task.isExpanded}"
fill="none"
viewBox="0 0 24 24"
stroke="currentColor"
>
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 5l7 7-7 7" />
</svg>
</button>
{{ task.task_id }}
</div>
</td>
<td class="px-4 py-3 whitespace-nowrap text-xs text-gray-500">
<div class="flex items-center">
{{ task.config?.name || task.task_id }}
<span v-if="task.sub_tasks && task.sub_tasks.length > 0"
class="ml-2 px-1.5 py-0.5 text-xs rounded-full bg-gray-100 text-gray-600">
{{ task.sub_tasks.length }}个子任务
</span>
</div>
</td>
<td class="px-4 py-3 whitespace-nowrap text-xs text-gray-500">
<span
:class="{
'bg-blue-100 text-blue-800': task.config?.schedule_type === 'daily',
'bg-purple-100 text-purple-800': task.config?.schedule_type === 'chain',
'bg-green-100 text-green-800': task.config?.schedule_type === 'once',
'bg-yellow-100 text-yellow-800': task.config?.schedule_type === 'interval'
}"
class="px-1.5 inline-flex text-xs leading-5 font-semibold rounded-full"
>
{{
task.config?.schedule_type === 'daily' ? '每日' :
task.config?.schedule_type === 'chain' ? '链式' :
task.config?.schedule_type === 'once' ? '一次性' :
task.config?.schedule_type === 'interval' ? '间隔' :
task.config?.schedule_type
}}
</span>
</td>
<td class="px-4 py-3 whitespace-nowrap text-xs text-gray-500">
{{
task.config?.schedule_type === 'chain' ? '依赖主任务' :
task.config?.schedule_type === 'interval' ?
(task.config?.interval_value || '-') + ' ' +
(task.config?.interval_unit === 'minutes' ? '分钟' :
task.config?.interval_unit === 'hours' ? '小时' :
task.config?.interval_unit === 'days' ? '天' :
task.config?.interval_unit === 'months' ? '月' :
task.config?.interval_unit === 'years' ? '年' :
task.config?.interval_unit || '') :
task.config?.schedule_time || '-'
}}
</td>
<td class="px-4 py-3 whitespace-nowrap text-xs text-gray-500">
<span v-if="task.execution?.success_rate !== undefined" class="inline-flex items-center">
{{ Math.round(task.execution.success_rate) }}%
<div class="ml-1.5 h-1 w-12 bg-gray-200 rounded-full overflow-hidden">
<div
class="h-full rounded-full"
:class="{
'bg-green-500': task.execution.success_rate >= 90,
'bg-yellow-500': task.execution.success_rate >= 60 && task.execution.success_rate < 90,
'bg-red-500': task.execution.success_rate < 60
}"
:style="{width: `${task.execution.success_rate}%`}"
></div>
</div>
</span>
<span v-else>-</span>
</td>
<td class="px-4 py-3 whitespace-nowrap text-xs text-gray-500">
{{ task.execution?.last_run || '未记录' }}
</td>
<td class="px-4 py-3 whitespace-nowrap text-xs text-gray-500">
<span
:class="{
'bg-green-100 text-green-800': task.config?.enabled === true,
'bg-red-100 text-red-800': task.config?.enabled === false
}"
class="px-1.5 inline-flex text-xs leading-5 font-semibold rounded-full"
>
{{ task.config?.enabled ? '已启用' : '已禁用' }}
</span>
</td>
<td class="px-4 py-3 whitespace-nowrap text-right text-xs font-medium">
<div class="flex justify-end space-x-1.5">
<button
@click="openTaskDetailModal(task.task_id)"
class="text-indigo-600 hover:text-indigo-900"
>
详情
</button>
<button
@click="openEditTaskModal(task.task_id)"
class="text-blue-600 hover:text-blue-900"
>
编辑
</button>
<button
@click="openCreateSubTaskModal(task.task_id)"
class="text-purple-600 hover:text-purple-900"
>
添加子任务
</button>
<button
@click="executeTask(task.task_id)"
class="text-green-600 hover:text-green-900"
>
执行
</button>
<button
v-if="task.config?.enabled !== undefined"
@click="toggleTaskEnabled(task.task_id, !task.config.enabled)"
:class="task.config.enabled ? 'text-orange-600 hover:text-orange-900' : 'text-teal-600 hover:text-teal-900'"
>
{{ task.config.enabled ? '禁用' : '启用' }}
</button>
<button
@click="confirmDeleteTask(task.task_id)"
class="text-red-600 hover:text-red-900"
>
删除
</button>
</div>
</td>
</tr>
<!-- 子任务行 -->
<template v-if="task.sub_tasks && task.sub_tasks.length > 0 && task.isExpanded">
<tr v-for="subTask in task.sub_tasks"
:key="subTask.task_id"
class="bg-[#fff8fa] hover:bg-[#fff2f6] border-l-4 border-[#fb7299]/30">
<td class="pl-12 pr-4 py-2.5 whitespace-nowrap text-xs font-medium text-gray-900">
<div class="flex items-center">
<svg class="w-3.5 h-3.5 text-gray-400 mr-1.5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M7 7h.01M7 3h5c.512 0 1.024.195 1.414.586l7 7a2 2 0 010 2.828l-7 7a2 2 0 01-2.828 0l-7-7A1.994 1.994 0 013 12V7a4 4 0 014-4z" />
</svg>
{{ subTask.task_id }}
</div>
</td>
<td class="px-4 py-3 whitespace-nowrap text-xs text-gray-500">
{{ subTask.config?.name || subTask.task_id }}
</td>
<td class="px-4 py-3 whitespace-nowrap text-xs text-gray-500">
<span class="px-1.5 inline-flex text-xs leading-5 font-semibold rounded-full bg-purple-100 text-purple-800">
链式
</span>
</td>
<td class="px-4 py-3 whitespace-nowrap text-xs text-gray-500">
依赖主任务
</td>
<td class="px-4 py-3 whitespace-nowrap text-xs text-gray-500">
<span v-if="subTask.execution?.success_rate !== undefined" class="inline-flex items-center">
{{ Math.round(subTask.execution.success_rate) }}%
<div class="ml-1.5 h-1 w-12 bg-gray-200 rounded-full overflow-hidden">
<div
class="h-full rounded-full"
:class="{
'bg-green-500': subTask.execution.success_rate >= 90,
'bg-yellow-500': subTask.execution.success_rate >= 60 && subTask.execution.success_rate < 90,
'bg-red-500': subTask.execution.success_rate < 60
}"
:style="{width: `${subTask.execution.success_rate}%`}"
></div>
</div>
</span>
<span v-else>-</span>
</td>
<td class="px-4 py-3 whitespace-nowrap text-xs text-gray-500">
{{ subTask.execution?.last_run || '未记录' }}
</td>
<td class="px-4 py-3 whitespace-nowrap text-xs text-gray-500">
<span
:class="{
'bg-green-100 text-green-800': subTask.config?.enabled === true,
'bg-red-100 text-red-800': subTask.config?.enabled === false
}"
class="px-1.5 inline-flex text-xs leading-5 font-semibold rounded-full"
>
{{ subTask.config?.enabled ? '已启用' : '已禁用' }}
</span>
</td>
<td class="px-4 py-3 whitespace-nowrap text-right text-xs font-medium">
<div class="flex justify-end space-x-1.5">
<button
@click="openTaskDetailModal(subTask.task_id)"
class="text-indigo-600 hover:text-indigo-900"
>
详情
</button>
<button
@click="openEditTaskModal(subTask.task_id)"
class="text-blue-600 hover:text-blue-900"
>
编辑
</button>
<button
v-if="subTask.config?.enabled !== undefined"
@click="toggleTaskEnabled(subTask.task_id, !subTask.config.enabled)"
:class="subTask.config.enabled ? 'text-orange-600 hover:text-orange-900' : 'text-teal-600 hover:text-teal-900'"
>
{{ subTask.config.enabled ? '禁用' : '启用' }}
</button>
<button
@click="confirmDeleteTask(subTask.task_id, task.task_id)"
class="text-red-600 hover:text-red-900"
>
删除
</button>
</div>
</td>
</tr>
</template>
</template>
</tbody>
</table>
</div>
</div>
</div>
</div>
</div>
</div>
<!-- 任务详情弹窗 -->
<TaskDetail
v-model:show="showTaskDetailModal"
:task="currentTask"
@view-history="fetchTaskHistory"
@edit-task="openEditTaskModal"
@execute-task="executeTask"
@toggle-enabled="toggleTaskEnabled"
@delete-task="confirmDeleteTask"
@refresh="fetchTasks"
/>
<!-- 任务历史弹窗 -->
<TaskHistory
v-model:show="showTaskHistoryModal"
:task-id="currentTask?.task_id"
:task-name="currentTask?.config?.name || currentTask?.task_id"
/>
<!-- 创建/编辑任务弹窗 -->
<TaskForm
v-model:show="showTaskFormModal"
:is-editing="isEditing"
:task-id="currentTask?.task_id"
:parent-task-id="parentTaskId"
:tasks="tasks"
@task-saved="fetchTasks"
/>
</template>
<script setup>
import { ref, reactive, onMounted, computed, watch } from 'vue'
import { showNotify, showDialog } from 'vant'
import 'vant/es/dialog/style'
import 'vant/es/notify/style'
import 'vant/es/loading/style'
import {
getAllSchedulerTasks,
getSchedulerTaskDetail,
createSchedulerTask,
updateSchedulerTask,
deleteSchedulerTask,
executeSchedulerTask,
getTaskHistory,
setTaskEnabled,
deleteSubTask
} from '../../../api/api'
import TaskForm from '../scheduler/TaskForm.vue'
import TaskDetail from '../scheduler/TaskDetail.vue'
import TaskHistory from '../scheduler/TaskHistory.vue'
// 防抖函数
const debounce = (fn, delay) => {
let timer = null
return function (...args) {
if (timer) clearTimeout(timer)
timer = setTimeout(() => {
fn.apply(this, args)
}, delay)
}
}
// 加载状态
const loading = ref(false)
// 任务列表
const tasks = ref([])
// 当前任务
const currentTask = ref(null)
// 弹窗控制
const showTaskFormModal = ref(false)
const showTaskDetailModal = ref(false)
const showTaskHistoryModal = ref(false)
const selectedTaskHistory = ref([])
// 是否为编辑模式
const isEditing = ref(false)
// 搜索关键词
const searchKeyword = ref('')
// 标签输入
const newTagInput = ref('')
// 父任务ID
const parentTaskId = ref(null)
// 执行任务
const executeTask = async (taskId) => {
try {
const response = await executeSchedulerTask(taskId, {
wait_for_completion: false
})
if (response.data && response.data.status === 'success') {
showNotify({ type: 'success', message: '任务执行已启动' })
// 刷新任务列表
fetchTasks()
} else {
const errorMessage = '执行任务失败: ' + (response.data?.message || '未知错误')
showNotify({ type: 'danger', message: errorMessage })
}
} catch (error) {
console.error('执行任务出错:', error)
showNotify({ type: 'danger', message: '执行任务出错: ' + (error.message || '未知错误') })
}
}
// 获取所有计划任务
const fetchTasks = debounce(async () => {
if (loading.value) return // 如果正在加载,则不重复获取
loading.value = true
try {
const response = await getAllSchedulerTasks({
include_subtasks: true,
detail_level: 'full'
})
if (response.data && response.data.status === 'success') {
// 为每个任务添加展开/收起状态
tasks.value = (response.data.tasks || []).map(task => {
return {
...task,
isExpanded: true // 默认展开
}
})
} else {
showNotify({ type: 'danger', message: '获取任务列表失败: ' + (response.data?.message || '未知错误') })
}
} catch (error) {
console.error('获取任务列表出错:', error)
showNotify({ type: 'danger', message: '获取任务列表出错: ' + (error.message || '未知错误') })
} finally {
loading.value = false
}
}, 300) // 300ms 的防抖延迟
// 刷新任务列表
const refreshTasks = () => {
fetchTasks()
}
// 打开任务详情弹窗
const openTaskDetailModal = async (taskId) => {
if (!taskId) {
return;
}
const response = await getSchedulerTaskDetail(taskId);
if (response.data?.status === 'success' && Array.isArray(response.data.tasks) && response.data.tasks.length > 0) {
const task = response.data.tasks[0];
if (!task.execution) {
task.execution = {
status: 'pending',
success_rate: 0,
avg_duration: 0,
total_runs: 0,
success_runs: 0,
fail_runs: 0
};
}
currentTask.value = task;
showTaskDetailModal.value = true;
} else {
showNotify({ type: 'danger', message: '获取任务详情失败:' + (response.data?.message || '未知错误') });
}
}
// 获取任务历史记录
const fetchTaskHistory = async (taskId) => {
try {
const response = await getTaskHistory({
task_id: taskId,
include_subtasks: true,
page: 1,
page_size: 20
})
if (response.data && response.data.status === 'success') {
showTaskHistoryModal.value = true
selectedTaskHistory.value = response.data.history || []
} else {
showNotify({ type: 'danger', message: '获取任务历史失败: ' + (response.data?.message || '未知错误') })
}
} catch (error) {
console.error('获取任务历史出错:', error)
showNotify({ type: 'danger', message: '获取任务历史出错: ' + (error.message || '未知错误') })
}
}
// 计算历史记录的成功率
const getSuccessRate = (historyList) => {
if (!historyList || historyList.length === 0) return 0
const successCount = historyList.filter(h => h.status === 'success').length
return Math.round((successCount / historyList.length) * 100)
}
// 启用/禁用任务
const toggleTaskEnabled = async (taskId, enabled) => {
try {
const response = await setTaskEnabled(taskId, enabled)
if (response.data && response.data.status === 'success') {
showNotify({ type: 'success', message: enabled ? '任务已启用' : '任务已禁用' })
// 刷新任务列表
fetchTasks()
} else {
showNotify({ type: 'danger', message: (enabled ? '启用' : '禁用') + '任务失败: ' + (response.data?.message || '未知错误') })
}
} catch (error) {
showNotify({ type: 'danger', message: '切换任务状态出错: ' + (error.message || '未知错误') })
}
}
// 打开编辑任务弹窗
const openEditTaskModal = async (taskId) => {
try {
// 重置状态
isEditing.value = true
parentTaskId.value = null // 确保编辑时parentTaskId为null
currentTask.value = null
const response = await getSchedulerTaskDetail(taskId)
if (response.data?.status === 'success' && Array.isArray(response.data.tasks) && response.data.tasks.length > 0) {
currentTask.value = response.data.tasks[0]
showTaskFormModal.value = true
} else {
showNotify({ type: 'danger', message: '获取任务详情失败:' + (response.data?.message || '未知错误') })
}
} catch (error) {
console.error('获取任务详情出错:', error)
showNotify({ type: 'danger', message: '获取任务详情出错: ' + (error.message || '未知错误') })
}
}
// 打开创建子任务弹窗
const openCreateSubTaskModal = async (taskId) => {
try {
// 重置状态
isEditing.value = false
currentTask.value = null
// 先获取主任务详情
const response = await getSchedulerTaskDetail(taskId)
if (response.data?.status === 'success' && Array.isArray(response.data.tasks) && response.data.tasks.length > 0) {
const mainTask = response.data.tasks[0]
currentTask.value = mainTask
parentTaskId.value = taskId
// 检查主任务是否有子任务
if (mainTask.sub_tasks && mainTask.sub_tasks.length > 0) {
// 如果有子任务,新子任务应该依赖于最后一个子任务
const lastSubTask = mainTask.sub_tasks[mainTask.sub_tasks.length - 1]
currentTask.value = {
...mainTask,
depends_on: {
task_id: lastSubTask.task_id,
name: lastSubTask.config?.name || lastSubTask.task_id
}
}
} else {
}
showTaskFormModal.value = true
} else {
showNotify({ type: 'danger', message: '获取主任务详情失败:' + (response.data?.message || '未知错误') })
}
} catch (error) {
console.error('获取主任务详情出错:', error)
showNotify({ type: 'danger', message: '获取主任务详情出错: ' + (error.message || '未知错误') })
}
}
// 打开创建任务弹窗
const openCreateTaskModal = () => {
// 重置所有状态
isEditing.value = false
parentTaskId.value = null
currentTask.value = null
showTaskFormModal.value = true
}
// 确认删除任务
const confirmDeleteTask = (taskId, parentTaskId = null) => {
const isSubTask = !!parentTaskId;
showDialog({
title: '确认删除',
message: isSubTask ? '确定要删除此子任务吗?此操作不可撤销。' : '确定要删除此任务吗?此操作不可撤销。',
showCancelButton: true,
confirmButtonText: '确定',
cancelButtonText: '取消',
confirmButtonColor: '#fb7299',
}).then(() => {
deleteTask(taskId, parentTaskId)
}).catch(() => {
// 取消删除
})
}
// 删除任务
const deleteTask = async (taskId, parentTaskId = null) => {
try {
console.log('开始删除任务:', taskId, parentTaskId ? `(父任务: ${parentTaskId})` : '');
let response;
if (parentTaskId) {
// 删除子任务
response = await deleteSubTask(parentTaskId, taskId)
} else {
// 删除主任务
response = await deleteSchedulerTask(taskId)
}
if (response.data && response.data.status === 'success') {
showNotify({ type: 'success', message: parentTaskId ? '子任务删除成功' : '任务删除成功' })
// 关闭所有相关的弹窗
showTaskDetailModal.value = false
showTaskHistoryModal.value = false
// 重新获取任务列表
fetchTasks()
} else {
showNotify({ type: 'danger', message: (parentTaskId ? '删除子任务失败: ' : '删除任务失败: ') + (response.data?.message || '未知错误') })
}
} catch (error) {
console.error('删除任务出错:', error)
showNotify({ type: 'danger', message: (parentTaskId ? '删除子任务出错: ' : '删除任务出错: ') + (error.message || '未知错误') })
}
}
// 初始化
onMounted(() => {
fetchTasks()
})
</script>
<style scoped>
.task-detail-dialog :deep(.van-dialog__content) {
max-height: 70vh;
overflow-y: auto;
}
.task-form-dialog :deep(.van-dialog__content) {
max-height: 70vh;
overflow-y: auto;
}
.task-form-dialog :deep(.van-dialog) {
max-height: 85vh;
overflow: hidden;
display: flex;
flex-direction: column;
}
.task-form-dialog :deep(.van-dialog__header) {
flex-shrink: 0;
padding: 10px 14px;
font-size: 13px;
}
.task-history-dialog :deep(.van-dialog__content) {
max-height: 70vh;
overflow-y: auto;
}
/* 优化滚动条样式 */
:deep(.van-dialog__content)::-webkit-scrollbar,
pre::-webkit-scrollbar,
.max-h-32::-webkit-scrollbar,
.max-h-28::-webkit-scrollbar {
width: 4px;
height: 4px;
}
:deep(.van-dialog__content)::-webkit-scrollbar-thumb,
pre::-webkit-scrollbar-thumb,
.max-h-32::-webkit-scrollbar-thumb,
.max-h-28::-webkit-scrollbar-thumb {
background: #ddd;
border-radius: 2px;
}
:deep(.van-dialog__content)::-webkit-scrollbar-thumb:hover,
pre::-webkit-scrollbar-thumb:hover,
.max-h-32::-webkit-scrollbar-thumb:hover,
.max-h-28::-webkit-scrollbar-thumb:hover {
background: #fb7299;
}
/* 弹窗标题样式 */
:deep(.van-dialog__header) {
padding: 12px 16px;
font-weight: 600;
color: #333;
border-bottom: 1px solid #f0f0f0;
font-size: 14px;
}
/* 表单元素焦点样式 */
input:focus, select:focus, textarea:focus {
border-color: #fb7299;
box-shadow: 0 0 0 2px rgba(251, 114, 153, 0.2);
}
/* 按钮悬停效果 */
button {
transition: all 0.2s ease;
}
/* 表格行悬停效果 */
tr.hover\:bg-gray-50:hover {
background-color: rgba(251, 114, 153, 0.05);
}
/* 卡片阴影效果 */
.shadow-sm {
box-shadow: 0 1px 2px 0 rgba(0, 0, 0, 0.05);
transition: box-shadow 0.2s ease;
}
.shadow-sm:hover {
box-shadow: 0 2px 4px 0 rgba(0, 0, 0, 0.1);
}
/* 标签样式 */
.rounded-md {
transition: background-color 0.2s ease;
}
</style>
|
2977094657/BiliHistoryFrontend
| 14,568
|
src/components/tailwind/page/VideoDetailsManager.vue
|
<!-- 视频详情管理组件 -->
<template>
<div class="bg-white rounded-lg border border-gray-200 p-6">
<!-- 操作按钮 -->
<div class="mb-6 flex flex-col space-y-4 sm:flex-row sm:space-y-0 sm:space-x-4">
<div class="flex space-x-4">
<button
@click="startFetchingDetails"
:disabled="stats.pendingVideosCount === 0 || isFetching"
class="px-4 py-2 bg-[#fb7299] text-white rounded-md hover:bg-[#fb7299]/90 disabled:opacity-50 disabled:cursor-not-allowed transition-all duration-200 border border-[#fb7299]/20"
>
<div class="flex items-center space-x-2">
<svg v-if="isFetching" class="animate-spin h-5 w-5" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
<circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
<path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
</svg>
<svg v-else class="h-5 w-5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-4l-4 4m0 0l-4-4m4 4V4" />
</svg>
<span>{{ isFetching ? '获取中...' : (stats.pendingVideosCount === 0 ? '无需获取' : '获取视频详情') }}</span>
</div>
</button>
<!-- 停止按钮 -->
<button
v-if="isFetching && progress.isProcessing && !progress.isComplete"
@click="stopFetching"
class="px-4 py-2 bg-red-600 text-white rounded-md hover:bg-red-700 transition-all duration-200 border border-red-600/20"
>
<div class="flex items-center space-x-2">
<svg class="h-5 w-5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 10h6v4H9z" />
</svg>
<span>停止获取</span>
</div>
</button>
</div>
<!-- 下载选项 -->
<div class="flex items-center space-x-2 bg-white/50 backdrop-blur-sm rounded-md px-4 py-2 border border-gray-200">
<input
type="checkbox"
id="useSessdata"
v-model="useSessdata"
class="w-4 h-4 text-[#fb7299] bg-gray-100 border-gray-300 rounded focus:ring-[#fb7299]"
:disabled="stats.pendingVideosCount === 0 || isFetching"
>
<label for="useSessdata" class="text-sm text-gray-700">
使用SESSDATA获取详情(对于公开视频可以不使用SESSDATA)
</label>
</div>
</div>
<!-- 加载中状态 -->
<div v-if="isLoading" class="flex justify-center items-center py-12">
<div class="animate-spin rounded-full h-16 w-16 border-b-2 border-[#fb7299]"></div>
</div>
<!-- 统计数据卡片 -->
<div v-if="!isLoading" class="grid grid-cols-1 md:grid-cols-4 gap-4 mb-6">
<div class="bg-white rounded-lg border border-gray-200 p-4 flex flex-col">
<span class="text-sm text-gray-500">历史记录视频总数</span>
<span class="text-2xl font-bold text-gray-800">{{ stats.totalHistoryVideos }}</span>
</div>
<div class="bg-white rounded-lg border border-gray-200 p-4 flex flex-col">
<span class="text-sm text-gray-500">已获取详情</span>
<span class="text-2xl font-bold text-green-600">{{ stats.existingVideosCount }}</span>
</div>
<div class="bg-white rounded-lg border border-gray-200 p-4 flex flex-col">
<span class="text-sm text-gray-500">已知失效视频</span>
<span class="text-2xl font-bold text-orange-500">{{ stats.invalidVideosCount }}</span>
</div>
<div class="bg-white rounded-lg border border-gray-200 p-4 flex flex-col">
<span class="text-sm text-gray-500">待获取视频</span>
<span class="text-2xl font-bold" :class="stats.pendingVideosCount > 0 ? 'text-blue-600' : 'text-gray-400'">
{{ stats.pendingVideosCount }}
</span>
</div>
</div>
<!-- 进度状态卡片 - 仅在获取时显示 -->
<div v-if="isFetching && !isLoading" class="space-y-6">
<!-- 总体进度 -->
<div class="bg-white rounded-lg border border-gray-200 p-4">
<div class="mb-4">
<div class="flex justify-between items-center mb-1 text-sm">
<span class="font-medium">处理进度: {{ progress.processedVideos || 0 }}/{{ progress.totalVideos || 0 }}</span>
<span>{{ progress.progressPercentage ? `${progress.progressPercentage.toFixed(1)}%` : '0%' }}</span>
</div>
<div class="w-full h-3 bg-gray-200 rounded-full overflow-hidden">
<div
class="h-full bg-[#fb7299] transition-all duration-300"
:style="{width: `${progress.progressPercentage || 0}%`}"
></div>
</div>
</div>
</div>
<!-- 状态卡片组 -->
<div class="grid grid-cols-2 md:grid-cols-4 gap-4">
<!-- 成功卡片 -->
<div class="bg-white rounded-lg border border-gray-200 p-4">
<div>
<p class="text-sm font-medium text-gray-500">成功获取</p>
<p class="text-2xl font-bold text-green-600">{{ progress.successCount || 0 }}</p>
</div>
</div>
<!-- 失败卡片 -->
<div class="bg-white rounded-lg border border-gray-200 p-4">
<div>
<p class="text-sm font-medium text-gray-500">获取失败</p>
<p class="text-2xl font-bold text-red-600">{{ progress.failedCount || 0 }}</p>
</div>
</div>
<!-- 跳过卡片 -->
<div class="bg-white rounded-lg border border-gray-200 p-4">
<div>
<p class="text-sm font-medium text-gray-500">跳过失效</p>
<p class="text-2xl font-bold text-yellow-600">{{ progress.skippedInvalidCount || 0 }}</p>
</div>
</div>
<!-- 时间卡片 -->
<div class="bg-white rounded-lg border border-gray-200 p-4">
<div>
<p class="text-sm font-medium text-gray-500">已用时间</p>
<p class="text-2xl font-bold text-blue-600">{{ progress.elapsedTime || '0秒' }}</p>
</div>
</div>
</div>
<!-- 失败视频列表 -->
<div v-if="progress.errorVideos && progress.errorVideos.length > 0" class="bg-white rounded-lg border border-gray-200 p-4">
<div class="font-medium text-sm mb-2 text-red-600 flex items-center">
<svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5 mr-1" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z" />
</svg>
获取失败的视频:
</div>
<div class="max-h-[120px] overflow-y-auto text-xs bg-gray-50 p-2 rounded border border-gray-200">
<div v-for="(bvid, index) in progress.errorVideos" :key="index" class="mb-1">
{{ bvid }}
</div>
</div>
</div>
<!-- 完成按钮 -->
<div v-if="progress.isComplete" class="flex justify-end">
<button
@click="completeFetching"
class="inline-flex items-center px-4 py-2 rounded-md text-white bg-green-600 hover:bg-green-700 font-medium"
>
<svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5 mr-2" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 13l4 4L19 7" />
</svg>
完成
</button>
</div>
</div>
</div>
</template>
<script setup>
import { ref, onMounted, onUnmounted } from 'vue'
import { getVideoDetailsStats, fetchVideoDetails, createVideoDetailsProgressSSE, stopVideoDetailsFetch } from '../../../api/api'
import { showNotify } from 'vant'
import 'vant/es/notify/style'
// 状态变量
const isLoading = ref(true)
const isFetching = ref(false)
const useSessdata = ref(true) // 默认使用SESSDATA
const stats = ref({
totalHistoryVideos: 0,
existingVideosCount: 0,
invalidVideosCount: 0,
pendingVideosCount: 0,
completionPercentage: 0,
errorTypeStats: {},
pendingVideos: []
})
// 进度相关
const progressSource = ref(null)
const progress = ref({
isProcessing: false,
totalVideos: 0,
processedVideos: 0,
successCount: 0,
failedCount: 0,
errorVideos: [],
skippedInvalidCount: 0,
progressPercentage: 0,
elapsedTime: '',
isComplete: false
})
// 获取统计数据
const fetchStats = async () => {
isLoading.value = true
try {
// 调用API获取视频详情统计数据
const response = await getVideoDetailsStats()
if (response.data.status === 'success') {
// 确保数据结构完整
const data = response.data.data || {}
stats.value = {
totalHistoryVideos: data.total_videos || 0,
existingVideosCount: data.videos_with_details || 0,
invalidVideosCount: 0, // 后端暂时没有这个字段
pendingVideosCount: data.videos_without_details || 0,
completionPercentage: data.completion_percentage || 0,
errorTypeStats: {}, // 后端暂时没有这个字段
pendingVideos: [] // 后端暂时没有这个字段
}
} else {
throw new Error(response.data.message || '获取统计数据失败')
}
} catch (error) {
console.error('获取视频详情统计失败:', error)
showNotify({
type: 'danger',
message: error.message || '获取统计数据失败'
})
} finally {
isLoading.value = false
}
}
// 格式化错误类型名称
const formatErrorType = (type) => {
const errorTypes = {
'parse_error': '解析错误',
'not_found': '视频不存在',
'restricted': '访问受限',
'api_error': 'API错误',
'timeout': '超时',
'network_error': '网络错误',
'404_not_found': '视频不存在',
'62002_invisible': '视频已设为私有'
}
return errorTypes[type] || type
}
// 开始获取视频详情
const startFetchingDetails = async () => {
try {
// 调用API启动获取流程,设置maxVideos=0表示获取全部
const response = await fetchVideoDetails({
max_videos: 0, // 获取全部视频
specific_videos: '',
use_sessdata: useSessdata.value // 传递是否使用SESSDATA的选项
})
if (response.data.status === 'success') {
isFetching.value = true
// 初始化进度对象
const data = response.data.data || {}
progress.value = {
isProcessing: data.is_processing || true,
totalVideos: data.total_videos || 0,
processedVideos: data.processed_videos || 0,
successCount: data.success_count || 0,
failedCount: data.failed_count || 0,
errorVideos: data.error_videos || [],
skippedInvalidCount: data.skipped_invalid_count || 0,
progressPercentage: data.progress_percentage || 0,
elapsedTime: typeof data.elapsed_time === 'number' ? `${data.elapsed_time.toFixed(2)}秒` : '0.00秒',
isComplete: false
}
// 启动进度监听
startProgressStream()
showNotify({
type: 'success',
message: '已开始获取视频详情'
})
} else {
throw new Error(response.data.message || '启动获取失败')
}
} catch (error) {
console.error('启动视频详情获取失败:', error)
showNotify({
type: 'danger',
message: error.message || '启动获取失败'
})
}
}
// 停止获取
const stopFetching = async () => {
try {
const response = await stopVideoDetailsFetch()
if (response.data.status === 'success') {
// 立即重置前端状态
closeProgressStream()
isFetching.value = false
// 重置进度状态到初始状态
progress.value = {
isProcessing: false,
totalVideos: 0,
processedVideos: 0,
successCount: 0,
failedCount: 0,
errorVideos: [],
skippedInvalidCount: 0,
progressPercentage: 0,
elapsedTime: '',
isComplete: false
}
showNotify({
type: 'success',
message: '任务已停止'
})
// 刷新统计数据
fetchStats()
} else {
throw new Error(response.data.message || '停止失败')
}
} catch (error) {
console.error('停止视频详情获取失败:', error)
showNotify({
type: 'danger',
message: error.message || '停止失败'
})
}
}
// 完成获取
const completeFetching = () => {
closeProgressStream()
isFetching.value = false
showNotify({
type: 'success',
message: `视频详情获取完成! 成功: ${progress.value.successCount}, 失败: ${progress.value.failedCount}`
})
// 刷新统计数据
fetchStats()
}
// 开始流式获取进度
const startProgressStream = () => {
// 关闭可能存在的连接
closeProgressStream()
try {
console.log('开始获取视频详情进度流')
// 使用接口文档中的更新间隔参数
progressSource.value = createVideoDetailsProgressSSE({ update_interval: 0.2 })
// 连接建立
progressSource.value.onopen = (event) => {
console.log('视频详情进度流连接已建立')
}
// 接收消息
progressSource.value.onmessage = (event) => {
try {
const data = JSON.parse(event.data)
console.log('收到进度更新:', data)
// 更新进度,映射API文档中的字段
progress.value = {
isProcessing: data.is_processing,
totalVideos: data.total_videos,
processedVideos: data.processed_videos,
successCount: data.success_count,
failedCount: data.failed_count,
errorVideos: data.error_videos || [],
skippedInvalidCount: data.skipped_invalid_count || 0,
progressPercentage: data.progress_percentage,
elapsedTime: data.elapsed_time,
isComplete: data.is_complete
}
// 处理完成
if (data.is_complete) {
console.log('视频详情获取完成')
showNotify({
type: 'success',
message: '视频详情获取任务已完成'
})
}
} catch (error) {
console.error('解析进度数据失败:', error)
}
}
// 错误处理
progressSource.value.onerror = (event) => {
console.error('视频详情进度流错误:', event)
closeProgressStream()
// 如果正在获取中,显示错误消息
if (isFetching.value) {
showNotify({
type: 'warning',
message: '进度更新连接已断开'
})
}
}
} catch (error) {
console.error('创建进度流失败:', error)
showNotify({
type: 'danger',
message: '无法获取实时进度'
})
}
}
// 关闭SSE连接
const closeProgressStream = () => {
if (progressSource.value) {
console.log('关闭视频详情进度流')
progressSource.value.close()
progressSource.value = null
}
}
// 组件挂载时获取统计数据
onMounted(() => {
fetchStats()
})
// 组件卸载时清理资源
onUnmounted(() => {
closeProgressStream()
})
</script>
<style scoped>
.animate-pulse {
animation: pulse 2s cubic-bezier(0.4, 0, 0.6, 1) infinite;
}
@keyframes pulse {
0%, 100% {
opacity: 1;
}
50% {
opacity: .7;
}
}
</style>
|
2881099/FreeSql.AdminLTE
| 3,477
|
Examples/net60_preview/net60_preview.xml
|
<?xml version="1.0"?>
<doc>
<assembly>
<name>net60_preview</name>
</assembly>
<members>
<member name="T:net60_preview.Entitys.AdminRoute">
<summary>
音乐
</summary>
</member>
<member name="P:net60_preview.Entitys.AdminRoute.Id">
<summary>
主键
</summary>
</member>
<member name="P:net60_preview.Entitys.AdminRoute.Path">
<summary>
路径
</summary>
</member>
<member name="P:net60_preview.Entitys.AdminRoute.Create_time">
<summary>
创建时间
</summary>
</member>
<member name="P:net60_preview.Entitys.AdminRoute.ParentId">
<summary>
父节点
</summary>
</member>
<member name="P:net60_preview.Entitys.AdminRoute.Name">
<summary>
标题
</summary>
</member>
<member name="P:net60_preview.Entitys.AdminRoute.Extdata">
<summary>
前端数据
</summary>
</member>
<member name="P:net60_preview.Entitys.AdminRoute.Remark">
<summary>
备注
</summary>
</member>
<member name="T:net60_preview.Entitys.Song">
<summary>
音乐
</summary>
</member>
<member name="P:net60_preview.Entitys.Song.Id">
<summary>
主键
</summary>
</member>
<member name="P:net60_preview.Entitys.Song.Create_time">
<summary>
创建时间
</summary>
</member>
<member name="P:net60_preview.Entitys.Song.Is_deleted">
<summary>
软删除
</summary>
</member>
<member name="P:net60_preview.Entitys.Song.Title">
<summary>
标题
</summary>
</member>
<member name="P:net60_preview.Entitys.Song.Url">
<summary>
地址
</summary>
</member>
<member name="T:net60_preview.Entitys.Tag">
<summary>
标签
</summary>
</member>
<member name="P:net60_preview.Entitys.Tag.Id">
<summary>
主键
</summary>
</member>
<member name="P:net60_preview.Entitys.Tag.Parent_id">
<summary>
父id
</summary>
</member>
<member name="P:net60_preview.Entitys.Tag.Ddd">
<summary>
测试字段
</summary>
</member>
<member name="P:net60_preview.Entitys.Tag.Name">
<summary>
名字
</summary>
</member>
<member name="T:net60_preview.Entitys.User">
<summary>
用户管理
</summary>
</member>
<member name="P:net60_preview.Entitys.User.Name">
<summary>
用户名
</summary>
</member>
<member name="T:net60_preview.Entitys.UserImage">
<summary>
用户图片
</summary>
</member>
<member name="P:net60_preview.Entitys.UserImage.Url">
<summary>
Url地址
</summary>
</member>
<member name="P:net60_preview.Entitys.UserImage.User_id">
<summary>
用户id
</summary>
</member>
</members>
</doc>
|
294coder/Efficient-MIF
| 2,873
|
Pansharpening_Hyper_SR_Matlab_Test_Package/FE-HPM/FE_HPM.m
|
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Description:
% FE_HPM fuses the upsampled MultiSpectral (MS) and PANchromatic (PAN) images by
% exploiting the high pass modulation injection model and the estimated filter via deconvolution.
%
% Interface:
% [I_Fus,D,PSF_l] = FE_HPM(I_MS,I_PAN,ratio,tap,lambda,mu,th,num_iter,filtername)
%
% Inputs:
% I_MS: MS image upsampled at PAN scale;
% I_PAN: PAN image;
% ratio: Scale ratio between MS and PAN. Pre-condition: Integer value.
% tap: Filter support;
% lambda: Coefficient for weighting the energy regularization term;
% mu: Coefficient for weighting the derivative regularization terms;
% th: Threshold on the kernel (it cuts to 0 values below threshold);
% num_iter_max: Max number of iteration (at least 3; not sensitive);
% filtername: Kind of derivative (default: 'Basic')
%
% Outputs:
% I_Fus,D: Pansharpened image;
% PSF_l: Estimated point spread function.
%
% Reference:
% [Vivone15] G. Vivone, M. Simoes, M. Dalla Mura, R. Restaino, J. Bioucas-Dias, G. A. Licciardi, and J. Chanussot, "Pansharpening based on semiblind deconvolution",
% IEEE Transactions on Geoscience and Remote Sensing, vol. 53, no. 4, pp. 1997-2010, 2015.
% [Vivone20] G. Vivone, M. Dalla Mura, A. Garzelli, R. Restaino, G. Scarpa, M.O. Ulfarsson, L. Alparone, and J. Chanussot, "A New Benchmark Based on Recent Advances in Multispectral Pansharpening: Revisiting pansharpening with classical and emerging pansharpening methods",
% IEEE Geoscience and Remote Sensing Magazine, doi: 10.1109/MGRS.2020.3019315.
% % % % % % % % % % % % %
%
% Version: 1
%
% % % % % % % % % % % % %
%
% Copyright (C) 2019
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [I_Fus,PSF_l] = FE_HPM(I_MS,I_PAN,ratio,tap,lambda,mu,th,num_iter,filtername)
imageHR = double(I_PAN);
I_MS = double(I_MS);
nBands = size(I_MS,3);
%%% Equalization
imageHR = repmat(imageHR,[1 1 size(I_MS,3)]);
for ii = 1 : size(I_MS,3)
imageHR(:,:,ii) = (imageHR(:,:,ii) - mean2(imageHR(:,:,ii))).*(std2(I_MS(:,:,ii))./std2(imageHR(:,:,ii))) + mean2(I_MS(:,:,ii));
end
PSF_l = FE(I_MS,I_PAN,ratio,tap,lambda,mu,th,num_iter,filtername);
PAN_LP = zeros(size(imageHR));
for ii = 1 : nBands
PAN_LP(:,:,ii) = imfilter(imageHR(:,:,ii),PSF_l,'replicate');
t = imresize(PAN_LP(:,:,ii),1/ratio,'nearest');
PAN_LP(:,:,ii) = interp23tap(t,ratio);
end
PAN_LP = double(PAN_LP);
I_Fus = I_MS .* (imageHR ./ (PAN_LP + eps));
end
|
294coder/Efficient-MIF
| 4,351
|
Pansharpening_Hyper_SR_Matlab_Test_Package/TV/TV_pansharpen.m
|
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Description:
% This function minimizes
% J(x) = || y - M*x ||^2 + lambda*TV(x)
% where
% y = [yms^T, ypan^T]^T
% x is the pansharpened ms image
% M models the relationship between
% y and x; see [Palsson07] for details
%
% Interface:
% x = TV_pansharpen(yms,ypan,alpha,lambda,c,maxiter,w)
%
% Inputs:
% yms: The observed MS image;
% ypan: The PAN image;
% alpha: convergence parameter 1, suggested value=0.75;
% c: convergence parameter 2, suggested value=8;
% maxiter: number of iterations;
% w: We assume the pan image to be a linear
% combination of the pansharpened ms image,
% w contains the weights.
% Output:
% x: Pansharpened image.
%
% Reference:
% [Palsson14] F. Palsson, J.R. Sveinsson, and M.O. Ulfarsson, A New Pansharpening Algorithm Based on Total Variation
% IEEE Geoscience and Remote Sensing Letters, vol. 11, no. 1, pp. 318 - 322, 2014.
% [Vivone20] G. Vivone, M. Dalla Mura, A. Garzelli, R. Restaino, G. Scarpa, M.O. Ulfarsson, L. Alparone, and J. Chanussot, "A New Benchmark Based on Recent Advances in Multispectral Pansharpening: Revisiting pansharpening with classical and emerging pansharpening methods",
% IEEE Geoscience and Remote Sensing Magazine, doi: 10.1109/MGRS.2020.3019315.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function x = TV_pansharpen(yms,ypan,alpha,lambda,c,maxiter,w)
z=zeros([size(ypan) size(yms,3)*2]);
x=zeros([size(ypan) size(yms,3)]);
for k=1:maxiter
b=computeb(yms,ypan,x,alpha,w);
z=znext(z,x,b,alpha,lambda,c);
x=xnext(z,b,alpha);
end
end
function b=computeb(yms,ypan,xk,alpha,w)
[Hxms, Hxpan]=computeH(xk,w);
b=alpha*xk+adjointH(yms-Hxms,ypan-Hxpan,w);
end
function [yms, ypan]=computeH(x,w)
ypan=zeros([size(x,1) size(x,2)]);
for i=1:size(x,3)
yms(:,:,i)=decimate(x(:,:,i));
ypan=ypan+w(i)*x(:,:,i);
end
end
function y=decimate(x)
% y = imfilter(x,fspecial('Gaussian',9,sigma),'replicate');
% y = imfilter(y,fspecial('average',4),'replicate');
% y = y(1:4:end,1:4:end);
% h=0.25*[1 1 1 1];
% x=imfilter(x,h'*h,'symmetric','same');
% y=downsample(downsample(x,4,1)',4,1)';
y=imresize(x,0.25,'bilinear');
% y=MTF_downsample(x,'QB','none',4,1);
% y=imresize(imresize(x,1/4,'bicubic'),4,'bicubic');
end
function x=adjointH(yms,ypan,w)
for i=1:size(yms,3)
x(:,:,i)=interpolate(yms(:,:,i))+w(i)*ypan;
end
end
function y=interpolate(x)
% y = upsample(upsample(x,4)',4)';
y=imresize(x,4,'bilinear');
% y = imfilter(y,fspecial('Gaussian',9,sigma),'replicate');
% y = imfilter(y,fspecial('average',4),'replicate');
% y=imresize(x,4,'bicubic');
% y=MTF_upsample(x,'IKONOS','none',4,1);
% y=interp23tap(x,4);
end
function z1=znext(z0,x0,b,alpha,lambda,c)
for i=1:size(x0,3)
W(:,:,i)= 2* alpha/lambda * sqrt(Dx(x0(:,:,i)).^2+Dy(x0(:,:,i)).^2)+c;
W(:,:,i+size(x0,3))=2 * alpha/lambda * sqrt(Dx(x0(:,:,i)).^2+Dy(x0(:,:,i)).^2)+c;
end
z1=(computeDb(b)+cIDDTz(z0,c))./W;
end
function DX = Dx(v)
DX=[diff(v,1,2) zeros(size(v,1),1)];
end
function DY = Dy(v)
DY=[diff(v); zeros(1,size(v,2))];
end
function Db=computeDb(b)
for i=1:size(b,3)
Db(:,:,i)=Dx(b(:,:,i));
end
for i=size(b,3)+1:2*size(b,3)
Db(:,:,i)=Dy(b(:,:,i-size(b,3)));
end
end
function ddtz=cIDDTz(z,c)
for i=1:size(z,3)/2
dtz(:,:,i)=DxT(z(:,:,i))+DyT(z(:,:,i+4));
end
ddtz=computeDb(dtz);
cIddtz=c*z-ddtz;
end
function DXT=DxT(v)
DXT=DyT(v')';
end
function DYT = DyT(v)
u0 = -v(1,:);
u1 = -diff(v);
u2 = v(end-1,:);
DYT = [u0; u1(1:(end-1),:); u2];
return
end
function x1=xnext(z1,b,alpha)
x1=(b-DTz(z1))./alpha;
end
function dtz=DTz(z)
for i=1:size(z,3)/2
dtz(:,:,i)=DxT(z(:,:,i))+DyT(z(:,:,i+4));
end
end
|
2977094657/BiliHistoryFrontend
| 12,704
|
src/components/tailwind/page/DynamicDownloader.vue
|
<template>
<div class="space-y-4">
<!-- 输入与操作 -->
<div class="bg-white rounded-lg border border-gray-200 p-4">
<div class="flex items-center space-x-3">
<div class="flex-1">
<SimpleSearchBar
v-model="inputMid"
placeholder="输入用户 MID"
@search="triggerQueryNow"
class="w-full"
/>
</div>
<button
class="px-4 py-2 bg-green-600 text-white rounded-md hover:opacity-90 disabled:opacity-50"
:disabled="!canStartDownload"
@click="handleStartDownload"
>下载</button>
<button
class="px-4 py-2 bg-gray-700 text-white rounded-md hover:opacity-90 disabled:opacity-50"
:disabled="!downloading"
@click="handleStop"
>停止</button>
</div>
</div>
<!-- 用户信息卡片 -->
<div v-if="hostInfo" class="bg-white rounded-lg border border-gray-200 p-4 flex items-center space-x-4">
<img :src="hostFaceUrl" alt="face" class="w-14 h-14 rounded-full object-cover border" />
<div class="flex-1 min-w-0">
<div class="text-base font-medium truncate">{{ hostInfo.up_name || `UID ${hostInfo.host_mid}` }}</div>
<div class="text-xs text-gray-500">动态数:{{ hostInfo.item_count }} · 核心数:{{ hostInfo.core_count }}</div>
<div class="text-xs text-gray-400">最近发布时间:{{ formatTs(hostInfo.last_publish_ts) }} · 最近抓取:{{ formatTs(hostInfo.last_fetch_time) }}</div>
</div>
<button
class="px-3 py-1.5 bg-green-600 text-white rounded-md hover:opacity-90 disabled:opacity-50"
:disabled="!canStartDownload"
@click="handleStartDownload"
>下载</button>
<button
class="ml-2 px-3 py-1.5 bg-red-600 text-white rounded-md hover:opacity-90 disabled:opacity-50"
:disabled="!hostMid || downloading || deleting"
@click="handleDeleteHost"
>删除</button>
</div>
<!-- 已抓取的UP列表 -->
<div class="bg-white rounded-lg border border-gray-200 p-4">
<div class="flex items-center justify-between mb-3">
<div class="text-sm font-medium">已抓取的UP</div>
<button class="text-xs text-gray-500 hover:text-gray-700" @click="loadHosts">刷新</button>
</div>
<div v-if="hostsLoading" class="text-xs text-gray-400">加载中...</div>
<div v-else>
<div v-if="hosts.length" class="grid gap-4 grid-cols-1 sm:grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-3">
<div v-for="h in hosts" :key="h.host_mid" class="group border rounded-md p-2 flex items-center space-x-2 hover:border-[#fb7299] cursor-pointer"
@click="selectHost(h.host_mid)">
<img :src="h.face_path ? toStaticUrl(h.face_path) : ''" class="w-9 h-9 rounded-full object-cover border" alt="face" />
<div class="min-w-0 flex-1">
<div class="text-xs font-medium truncate">{{ h.up_name || h.host_mid }}</div>
<div class="text-[11px] text-gray-500 truncate">动态:{{ h.item_count }} · 抓取:{{ formatTs(h.last_fetch_time) }}</div>
</div>
</div>
</div>
<div v-else class="text-xs text-gray-400">暂无数据</div>
</div>
</div>
<!-- SSE 实时日志:下载中或有历史日志时显示 -->
<div v-if="downloading || logs.length" class="bg-white rounded-lg border border-gray-200 p-4">
<div class="flex items-center justify-between">
<div class="text-sm font-medium">实时日志</div>
<button class="text-xs text-gray-500 hover:text-gray-700" @click="logs=[]">清空</button>
</div>
<div ref="logsContainer" class="mt-2 h-40 overflow-auto bg-gray-50 border rounded p-2 text-xs whitespace-pre-wrap">
<template v-if="logs.length">
<div v-for="(line, idx) in logs" :key="idx" class="text-gray-700">{{ line }}</div>
</template>
<div v-else class="text-gray-400">暂无日志</div>
</div>
</div>
<!-- 已下载动态(数据库读取) -->
<div v-if="hostMid && items.length" class="bg-white rounded-lg border border-gray-200 p-4">
<div class="text-sm font-medium mb-3">已下载动态</div>
<div class="space-y-3">
<div v-for="it in items" :key="it.id_str">
<component
:is="isVideoDynamic(it) ? DynamicCardVideo : DynamicCardNormal"
:item="it"
:face-url="hostFaceUrl"
/>
</div>
</div>
<div class="mt-3 flex justify-center">
<button class="px-3 py-1.5 text-sm bg-white border rounded hover:bg-gray-50 disabled:opacity-50" :disabled="loadingMore || noMore" @click="loadMore">
{{ noMore ? '没有更多了' : (loadingMore ? '加载中...' : '加载更多') }}
</button>
</div>
</div>
</div>
</template>
<script setup>
import { ref, computed, onUnmounted, watch, nextTick } from 'vue'
import { showDialog } from 'vant'
import 'vant/es/dialog/style'
import { toStaticUrl } from '@/utils/imageUrl'
import DynamicCardVideo from '@/components/tailwind/dynamic/DynamicCardVideo.vue'
import DynamicCardNormal from '@/components/tailwind/dynamic/DynamicCardNormal.vue'
import SimpleSearchBar from '@/components/tailwind/SimpleSearchBar.vue'
import {
getDynamicDbHosts,
getDynamicDbSpace,
startDynamicAutoFetch,
createDynamicProgressSSE,
stopDynamicAutoFetch,
deleteDynamicSpace
} from '@/api/api'
// 输入 mid
const inputMid = ref('')
const hostMid = ref('')
// 主机信息与头像
const hostInfo = ref(null)
const hostFaceUrl = computed(() => hostInfo.value?.face_path ? toStaticUrl(hostInfo.value.face_path) : '')
// UP 列表
const hosts = ref([])
const hostsLoading = ref(false)
// 列表 & 分页
const items = ref([])
const limit = ref(20)
const offset = ref(0)
const total = ref(0)
const loadingMore = ref(false)
const noMore = ref(false)
// 下载状态与 SSE
const downloading = ref(false)
const deleting = ref(false)
let sse = null
const logs = ref([])
let queryTimer = null
const logsContainer = ref(null)
const canStartDownload = computed(() => !!hostMid.value && !downloading.value)
const formatTs = (ts) => {
if (!ts) return '-'
try {
const d = new Date(ts * 1000)
return [d.getFullYear(), d.getMonth() + 1, d.getDate()].join('-') + ' ' + [d.getHours(), d.getMinutes(), d.getSeconds()].map(n => String(n).padStart(2, '0')).join(':')
} catch {
return String(ts)
}
}
// 从 hosts 里尝试读取基本信息(face/up_name)
const fetchHostInfo = async (mid) => {
const res = await getDynamicDbHosts(200, 0)
const list = res?.data?.data || []
const found = list.find(x => String(x.host_mid) === String(mid))
hostInfo.value = found || { host_mid: String(mid) }
}
const loadHosts = async () => {
try {
hostsLoading.value = true
const res = await getDynamicDbHosts(50, 0)
hosts.value = res?.data?.data || []
} catch (e) {
// 忽略错误
} finally {
hostsLoading.value = false
}
}
const selectHost = async (mid) => {
inputMid.value = String(mid)
await triggerQueryNow()
}
const refreshList = async (reset = true) => {
if (!hostMid.value) return
if (reset) {
items.value = []
offset.value = 0
noMore.value = false
}
const res = await getDynamicDbSpace(hostMid.value, limit.value, offset.value)
total.value = res?.data?.total || 0
const rows = res?.data?.items || []
items.value = reset ? rows : items.value.concat(rows)
offset.value += rows.length
if (!rows.length || items.value.length >= total.value) noMore.value = true
}
// 手动查询入口已移除,改为输入 1 秒后自动触发
// 去重追加日志:仅当与上一条不同才加入
const addLog = (line) => {
const msg = String(line || '').trim()
if (!msg) return
const last = logs.value[logs.value.length - 1]
if (last !== msg) {
logs.value.push(msg)
// 追加后自动滚动到底部
nextTick(() => {
if (logsContainer.value) {
logsContainer.value.scrollTop = logsContainer.value.scrollHeight
}
})
}
}
const openSSE = (mid) => {
closeSSE()
try {
sse = createDynamicProgressSSE(mid)
sse.onopen = () => {
addLog(`[SSE] connected for ${mid}`)
}
// 仅识别最终完成格式:"抓取完成!共获取 xx 条动态,总计 xx 页"
const FINAL_DONE_RE = /\[全部抓取完毕\]\s*抓取完成!共获取\s+\d+\s*条动态,\s*总计\s+\d+\s*页/
// 显式监听 progress 事件名(后端事件名: progress)
sse.addEventListener('progress', (evt) => {
try {
const data = JSON.parse(evt.data)
const msg = data?.message || evt.data
addLog(String(msg))
// 仅在最终完成消息出现时自动停止
if (FINAL_DONE_RE.test(String(msg))) {
if (downloading.value) handleStop()
}
} catch {
addLog(String(evt.data))
}
})
// 兜底接收未命名事件
sse.onmessage = (evt) => {
try {
const data = JSON.parse(evt.data)
const msg = data?.message || evt.data
addLog(String(msg))
if (FINAL_DONE_RE.test(String(msg))) {
if (downloading.value) handleStop()
}
} catch {
addLog(String(evt.data))
}
}
sse.onerror = (evt) => {
addLog('[SSE] error, will close')
closeSSE()
}
} catch (e) {
addLog(`[SSE] create failed: ${e?.message || e}`)
}
}
const closeSSE = () => {
if (sse) {
try { sse.close() } catch {}
sse = null
}
}
const handleStartDownload = async () => {
if (!hostMid.value || downloading.value) return
downloading.value = true
logs.value.push(`Start auto fetch for MID ${hostMid.value}`)
openSSE(hostMid.value)
try {
await startDynamicAutoFetch(hostMid.value, {
need_top: false,
save_to_db: true,
save_media: true
})
} catch (e) {
logs.value.push(`start error: ${e?.message || e}`)
}
}
const handleStop = async () => {
if (!hostMid.value) return
try {
await stopDynamicAutoFetch(hostMid.value)
addLog('Stop requested')
} catch (e) {
addLog(`stop error: ${e?.message || e}`)
} finally {
downloading.value = false
closeSSE()
// 停止后刷新一次列表
await refreshList(true)
// 停止后刷新头像(可能在抓取期间生成了face)
await fetchHostInfo(hostMid.value)
}
}
const confirmDelete = (mid, name) => {
return new Promise((resolve) => {
showDialog({
title: '⚠️ 危险操作',
message: `即将删除 ${name} (UID: ${mid}) 的所有动态媒体与数据库记录。\n\n此操作不可恢复,请谨慎确认!`,
showCancelButton: true,
confirmButtonText: '确认删除',
cancelButtonText: '取消'
}).then(() => {
// 第二次确认
showDialog({
title: '🚨 最终确认',
message: `请再次确认删除 ${name} (UID: ${mid}) 的所有数据。\n\n点击确认后将立即执行删除操作!`,
showCancelButton: true,
confirmButtonText: '立即删除',
cancelButtonText: '取消'
}).then(() => resolve(true)).catch(() => resolve(false))
}).catch(() => resolve(false))
})
}
const handleDeleteHost = async () => {
if (!hostMid.value || downloading.value || deleting.value) return
const mid = String(hostMid.value)
const name = hostInfo.value?.up_name || `UID ${mid}`
const confirmed = await confirmDelete(mid, name)
if (!confirmed) return
await executeDelete(mid, name, true)
}
const executeDelete = async (mid, name, clearSelection) => {
try {
deleting.value = true
addLog(`Delete requested for ${name} (MID: ${mid})`)
await deleteDynamicSpace(mid)
addLog(`Delete success for ${name} (MID: ${mid})`)
if (clearSelection) {
// 清空本地列表、选择状态并刷新
items.value = []
offset.value = 0
total.value = 0
noMore.value = true
hostInfo.value = null
hostMid.value = ''
inputMid.value = ''
}
await loadHosts()
} catch (e) {
const errorMsg = e?.message || e
addLog(`delete error: ${errorMsg}`)
showDialog({
title: '删除失败',
message: `删除 ${name} 失败:\n${errorMsg}`,
confirmButtonText: '确定'
})
} finally {
deleting.value = false
}
}
const isVideoDynamic = (it) => {
// 有 bvid 即视为视频动态;或 type 包含 VIDEO
if (it?.bvid) return true
const t = String(it?.type || '')
return t.includes('VIDEO') || t.includes('AV')
}
const loadMore = async () => {
if (loadingMore.value || noMore.value) return
loadingMore.value = true
try {
await refreshList(false)
} finally {
loadingMore.value = false
}
}
onUnmounted(() => {
closeSSE()
if (queryTimer) clearTimeout(queryTimer)
})
// 监听输入,1秒后自动查询
watch(() => inputMid.value, (val) => {
const mid = String(val || '').trim()
if (!mid) return
if (queryTimer) clearTimeout(queryTimer)
queryTimer = setTimeout(async () => {
if (hostMid.value !== mid) {
hostMid.value = mid
await fetchHostInfo(mid)
await refreshList(true)
}
}, 1000)
})
// 立即触发查询(供按回车使用)
const triggerQueryNow = async () => {
const mid = String(inputMid.value || '').trim()
if (!mid) return
if (queryTimer) clearTimeout(queryTimer)
if (hostMid.value !== mid) {
hostMid.value = mid
await fetchHostInfo(mid)
await refreshList(true)
}
}
// 初始化加载UP列表
loadHosts()
</script>
<style scoped>
</style>
|
294coder/Efficient-MIF
| 3,152
|
Pansharpening_Hyper_SR_Matlab_Test_Package/SR-D/Dict_Learn.m
|
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Dict_Learn is the dictionary learning method for the
% compressive sensing approach for Pansharpening proposed in [Vicinanza15].
%
% INPUTS
% I_PAN_D: Details of the panchromatic image;
% I_PAN_LR_D: Details of the low resolution panchromatic image;
% I_MS_LR_D: Details of the MS original image or the MS original image (depending on the flag "do_detail" in CSDetails);
% resize_fact: Resize factor (ratio between PAN and MS images);
% TS: Tiling (dimensions of the patches are TS x TS, e.g. 7 x 7);
% ol: Overlap in pixels between contiguous tiles.
%
% OUTPUTS
% Dh: High spatial resolution dictionary (PAN details) built as in [Vicinanza15];
% Dl: Low spatial resolution dictionary (Low resolution PAN details) built as in [Vicinanza15];
% ytilde_k: Patches in column form of the details of the MS original image or the MS original image (depending on the flag "do_detail" in CSDetails).
%
% REFERENCE
% [Vicinanza15] M.R. Vicinanza, et al. "A pansharpening method based on the sparse representation of injected details."
% IEEE Geoscience and Remote Sensing Letters 12.1 (2015): 180-184.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [Dh, Dl, ytilde_k] = Dict_Learn(I_PAN_D, I_PAN_LR_D, I_MS_LR_D, resize_fact, TS, ol)
nr = ceil ((size(I_PAN_D,1)/resize_fact - ol) / (TS - ol));
nc = ceil ((size(I_PAN_D,2)/resize_fact - ol) / (TS - ol));
nBands = size (I_MS_LR_D,3);
Dh = zeros (TS^2*resize_fact^2*nBands, nr*nc);
Dl = zeros (TS^2*nBands, nr*nc);
ytilde_k = zeros (TS^2*nBands, nr*nc);
% Building the dictionaries (Dh and Dl)
icount = 0;
for irow=1:nr
for icol=1:nc
icount = icount + 1;
shiftr = 0; shiftc = 0;
if irow == nr && mod(size(I_MS_LR_D,1)-ol, TS-ol) ~= 0
shiftr = TS-ol - mod (size(I_MS_LR_D,1)-ol, TS-ol);
end
if icol == nc && mod(size(I_MS_LR_D,2)-ol, TS-ol) ~= 0
shiftc = TS-ol - mod (size(I_MS_LR_D,2)-ol, TS-ol);
end
blockr = ((irow-1)*(TS-ol)*resize_fact+1 - shiftr*resize_fact) : ((irow*TS-(irow-1)*ol)*resize_fact - shiftr*resize_fact);
blockc = ((icol-1)*(TS-ol)*resize_fact+1 - shiftc*resize_fact) : ((icol*TS-(icol-1)*ol)*resize_fact - shiftc*resize_fact);
blockrl = ((irow-1)*(TS-ol)+1 - shiftr) : (irow*TS-(irow-1)*ol - shiftr);
blockcl = ((icol-1)*(TS-ol)+1 - shiftc) : (icol*TS-(icol-1)*ol - shiftc);
for iband = 1:nBands
colmn = I_PAN_D(blockr,blockc,iband);
colmnlr = I_PAN_LR_D(blockrl,blockcl,iband);
colmny = I_MS_LR_D(blockrl,blockcl,iband);
Dh((iband-1)*TS^2*resize_fact^2+1:(iband-1)*TS^2*resize_fact^2+length(colmn(:)),icount) = (colmn(:));
Dl((iband-1)*TS^2+1:(iband-1)*TS^2+length(colmnlr(:)),icount) = (colmnlr(:));
ytilde_k((iband-1)*TS^2+1:(iband-1)*TS^2+length(colmny(:)),icount) = (colmny(:));
end
end
end
end
|
281677160/openwrt-package
| 1,391
|
luci-app-passwall2/luasrc/view/passwall2/server/users_list_status.htm
|
<%
local api = require "luci.passwall2.api"
-%>
<script type="text/javascript">
//<![CDATA[
var _users_status = document.getElementsByClassName('_users_status');
for(var i = 0; i < _users_status.length; i++) {
var id = _users_status[i].parentElement.parentElement.parentElement.id;
id = id.substr(id.lastIndexOf("-") + 1);
XHR.get('<%=api.url("server_user_status")%>', {
index: i,
id: id
},
function(x, result) {
_users_status[result.index].setAttribute("style","font-weight:bold;");
_users_status[result.index].setAttribute("color",result.status ? "green":"red");
_users_status[result.index].innerHTML = (result.status ? '✓' : 'X');
}
);
}
var edit_btn = document.getElementById("cbi-passwall2_server-user").getElementsByClassName("cbi-button cbi-button-edit");
for (var i = 0; i < edit_btn.length; i++) {
try {
var onclick_str = edit_btn[i].getAttribute("onclick");
var id = onclick_str.substring(onclick_str.lastIndexOf('/') + 1, onclick_str.length - 1);
var td = edit_btn[i].parentNode;
var new_div = "";
//添加"日志"按钮
new_div += '<input class="btn cbi-button cbi-button-add" type="button" value="<%:Log%>" onclick="window.open(\'' + '<%=api.url("server_user_log")%>' + '?id=' + id + '\', \'_blank\')"/> ';
td.innerHTML = new_div + td.innerHTML;
}
catch(err) {
console.error(err);
}
}
//]]>
</script>
|
281677160/openwrt-package
| 1,075
|
luci-app-passwall2/luasrc/view/passwall2/server/log.htm
|
<%
local api = require "luci.passwall2.api"
-%>
<script type="text/javascript">
//<![CDATA[
function clear_log(btn) {
XHR.get('<%=api.url("server_clear_log")%>', null,
function(x, data) {
if(x && x.status == 200) {
var log_textarea = document.getElementById('log_textarea');
log_textarea.innerHTML = "";
log_textarea.scrollTop = log_textarea.scrollHeight;
}
}
);
}
XHR.poll(3, '<%=api.url("server_get_log")%>', null,
function(x, data) {
if(x && x.status == 200) {
var log_textarea = document.getElementById('log_textarea');
log_textarea.innerHTML = x.responseText;
log_textarea.scrollTop = log_textarea.scrollHeight;
}
}
);
//]]>
</script>
<fieldset class="cbi-section" id="_log_fieldset">
<legend>
<%:Logs%>
</legend>
<input class="btn cbi-button cbi-button-remove" type="button" onclick="clear_log()" value="<%:Clear logs%>" />
<textarea id="log_textarea" class="cbi-input-textarea" style="width: 100%;margin-top: 10px;" data-update="change" rows="20" wrap="off" readonly="readonly"></textarea>
</fieldset>
|
294coder/Efficient-MIF
| 3,917
|
Pansharpening_Hyper_SR_Matlab_Test_Package/SR-D/OMP_Rec_Detile.m
|
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% OMP_Rec_Detile performs:
% 1) The estimation of the coefficients \alpha at reduced resolution using an orthogonal matching pursuit (OMP) procedure for multispectral images;
% 2) The reconstruction of the patches at full resolution using the hypothesis of invariance among scales of the \alpha coefficients;
% 3) The detiling step to get the final image details at full resolution for the approach proposed in [Vicinanza15].
%
% INPUTS
% Dl: Low spatial resolution dictionary (Low resolution PAN details) built as in [Vicinanza15];
% Dh: High spatial resolution dictionary (PAN details) built as in [Vicinanza15];
% ytilde_k: Patches in column form of the details of the MS original image or the MS original image (depending on the flag "do_detail" in CSDetails);
% H_PAN,L_PAN,C_PAN: PAN (row and column) dimensions and number of MS spectral bands;
% resize_fact: Resize factor (ratio between PAN and MS images);
% TS: Tiling (dimensions of the patches are TS x TS, e.g. 7 x 7);
% ol: Overlap in pixels between contiguous tiles.
% n_atoms: max number of representation atoms
%
% OUTPUT
% I_Fus_CS: Reconstructed details (or fused image if do_detail flag is 0) using the CS approach in [Vicinanza15] for the final pansharpening product.
%
% REFERENCE
% [Vicinanza15] M.R. Vicinanza, et al. "A pansharpening method based on the sparse representation of injected details."
% IEEE Geoscience and Remote Sensing Letters 12.1 (2015): 180-184.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function I_Fus_CS = OMP_Rec_Detile(Dl, Dh, ytilde_k, H_PAN, L_PAN, C_MS, resize_fact, ol, TS, n_atoms)
I_Fus_CS = zeros ([H_PAN L_PAN C_MS]);
countpx = zeros ([H_PAN L_PAN C_MS]);
nr = ceil ((H_PAN/resize_fact - ol) / (TS - ol));
nc = ceil ((L_PAN/resize_fact - ol) / (TS - ol));
shiftr_glob = 0; shiftc_glob = 0;
if mod(H_PAN/resize_fact-ol, TS-ol) ~= 0
shiftr_glob = TS-ol - mod (H_PAN/resize_fact-ol, TS-ol);
end
if mod(L_PAN/resize_fact-ol, TS-ol) ~= 0
shiftc_glob = TS-ol - mod (L_PAN/resize_fact-ol, TS-ol);
end
alpha_count = 0;
Latom = size (Dl, 2);
Dict_Size = size (ytilde_k, 2);
iatom = 0;
for irow=1:nr
for icol=1:nc
iatom = iatom+1;
if irow == nr
shiftr = shiftr_glob;
else
shiftr = 0;
end
if icol == nc
shiftc = shiftc_glob;
else
shiftc = 0;
end
blockr = ((irow-1)*(TS-ol)*resize_fact+1 - shiftr*resize_fact) : ((irow*TS-(irow-1)*ol)*resize_fact - shiftr*resize_fact);
blockc = ((icol-1)*(TS-ol)*resize_fact+1 - shiftc*resize_fact) : ((icol*TS-(icol-1)*ol)*resize_fact - shiftc*resize_fact);
Lr = length (blockr); Lc = length (blockc);
y_cur = ytilde_k(:,iatom);
% Sparse coding with OMP for MS data
[alpha,inds] = OMP(Dl, y_cur, C_MS, iatom, n_atoms);
% Patch reconstruction and detiling
for iband = 1:C_MS
reconstr_patch = Dh((iband-1)*TS^2*resize_fact^2+1:iband*TS^2*resize_fact^2,inds) * alpha(:,iband);
I_Fus_CS(blockr,blockc,iband) = I_Fus_CS(blockr,blockc,iband) + reshape (reconstr_patch, Lr, Lc);
countpx(blockr,blockc,iband) = countpx(blockr,blockc,iband) +1;
end
if mod(iatom,100)==1
fprintf ('OMP band by band and detile: atom %i of %i\n', iatom, Dict_Size);
end
alpha_count = alpha_count + sum( sum(alpha,2)~=0 );
end
end
% Average overlapping patches
I_Fus_CS = I_Fus_CS ./ countpx;
fprintf ('Sparsity di alfa = %.2f: %.1f atoms on %i used for each patch on average\n', (Dict_Size*Latom-alpha_count)/Dict_Size/Latom*100, alpha_count/Dict_Size, Dict_Size)
end
|
294coder/Efficient-MIF
| 1,711
|
Pansharpening_Hyper_SR_Matlab_Test_Package/SR-D/OMP.m
|
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% OMP is the Orthogonal matching Pursuit (OMP) modified to work with multispectral data.
%
% INPUTS
% D: Dictionary (matrix);
% y: Measurements (column vector);
% delta: Maximum error allowed for the constraint y = D a;
% nBands: Number of MS spectral bands;
% iatom: Id of the actual atom under analysis.
% n_atoms: max number of representation atoms
%
% OUTPUTS
% a: Estimated alphas;
% indx: Vector of the atom positions in the dictionary.
%
% REFERENCE
% [Vicinanza15] M.R. Vicinanza, et al. "A pansharpening method based on the sparse representation of injected details."
% IEEE Geoscience and Remote Sensing Letters 12.1 (2015): 180-184.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [a, indx] = OMP(D, y, nBands, iatom, n_atoms)
L_atom = size(D);
n = round(L_atom / nBands);
delta = 0;
res = y;
curr_delta = sum (res.^2);
j = 0;
while curr_delta > delta && j < n_atoms
j = j+1;
if j==1
indx = iatom;
else
proj = D' * res;
[~, imax] = max(abs(proj));
imax = imax(1);
indx = cat(2,indx,imax);
end
a = zeros (j, nBands);
for iband = 1:nBands
Di = D((iband-1)*n+1:iband*n,indx(1:j));
yi = y((iband-1)*n+1:iband*n);
DitDi = Di'*Di;
if det (DitDi) > 1e-1
a(:,iband) = ((DitDi)\(Di')) * yi;
end
Da((iband-1)*n+1:iband*n) = Di * a(:,iband);
end
res = y - Da';
curr_delta = sum(res.^2);
end
end
|
294coder/Efficient-MIF
| 3,265
|
Pansharpening_Hyper_SR_Matlab_Test_Package/SR-D/CS.m
|
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Description:
% CSDetails is the Compressive Sensing (CS) approach for Pansharpening proposed in [Vicinanza15].
%
% Interface:
% I_Fus_CS = CSDetails(I_MS, I_PAN, I_MS_LR, resize_fact, sensor, TS, ol, n_atoms)
%
% Inputs:
% I_MS: Multispectral (MS) original image upsampled to the PAN scale;
% I_PAN: Panchromatic (PAN) image;
% I_MS_LR: MS original image;
% ratio: Scale ratio between MS and PAN. Pre-condition: Integer value;
% sensor: String for type of sensor (e.g. 'WV2', 'IKONOS');
% TS: Tiling (dimensions of the patches are TS x TS, e.g. 7 x 7);
% ol: Overlap in pixels between contiguous tile;
% n_atoms: max number of representation atoms (default value = 10).
%
% Output:
% I_Fus_CS: Fusion image using the CS approach in [Vicinanza15].
%
% References:
% [Vicinanza15] M.R. Vicinanza, R. Restaino, G. Vivone, M. Dalla Mura, and J. Chanussot, "A pansharpening method based on the sparse representation of injected details",
% IEEE Geoscience and Remote Sensing Letters, vol. 12, no. 1, pp. 180-184, 2015.
% [Vivone20] G. Vivone, M. Dalla Mura, A. Garzelli, R. Restaino, G. Scarpa, M.O. Ulfarsson, L. Alparone, and J. Chanussot, "A New Benchmark Based on Recent Advances in Multispectral Pansharpening: Revisiting pansharpening with classical and emerging pansharpening methods",
% IEEE Geoscience and Remote Sensing Magazine, doi: 10.1109/MGRS.2020.3019315.
% % % % % % % % % % % % %
%
% Version: 1
%
% % % % % % % % % % % % %
%
% Copyright (C) 2019
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function I_Fus_CS = CS(I_MS, I_PAN, I_MS_LR, ratio, sensor, TS, ol, n_atoms)
if nargin < 9
n_atoms = 10;
end
imageLR = double(I_MS);
imageHR = double(I_PAN);
imageLR_LR = double(I_MS_LR);
%%% Equalization
imageHR = repmat (imageHR, [1 1 size(I_MS,3)]);
for ii = 1 : size(imageLR_LR,3)
% imageHR(:,:,ii) = equalize_image (imageHR(:,:,ii), imageLR(:,:,ii));
imageHR(:,:,ii) = (imageHR(:,:,ii) - mean2(imageHR(:,:,ii))) / std2(imageHR(:,:,ii))...
* std2(imageLR(:,:,ii)) + mean2(imageLR(:,:,ii));
end
%%% Extract details using MTF-based filters
imageLR_LP = MTF(imageLR, sensor, ratio);
imageLR_D = imageLR - imageLR_LP;
imageHR_LP = MTF(imageHR, sensor, ratio);
for ii = 1:size(imageHR,3)
imageHR_LP(:,:,ii) = imresize(imresize(imageHR_LP(:,:,ii), 1/ratio, 'nearest'), ratio);
end
imageHR_D = imageHR - imageHR_LP;
%%% Decimation MS
for ii = 1 : size(imageLR,3)
imageLR_LR(:,:,ii) = double(imresize(imageLR_D(:,:,ii),1/ratio, 'nearest'));
end
%%% Degradation PAN
imageHR_LR = resize_images(imageHR_D, 1, ratio, sensor);
%%% Dictionary learning
[Dh, Dl, ytilde_k] = Dict_Learn(imageHR_D, imageHR_LR, imageLR_LR, ratio, TS, ol);
%%% Sparse coefficient estimation and HR signal reconstruction
I_Fus_CS = OMP_Rec_Detile(Dl, Dh, ytilde_k, size(imageHR,1), size(imageHR,2), size(imageLR_LR, 3), ratio, ol , TS, n_atoms);
I_Fus_CS = imageLR + I_Fus_CS;
end
|
294coder/Efficient-MIF
| 3,215
|
Pansharpening_Hyper_SR_Matlab_Test_Package/PWMBF/compute_PhiX.m
|
function PhiX=compute_PhiX(X,L,h,type)
vec = @(x) x(:);
[N,r]=size(X);
switch lower(type)
case 'dwt'
M=N;
PhiX=zeros(size(X));
for k=1:r
PhiX(:,k)=vec(midwt(reshape(X(:,k),[sqrt(M) sqrt(M)]),h,L));
end
case 'dwt2'
M=N;
PhiX=zeros(size(X));
for k=1:r
PhiX(:,k)=vec(IWT2_PO(reshape(X(:,k),[sqrt(M) sqrt(M)]),log2(sqrt(M))-L,h));
end
case 'rwt'
M=N/(3*L+1);
PhiX=zeros(M,r);
for k=1:r
PhiX(:,k)=vec(mirdwt(reshape(X(1:M,k),[sqrt(M) sqrt(M)]),reshape(X(M+1:end,k),[sqrt(M) 3*L*sqrt(M)]),h,L))*2;
end
case 'swt'
M=N/(3*L+1);
PhiX=zeros(M,r);
for k=1:r
PhiX(:,k)=vec(iswt2(reshape(X(:,k),[sqrt(M) sqrt(M) 3*L+1]),'db4'));
end
case 'iso'
M=N/(L+1);
PhiX=zeros(M,r);
for k=1:r
xc=reshape(X(:,k),[sqrt(M) (L+1)*sqrt(M)]);
xc=mat2cell(xc,[sqrt(M)],repmat(sqrt(M),[1 L+1]));
PhiX(:,k)=vec(atrousrec(xc,'maxflat'));
end
case 'cwt'
J=L;
[Faf, Fsf] = FSfarras; % 1st stage anal. & synth. filters
[af, sf] = dualfilt1;
PhiX=zeros(size(X,1)/2,size(X,2));
n=sqrt(size(X,1)/2);
for c=1:r
W=X(:,c);
j_offset=0;
for j=1:J
for k=1:3
w2{j}{1}{k}=reshape(W(j_offset+1+(k-1)*(n/2^j)^2:j_offset+k*(n/2^j)^2),[n/2^j n/2^j]);
w2{j}{2}{k}=reshape(W(j_offset+n^2+1+(k-1)*(n/2^j)^2:j_offset+n^2+k*(n/2^j)^2),[n/2^j n/2^j]);
end
j_offset=j_offset+3*(n/2^j)^2;
end
w2{J+1}{1}=reshape(W(n^2-(n/2^(J))^2+1:n^2),[n/2^J n/2^J]);
w2{J+1}{2}=reshape(W(2*n^2-(n/2^(J))^2+1:2*n^2),[n/2^J n/2^J]);
PhiX(:,c)=vec(idualtree2D(w2,J,Fsf,sf));
end
case 'cplxdt'
J=L;
[Faf, Fsf] = FSfarras; % 1st stage anal. & synth. filters
[af, sf] = dualfilt1;
PhiX=zeros(size(X,1)/4,size(X,2));
n=sqrt(size(X,1)/4);
for c=1:r
W=X(:,c);
j_offset=0;
for j=1:J
l_offset=0;
for l=1:2
for k=1:3
w2{j}{1}{l}{k}=reshape(W(j_offset+l_offset+1+(k-1)*(n/2^j)^2:j_offset+l_offset+k*(n/2^j)^2),[n/2^j n/2^j]);
w2{j}{2}{l}{k}=reshape(W(j_offset+l_offset+2*n^2+1+(k-1)*(n/2^j)^2:j_offset+l_offset+2*n^2+k*(n/2^j)^2),[n/2^j n/2^j]);
end
l_offset=l_offset+3*(n/2^j)^2;
end
j_offset=j_offset+6*(n/2^j)^2;
end
w2{J+1}{1}{1}=reshape(W(2*n^2-2*(n/2^(J))^2+1:2*n^2-(n/2^(J))^2),[n/2^J n/2^J]);
w2{J+1}{1}{2}=reshape(W(2*n^2-(n/2^(J))^2+1:2*n^2),[n/2^J n/2^J]);
w2{J+1}{2}{1}=reshape(W(4*n^2-2*(n/2^(J))^2+1:4*n^2-(n/2^(J))^2),[n/2^J n/2^J]);
w2{J+1}{2}{2}=reshape(W(4*n^2-(n/2^(J))^2+1:4*n^2),[n/2^J n/2^J]);
PhiX(:,c)=vec(icplxdual2D(w2,J,Fsf,sf));
end
otherwise
error(['Unknown method ' type]);
end
|
294coder/Efficient-MIF
| 2,699
|
Pansharpening_Hyper_SR_Matlab_Test_Package/PWMBF/compute_PhiTX.m
|
function PhiTX=compute_PhiTX(X,L,h,type)
vec = @(x) x(:);
[M,T]=size(X);
switch lower(type)
case 'dwt2'
PhiTX=zeros(size(X));
for k=1:T
PhiTX(:,k)=vec(FWT2_PO(reshape(X(:,k),[sqrt(M) sqrt(M)]),log2(sqrt(M))-L,h));
end
case 'dwt'
PhiTX=zeros(size(X));
for k=1:T
PhiTX(:,k)=vec(mdwt(reshape(X(:,k),[sqrt(M) sqrt(M)]),h,L));
end
case 'rwt'
PhiTX=zeros((3*L+1)*M,T);
for k=1:T
[xl xh L]=mrdwt(reshape(X(:,k),[sqrt(M) sqrt(M)]),h,L);
PhiTX(:,k)=vec([xl xh])/2;
end
case 'swt'
PhiTX=zeros((3*L+1)*M,T);
for k=1:T
PhiTX(:,k)=vec(myswt2(reshape(X(:,k),[sqrt(M) sqrt(M)]),L,'db4'));
end
case 'iso'
PhiTX=zeros((L+1)*M,T);
for k=1:T
PhiTX(:,k)=vec(cell2mat(atrousdec(reshape(X(:,k),[sqrt(M) sqrt(M)]),'maxflat',L)));
end
case 'cwt'
J=L;
[Faf, Fsf] = FSfarras; % 1st stage anal. & synth. filters
[af, sf] = dualfilt1;
for k=1:T
w=dualtree2D(reshape(X(:,k),[sqrt(M) sqrt(M)]),J,Faf,af);
W=[];
for j=1:J
W=[W' vec(w{j}{1}{1})']';
W=[W' vec(w{j}{1}{2})']';
W=[W' vec(w{j}{1}{3})']';
end
W=[W' vec(w{J+1}{1})']';
for j=1:J
W=[W' vec(w{j}{2}{1})']';
W=[W' vec(w{j}{2}{2})']';
W=[W' vec(w{j}{2}{3})']';
end
W=[W' vec(w{J+1}{2})']';
PhiTX(:,k)=W;
end
case 'cplxdt'
J=L;
[Faf, Fsf] = FSfarras; % 1st stage anal. & synth. filters
[af, sf] = dualfilt1;
for k=1:T
w=cplxdual2D(reshape(X(:,k),[sqrt(M) sqrt(M)]),J,Faf,af);
W=[];
for j=1:J
W=[W' vec(w{j}{1}{1}{1})']';
W=[W' vec(w{j}{1}{1}{2})']';
W=[W' vec(w{j}{1}{1}{3})']';
W=[W' vec(w{j}{1}{2}{1})']';
W=[W' vec(w{j}{1}{2}{2})']';
W=[W' vec(w{j}{1}{2}{3})']';
end
W=[W' vec(w{J+1}{1}{1})']';
W=[W' vec(w{J+1}{1}{2})']';
for j=1:J
W=[W' vec(w{j}{2}{1}{1})']';
W=[W' vec(w{j}{2}{1}{2})']';
W=[W' vec(w{j}{2}{1}{3})']';
W=[W' vec(w{j}{2}{2}{1})']';
W=[W' vec(w{j}{2}{2}{2})']';
W=[W' vec(w{j}{2}{2}{3})']';
end
W=[W' vec(w{J+1}{2}{1})']';
W=[W' vec(w{J+1}{2}{2})']';
PhiTX(:,k)=W;
end
otherwise
error(['Unknown method ' type]);
end
|
2881099/FreeSql.AdminLTE
| 1,227
|
Examples/net80_blazor/FodyWeavers.xsd
|
<?xml version="1.0" encoding="utf-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
<!-- This file was generated by Fody. Manual changes to this file will be lost when your project is rebuilt. -->
<xs:element name="Weavers">
<xs:complexType>
<xs:all>
<xs:element name="Rougamo" minOccurs="0" maxOccurs="1" type="xs:anyType" />
</xs:all>
<xs:attribute name="VerifyAssembly" type="xs:boolean">
<xs:annotation>
<xs:documentation>'true' to run assembly verification (PEVerify) on the target assembly after all weavers have been executed.</xs:documentation>
</xs:annotation>
</xs:attribute>
<xs:attribute name="VerifyIgnoreCodes" type="xs:string">
<xs:annotation>
<xs:documentation>A comma-separated list of error codes that can be safely ignored in assembly verification.</xs:documentation>
</xs:annotation>
</xs:attribute>
<xs:attribute name="GenerateXsd" type="xs:boolean">
<xs:annotation>
<xs:documentation>'false' to turn off automatic generation of the XML Schema file.</xs:documentation>
</xs:annotation>
</xs:attribute>
</xs:complexType>
</xs:element>
</xs:schema>
|
2881099/FreeSql.AdminLTE
| 5,129
|
Examples/net80_blazor/Program.cs
|
using FreeSql;
using net80_blazor.Admin;
using net80_blazor.Entities;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Serialization;
using System.Reflection;
using Yitter.IdGenerator;
var builder = WebApplication.CreateBuilder(args);
Func<IServiceProvider, IFreeSql> fsqlFactory = r =>
{
IFreeSql fsql = new FreeSql.FreeSqlBuilder()
.UseConnectionString(FreeSql.DataType.Sqlite, @"Data Source=freedb.db")
.UseMonitorCommand(cmd => Console.WriteLine($"[{DateTime.Now.ToString("HH:mm:ss")}] {cmd.CommandText}\r\n"))//SQL
.UseNoneCommandParameter(true)
.UseAutoSyncStructure(true) //Զͬʵṹݿ⣬FreeSqlɨֻCRUDʱŻɱ
.Build();
YitIdHelper.SetIdGenerator(new IdGeneratorOptions(1) { WorkerIdBitLength = 6 });
var serverTime = fsql.Ado.QuerySingle(() => DateTime.UtcNow);
var timeOffset = DateTime.UtcNow.Subtract(serverTime);
fsql.Aop.AuditValue += (_, e) =>
{
//ݿʱ
if ((e.Column.CsType == typeof(DateTime) || e.Column.CsType == typeof(DateTime?))
&& e.Column.Attribute.ServerTime != DateTimeKind.Unspecified
&& (e.Value == null || (DateTime)e.Value == default || (DateTime?)e.Value == default))
{
e.Value = (e.Column.Attribute.ServerTime == DateTimeKind.Utc ? DateTime.UtcNow : DateTime.Now).Subtract(timeOffset);
}
//ѩId
if (e.Column.CsType == typeof(long)
&& e.Property.GetCustomAttribute<SnowflakeAttribute>(false) != null
&& (e.Value == null || (long)e.Value == default || (long?)e.Value == default))
{
e.Value = YitIdHelper.NextId();
}
//if (user == null || user.Id <= 0)
//{
// return;
//}
//if (e.AuditValueType is AuditValueType.Insert or AuditValueType.InsertOrUpdate)
//{
// switch (e.Property.Name)
// {
// case "CreatedUserId":
// case "OwnerId":
// case "MemberId":
// if (e.Value == null || (long)e.Value == default || (long?)e.Value == default)
// {
// e.Value = user.Id;
// }
// break;
// case "CreatedUserName":
// if (e.Value == null || ((string)e.Value).IsNull())
// {
// e.Value = user.UserName;
// }
// break;
// }
//}
//if (e.AuditValueType is AuditValueType.Update or AuditValueType.InsertOrUpdate)
//{
// switch (e.Property.Name)
// {
// case "ModifiedUserId":
// e.Value = user.Id;
// break;
// case "ModifiedUserName":
// e.Value = user.UserName;
// break;
// }
//}
};
if (fsql.Select<MenuEntity>().Any() == false)
{
var repo = fsql.GetRepository<MenuEntity>();
repo.DbContextOptions.EnableCascadeSave = true;
repo.Insert(new[]
{
new MenuEntity
{
Label = "ͨù",
ParentId = 0,
Path = "",
Sort = 100,
TargetBlank = false,
Icon = "",
Type = MenuEntityType.˵,
Childs = new List<MenuEntity>
{
new MenuEntity
{
Label = "˵",
Path = "Admin/Menu",
Sort = 101,
TargetBlank = false,
Icon = "",
Type = MenuEntityType.˵,
},
new MenuEntity
{
Label = "ɫ",
Path = "Admin/Role",
Sort = 102,
TargetBlank = false,
Icon = "",
Type = MenuEntityType.˵,
},
new MenuEntity
{
Label = "û",
Path = "Admin/User",
Sort = 103,
TargetBlank = false,
Icon = "",
Type = MenuEntityType.˵,
}
}
},
});
}
return fsql;
};
builder.Services.AddSingleton(fsqlFactory);
builder.Services.AddScoped<UnitOfWorkManager>();
builder.Services.AddFreeRepository(null, typeof(Program).Assembly);
builder.Services.AddControllersWithViews()
//.AddJsonOptions(options => { options.JsonSerializerOptions.Converters.Add(new JsonStringEnumConverter()); })
.AddNewtonsoftJson(options =>
{
//options.SerializerSettings.Converters.Add(new StringEnumConverter());
//options.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
options.SerializerSettings.Converters.Add(new IsoDateTimeConverter() { DateTimeFormat = "yyyy-MM-dd HH:mm:ss" });
//options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
//һ,ʹշʽkey
options.SerializerSettings.ContractResolver = new DefaultContractResolver();
});
builder.Services.AddRazorComponents()
.AddInteractiveServerComponents();
builder.Services.AddSwaggerGen();
builder.Services.AddScoped<CustomExceptionFilter>();
builder.Services.AddCors(options => options.AddPolicy("cors_all", builder => builder
.AllowAnyHeader()
.AllowAnyMethod()
.AllowAnyOrigin()
));
var app = builder.Build();
var applicationLifeTime = app.Services.GetService<IHostApplicationLifetime>();
app.Use(async (context, next) =>
{
TransactionalAttribute.SetServiceProvider(context.RequestServices);
await next();
});
app.UseCors("cors_all");
if (!app.Environment.IsDevelopment())
{
app.UseExceptionHandler("/Error", createScopeForErrors: true);
}
app.UseDefaultFiles().UseStaticFiles();
app.UseAntiforgery();
app.MapControllers();
app.MapRazorComponents<App>()
.AddInteractiveServerRenderMode();
app.Run();
|
281677160/openwrt-package
| 1,619
|
luci-app-passwall2/luasrc/view/passwall2/rule/rule_version.htm
|
<%
local api = require "luci.passwall2.api"
local geoip_update = api.uci_get_type("global_rules", "geoip_update", "1") == "1" and "checked='checked'" or ""
local geosite_update = api.uci_get_type("global_rules", "geosite_update", "1") == "1" and "checked='checked'" or ""
-%>
<script type="text/javascript">
//<![CDATA[
function update_rules(btn) {
btn.disabled = true;
btn.value = '<%:Updating...%>';
var div = document.getElementById('_rule_div');
var domList = div.getElementsByTagName('input');
var checkBoxList = [];
var len = domList.length;
while(len--) {
var dom = domList[len];
if(dom.type == 'checkbox' && dom.checked) {
checkBoxList.push(dom.name);
}
}
XHR.get('<%=api.url("update_rules")%>', {
update: checkBoxList.join(",")
},
function(x, data) {
if(x && x.status == 200) {
window.location.href = '<%=api.url("log")%>';
} else {
alert("<%:Error%>");
btn.disabled = false;
btn.value = '<%:Manually update%>';
}
}
);
}
//]]>
</script>
<div class="cbi-value" id="_rule_div">
<label class="cbi-value-title">
<%:Manually update%>
</label>
<div class="cbi-value-field">
<div>
<label>
<input class="cbi-input-checkbox" type="checkbox" name="geoip" value="1" <%=geoip_update%> />
geoip
</label>
<label>
<input class="cbi-input-checkbox" type="checkbox" name="geosite" value="1" <%=geosite_update%> />
geosite
</label>
<input class="btn cbi-button cbi-button-apply" type="button" id="update_rules_btn" onclick="update_rules(this)" value="<%:Manually update%>" />
</div>
</div>
</div>
|
2977094657/BiliHistoryFrontend
| 48,281
|
src/components/tailwind/page/BiliTools.vue
|
<template>
<div class="min-h-screen bg-gray-50/30">
<div class="py-6">
<div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
<!-- 主内容卡片 -->
<div class="bg-white rounded-lg overflow-hidden">
<!-- 标签导航 -->
<div class="border-b border-gray-200">
<nav class="-mb-px flex px-6 overflow-x-auto" aria-label="B站工具选项卡">
<button
@click="activeTab = 'video-stats'"
class="py-4 px-3 border-b-2 font-medium text-sm flex items-center space-x-2"
:class="activeTab === 'video-stats'
? 'border-[#fb7299] text-[#fb7299]'
: 'border-transparent text-gray-500 hover:text-gray-700 hover:border-gray-300'"
>
<svg class="w-5 h-5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 19v-6a2 2 0 00-2-2H5a2 2 0 00-2 2v6a2 2 0 002 2h2a2 2 0 002-2zm0 0V9a2 2 0 012-2h2a2 2 0 012 2v10m-6 0a2 2 0 002 2h2a2 2 0 002-2m0 0V5a2 2 0 012-2h2a2 2 0 012 2v14a2 2 0 01-2 2h-2a2 2 0 01-2-2z" />
</svg>
<span>视频观看总时长</span>
</button>
<button
@click="activeTab = 'video-download'"
class="ml-8 py-4 px-3 border-b-2 font-medium text-sm flex items-center space-x-2"
:class="activeTab === 'video-download'
? 'border-[#fb7299] text-[#fb7299]'
: 'border-transparent text-gray-500 hover:text-gray-700 hover:border-gray-300'"
>
<svg class="w-5 h-5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-4l-4 4m0 0l-4-4m4 4V4" />
</svg>
<span>视频下载</span>
</button>
<button
@click="activeTab = 'comment-query'"
class="ml-8 py-4 px-3 border-b-2 font-medium text-sm flex items-center space-x-2"
:class="activeTab === 'comment-query'
? 'border-[#fb7299] text-[#fb7299]'
: 'border-transparent text-gray-500 hover:text-gray-700 hover:border-gray-300'"
>
<svg class="w-5 h-5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8 10h.01M12 10h.01M16 10h.01M9 16H5a2 2 0 01-2-2V6a2 2 0 012-2h14a2 2 0 012 2v8a2 2 0 01-2 2h-5l-5 5v-5z" />
</svg>
<span>评论查询</span>
</button>
</nav>
</div>
<!-- 内容区域 -->
<div class="transition-all duration-300">
<!-- 视频观看时长信息 -->
<div v-if="activeTab === 'video-stats'" class="animate-fadeIn">
<div class="bg-white">
<!-- 致谢信息 -->
<div class="mb-3 flex items-center justify-center h-7 px-3 py-0 bg-[#fb7299]/5 rounded-md border border-[#fb7299]/20 mx-6 mt-4">
<a href="https://www.xiaoheihe.cn/app/user/profile/55542982" target="_blank" rel="noopener noreferrer" class="flex items-center hover:opacity-80 transition-opacity mr-1.5">
<img src="https://imgheybox.max-c.com/avatar/2025/02/16/20a399e3b78c0db29b5ec14361b3e348.png?imageMogr2/thumbnail/400x400%3E" alt="shengyI头像" class="h-5 w-5 rounded-full mr-1.5" />
</a>
<span class="text-xs text-gray-700">感谢小黑盒用户
<a
href="https://www.xiaoheihe.cn/app/bbs/link/153880174"
target="_blank"
rel="noopener noreferrer"
class="text-[#fb7299] font-medium hover:underline"
>
shengyI
</a>
提供思路
</span>
</div>
<!-- 输入表单 -->
<div class="px-4 py-4 border-b border-gray-100">
<h2 class="text-base font-medium text-gray-900 mb-2">视频时长信息查询</h2>
<p class="text-xs text-gray-600 mb-3">
输入B站视频BV号,查询该视频的观看时长信息。<span class="text-[#fb7299] font-medium">注意:只有被UP主添加到合集(season_id)的视频才能查询到观看时长数据。</span>
</p>
<div class="relative">
<input
v-model="bvid"
type="text"
placeholder="输入视频BV号,例如:BV1hu411h7ot"
class="w-full px-4 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-[#fb7299] focus:border-transparent pr-10"
@input="debouncedFetchVideoStats"
/>
<div class="absolute inset-y-0 right-0 flex items-center pr-3 pointer-events-none">
<svg v-if="loading" class="animate-spin h-5 w-5 text-[#fb7299]" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
<circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
<path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
</svg>
</div>
</div>
<div class="mt-3 flex items-center">
<input
type="checkbox"
id="use-sessdata"
v-model="useSessdata"
class="h-4 w-4 text-[#fb7299] focus:ring-[#fb7299] border-gray-300 rounded"
@change="bvid && debouncedFetchVideoStats()"
/>
<label for="use-sessdata" class="ml-2 block text-sm text-gray-600">
使用登录状态查询(用于需要登录才能查看的视频)
</label>
</div>
</div>
<!-- 结果展示 -->
<div v-if="videoStats" class="px-6 py-5">
<!-- 如果是合集视频 -->
<div v-if="videoStats.status === 'success'">
<!-- 查询的视频信息 -->
<div v-if="queriedVideo" class="mb-4 bg-white border border-[#fb7299]/20 rounded-lg overflow-hidden">
<div class="bg-[#fb7299]/5 px-3 py-2 border-b border-[#fb7299]/20">
<h3 class="text-sm font-medium text-gray-900 flex items-center">
<svg class="w-4 h-4 mr-1.5 text-[#fb7299]" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 10l4.553-2.276A1 1 0 0121 8.618v6.764a1 1 0 01-1.447.894L15 14M5 18h8a2 2 0 002-2V8a2 2 0 00-2-2H5a2 2 0 00-2 2v8a2 2 0 002 2z" />
</svg>
查询视频详情
</h3>
</div>
<div class="p-3">
<div class="flex flex-col md:flex-row">
<div class="md:w-52 flex-shrink-0 mb-3 md:mb-0">
<img
:src="queriedVideo.cover"
class="w-full h-28 md:h-32 object-cover rounded shadow-sm"
alt="视频封面"
/>
</div>
<div class="md:ml-4 flex-1">
<h4 class="text-sm font-medium text-gray-900 hover:text-[#fb7299]">
<a :href="`https://www.bilibili.com/video/${queriedVideo.bvid}`" target="_blank">{{ queriedVideo.title }}</a>
</h4>
<p class="text-xs text-gray-500 mt-1">BV: {{ queriedVideo.bvid }}</p>
<div class="mt-3 grid grid-cols-2 md:grid-cols-5 gap-2">
<div class="bg-gray-50 p-2 rounded-lg">
<p class="text-xs text-gray-500">视频时长</p>
<p class="text-sm font-semibold text-gray-900">{{ formatDuration(queriedVideo.duration) }}</p>
</div>
<div class="bg-gray-50 p-2 rounded-lg">
<p class="text-xs text-gray-500">观看次数</p>
<p class="text-sm font-semibold text-gray-900">{{ formatNumber(queriedVideo.vv) }}</p>
</div>
<div class="bg-gray-50 p-2 rounded-lg">
<p class="text-xs text-gray-500">总观看时长</p>
<p class="text-sm font-semibold text-[#fb7299]">
{{ formatDurationHours(queriedVideo.vt) }}
</p>
<p class="text-xs text-gray-500">{{ formatDurationDays(queriedVideo.vt) }}</p>
</div>
<div class="bg-gray-50 p-2 rounded-lg">
<p class="text-xs text-gray-500">平均观看时长</p>
<p class="text-sm font-semibold text-gray-900">
{{ formatDuration(Math.round((queriedVideo.vt * 60) / queriedVideo.vv)) }}
</p>
</div>
<div class="bg-gray-50 p-2 rounded-lg">
<p class="text-xs text-gray-500">完播率</p>
<p class="text-sm font-semibold text-gray-900">
{{ secondsToPercent(Math.round((queriedVideo.vt * 60) / queriedVideo.vv), queriedVideo.duration) }}%
</p>
<div class="w-full bg-gray-200 rounded-full h-1.5 mt-1">
<div
class="bg-[#fb7299] h-1.5 rounded-full"
:style="`width: ${Math.min(100, Math.round(((queriedVideo.vt * 60) / queriedVideo.vv) / queriedVideo.duration * 100))}%`"
></div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<!-- 视频列表 -->
<div class="mt-4">
<h3 class="text-base font-medium text-gray-900 mb-3 flex items-center">
<svg class="w-4 h-4 mr-2 text-[#fb7299]" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 6h16M4 10h16M4 14h16M4 18h16" />
</svg>
视频列表
</h3>
<div class="overflow-x-auto rounded-lg border border-gray-200">
<table class="min-w-full divide-y divide-gray-200">
<thead class="bg-gray-50">
<tr>
<th scope="col" class="px-3 py-2 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">视频信息</th>
<th
scope="col"
class="px-3 py-2 text-left text-xs font-medium text-gray-500 uppercase tracking-wider cursor-pointer"
@click="sortBy('duration')"
>
<div class="flex items-center">
时长
<svg
v-if="sortKey === 'duration'"
class="w-3 h-3 ml-1"
fill="none"
viewBox="0 0 24 24"
stroke="currentColor"
>
<path
stroke-linecap="round"
stroke-linejoin="round"
stroke-width="2"
:d="sortDirection === 'asc'
? 'M5 15l7-7 7 7'
: 'M19 9l-7 7-7-7'"
/>
</svg>
</div>
</th>
<th
scope="col"
class="px-3 py-2 text-left text-xs font-medium text-gray-500 uppercase tracking-wider cursor-pointer"
@click="sortBy('vv')"
>
<div class="flex items-center">
观看次数
<svg
v-if="sortKey === 'vv'"
class="w-3 h-3 ml-1"
fill="none"
viewBox="0 0 24 24"
stroke="currentColor"
>
<path
stroke-linecap="round"
stroke-linejoin="round"
stroke-width="2"
:d="sortDirection === 'asc'
? 'M5 15l7-7 7 7'
: 'M19 9l-7 7-7-7'"
/>
</svg>
</div>
</th>
<th
scope="col"
class="px-3 py-2 text-left text-xs font-medium text-gray-500 uppercase tracking-wider cursor-pointer"
@click="sortBy('vt')"
>
<div class="flex items-center">
总观看时长
<svg
v-if="sortKey === 'vt'"
class="w-3 h-3 ml-1"
fill="none"
viewBox="0 0 24 24"
stroke="currentColor"
>
<path
stroke-linecap="round"
stroke-linejoin="round"
stroke-width="2"
:d="sortDirection === 'asc'
? 'M5 15l7-7 7 7'
: 'M19 9l-7 7-7-7'"
/>
</svg>
</div>
</th>
<th
scope="col"
class="px-3 py-2 text-left text-xs font-medium text-gray-500 uppercase tracking-wider cursor-pointer"
@click="sortBy('avgWatchTime')"
>
<div class="flex items-center">
平均观看时长
<svg
v-if="sortKey === 'avgWatchTime'"
class="w-3 h-3 ml-1"
fill="none"
viewBox="0 0 24 24"
stroke="currentColor"
>
<path
stroke-linecap="round"
stroke-linejoin="round"
stroke-width="2"
:d="sortDirection === 'asc'
? 'M5 15l7-7 7 7'
: 'M19 9l-7 7-7-7'"
/>
</svg>
</div>
</th>
<th
scope="col"
class="px-3 py-2 text-left text-xs font-medium text-gray-500 uppercase tracking-wider cursor-pointer"
@click="sortBy('finishRate')"
>
<div class="flex items-center">
完播率
<svg
v-if="sortKey === 'finishRate'"
class="w-3 h-3 ml-1"
fill="none"
viewBox="0 0 24 24"
stroke="currentColor"
>
<path
stroke-linecap="round"
stroke-linejoin="round"
stroke-width="2"
:d="sortDirection === 'asc'
? 'M5 15l7-7 7 7'
: 'M19 9l-7 7-7-7'"
/>
</svg>
</div>
</th>
</tr>
</thead>
<tbody class="bg-white divide-y divide-gray-200">
<tr v-for="video in sortedVideos" :key="video.bvid" class="hover:bg-gray-50 transition-colors"
:class="{'bg-[#fb7299]/5 border-l-4 border-[#fb7299]': video.bvid === bvid}"
>
<td class="px-3 py-2 whitespace-nowrap">
<div class="flex items-center">
<div class="flex-shrink-0 h-10 w-16">
<img class="h-10 w-16 object-cover rounded shadow-sm" :src="normalizeImageUrl(video.cover)" alt="" />
</div>
<div class="ml-3 max-w-xs">
<div class="text-xs font-medium text-gray-900 truncate hover:text-[#fb7299]" :title="video.title">
<a :href="`https://www.bilibili.com/video/${video.bvid}`" target="_blank">{{ video.title }}</a>
</div>
<div class="text-xs text-gray-500">BV: {{ video.bvid }}</div>
</div>
</div>
</td>
<td class="px-3 py-2 whitespace-nowrap">
<div class="text-xs text-gray-900">{{ formatDuration(video.duration) }}</div>
</td>
<td class="px-3 py-2 whitespace-nowrap">
<div class="text-xs text-gray-900 font-medium">{{ formatNumber(video.vv) }}</div>
</td>
<td class="px-3 py-2 whitespace-nowrap">
<div class="text-xs font-medium text-[#fb7299]">{{ formatDurationHours(video.vt) }}</div>
<div class="text-xs text-gray-500">{{ formatDurationDays(video.vt) }}</div>
</td>
<td class="px-3 py-2 whitespace-nowrap">
<div class="text-xs text-gray-900">{{ formatDuration(Math.round((video.vt * 60) / video.vv)) }}</div>
</td>
<td class="px-3 py-2 whitespace-nowrap">
<div class="text-xs text-gray-900">{{ secondsToPercent(Math.round((video.vt * 60) / video.vv), video.duration) }}%</div>
<div class="w-full bg-gray-200 rounded-full h-1 mt-1">
<div class="bg-[#fb7299] h-1 rounded-full" :style="`width: ${Math.min(100, Math.round(((video.vt * 60) / video.vv) / video.duration * 100))}%`"></div>
</div>
</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
<!-- 如果不是合集视频 -->
<div v-else-if="videoStats.status === 'info'" class="p-5">
<div class="bg-blue-50 p-4 rounded-lg flex">
<svg class="w-5 h-5 text-blue-400 mr-3 flex-shrink-0" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
</svg>
<p class="text-sm text-blue-700">{{ videoStats.message }}</p>
</div>
</div>
<!-- 如果发生错误 -->
<div v-else-if="videoStats.status === 'error'" class="p-5">
<div class="bg-red-50 p-4 rounded-lg flex">
<svg class="w-5 h-5 text-red-400 mr-3 flex-shrink-0" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 8v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
</svg>
<p class="text-sm text-red-700">{{ videoStats.message }}</p>
</div>
</div>
</div>
<!-- 加载中状态 -->
<div v-if="loading && !videoStats" class="flex justify-center items-center py-16">
<div class="animate-spin h-10 w-10 border-4 border-[#fb7299] border-t-transparent rounded-full"></div>
<p class="ml-4 text-gray-600">正在获取视频数据...</p>
</div>
<!-- 空状态 -->
<div v-if="!loading && !videoStats" class="flex flex-col items-center justify-center py-16 px-6 text-center">
<svg class="w-16 h-16 text-gray-300" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="1" d="M15 10l4.553-2.276A1 1 0 0121 8.618v6.764a1 1 0 01-1.447.894L15 14M5 18h8a2 2 0 002-2V8a2 2 0 00-2-2H5a2 2 0 00-2 2v8a2 2 0 002 2z" />
</svg>
<p class="mt-4 text-gray-500">输入视频BV号后查询观看时长信息</p>
</div>
</div>
</div>
<!-- 视频下载 -->
<div v-if="activeTab === 'video-download'" class="animate-fadeIn">
<VideoDownloader />
</div>
<!-- 评论查询 -->
<div v-if="activeTab === 'comment-query'" class="animate-fadeIn">
<div class="bg-white p-6">
<!-- 用户ID输入区域 -->
<div class="mb-6 bg-transparent">
<h2 class="text-lg font-medium text-gray-900 mb-3">B站评论查询</h2>
<p class="text-sm text-gray-600 mb-4">
输入B站用户UID,查询该用户的全部评论记录。
</p>
<div class="flex space-x-3">
<div class="flex-1">
<div class="relative">
<input
v-model="queryUserId"
type="text"
placeholder="输入用户UID,例如:12345678"
class="w-full px-4 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-[#fb7299] focus:border-transparent pr-10"
@keyup.enter="fetchUserComments()"
/>
<div class="absolute inset-y-0 right-0 flex items-center pr-3">
<svg v-if="commentLoading" class="animate-spin h-5 w-5 text-[#fb7299]" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
<circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
<path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
</svg>
<button
v-else
@click="fetchUserComments()"
class="text-[#fb7299] hover:text-[#fb7299]/80 transition-colors"
>
<svg class="h-5 w-5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z" />
</svg>
</button>
</div>
</div>
</div>
</div>
</div>
<!-- 筛选区域 -->
<div v-if="comments.length > 0 || commentLoading" class="mb-6 bg-transparent">
<div class="mb-4">
<!-- 总评论数显示 -->
<div class="mb-3 flex items-center text-sm text-gray-600">
<span>共</span>
<span class="mx-1 text-[#fb7299] font-medium">{{ commentTotal }}</span>
<span>条评论</span>
</div>
<div class="flex flex-nowrap items-center space-x-2">
<!-- 关键词搜索 -->
<div class="flex-1 min-w-0">
<div class="relative">
<div class="flex h-9 items-center rounded-md border border-gray-300 bg-white focus-within:border-[#fb7299] transition-colors duration-200">
<!-- 搜索图标 -->
<div class="pl-3 text-gray-400">
<svg xmlns="http://www.w3.org/2000/svg" class="h-3.5 w-3.5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z" />
</svg>
</div>
<!-- 输入框 -->
<input
v-model="commentKeyword"
type="search"
placeholder="搜索评论内容..."
class="h-full w-full border-none bg-transparent px-2 pr-3 text-gray-700 focus:outline-none focus:ring-0 text-xs leading-none"
@keyup.enter="handleCommentSearch"
/>
</div>
</div>
</div>
<!-- 评论类型筛选 -->
<div class="w-24 flex-shrink-0">
<div class="relative">
<button
@click="toggleCommentTypeDropdown"
type="button"
class="w-full py-1.5 px-2 border border-gray-300 rounded-md text-xs text-gray-800 focus:border-[#fb7299] focus:outline-none focus:ring focus:ring-[#fb7299]/20 flex items-center justify-between bg-white transition-colors duration-200 h-9 whitespace-nowrap overflow-hidden"
>
<span class="truncate mr-1">{{ getCommentTypeText(commentType) }}</span>
<svg class="w-3 h-3 text-[#fb7299] flex-shrink-0" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 9l-7 7-7-7" />
</svg>
</button>
<!-- 评论类型下拉菜单 -->
<div
v-if="showCommentTypeDropdown"
class="absolute z-10 mt-1 w-full rounded-md bg-white shadow-lg ring-1 ring-black ring-opacity-5 focus:outline-none"
>
<div class="py-1">
<button
v-for="option in commentTypeOptions"
:key="option.value"
@click="selectCommentType(option.value)"
class="w-full px-2 py-1 text-xs text-left hover:bg-[#fb7299]/5 hover:text-[#fb7299] transition-colors flex items-center whitespace-nowrap"
:class="{'text-[#fb7299] bg-[#fb7299]/5 font-medium': commentType === option.value}"
>
{{ option.label }}
</button>
</div>
</div>
</div>
</div>
<!-- 内容类型筛选 -->
<div class="w-24 flex-shrink-0">
<div class="relative">
<button
@click="toggleContentTypeDropdown"
type="button"
class="w-full py-1.5 px-2 border border-gray-300 rounded-md text-xs text-gray-800 focus:border-[#fb7299] focus:outline-none focus:ring focus:ring-[#fb7299]/20 flex items-center justify-between bg-white transition-colors duration-200 h-9 whitespace-nowrap overflow-hidden"
>
<span class="truncate mr-1">{{ getContentTypeText(contentTypeFilter) }}</span>
<svg class="w-3 h-3 text-[#fb7299] flex-shrink-0" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 9l-7 7-7-7" />
</svg>
</button>
<!-- 内容类型下拉菜单 -->
<div
v-if="showContentTypeDropdown"
class="absolute z-10 mt-1 w-full rounded-md bg-white shadow-lg ring-1 ring-black ring-opacity-5 focus:outline-none"
>
<div class="py-1">
<button
v-for="option in contentTypeOptions"
:key="option.value"
@click="selectContentType(option.value)"
class="w-full px-2 py-1 text-xs text-left hover:bg-[#fb7299]/5 hover:text-[#fb7299] transition-colors flex items-center whitespace-nowrap"
:class="{'text-[#fb7299] bg-[#fb7299]/5 font-medium': contentTypeFilter === option.value}"
>
{{ option.label }}
</button>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<!-- 评论列表 -->
<div class="bg-white rounded-lg border border-gray-200 overflow-hidden">
<!-- 评论项 -->
<div v-if="!commentLoading && comments.length > 0" class="divide-y divide-gray-100">
<div v-for="comment in comments" :key="comment.rpid" class="p-4 md:p-6">
<div class="space-y-2">
<!-- 评论内容 -->
<p class="text-gray-800 text-sm md:text-base whitespace-pre-wrap leading-relaxed">{{ comment.message }}</p>
<!-- 评论元数据 -->
<div class="flex items-center justify-between text-xs text-gray-500">
<div class="flex items-center space-x-3">
<span :class="comment.type === 1 ? 'text-[#fb7299]' : 'text-[#fb7299]'">
{{ getCommentTypeDisplay(comment.type) }}
</span>
<span>{{ comment.time_str }}</span>
</div>
<a
:href="getCommentLink(comment)"
target="_blank"
class="text-[#fb7299] hover:text-[#fb7299]/80 transition-colors"
>
查看原文 →
</a>
</div>
</div>
</div>
</div>
<!-- 加载状态 -->
<div v-if="commentLoading" class="flex justify-center items-center py-16">
<div class="flex flex-col items-center">
<div class="animate-spin h-8 w-8 border-3 border-[#fb7299] border-t-transparent rounded-full"></div>
<p class="text-gray-500 text-sm mt-4">加载评论中...</p>
</div>
</div>
<!-- 空状态 -->
<div v-if="!commentLoading && comments.length === 0" class="flex justify-center items-center py-16">
<div class="flex flex-col items-center">
<div class="bg-[#fb7299]/5 rounded-full p-3 mb-3">
<svg class="w-8 h-8 text-[#fb7299]" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.5" d="M8 10h.01M12 10h.01M16 10h.01M9 16H5a2 2 0 01-2-2V6a2 2 0 012-2h14a2 2 0 012 2v8a2 2 0 01-2 2h-5l-5 5v-5z" />
</svg>
</div>
<p class="text-gray-600 font-medium">暂无评论数据</p>
<p v-if="hasActiveCommentFilters" class="text-gray-500 text-sm mt-1 text-center max-w-sm">
尝试调整搜索条件
</p>
<button
v-if="hasActiveCommentFilters"
@click="clearCommentFilters"
class="mt-4 px-4 py-2 text-white bg-[#fb7299] hover:bg-[#fb7299]/90 rounded-md text-sm transition-colors"
>
清除筛选
</button>
</div>
</div>
</div>
<!-- 分页控件 -->
<div v-if="commentTotalPages > 0" class="mt-6 flex justify-center">
<div class="mx-auto mb-5 mt-8 max-w-4xl lm:text-xs">
<div class="flex justify-between items-center space-x-4 lm:mx-5">
<button
@click="handleCommentPageChange(commentCurrentPage - 1)"
:disabled="commentCurrentPage === 1"
class="flex items-center text-gray-500 hover:text-[#fb7299] disabled:opacity-40 disabled:cursor-not-allowed transition-colors px-3 py-2"
>
<svg class="w-5 h-5 mr-1" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 19l-7-7 7-7" />
</svg>
<span class="hidden sm:inline">上一页</span>
</button>
<div class="flex items-center text-gray-700 lm:text-xs">
<div class="relative mx-1 inline-block">
<input
type="number"
v-model="commentPageInput"
@keyup.enter="handleCommentJumpPage"
@blur="handleCommentJumpPage"
@focus="$event.target.select()"
min="1"
:max="commentTotalPages"
class="h-8 w-12 rounded border border-gray-200 px-2 text-center text-gray-700 transition-colors [appearance:textfield] hover:border-[#fb7299] focus:border-[#fb7299] focus:outline-none focus:ring-1 focus:ring-[#fb7299]/30 lm:h-6 lm:w-10 lm:text-xs [&::-webkit-inner-spin-button]:appearance-none [&::-webkit-outer-spin-button]:appearance-none"
/>
</div>
<span class="text-gray-500 mx-1">/ {{ commentTotalPages }}</span>
</div>
<button
@click="handleCommentPageChange(commentCurrentPage + 1)"
:disabled="commentCurrentPage === commentTotalPages"
class="flex items-center text-gray-500 hover:text-[#fb7299] disabled:opacity-40 disabled:cursor-not-allowed transition-colors px-3 py-2"
>
<span class="hidden sm:inline">下一页</span>
<svg class="w-5 h-5 ml-1" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 5l7 7-7 7" />
</svg>
</button>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</template>
<script setup>
import { ref, onMounted, watch, computed } from 'vue'
import { useRoute } from 'vue-router'
import VideoDownloader from './VideoDownloader.vue'
import { showNotify } from 'vant'
import 'vant/es/notify/style'
import { getVideoSeasonInfo, getComments } from '../../../api/api'
import { normalizeImageUrl } from '@/utils/imageUrl.js'
const route = useRoute()
// 当前激活的标签
const activeTab = ref('video-stats')
// 监听路由变化以更新激活的标签
watch(
() => route.query.tab,
(tab) => {
if (tab && ['video-stats', 'video-download', 'comment-query'].includes(tab)) {
activeTab.value = tab
}
},
{ immediate: true }
)
// 组件挂载时根据URL初始化标签
onMounted(() => {
const { tab } = route.query
if (tab && ['video-stats', 'video-download', 'comment-query'].includes(tab)) {
activeTab.value = tab
}
})
// 视频观看时长数据
const bvid = ref('')
const videoStats = ref(null)
const loading = ref(false)
const useSessdata = ref(true)
// 排序状态
const sortKey = ref('vt') // 默认按总观看时长排序
const sortDirection = ref('desc') // 默认降序
// 查询的视频信息
const queriedVideo = computed(() => {
if (!videoStats.value || !videoStats.value.videos || !bvid.value) return null
return videoStats.value.videos.find(v => v.bvid.toLowerCase() === bvid.value.toLowerCase())
})
// 计算合集总观看时长
const totalWatchTime = computed(() => {
if (!videoStats.value || !videoStats.value.videos) return 0
return videoStats.value.videos.reduce((total, video) => total + video.vt, 0)
})
// 排序后的视频列表
const sortedVideos = computed(() => {
if (!videoStats.value || !videoStats.value.videos) return []
const videos = [...videoStats.value.videos]
return videos.sort((a, b) => {
let aValue, bValue
if (sortKey.value === 'avgWatchTime') {
aValue = a.vt / a.vv
bValue = b.vt / b.vv
} else if (sortKey.value === 'finishRate') {
// 计算完播率:平均观看时长(秒) / 视频时长(秒) * 100
aValue = Math.min(100, Math.round(((a.vt * 60) / a.vv) / a.duration * 100))
bValue = Math.min(100, Math.round(((b.vt * 60) / b.vv) / b.duration * 100))
} else {
aValue = a[sortKey.value]
bValue = b[sortKey.value]
}
if (sortDirection.value === 'asc') {
return aValue - bValue
} else {
return bValue - aValue
}
})
})
// 切换排序
const sortBy = (key) => {
if (sortKey.value === key) {
// 如果已经是按这个键排序,则切换方向
sortDirection.value = sortDirection.value === 'asc' ? 'desc' : 'asc'
} else {
// 否则切换排序字段,默认降序
sortKey.value = key
sortDirection.value = 'desc'
}
}
// 防抖函数
let timeout = null
const debouncedFetchVideoStats = () => {
clearTimeout(timeout)
timeout = setTimeout(() => {
if (bvid.value.trim().length >= 10) { // BV号至少10个字符
fetchVideoStats()
}
}, 800) // 800ms延迟
}
// 获取视频观看时长信息
const fetchVideoStats = async () => {
if (!bvid.value || bvid.value.trim().length < 10) {
return
}
loading.value = true
videoStats.value = null
try {
// 使用api.js中定义的方法
const response = await getVideoSeasonInfo({
bvid: bvid.value.trim(),
use_sessdata: useSessdata.value
})
videoStats.value = response.data
// 初始设置合适的排序
if (videoStats.value && videoStats.value.status === 'success') {
sortKey.value = 'vt'
sortDirection.value = 'desc'
}
} catch (error) {
console.error('获取视频观看时长信息失败:', error)
videoStats.value = {
status: 'error',
message: error.response?.data?.message || '获取视频信息失败,请检查网络连接或稍后重试'
}
} finally {
loading.value = false
}
}
// 格式化数字
const formatNumber = (num) => {
return new Intl.NumberFormat('zh-CN').format(num)
}
// 格式化时长 (分钟 -> mm:ss)
const formatDuration = (minutes) => {
// 视频时长仍然是秒级的,所以保持不变
const mins = Math.floor(minutes / 60)
const remainingSeconds = minutes % 60
return `${mins}:${remainingSeconds.toString().padStart(2, '0')}`
}
// 格式化时长 (分钟 -> 小时)
const formatDurationHours = (minutes) => {
// 后端返回的是分钟级别的数据
const hours = Math.floor(minutes / 60)
const remainingMinutes = minutes % 60
return `${hours} 小时 ${remainingMinutes} 分钟`
}
// 格式化时长 (分钟 -> 天/月/年)
const formatDurationDays = (minutes) => {
const days = Math.floor(minutes / (60 * 24)) // 一天有 24*60 分钟
if (days >= 365) {
// 超过365天显示为年
const years = Math.floor(days / 365)
const remainingDays = days % 365
if (remainingDays > 30) {
const months = Math.floor(remainingDays / 30)
return `约 ${years} 年 ${months} 个月`
} else {
return `约 ${years} 年 ${remainingDays} 天`
}
} else if (days >= 30) {
// 超过30天显示为月
const months = Math.floor(days / 30)
const remainingDays = days % 30
return `约 ${months} 个月 ${remainingDays} 天`
} else if (days > 0) {
// 显示为天和小时
const hours = Math.floor((minutes % (60 * 24)) / 60)
return `约 ${days} 天 ${hours} 小时`
}
return '' // 如果不足1天,不显示
}
// 计算完播率百分比
const secondsToPercent = (watchedSeconds, totalSeconds) => {
if (!totalSeconds) return 0
// watchedSeconds 是从分钟转换为秒的平均观看时长
// totalSeconds 是视频总时长(秒)
return Math.min(100, Math.round((watchedSeconds / totalSeconds) * 100))
}
// ===== 评论查询功能 =====
// 评论查询数据
const queryUserId = ref('')
const comments = ref([])
const commentLoading = ref(false)
const commentCurrentPage = ref(1)
const commentPageSize = ref(20)
const commentTotal = ref(0)
const commentTotalPages = ref(0)
const commentKeyword = ref('')
const commentType = ref('all')
const contentTypeFilter = ref('0')
const commentPageInput = ref('1')
// 下拉菜单状态
const showCommentTypeDropdown = ref(false)
const showContentTypeDropdown = ref(false)
// 下拉菜单选项数据
const commentTypeOptions = [
{ value: 'all', label: '全部' },
{ value: 'root', label: '一级' },
{ value: 'reply', label: '二级' }
]
const contentTypeOptions = [
{ value: '0', label: '全部' },
{ value: '1', label: '视频' },
{ value: '17', label: '动态' },
{ value: '11', label: '旧动态' }
]
// 是否有活跃的评论筛选条件
const hasActiveCommentFilters = computed(() => {
return commentKeyword.value !== '' || commentType.value !== 'all' || contentTypeFilter.value !== '0'
})
// 获取评论类型显示文本
const getCommentTypeText = (type) => {
const option = commentTypeOptions.find(opt => opt.value === type)
return option ? option.label : '全部'
}
// 获取内容类型显示文本
const getContentTypeText = (type) => {
const option = contentTypeOptions.find(opt => opt.value === type)
return option ? option.label : '全部'
}
// 获取评论类型显示文本(单个评论)
const getCommentTypeDisplay = (type) => {
switch (type) {
case 1:
return '视频评论'
case 11:
case 17:
return '动态评论'
default:
return '其他评论'
}
}
// 获取评论链接
const getCommentLink = (comment) => {
const { type, oid, rpid } = comment
switch (type) {
case 1: // 视频评论
return `https://www.bilibili.com/video/av${oid}#reply${rpid}`
case 11: // 动态评论类型11
return `https://t.bilibili.com/${oid}?type=2#reply${rpid}`
case 17: // 动态评论类型17
return `https://t.bilibili.com/${oid}#reply${rpid}`
default:
return '#'
}
}
// 切换评论类型下拉菜单
const toggleCommentTypeDropdown = () => {
showCommentTypeDropdown.value = !showCommentTypeDropdown.value
showContentTypeDropdown.value = false
}
// 切换内容类型下拉菜单
const toggleContentTypeDropdown = () => {
showContentTypeDropdown.value = !showContentTypeDropdown.value
showCommentTypeDropdown.value = false
}
// 选择评论类型
const selectCommentType = (value) => {
commentType.value = value
showCommentTypeDropdown.value = false
commentCurrentPage.value = 1
fetchUserComments()
}
// 选择内容类型
const selectContentType = (value) => {
contentTypeFilter.value = value
showContentTypeDropdown.value = false
commentCurrentPage.value = 1
fetchUserComments()
}
// 获取用户评论列表
const fetchUserComments = async () => {
if (!queryUserId.value) {
showNotify({
type: 'warning',
message: '请输入用户UID'
})
return
}
commentLoading.value = true
try {
const response = await getComments(
queryUserId.value,
commentCurrentPage.value,
commentPageSize.value,
commentType.value,
commentKeyword.value,
contentTypeFilter.value
)
if (response.data) {
comments.value = response.data.comments || []
commentTotal.value = response.data.total || 0
commentTotalPages.value = response.data.total_pages || 0
commentPageInput.value = commentCurrentPage.value.toString()
}
} catch (error) {
console.error('获取评论列表失败:', error)
showNotify({
type: 'danger',
message: error.response?.data?.message || '获取评论列表失败'
})
comments.value = []
commentTotal.value = 0
commentTotalPages.value = 0
} finally {
commentLoading.value = false
}
}
// 处理评论搜索
const handleCommentSearch = () => {
commentCurrentPage.value = 1
fetchUserComments()
}
// 处理评论页码变化
const handleCommentPageChange = (newPage) => {
if (newPage >= 1 && newPage <= commentTotalPages.value) {
commentCurrentPage.value = newPage
fetchUserComments()
}
}
// 处理评论跳转页
const handleCommentJumpPage = () => {
const targetPage = parseInt(commentPageInput.value)
if (!isNaN(targetPage) && targetPage >= 1 && targetPage <= commentTotalPages.value) {
if (targetPage !== commentCurrentPage.value) {
commentCurrentPage.value = targetPage
fetchUserComments()
}
} else {
commentPageInput.value = commentCurrentPage.value.toString()
}
}
// 清除评论筛选条件
const clearCommentFilters = () => {
commentKeyword.value = ''
commentType.value = 'all'
contentTypeFilter.value = '0'
commentCurrentPage.value = 1
fetchUserComments()
}
</script>
<style scoped>
.animate-fadeIn {
animation: fadeIn 0.3s ease-in-out;
}
@keyframes fadeIn {
from { opacity: 0; }
to { opacity: 1; }
}
</style>
|
2977094657/BiliHistoryFrontend
| 6,342
|
src/components/tailwind/page/History.vue
|
<template>
<!-- 主要内容区域 -->
<div>
<!-- 导航栏 -->
<Navbar
v-if="currentContent === 'history' && !showRemarks"
@refresh-data="refreshData"
v-model:date="date"
v-model:category="category"
v-model:business="business"
v-model:businessLabel="businessLabel"
v-model:pageSize="pageSize"
:total="total"
@click-date="show = true"
:layout="layout"
@change-layout="layout = $event"
:is-batch-mode="isBatchMode"
:show-remarks="showRemarks"
@toggle-batch-mode="isBatchMode = !isBatchMode"
@toggle-remarks="showRemarks = !showRemarks"
/>
<!-- 内容区域 -->
<div>
<div class="mx-auto max-w-7xl sm:px-2 lg:px-8">
<div class="">
<!-- 历史记录内容 -->
<HistoryContent
v-if="currentContent === 'history' && !showRemarks"
ref="historyContentRef"
:selected-year="selectedYear"
:page="page"
:pageSize="pageSize"
@update:total-pages="totalPages = $event"
@update:total="total = $event"
@update:date="date = $event"
@update:category="category = $event"
v-model:show="show"
v-model:showBottom="showBottom"
:layout="layout"
:date="date"
:category="category"
:business="business"
:is-batch-mode="isBatchMode"
/>
<!-- 备注列表内容 -->
<Remarks v-else-if="showRemarks" />
<!-- 设置内容 -->
<Settings v-else-if="currentContent === 'settings'" />
</div>
<!-- 分页组件 -->
<div v-if="currentContent === 'history' && !showRemarks && total > 0" class="mx-auto mb-5 mt-8 max-w-4xl">
<Pagination :current-page="page" :total-pages="totalPages" :use-routing="true" />
</div>
</div>
</div>
</div>
</template>
<script setup>
import { ref, onMounted, watch, onUnmounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import Navbar from '../Navbar.vue'
import HistoryContent from '../HistoryContent.vue'
import Pagination from '../Pagination.vue'
import Settings from '../Settings.vue'
import Remarks from './Remarks.vue'
// 定义 props
const props = defineProps({
defaultShowRemarks: {
type: Boolean,
default: false
}
})
// 当前显示的内容
const currentContent = ref('history')
// 路由对象
const router = useRouter()
const route = useRoute()
// 状态
const page = ref(parseInt(route.params.pageNumber) || 1)
const totalPages = ref(1)
const selectedYear = ref(new Date().getFullYear())
const show = ref(false)
const showBottom = ref(false)
const date = ref('')
const total = ref(0)
const category = ref('')
const layout = ref(localStorage.getItem('defaultLayout') || 'grid')
const isBatchMode = ref(false)
const showRemarks = ref(props.defaultShowRemarks)
const business = ref('')
const businessLabel = ref('')
const pageSize = ref(parseInt(localStorage.getItem('pageSize')) || 30)
// 组件引用
const historyContentRef = ref(null)
// 刷新数据方法
const refreshData = async () => {
console.log('History - refreshData 被调用')
console.log('当前日期:', date.value)
console.log('当前分区:', category.value)
console.log('当前业务类型:', business.value)
try {
if (historyContentRef.value && typeof historyContentRef.value.refreshData === 'function') {
await historyContentRef.value.refreshData()
} else if (historyContentRef.value && typeof historyContentRef.value.fetchHistoryByDateRange === 'function') {
await historyContentRef.value.fetchHistoryByDateRange()
} else {
console.error('刷新数据失败: HistoryContent 组件的 refreshData 方法不可用')
}
} catch (error) {
console.error('刷新数据失败:', error)
}
}
// 监听 date 和 category 的变化
watch([date, category], ([newDate, newCategory], [oldDate, oldCategory]) => {
console.log('History - date/category 变化:', {
date: { old: oldDate, new: newDate },
category: { old: oldCategory, new: newCategory }
})
})
// 监听路由变化
watch(
() => route.path,
(path) => {
if (path === '/settings') {
currentContent.value = 'settings'
showRemarks.value = false
} else if (path === '/remarks') {
currentContent.value = 'history'
showRemarks.value = true
} else if (path === '/' || path.startsWith('/page/')) {
currentContent.value = 'history'
showRemarks.value = false
}
},
{ immediate: true }
)
// 组件挂载时设置初始状态
onMounted(() => {
// 设置初始的备注显示状态
if (props.defaultShowRemarks || route.path === '/remarks') {
showRemarks.value = true
}
// 确保路由参数是单个字符串并进行类型转换
const pageParam = Array.isArray(route.params.pageNumber)
? route.params.pageNumber[0]
: route.params.pageNumber
page.value = parseInt(pageParam) || 1
if (page.value !== 1 && !route.path.startsWith('/remarks')) {
router.push(`/page/${page.value}`)
}
// 监听布局设置变更事件
window.addEventListener('layout-setting-changed', handleLayoutSettingChanged)
})
// 组件卸载时清理事件监听器
onUnmounted(() => {
window.removeEventListener('layout-setting-changed', handleLayoutSettingChanged)
})
// 处理布局设置变更事件 - 从设置页面接收
const handleLayoutSettingChanged = (event) => {
if (event.detail && typeof event.detail.layout === 'string') {
layout.value = event.detail.layout
}
}
// 监听布局变化,同步到localStorage并触发全局事件
watch(layout, (newLayout) => {
// 保存到localStorage
localStorage.setItem('defaultLayout', newLayout)
// 触发全局事件通知设置页面
try {
const event = new CustomEvent('layout-changed', {
detail: { layout: newLayout }
})
window.dispatchEvent(event)
} catch (error) {
console.error('触发布局变更事件失败:', error)
}
})
// 修改路由参数监听部分
watch(
[() => route.params.pageNumber, () => route.path],
([newPage, path], [oldPage, oldPath]) => {
if (newPage === oldPage && path === oldPath) return
if (path === '/') {
if (page.value !== 1) {
page.value = 1
}
} else if (newPage) {
// 确保 newPage 是单个字符串
const pageStr = Array.isArray(newPage) ? newPage[0] : newPage
const pageNum = parseInt(pageStr)
if (page.value !== pageNum) {
page.value = pageNum
}
}
},
{ immediate: true }
)
</script>
<style scoped>
@keyframes bounce-x {
0%, 100% {
transform: translateX(0);
}
50% {
transform: translateX(4px);
}
}
.animate-bounce-x {
animation: bounce-x 1.5s infinite;
}
</style>
|
281677160/openwrt-package
| 3,337
|
luci-app-passwall2/luasrc/view/passwall2/rule/geoview.htm
|
<%
local api = require "luci.passwall2.api"
-%>
<style>
.faq-title {
color: var(--primary);
font-weight: bolder;
margin-bottom: 0.5rem;
display: inline-block;
}
.faq-item {
margin-bottom: 0.8rem;
line-height:1.2rem;
}
</style>
<div class="cbi-value">
<ul>
<b class="faq-title"><%:Tips:%></b>
<li class="faq-item">1. <span><%:By entering a domain or IP, you can query the Geo rule list they belong to.%></span></li>
<li class="faq-item">2. <span><%:By entering a GeoIP or Geosite, you can extract the domains/IPs they contain.%></span></li>
<li class="faq-item">3. <span><%:Use the GeoIP/Geosite query function to verify if the entered Geo rules are correct.%></span></li>
</ul>
</div>
<div class="cbi-value" id="cbi-geoview-lookup"><label class="cbi-value-title" for="geoview.lookup"><%:Domain/IP Query%></label>
<div class="cbi-value-field">
<input type="text" class="cbi-textfield" id="geoview.lookup" name="geoview.lookup" />
<input class="btn cbi-button cbi-button-apply" type="button" id="lookup-view_btn"
onclick='do_geoview(this, "lookup", document.getElementById("geoview.lookup").value)'
value="<%:Query%>" />
<br />
<div class="cbi-value-description">
<%:Enter a domain or IP to query the Geo rule list they belong to.%>
</div>
</div>
</div>
<div class="cbi-value" id="cbi-geoview-extract"><label class="cbi-value-title" for="geoview.extract"><%:GeoIP/Geosite Query%></label>
<div class="cbi-value-field">
<input type="text" class="cbi-textfield" id="geoview.extract" name="geoview.extract" />
<input class="btn cbi-button cbi-button-apply" type="button" id="extract-view_btn"
onclick='do_geoview(this, "extract", document.getElementById("geoview.extract").value)'
value="<%:Query%>" />
<br />
<div class="cbi-value-description">
<%:Enter a GeoIP or Geosite to extract the domains/IPs they contain. Format: geoip:cn or geosite:gfw%>
</div>
</div>
</div>
<div class="cbi-value">
<textarea id="geoview_textarea" class="cbi-input-textarea" style="width: 100%; margin-top: 10px;" rows="25" wrap="off" readonly="readonly"></textarea>
</div>
<script type="text/javascript">
//<![CDATA[
var lookup_btn = document.getElementById("lookup-view_btn");
var extract_btn = document.getElementById("extract-view_btn");
var QueryText = '<%:Query%>';
var QueryingText = '<%:Querying%>';
function do_geoview(btn,action,value) {
value = value.trim();
if (!value) {
alert("<%:Please enter query content!%>");
return;
}
lookup_btn.disabled = true;
extract_btn.disabled = true;
btn.value = QueryingText;
var textarea = document.getElementById('geoview_textarea');
textarea.textContent = "";
fetch('<%= api.url("geo_view") %>?action=' + action + '&value=' + encodeURIComponent(value))
.then(response => response.text())
.then(data => {
textarea.textContent = data;
lookup_btn.disabled = false;
extract_btn.disabled = false;
btn.value = QueryText;
})
}
document.getElementById("geoview.lookup").addEventListener("keydown", function(event) {
if (event.key === "Enter") {
event.preventDefault();
lookup_btn.click();
}
});
document.getElementById("geoview.extract").addEventListener("keydown", function(event) {
if (event.key === "Enter") {
event.preventDefault();
extract_btn.click();
}
});
//]]>
</script>
|
294coder/Efficient-MIF
| 3,465
|
Pansharpening_Hyper_SR_Matlab_Test_Package/PWMBF/PWMBF.m
|
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Description:
% Model-based fusion using PCA and wavelets.
%
% Interface:
% Z = PWMBF(Pan,Low,ratio,r,wavelet,degrade,reduced,whiten)
%
% Inputs:
% Pan : Panchromatic image;
% Low: Low spatial resolution MS image;
% ratio: Scale ratio between Pan and Low;
% r: Number of principal components;
% wavelet: flag;
% degrade: flag.
%
% Output:
% Z: Pansharpened image;
%
% References:
% [Palsson15] F. Palsson, J.R. Sveinsson, M.O. Ulfarsson, J.A. Benediktsson, "Model-based fusion of multi-and hyperspectral images using PCA and wavelets",
% IEEE Transactions on Geoscience and Remote Sensing, vol. 53, no. 5, pp. 2652-2663, May 2015.
% [Vivone20] G. Vivone, M. Dalla Mura, A. Garzelli, R. Restaino, G. Scarpa, M.O. Ulfarsson, L. Alparone, and J. Chanussot, "A New Benchmark Based on Recent Advances in Multispectral Pansharpening: Revisiting pansharpening with classical and emerging pansharpening methods",
% IEEE Geoscience and Remote Sensing Magazine, doi: 10.1109/MGRS.2020.3019315.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function Z = PWMBF(Pan,Low,ratio,r,wavelet,degrade)
addpath(sprintf('%s/rwt/bin',pwd))
% Wavelet parameters
L=4;
type='rwt';
Low=double(Low);
Pan=double(Pan);
N=size(Pan,1);
Q=size(Pan,3);
nb=size(Low,3);
if(r>nb)
error('Number of PCs greater than number of bands');
end
X=Pan;
Ylow=Low;
if(degrade)
X=imresize(Pan,1/ratio);
Ylow=imresize(Low,1/ratio);
N=N/4;
end
% Upsample Y
Y=imresize(Ylow,ratio,'bicubic');
% Degrade X
Xtilde=imresize(imresize(X,1/ratio,'bilinear'),ratio,'bicubic');
X=reshape(X,[N^2 Q]);
Xtilde=reshape(Xtilde,[N^2 Q]);
Y=reshape(Y,[N^2 nb]);
% PCA transform
[F, D, R]=svd(Y,'econ');
G=F*D;
U=R;
wfilter=daubcqf(4,'min');
if wavelet
x=compute_PhiTX(Xtilde,L,wfilter,type);
x0=compute_PhiTX(X,L,wfilter,type);
y=compute_PhiTX(G(:,1:r),L,wfilter,type);
yl=y(1:N^2,:);
zh=zeros(3*L*N^2,r);
for p=1:r
for j=1:3*L
xh=x(j*N^2+1:(j+1)*N^2,:);
xh0=x0(j*N^2+1:(j+1)*N^2,:);
yh=y(j*N^2+1:(j+1)*N^2,p);
Cyy=yh'*yh/N^2;
Cyx=yh'*xh/N^2;
Cxx=xh'*xh/N^2;
Cn=diag(mad(abs(yh))/0.6745).^2;
inv_Cxx=inv(Cxx);
Cy_x=Cyy-Cyx*inv_Cxx*Cyx';
if Q>1
CyxiCxx=Cyx*inv_Cxx;
mu_zx=xh*CyxiCxx';
mu_zx0=xh0*CyxiCxx';
else
mu_zx=repmat((Cyx*inv_Cxx)',[N^2 1]).*xh;
mu_zx0=repmat((Cyx*inv_Cxx)',[N^2 1]).*xh0;
end
ymu=yh-mu_zx;
CC=Cy_x*inv(Cy_x+Cn);
zh((j-1)*N^2+1:N^2+(j-1)*N^2,p)=mu_zx0+ymu*CC;
end
end
z=[yl;zh];
B=compute_PhiX(z,L,wfilter,type);
deg=0;
if deg == 1
U = U(:,1:r);
Zhat=B*U';
else
G(:,1:r)=B;
Zhat=G*U';
end
else
Cn=0;
yh=G(:,1:r);
xh=Xtilde;
xh0=X;
Cyy=yh'*yh/N^2;
Cyx=yh'*xh/N^2;
Cxx=xh'*xh/N^2;
inv_Cxx=inv(Cxx);
Cy_x=Cyy-Cyx*inv_Cxx*Cyx';
CyxiCxx=Cyx*inv_Cxx;
mu_zx=xh*CyxiCxx';
mu_zx0=xh0*CyxiCxx';
ymu=yh-mu_zx;
CC=Cy_x/(Cy_x+Cn);
B=mu_zx0+ymu*CC;
G(:,1:r)=B;
Zhat=G*U';
end
Z=reshape(Zhat,[N N nb]);
end
|
294coder/Efficient-MIF
| 14,464
|
Pansharpening_Hyper_SR_Matlab_Test_Package/RR/RRpansharp.m
|
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Description:
% This method performs pansharpening. We assume that
% the noisy satellite images yi, i=1,...,L, where y1 is the PAN image
% and yi, i=2,...,L are the observed MS images, are related to the full
% resolution target images by
%
% yi = Mi*Bi*xi + ni, i=1,...,L
%
% where Mi is a downsampling operator, Bi is a circulant blurring matrix,
% and ni is noise. The method solves
% min (1/2) sum_{i=1}^L || y_i - Mi*Bi*G*fi ||^2 + lambda * phi(G)
% F, G
% where phi is a regularizer function.
% The function returns Xhat=G*F'. See [1] and [2] for details.
%
% Interface:
% Xhat_im = RRpansharp(Yim,varargin)
%
% Inputs:
% Yim : 1xL cell array containing the observed images the first image
% is the PAN image and the last L-1 images are the MS images;
% CDiter: Number of cyclic descent iterations.
% CDiter=100 is the default;
% r: The subspace dimension;
% lambda: The regularization parameter, lambda=0.005 is the
% default;
% q: penalty weights;
% X0: Initial value for X = G * F'.
%
% Outputs:
% Xhat_im: estimated image (3D) at high resolution for each
% spectral channel.
%
% References:
% [Ulfarsson19] M.O. Ulfarsson, F. Palsson, M.Dalla Mura, J.R. Sveinsson, "Sentinel-2 Sharpening using a Reduced-Rank Method",
% IEEE Transactions on Geoscience and Remote Sensing, vol. 57, no. 9, pp. 6408-6420, 2019.
% [Palsson19] F. Palsson, MO. Ulfarsson, and JR. Sveinsson, "Model-Based Reduced-Rank Pansharpening",
% IEEE Geoscience and Remote Sensing Letters, 2019
% [Vivone20] G. Vivone, M. Dalla Mura, A. Garzelli, R. Restaino, G. Scarpa, M.O. Ulfarsson, L. Alparone, and J. Chanussot, "A New Benchmark Based on Recent Advances in Multispectral Pansharpening: Revisiting pansharpening with classical and emerging pansharpening methods",
% IEEE Geoscience and Remote Sensing Magazine, doi: 10.1109/MGRS.2020.3019315.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function Xhat_im = RRpansharp(Yim,varargin)
% import the manopt optimizer
addpath('./manopt')
p1=pwd;
cd('./manopt');
importmanopt
cd(p1)
% initialization
CDiter=10;
r=7;
lambda=0.005;
X0 = '';
tolgradnorm = 0.1;
if(r==7)
q = [1, 1.5, 4, 8, 15, 15, 20 ]';
else
q = ones(r,1);
end
Gstep_only=0;
GCV = 0;
for i=1:2:(length(varargin)-1)
switch varargin{i}
case 'CDiter'
CDiter=varargin{i+1};
case 'r'
r=varargin{i+1};
case 'lambda'
lambda=varargin{i+1};
case 'q'
q=varargin{i+1};
case 'X0'
X0 = varargin{i+1};
case 'tolgradnorm'
tolgradnorm = varargin{i+1};
case 'Gstep_only'
Gstep_only = varargin{i+1};
case 'GCV'
GCV = varargin{i+1};
case 'd'
d = varargin{i+1};
case 'mtf'
mtf = varargin{i+1};
end
end
tic;
if(length(q)~=r), error('The length of q has to match r'); end
% dimensions of the inputs
L=length(Yim);
for i=1:L, Yim{i}=double(Yim{i}); end
[nl,nc] = size(Yim{1});
n = nl*nc;
[Yim2, av] = normaliseData(Yim);
% Sequence of bands
% [B1 B2 B3 B4 B5 B6 B7 B8 B8A B9 B11 B12]
% subsampling factors (in pixels)
%d = [6 1 1 1 2 2 2 1 2 6 2 2]';
% convolution operators (Gaussian convolution filters), taken from ref [5]
%mtf = [ .32 .26 .28 .24 .38 .34 .34 .26 .33 .26 .22 .23];
sdf = d.*sqrt(-2*log(mtf)/pi^2)';
% Do not sharpen high-res bands
sdf(d==1) = 0;
% remove border for computing the subspace and the result (because of
% circular assumption
limsub = 2;
% kernel filter support
dx = 12;
dy = 12;
% Define blurring operators
FBM = createConvKernel(sdf,d,nl,nc,L,dx,dy);
% IMPORTANT!!!
% Note that the blur kernels are shifted to accomodate the co-registration
% of real images with different resolutions.
[Y,M,F]=initialization(Yim2,sdf,nl,nc,L,dx,dy,d,limsub,r);
Mask=reshape(M,[n,L])';
% CD
if isempty(X0)
Z = zeros(r,n);
else
[X0, ~] = normaliseData(X0);
X0 = reshape(X0,[n,L])';
[F,D,V]=svd(X0,'econ');
F = F(:,1:r);
Z = D(1:r,1:r)*V(:,1:r)';
end
% Operators for differences
[FDH,FDV,FDHC,FDVC] = createDiffkernels(nl,nc,r);
% Compute weights
sigmas = 1;
W = computeWeights(Y,d,sigmas,nl);
Whalf=W.^(1/2);
if( GCV == 1), Gstep_only=1; end
if( Gstep_only ~= 0), CDiter=1; end
for jCD=1:CDiter
[Z,Jcost(jCD),options]=Zstep(Y,FBM,F,lambda,nl,nc,Z,Mask,q,FDH,FDV,FDHC,FDVC,W,Whalf,tolgradnorm);
if(Gstep_only==0)
F1=Fstep(F,Z,Y,FBM,nl,nc,Mask);
F=F1;
end
if( GCV==1 )
Ynoise = ( abs(Y) > 0 ) .* randn( size(Y) );
[Znoise]=Zstep(Ynoise,FBM,F,lambda,nl,nc,Z,Mask,q,FDH,FDV,FDHC,FDVC,W,Whalf,tolgradnorm);
HtHBXnoise = Mask.*ConvCM(F*Znoise,FBM,nl);
Ynoise = Ynoise([2:end],:);
HtHBXnoise = HtHBXnoise([2:end],:);
den = trace(Ynoise*(Ynoise - HtHBXnoise)');
HtHBX=Mask.*ConvCM(F*Z,FBM,nl);
num = norm( Y([2:end],:) - HtHBX([2:end],:) , 'fro')^2;
end
end
Xhat_im = conv2im(F*Z,nl,nc,L);
Xhat_im = unnormaliseData(Xhat_im,av);
Xhat_im = Xhat_im(:,:,2:end);
end
function [Y,M,F]=initialization(Yim2,sdf,nl,nc,L,dx,dy,d,limsub,r)
FBM2 = createConvKernelSubspace(sdf,nl,nc,L,dx,dy);
% Generate LR MS image FOR SUBSPACE
% Upsample image via interpolation
for i=1:L
Ylim(:,:,i) = imresize(Yim2{i},d(i));
end
Y2im=real(ifft2(fft2(Ylim).*FBM2));
Y2tr=Y2im(limsub+1:end-limsub,limsub+1:end-limsub,:);
Y2n = reshape(Y2tr,[(nl-4)*(nc-4),L]);
% SVD analysis
% Y2n is the image for subspace with the removed border
[F,D,P] = svd(Y2n','econ');
F=F(:,1:r);
[M, Y] = createSubsampling(Yim2,d,nl,nc,L);
end
function [Z, xcost,options]=Zstep(Y,FBM,F,tau,nl,nc,Z,Mask,q,FDH,FDV,FDHC,FDVC,W,Whalf,tolgradnorm)
r = size(F,2);
n = nl*nc;
UBTMTy=F'*ConvCM(Y,conj(FBM),nl);
[Z] = CG(Z,F,Y,UBTMTy,FBM,Mask,nl,nc,r,tau,q,FDH,FDV,FDHC,FDVC,W);
xcost=1;
options=[];
end
function F1=Fstep(F,Z,Y,FBM,nl,nc,Mask)
F0=F;% U; % initialization
BTXhat = ConvCM(F0*Z,FBM,nl);
MBTXhat=Mask.*BTXhat;
[L,r]=size(F);
for ii=1:L
MBZT(:,:,ii)=repmat(Mask(ii,:),[r,1]).*ConvCM(Z,repmat(FBM(:,:,ii),[1,1,r]),nl);
A(:,:,ii)=MBZT(:,:,ii)*MBZT(:,:,ii)';
ZBMTy(:,ii)=MBZT(:,:,ii)*Y(ii,:)';
end
ZBYT=ZBMTy';% BTY*Z';
manifold = stiefelfactory(L,r,1); %euclideanfactory(L,r);
problem.M = manifold;
problem.cost = @(F) costF(F,MBZT,Y);
problem.egrad = @(F) egrad(F,A,ZBYT);
warning('off', 'manopt:getHessian:approx')
options.tolgradnorm = 1e-2;
options.verbosity=0;
[F1, xcost, info, options] = trustregions(problem,F0,options);
end
% Cost functions
function [Ju]=costF(F,MBZT,Y)
L=size(F,1);
Ju=0;
for i=1:L
fi=F(i,:)';
yi=Y(i,:)';
Ju=Ju+0.5*norm(MBZT(:,:,i)'*fi-yi,'fro')^2;
end
end
function [Du]=egrad(F,A,ZBYT)
p=size(A,3);
Du=0*F;
for ii=1:p
Du(ii,:)=F(ii,:)*A(:,:,ii)'-ZBYT(ii,:);
end
end
%%% AUXILILARY FUNCTIONS
function [FDH,FDV,FDHC,FDVC] = createDiffkernels(nl,nc,r)
dh = zeros(nl,nc);
dh(1,1) = 1;
dh(1,nc) = -1;
dv = zeros(nl,nc);
dv(1,1) = 1;
dv(nl,1) = -1;
FDH = repmat(fft2(dh),1,1,r);
FDV = repmat(fft2(dv),1,1,r);
FDHC = conj(FDH);
FDVC = conj(FDV);
end
function [Yim, av] = normaliseData(Yim)
% Normalize each cell to unit power
if iscell(Yim)
% mean squared power = 1
nb = length(Yim);
for i=1:nb
av(i,1) = mean2(Yim{i}.^2);
Yim{i,1} = sqrt(Yim{i}.^2/av(i,1));
end
else
nb = size(Yim,3);
for i=1:nb
av(i,1) = mean2(Yim(:,:,i).^2);
Yim(:,:,i) = sqrt(Yim(:,:,i).^2/av(i,1));
end
end
end
function FBM = createConvKernel(sdf,d,nl,nc,L,dx,dy)
%--------------------------------------------------------------------------
% Build convolution kernels
%--------------------------------------------------------------------------
middlel=((nl)/2);
middlec=((nc)/2);
% kernel filters expanded to size [nl,nc]
B = zeros(nl,nc,L);
% fft2 of kernels
FBM = zeros(nl,nc,L);
for i=1:L
if d(i) > 1
h = fspecial('gaussian',[dx,dy],sdf(i));
B((middlel-dy/2+1:middlel+dy/2)-d(i)/2+1,(middlec-dx/2+1:middlec+dx/2)-d(i)/2+1,i) = h; %run
% circularly center
B(:,:,i)= fftshift(B(:,:,i));
% normalize
B(:,:,i) = B(:,:,i)/sum(sum(B(:,:,i)));
FBM(:,:,i) = fft2(B(:,:,i));
else
B(1,1,i) = 1;
FBM(:,:,i) = fft2(B(:,:,i));
end
end
end
function FBM2 = createConvKernelSubspace(sdf,nl,nc,L,dx,dy)
%--------------------------------------------------------------------------
% Build convolution kernels FOR SUBSPACE!!!!
%--------------------------------------------------------------------------
%
middlel=round((nl+1)/2);
middlec=round((nc+1)/2);
dx = dx+1;
dy = dy+1;
% kernel filters expanded to size [nl,nc]
B = zeros(nl,nc,L);
% fft2 of kernels
FBM2 = zeros(nl,nc,L);
s2 = max(sdf);
for i=1:L
if sdf(i) < s2
h = fspecial('gaussian',[dx,dy],sqrt(s2^2-sdf(i)^2));
B(middlel-(dy-1)/2:middlel+(dy-1)/2,middlec-(dx-1)/2:middlec+(dx-1)/2,i) = h;
%circularly center
B(:,:,i)= fftshift(B(:,:,i));
% normalize
B(:,:,i) = B(:,:,i)/sum(sum(B(:,:,i)));
FBM2(:,:,i) = fft2(B(:,:,i));
else
% unit impulse
B(1,1,i) = 1;
FBM2(:,:,i) = fft2(B(:,:,i));
end
end
end
function X = ConvCM(X,FKM,nl,nc,L)
if nargin == 3
[L,n] = size(X);
nc = n/nl;
end
X = conv2mat(real(ifft2(fft2(conv2im(X,nl,nc,L)).*FKM)));
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% define a circular convolution (the same for all bands) accepting a
% matrix and returnig a matrix
% size(X) is [no_bands_ms,n]
% FKM is the of the cube containing the fft2 of the convolution kernels
% ConvCM = @(X,FKM) reshape(real(ifft2(fft2(reshape(X', nl,nc,nb)).*FKM)), nl*nc,nb)';
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
end
function X = conv2mat(X,nl,nc,L)
if ndims(X) == 3
[nl,nc,L] = size(X);
X = reshape(X,nl*nc,L)';
elseif ndims(squeeze(X)) == 2
L = 1;
[nl,nc] = size(X);
X = reshape(X,nl*nc,L)';
end
end
function [M, Y] = createSubsampling(Yim,d,nl,nc,L)
% subsampling matrix
M = zeros(nl,nc,L);
indexes = cell([L 1]);
for i=1:L
im = ones(floor(nl/d(i)),floor(nc/d(i)));
maux = zeros(d(i));
maux(1,1) = 1;
M(:,:,i) = kron(im,maux);
indexes{i} = find(M(:,:,i) == 1);
Y(i,indexes{i}) = conv2mat(Yim{i},nl/d(i),nc/d(i),1);
end
end
function [Yim] = unnormaliseData(Yim, av)
if iscell(Yim)
% mean squared power = 1
nb = length(Yim);
for i=1:nb
Yim{i,1} = sqrt(Yim{i}.^2*av(i,1));
end
else
nb = size(Yim,3);
for i=1:nb
Yim(:,:,i) = sqrt(Yim(:,:,i).^2*av(i,1));
end
end
end
function W = computeWeights(Y,d,sigmas,nl)
% As in eq. (14) and (15)
% Compute weigts for each pixel based on HR bands
hr_bands = d==1;
hr_bands = find(hr_bands)';
for i=hr_bands
% grad(:,:,i) = imgradient(conv2im(Y(i,:),nl),'prewitt').^2;
% Intermediate gives also good results compared to prewitt
grad(:,:,i) = imgradient(conv2im(Y(i,:),nl),'intermediate').^2;
end
grad = sqrt(max(grad,[],3));
grad = grad / quantile(grad(:),0.95);
Wim = exp(-grad.^2/2/sigmas^2);
Wim(Wim<0.5) = 0.5;
W = conv2mat(Wim,nl);
end
function X = conv2im(X,nl,nc,L)
if size(X,2)==1
X = conv2mat(X,nl,nc,L);
end
if nargin == 2
[L,n] = size(X);
if n==1
X = conv2mat(X,nl,nc,L);
end
nc = n/nl;
end
X = reshape(X',nl,nc,L);
end
function [J,gradJ,AtAg] = grad_cost_G(Z,F,Y,UBTMTy,FBM,Mask,nl,nc,r,tau,q,FDH,FDV,FDHC,FDVC,W)
X=F*Z;
BX=ConvCM(X,FBM,nl);
HtHBX=Mask.*BX;
ZH=ConvCM(Z,FDHC,nl);
Zv=ConvCM(Z,FDVC,nl);
ZHW=ZH.*W;
ZVW=Zv.*W;
grad_pen=ConvCM(ZHW,FDH,nl)+ConvCM(ZVW,FDV,nl);
AtAg = F'*ConvCM(HtHBX,conj(FBM),nl)+2*tau*(q*ones(1,nl*nc)).*grad_pen;
gradJ=AtAg-UBTMTy;
J = 1/2 * sum( sum( Z .* AtAg ) ) - sum( sum( Z.*UBTMTy ) );
end
function [ Z ] = CG(Z,F,Y,UBTMTy,FBM,Mask,nl,nc,r,tau,q,FDH,FDV,FDHC,FDVC,W)
maxiter = 1000;
tolgradnorm = 0.1;%1e-6;
[cost,grad] = grad_cost_G(Z,F,Y,UBTMTy,FBM,Mask,nl,nc,r,tau,q,FDH,FDV,FDHC,FDVC,W);
gradnorm = norm(grad(:));
iter = 0;
res = -grad;
while ( gradnorm > tolgradnorm & iter < maxiter )
iter = iter + 1;
% fprintf('%5d\t%+.16e\t%.8e\n', iter, cost, gradnorm);
if( iter == 1 )
desc_dir = res;
else
beta = ( res(:).' * res(:) ) / ( old_res(:).' * old_res(:) );
desc_dir = res + beta * desc_dir;
end
[~, ~, AtAp] = grad_cost_G(desc_dir,F,Y,UBTMTy,FBM,Mask,nl,nc,r,tau,q,FDH,FDV,FDHC,FDVC,W);
alpha = ( res(:).' * res(:) ) / ( desc_dir(:).' * AtAp(:) );
Z1 = Z + alpha * desc_dir;
old_res = res;
res = res - alpha* AtAp;
gradnorm = norm( res(:) );
% Transfer iterate info
Z = Z1;
end
end
|
2881099/FreeSql.AdminLTE
| 1,168
|
Examples/net60_preview/Entitys/AdminRoute.cs
|
using FreeSql.DataAnnotations;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
namespace net60_preview.Entitys
{
/// <summary>
/// 音乐
/// </summary>
public class AdminRoute
{
/// <summary>
/// 主键
/// </summary>
[Column(IsIdentity = true)]
public int Id { get; set; }
/// <summary>
/// 路径
/// </summary>
public string Path { get; set; }
/// <summary>
/// 创建时间
/// </summary>
public DateTime? Create_time { get; set; }
[Navigate(nameof(ParentId))]
public List<AdminRoute> Childs { get; set; }
/// <summary>
/// 父节点
/// </summary>
public int ParentId { get; set; }
[Navigate(nameof(ParentId))]
public AdminRoute Parent { get; set; }
/// <summary>
/// 标题
/// </summary>
public string Name { get; set; }
/// <summary>
/// 前端数据
/// </summary>
public string Extdata { get; set; }
/// <summary>
/// 备注
/// </summary>
public string Remark { get; set; }
}
}
|
2977094657/BiliHistoryFrontend
| 27,569
|
src/components/tailwind/page/AnimatedAnalytics.vue
|
<template>
<div class="h-screen">
<analytics-layout>
<!-- 固定在顶部的导航 -->
<div class="fixed top-0 left-0 right-0 z-50">
<div class="bg-white/5 backdrop-blur-md border-b border-white/10 dark:bg-black/5 dark:border-gray-800/50">
<div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
<div class="flex justify-between items-center h-16">
<!-- 添加返回按钮 -->
<div class="flex items-center">
<button
@click="goToHome"
class="mr-3 p-1 rounded-full hover:bg-white/20 dark:hover:bg-black/20 transition-colors"
title="返回首页"
>
<svg xmlns="http://www.w3.org/2000/svg" class="h-6 w-6 text-[#fb7299] dark:text-[#fc9b7a]" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M3 12l2-2m0 0l7-7 7 7M5 10v10a1 1 0 001 1h3m10-11l2 2m-2-2v10a1 1 0 01-1 1h-3m-6 0a1 1 0 001-1v-4a1 1 0 011-1h2a1 1 0 011 1v4a1 1 0 001 1m-6 0h6" />
</svg>
</button>
<h1 class="text-2xl font-bold bg-gradient-to-r from-[#fb7299] to-[#fc9b7a] bg-clip-text text-transparent">
{{ selectedYear }}年度回顾
</h1>
</div>
<div class="flex items-center space-x-4">
<select
v-model="selectedYear"
class="w-24 bg-white/10 backdrop-blur text-gray-800 dark:text-white border border-white/20 dark:border-gray-700 rounded-lg px-3 py-1 focus:ring-2 focus:ring-[#fb7299] focus:border-transparent transition-colors duration-200"
:disabled="loading"
>
<option v-for="year in availableYears" :key="year" :value="year">
{{ year }}年
</option>
</select>
<!-- 强制刷新按钮 -->
<button
@click="handleForceRefresh"
:disabled="loading"
class="inline-flex items-center text-gray-600 dark:text-gray-300 hover:text-[#fb7299] dark:hover:text-[#fb7299] disabled:opacity-50 disabled:cursor-not-allowed transition-colors duration-200"
>
<svg
class="w-5 h-5"
:class="{'animate-spin': loading}"
xmlns="http://www.w3.org/2000/svg"
fill="none"
viewBox="0 0 24 24"
stroke="currentColor"
>
<circle
v-if="loading"
class="opacity-25"
cx="12"
cy="12"
r="10"
stroke="currentColor"
stroke-width="4"
></circle>
<path
v-if="loading"
class="opacity-75"
fill="currentColor"
d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"
></path>
<path
v-if="!loading"
stroke="currentColor"
stroke-linecap="round"
stroke-linejoin="round"
stroke-width="2"
d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15"
></path>
</svg>
<span class="ml-2">{{ loading ? '加载中' : '强制刷新' }}</span>
</button>
</div>
</div>
</div>
</div>
</div>
<!-- 主要内容区域 -->
<div class="relative h-full pt-16">
<!-- 页面容器 -->
<div class="h-full">
<!-- 加载状态 -->
<div v-if="loading"
class="fixed inset-0 flex items-center justify-center z-50 bg-white/80 dark:bg-gray-900/80 backdrop-blur-sm"
style="min-height: 100vh"
>
<div class="text-center">
<svg
class="w-12 h-12 mx-auto mb-4 animate-spin text-[#fb7299]"
xmlns="http://www.w3.org/2000/svg"
fill="none"
viewBox="0 0 24 24"
>
<circle
class="opacity-25"
cx="12"
cy="12"
r="10"
stroke="currentColor"
stroke-width="4"
></circle>
<path
class="opacity-75"
fill="currentColor"
d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"
></path>
</svg>
<div class="space-y-2">
<p class="text-lg font-medium text-gray-800 dark:text-gray-200">正在分析{{ selectedYear }}年的观看数据</p>
<p class="text-sm text-gray-600 dark:text-gray-400">
{{ loading && viewingData === null ? '首次加载数据可能需要30秒到1分钟,具体加载时间取决于数据量' : '正在从缓存加载数据,预计3-5秒' }}
</p>
</div>
</div>
</div>
<!-- 内容页面 -->
<Transition mode="out-in" name="fade">
<!-- 开场页 -->
<HeroPage v-if="currentPage === 0" key="hero" :year="selectedYear" />
<!-- 数据概览页 -->
<OverviewPage v-else-if="currentPage === 1" key="overview" :viewing-data="monthlyStatsData" />
<!-- 时间分析页 -->
<TimeAnalysisPage v-else-if="currentPage === 2" key="time-analysis" :viewing-data="timeSlotsData" :selected-year="selectedYear" />
<!-- 时间分布分析页 -->
<TimeDistributionPage v-else-if="currentPage === 3" key="time-distribution" :viewing-data="weeklyStatsData" />
<!-- 月度趋势页 -->
<MonthlyPage v-else-if="currentPage === 4" key="monthly" :viewing-data="monthlyStatsData" />
<!-- 连续观看页 -->
<StreakPage v-else-if="currentPage === 5" key="streak" :viewing-data="continuityData" :selected-year="selectedYear" />
<!-- 最爱重温页 -->
<RewatchPage v-else-if="currentPage === 6" key="rewatch" :viewing-data="watchCountsData" />
<!-- 视频完成率分析页 -->
<OverallCompletionPage v-else-if="currentPage === 7" key="overall-completion" :viewing-data="completionRatesData" />
<!-- UP主完成率分析页 -->
<AuthorCompletionPage v-else-if="currentPage === 8" key="author-completion" :viewing-data="authorCompletionData" />
<!-- 标签分析页 -->
<TagsPage v-else-if="currentPage === 9" key="tags" :viewing-data="tagAnalysisData" />
<!-- 视频时长分析页 -->
<DurationAnalysisPage v-else-if="currentPage === 10" key="duration-analysis" :viewing-data="durationAnalysisData" />
<!-- 标题分析页 -->
<TitleAnalysisPage v-else-if="currentPage === 11" key="title-analysis" :title-analytics="keywordAnalyticsData" />
<!-- 标题趋势分析页 -->
<TitleTrendAnalysisPage v-else-if="currentPage === 12" key="title-trend-analysis" :title-analytics="trendAnalyticsData" />
<!-- 标题长度分析页 -->
<TitleLengthAnalysisPage v-else-if="currentPage === 13" key="title-length-analysis" :title-analytics="lengthAnalyticsData" />
<!-- 标题情感分析页 -->
<TitleSentimentAnalysisPage v-else-if="currentPage === 14" key="title-sentiment-analysis" :title-analytics="sentimentAnalyticsData" />
<!-- 标题互动分析页 -->
<TitleInteractionAnalysisPage v-else-if="currentPage === 15" key="title-interaction-analysis" :title-analytics="interactionAnalyticsData" />
<!-- 热门命中率分析页 -->
<PopularHitRatePage v-else-if="currentPage === 16" key="popular-hit-rate" :selected-year="selectedYear" :hit-rate-data="popularHitRateData" />
<!-- 热门预测能力分析页 -->
<PopularPredictionPage v-else-if="currentPage === 17" key="popular-prediction" :data="popularPredictionData?.prediction_analysis" />
<!-- UP主热门关联分析页 -->
<AuthorPopularAssociationPage v-else-if="currentPage === 18" key="author-popular-association" :data="authorPopularAssociationData?.association_analysis" />
<!-- 热门视频分区分布分析页 -->
<CategoryPopularDistributionPage v-else-if="currentPage === 19" key="category-popular-distribution" :selected-year="selectedYear" :distribution-data="categoryPopularDistributionData" />
<!-- 热门视频时长分布分析页 -->
<DurationPopularDistributionPage v-else-if="currentPage === 20" key="duration-popular-distribution" :selected-year="selectedYear" :duration-data="durationPopularDistributionData" />
</Transition>
</div>
</div>
</analytics-layout>
</div>
</template>
<script setup>
import { ref, watch, onMounted, onUnmounted } from 'vue'
import { getTitleKeywordAnalysis, getTitleLengthAnalysis, getTitleSentimentAnalysis, getTitleTrendAnalysis, getTitleInteractionAnalysis, getViewingMonthlyStats, getViewingWeeklyStats, getViewingTimeSlots, getViewingContinuity, getViewingWatchCounts, getViewingCompletionRates, getViewingAuthorCompletion, getViewingTagAnalysis, getViewingDurationAnalysis, getPopularHitRate, getPopularPredictionAbility, getAuthorPopularAssociation, getCategoryPopularDistribution, getDurationPopularDistribution } from '../../../api/api.js'
import HeroPage from '../analytics/pages/HeroPage.vue'
import OverviewPage from '../analytics/pages/OverviewPage.vue'
import StreakPage from '../analytics/pages/StreakPage.vue'
import TimeAnalysisPage from '../analytics/pages/TimeAnalysisPage.vue'
import RewatchPage from '../analytics/pages/RewatchPage.vue'
import OverallCompletionPage from '../analytics/pages/OverallCompletionPage.vue'
import AuthorCompletionPage from '../analytics/pages/AuthorCompletionPage.vue'
import TagsPage from '../analytics/pages/TagsPage.vue'
import TimeDistributionPage from '../analytics/pages/TimeDistributionPage.vue'
import MonthlyPage from '../analytics/pages/MonthlyPage.vue'
import DurationAnalysisPage from '../analytics/pages/DurationAnalysisPage.vue'
import TitleAnalysisPage from '../analytics/pages/TitleAnalysisPage.vue'
import TitleLengthAnalysisPage from '../analytics/pages/TitleLengthAnalysisPage.vue'
import TitleSentimentAnalysisPage from '../analytics/pages/TitleSentimentAnalysisPage.vue'
import TitleTrendAnalysisPage from '../analytics/pages/TitleTrendAnalysisPage.vue'
import TitleInteractionAnalysisPage from '../analytics/pages/TitleInteractionAnalysisPage.vue'
import PopularHitRatePage from '../analytics/pages/PopularHitRatePage.vue'
import PopularPredictionPage from '../analytics/pages/PopularPredictionPage.vue'
import AuthorPopularAssociationPage from '../analytics/pages/AuthorPopularAssociationPage.vue'
import CategoryPopularDistributionPage from '../analytics/pages/CategoryPopularDistributionPage.vue'
import DurationPopularDistributionPage from '../analytics/pages/DurationPopularDistributionPage.vue'
import AnalyticsLayout from '../analytics/layout/AnalyticsLayout.vue'
import { CanvasRenderer } from 'echarts/renderers'
import { LineChart, BarChart, PieChart } from 'echarts/charts'
import {
GridComponent,
TooltipComponent,
LegendComponent,
TitleComponent
} from 'echarts/components'
import { use } from 'echarts/core'
import 'echarts-wordcloud'
import { useRouter, useRoute } from 'vue-router'
// 注册必要的组件
use([
CanvasRenderer,
LineChart,
BarChart,
PieChart,
GridComponent,
TooltipComponent,
LegendComponent,
TitleComponent
])
// 状态
const router = useRouter()
const route = useRoute()
const selectedYear = ref(new Date().getFullYear())
const availableYears = ref([])
const loading = ref(false)
// 已删除原有的 analyticsData,现在使用拆分后的独立数据
const keywordAnalyticsData = ref(null)
const lengthAnalyticsData = ref(null)
const sentimentAnalyticsData = ref(null)
const trendAnalyticsData = ref(null)
const interactionAnalyticsData = ref(null)
// 观看时间分析数据(逐步拆分中)
const monthlyStatsData = ref(null)
const weeklyStatsData = ref(null)
const timeSlotsData = ref(null)
const continuityData = ref(null)
const watchCountsData = ref(null)
const completionRatesData = ref(null)
const authorCompletionData = ref(null)
const tagAnalysisData = ref(null)
const durationAnalysisData = ref(null)
const popularHitRateData = ref(null)
const popularPredictionData = ref(null)
const authorPopularAssociationData = ref(null)
const categoryPopularDistributionData = ref(null)
const durationPopularDistributionData = ref(null)
const viewingData = ref(null)
const currentPage = ref(0)
const isTransitioning = ref(false)
// 滚动和触摸相关状态
let touchStartX = 0
let touchStartY = 0
let lastWheelTime = 0
const wheelThreshold = 30 // 降低滚动阈值
const wheelCooldown = 800 // 增加冷却时间以适应新的动画持续时间
// 页面配置
const pages = [
{ name: '开场', color: '#fb7299' },
{ name: '数据概览', color: '#fc9b7a' },
// 时间相关分析
{ name: '时间分析', color: '#fb7299' },
{ name: '时间分布', color: '#fc9b7a' },
{ name: '月度趋势', color: '#fb7299' },
// 观看行为分析
{ name: '连续观看', color: '#fc9b7a' },
{ name: '最爱重温', color: '#fb7299' },
{ name: '视频完成率', color: '#fc9b7a' },
// 内容分析
{ name: 'UP主完成率', color: '#fb7299' },
{ name: '标签分析', color: '#fc9b7a' },
{ name: '视频时长分析', color: '#fb7299' },
// 标题分析
{ name: '标题分析', color: '#fc9b7a' },
{ name: '标题趋势分析', color: '#fb7299' },
{ name: '标题长度分析', color: '#fc9b7a' },
{ name: '标题情感分析', color: '#fb7299' },
{ name: '标题互动分析', color: '#fc9b7a' },
// 热门视频分析
{ name: '热门命中率', color: '#fb7299' },
{ name: '预测能力', color: '#fc9b7a' },
{ name: 'UP主热门关联', color: '#fb7299' },
{ name: '分区分布', color: '#fc9b7a' },
{ name: '时长分布', color: '#fb7299' }
]
// 监听页面切换
watch(currentPage, (newPage) => {
// 减少过渡动画时间
isTransitioning.value = true
setTimeout(() => {
isTransitioning.value = false
}, 300)
// 更新 URL
router.push({
query: {
...route.query,
page: newPage
}
})
})
// 修改页面切换处理
const handlePageTransition = async (newPage) => {
if (isTransitioning.value) return
currentPage.value = newPage
// 切换页面时加载对应的数据
await fetchPageData(newPage)
}
// 修改滚轮事件处理
const handleWheel = (e) => {
// 如果正在加载,阻止滚动
if (loading.value) {
e.preventDefault()
return
}
const now = Date.now()
if (isTransitioning.value || now - lastWheelTime < wheelCooldown) return
const deltaY = Math.abs(e.deltaY)
if (deltaY < wheelThreshold) return
lastWheelTime = now
if (e.deltaY > 0 && currentPage.value < pages.length - 1) {
handlePageTransition(currentPage.value + 1)
} else if (e.deltaY < 0 && currentPage.value > 0) {
handlePageTransition(currentPage.value - 1)
}
}
// 检测是否为真正的触摸设备
const isTouchDevice = () => {
return 'ontouchstart' in window && navigator.maxTouchPoints > 0
}
// 修改触摸事件处理 - 只在真正的触摸设备上启用
const handleTouchStart = (e) => {
// 只在真正的触摸设备上处理触摸事件
if (!isTouchDevice()) return
// 如果正在加载,阻止触摸事件
if (loading.value || isTransitioning.value) return
touchStartX = e.touches[0].clientX
touchStartY = e.touches[0].clientY
}
const handleTouchMove = (e) => {
// 只在真正的触摸设备上处理触摸事件
if (!isTouchDevice()) return
// 如果正在加载,阻止触摸移动
if (loading.value) {
e.preventDefault()
return
}
if (isTransitioning.value) return
e.preventDefault() // 防止页面滚动
}
const handleTouchEnd = (e) => {
// 只在真正的触摸设备上处理触摸事件
if (!isTouchDevice()) return
// 如果正在加载,阻止触摸结束事件
if (loading.value || isTransitioning.value) return
const touchEndX = e.changedTouches[0].clientX
const touchEndY = e.changedTouches[0].clientY
const deltaX = touchEndX - touchStartX
const deltaY = touchEndY - touchStartY
if (Math.abs(deltaY) > Math.abs(deltaX)) {
if (Math.abs(deltaY) < 50) return
if (deltaY < 0 && currentPage.value < pages.length - 1) {
handlePageTransition(currentPage.value + 1)
} else if (deltaY > 0 && currentPage.value > 0) {
handlePageTransition(currentPage.value - 1)
}
}
}
// 按需加载数据的函数
const fetchPageData = async (pageNumber, forceRefresh = false) => {
if (loading.value) return
loading.value = true
try {
console.log(`开始获取第${pageNumber}页数据...`)
switch (pageNumber) {
case 0: // 开场页 - 不需要加载数据,但需要获取可用年份
if (!availableYears.value.length || forceRefresh) {
const response = await getViewingMonthlyStats(selectedYear.value, !forceRefresh)
if (response.data.status === 'success' && response.data.data.available_years) {
availableYears.value = response.data.data.available_years
if (!availableYears.value.includes(selectedYear.value)) {
selectedYear.value = availableYears.value[0]
}
}
}
break
case 1: // 月度统计页
if (!monthlyStatsData.value || forceRefresh) {
const response = await getViewingMonthlyStats(selectedYear.value, !forceRefresh)
if (response.data.status === 'success') {
monthlyStatsData.value = response.data.data
// 从第一个接口获取可用年份
if (response.data.data.available_years) {
availableYears.value = response.data.data.available_years
if (!availableYears.value.includes(selectedYear.value)) {
selectedYear.value = availableYears.value[0]
}
}
}
}
break
case 2: // 时间分析页
if (!timeSlotsData.value || forceRefresh) {
const response = await getViewingTimeSlots(selectedYear.value, !forceRefresh)
if (response.data.status === 'success') {
timeSlotsData.value = response.data.data
}
}
break
case 3: // 时间分布分析页
if (!weeklyStatsData.value || forceRefresh) {
const response = await getViewingWeeklyStats(selectedYear.value, !forceRefresh)
if (response.data.status === 'success') {
weeklyStatsData.value = response.data.data
}
}
break
case 4: // 月度趋势页
if (!monthlyStatsData.value || forceRefresh) {
const response = await getViewingMonthlyStats(selectedYear.value, !forceRefresh)
if (response.data.status === 'success') {
monthlyStatsData.value = response.data.data
}
}
break
case 5: // 连续观看记录页
if (!continuityData.value || forceRefresh) {
const response = await getViewingContinuity(selectedYear.value, !forceRefresh)
if (response.data.status === 'success') {
continuityData.value = response.data.data
}
}
break
case 6: // 最爱重温页
if (!watchCountsData.value || forceRefresh) {
const response = await getViewingWatchCounts(selectedYear.value, !forceRefresh)
if (response.data.status === 'success') {
watchCountsData.value = response.data.data
}
}
break
case 7: // 视频完成率分析页
if (!completionRatesData.value || forceRefresh) {
const response = await getViewingCompletionRates(selectedYear.value, !forceRefresh)
if (response.data.status === 'success') {
completionRatesData.value = response.data.data
}
}
break
case 8: // UP主完成率分析页
if (!authorCompletionData.value || forceRefresh) {
const response = await getViewingAuthorCompletion(selectedYear.value, !forceRefresh)
if (response.data.status === 'success') {
authorCompletionData.value = response.data.data
}
}
break
case 9: // 标签分析页
if (!tagAnalysisData.value || forceRefresh) {
const response = await getViewingTagAnalysis(selectedYear.value, !forceRefresh)
if (response.data.status === 'success') {
tagAnalysisData.value = response.data.data
}
}
break
case 10: // 视频时长分析页
if (!durationAnalysisData.value || forceRefresh) {
const response = await getViewingDurationAnalysis(selectedYear.value, !forceRefresh)
if (response.data.status === 'success') {
durationAnalysisData.value = response.data.data
}
}
break
case 11: // 标题分析页
if (!keywordAnalyticsData.value || forceRefresh) {
const response = await getTitleKeywordAnalysis(selectedYear.value, !forceRefresh)
if (response.data.status === 'success') {
keywordAnalyticsData.value = response.data.data
}
}
break
case 12: // 标题趋势分析页
if (!trendAnalyticsData.value || forceRefresh) {
const response = await getTitleTrendAnalysis(selectedYear.value, !forceRefresh)
if (response.data.status === 'success') {
trendAnalyticsData.value = response.data.data
}
}
break
case 13: // 标题长度分析页
if (!lengthAnalyticsData.value || forceRefresh) {
const response = await getTitleLengthAnalysis(selectedYear.value, !forceRefresh)
if (response.data.status === 'success') {
lengthAnalyticsData.value = response.data.data
}
}
break
case 14: // 标题情感分析页
if (!sentimentAnalyticsData.value || forceRefresh) {
const response = await getTitleSentimentAnalysis(selectedYear.value, !forceRefresh)
if (response.data.status === 'success') {
sentimentAnalyticsData.value = response.data.data
}
}
break
case 15: // 标题互动分析页
if (!interactionAnalyticsData.value || forceRefresh) {
const response = await getTitleInteractionAnalysis(selectedYear.value, !forceRefresh)
if (response.data.status === 'success') {
interactionAnalyticsData.value = response.data.data
}
}
break
case 16: // 热门命中率分析页
if (!popularHitRateData.value || forceRefresh) {
const response = await getPopularHitRate(selectedYear.value, !forceRefresh)
if (response.data.status === 'success') {
popularHitRateData.value = response.data.data
}
}
break
case 17: // 热门预测能力分析页
if (!popularPredictionData.value || forceRefresh) {
const response = await getPopularPredictionAbility(selectedYear.value, !forceRefresh)
if (response.data.status === 'success') {
popularPredictionData.value = response.data.data
}
}
break
case 18: // UP主热门关联分析页
if (!authorPopularAssociationData.value || forceRefresh) {
const response = await getAuthorPopularAssociation(selectedYear.value, !forceRefresh)
if (response.data.status === 'success') {
authorPopularAssociationData.value = response.data.data
}
}
break
case 19: // 热门视频分区分布分析页
if (!categoryPopularDistributionData.value || forceRefresh) {
const response = await getCategoryPopularDistribution(selectedYear.value, !forceRefresh)
if (response.data.status === 'success') {
categoryPopularDistributionData.value = response.data.data
}
}
break
case 20: // 热门视频时长分布分析页
if (!durationPopularDistributionData.value || forceRefresh) {
const response = await getDurationPopularDistribution(selectedYear.value, !forceRefresh)
if (response.data.status === 'success') {
durationPopularDistributionData.value = response.data.data
}
}
break
default:
console.log(`第${pageNumber}页暂未配置数据加载`)
break
}
console.log(`第${pageNumber}页数据加载完成`)
} catch (error) {
console.error(`获取第${pageNumber}页数据失败:`, error)
} finally {
loading.value = false
}
}
// 兼容旧的函数名,用于强制刷新所有数据
const fetchAnalyticsData = async (forceRefresh = false) => {
if (forceRefresh) {
// 清空现有数据
keywordAnalyticsData.value = null
lengthAnalyticsData.value = null
sentimentAnalyticsData.value = null
trendAnalyticsData.value = null
interactionAnalyticsData.value = null
monthlyStatsData.value = null
weeklyStatsData.value = null
timeSlotsData.value = null
continuityData.value = null
watchCountsData.value = null
completionRatesData.value = null
authorCompletionData.value = null
tagAnalysisData.value = null
durationAnalysisData.value = null
popularHitRateData.value = null
popularPredictionData.value = null
authorPopularAssociationData.value = null
categoryPopularDistributionData.value = null
durationPopularDistributionData.value = null
viewingData.value = null
}
// 只加载当前页面的数据
await fetchPageData(currentPage.value, forceRefresh)
}
// 移除单独的年份获取方法
const refreshData = async (forceRefresh = false) => {
// 直接调用 fetchPageData,避免重复设置 loading 状态
await fetchPageData(currentPage.value, forceRefresh)
}
// 强制刷新方法
const handleForceRefresh = async () => {
if (loading.value) return
await refreshData(true)
}
// 监听年份变化
watch(selectedYear, async (newYear) => {
if (newYear) {
// 年份变化时,重新加载当前页面的数据
await fetchPageData(currentPage.value, true) // 强制刷新
}
})
// 生命周期钩子
onMounted(async () => {
// 从 URL 读取页码
const pageFromUrl = parseInt(Array.isArray(route.query.page) ? route.query.page[0] : route.query.page || '0')
if (!isNaN(pageFromUrl) && pageFromUrl >= 0 && pageFromUrl < pages.length) {
currentPage.value = pageFromUrl
}
// 确保获取可用年份(如果还没有获取)
if (!availableYears.value.length) {
try {
const response = await getViewingMonthlyStats(selectedYear.value, true)
if (response.data.status === 'success' && response.data.data.available_years) {
availableYears.value = response.data.data.available_years
if (!availableYears.value.includes(selectedYear.value)) {
selectedYear.value = availableYears.value[0]
}
}
} catch (error) {
console.error('获取可用年份失败:', error)
}
}
// 只加载当前页面的数据
await fetchPageData(currentPage.value)
window.addEventListener('wheel', handleWheel, { passive: false })
// 只在真正的触摸设备上添加触摸事件监听器
if (isTouchDevice()) {
window.addEventListener('touchstart', handleTouchStart)
window.addEventListener('touchmove', handleTouchMove, { passive: false })
window.addEventListener('touchend', handleTouchEnd)
}
})
onUnmounted(() => {
window.removeEventListener('wheel', handleWheel)
// 只在真正的触摸设备上移除触摸事件监听器
if (isTouchDevice()) {
window.removeEventListener('touchstart', handleTouchStart)
window.removeEventListener('touchmove', handleTouchMove)
window.removeEventListener('touchend', handleTouchEnd)
}
})
// 添加返回首页的方法
const goToHome = () => {
router.push('/')
}
</script>
<style>
.fade-enter-active,
.fade-leave-active {
transition: opacity 0.3s ease;
}
.fade-enter-from,
.fade-leave-to {
opacity: 0;
}
/* 添加过渡效果 */
select {
appearance: none;
background-image: url("data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' fill='none' viewBox='0 0 20 20'%3e%3cpath stroke='%23fb7299' stroke-linecap='round' stroke-linejoin='round' stroke-width='1.5' d='M6 8l4 4 4-4'/%3e%3c/svg%3e");
background-position: right 0.5rem center;
background-repeat: no-repeat;
background-size: 1.5em 1.5em;
padding-right: 2.5rem;
}
select:focus {
outline: none;
box-shadow: 0 0 0 2px rgba(251, 114, 153, 0.2);
}
/* 移除深色模式媒体查询,始终使用浅色模式 */
</style>
|
2977094657/BiliHistoryFrontend
| 14,503
|
src/components/tailwind/page/Downloads.vue
|
<template>
<div class="overflow-y-auto">
<!-- 搜索框 -->
<div class="mb-6">
<SimpleSearchBar
v-model="searchTerm"
placeholder="搜索已下载的视频或目录路径..."
@search="loadDownloadedVideos"
class="w-full"
/>
</div>
<!-- 主要内容 -->
<div>
<!-- 下载数据加载中的占位 -->
<div v-if="isLoading" class="flex flex-col items-center justify-center py-12">
<svg class="animate-spin h-8 w-8 text-[#fb7299] mb-4" fill="none" viewBox="0 0 24 24">
<circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
<path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
</svg>
<p class="text-gray-500">加载中,请稍候...</p>
</div>
<!-- 没有数据时的显示 -->
<div v-else-if="!downloads.videos || downloads.videos.length === 0" class="flex flex-col items-center justify-center py-12">
<svg class="w-16 h-16 text-gray-400 mb-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.5" d="M7 16a4 4 0 01-.88-7.903A5 5 0 1115.9 6L16 6a5 5 0 011 9.9M9 19l3 3m0 0l3-3m-3 3V10" />
</svg>
<p class="text-xl font-medium text-gray-600 mb-2">暂无下载记录</p>
<p class="text-gray-500 mb-4 text-center">
你还没有下载任何视频,在浏览历史记录时可以点击"下载"按钮下载视频。
</p>
</div>
<!-- 下载视频列表 -->
<div v-else>
<p class="text-sm text-gray-500 mb-4">
共找到 {{ downloads.total }} 个下载记录,当前第 {{ downloads.page }} 页,共 {{ downloads.pages }} 页
</p>
<div class="grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-4 xl:grid-cols-5 gap-3">
<div v-for="(video, index) in downloads.videos" :key="index" class="bg-white/50 backdrop-blur-sm rounded-md overflow-hidden border border-gray-200/50 hover:border-[#fb7299] hover:shadow-sm transition-all duration-200 relative group">
<!-- 视频封面 -->
<div class="relative pb-[56.25%] overflow-hidden cursor-pointer group" @click="handleVideoClick(video)">
<img
:src="normalizeImageUrl(video.cover) || 'https://i0.hdslb.com/bfs/archive/c9e72655b7c9c9c68a30d3275313c501e68427d1.jpg'"
:alt="video.title"
class="absolute inset-0 w-full h-full object-cover group-hover:scale-105 transition-transform duration-300"
loading="lazy"
onerror="this.src='https://i0.hdslb.com/bfs/archive/c9e72655b7c9c9c68a30d3275313c501e68427d1.jpg'"
/>
<!-- 播放按钮覆盖 -->
<div class="absolute inset-0 flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity">
<button
v-if="video.files && video.files.length > 0 && !video.files[0].is_audio_only"
@click.stop="playVideo(video.files[0].file_path)"
class="w-8 h-8 rounded-full bg-[#fb7299]/80 text-white flex items-center justify-center backdrop-blur-sm"
>
<svg class="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M14.752 11.168l-3.197-2.132A1 1 0 0010 9.87v4.263a1 1 0 001.555.832l3.197-2.132a1 1 0 000-1.664z" />
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
</svg>
</button>
</div>
<!-- 文件信息标签 -->
<div class="absolute bottom-1 right-1 bg-black/60 backdrop-blur-sm px-1 py-0.5 rounded text-white text-[10px]">
<div v-if="video.files && video.files.length > 0">
{{ video.files[0].size_mb.toFixed(1) }} MB
</div>
</div>
<!-- 删除按钮 -->
<div class="absolute right-1.5 top-1.5 z-20 hidden group-hover:flex items-center justify-center w-6 h-6 bg-[#7d7c75]/60 backdrop-blur-sm hover:bg-[#7d7c75]/80 rounded-md cursor-pointer transition-all duration-200"
@click.stop="handleDeleteVideo(video)">
<svg class="w-3.5 h-3.5 text-white" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16" />
</svg>
</div>
<!-- 多文件角标 -->
<div v-if="video.files && video.files.length > 1"
class="absolute left-1 top-1 rounded bg-[#fb7299] px-1 py-0.5 text-[10px] text-white">
{{ video.files.length }}
</div>
</div>
<!-- 视频信息 -->
<div class="p-2 flex flex-col space-y-1">
<!-- 标题 -->
<div class="line-clamp-1 text-xs text-gray-900 font-medium cursor-pointer" @click="handleVideoClick(video)">
{{ video.title }}
</div>
<!-- 作者信息 -->
<div class="flex items-center space-x-1">
<img
:src="normalizeImageUrl(video.author_face) || 'https://i1.hdslb.com/bfs/face/1b6f746be0d0c8324e01e618c5e85e113a8b38be.jpg'"
:alt="video.author_name"
class="w-3.5 h-3.5 rounded-full object-cover cursor-pointer"
loading="lazy"
onerror="this.src='https://i1.hdslb.com/bfs/face/1b6f746be0d0c8324e01e618c5e85e113a8b38be.jpg'"
@click.stop="handleAuthorClick(video)"
/>
<span class="text-[10px] text-gray-600 truncate hover:text-[#fb7299] cursor-pointer" @click.stop="handleAuthorClick(video)">
{{ video.author_name || '未知UP主' }}
</span>
</div>
<!-- 下载时间 -->
<div class="flex justify-between items-center text-[10px] text-gray-500">
<div class="flex items-center space-x-1">
<svg class="w-2.5 h-2.5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8 7V3m8 4V3m-9 8h10M5 21h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v12a2 2 0 002 2z" />
</svg>
<span>{{ video.download_date }}</span>
</div>
</div>
</div>
</div>
</div>
<!-- 分页 -->
<div class="mt-8 flex justify-center">
<Pagination
:current-page="currentPage"
:total-pages="downloads.pages"
@page-change="handlePageChange"
/>
</div>
</div>
</div>
<!-- 视频播放对话框 -->
<VideoPlayerDialog
v-model:show="showVideoPlayer"
:video-path="currentVideoPath"
/>
<!-- 删除确认对话框 -->
<Teleport to="body">
<div v-if="showDeleteConfirm" class="fixed inset-0 z-50 flex items-center justify-center">
<!-- 遮罩层 -->
<div class="fixed inset-0 bg-black/50 backdrop-blur-sm" @click="showDeleteConfirm = false"></div>
<!-- 弹窗内容 -->
<div class="relative bg-white rounded-lg border border-gray-200 w-[500px] z-10 p-6">
<h3 class="text-lg font-medium text-gray-900 mb-4">确认删除视频</h3>
<p class="text-gray-600 mb-4">
确定要删除以下视频吗?此操作不可恢复。
</p>
<p class="font-medium text-gray-800 mb-2">{{ currentVideo?.title || '未知视频' }}</p>
<!-- 显示CID和目录信息 -->
<div class="mb-3 text-sm text-gray-500">
<p v-if="currentVideo?.cid">CID: {{ currentVideo?.cid }}</p>
<!-- 目录信息显示 -->
<div class="mt-2">
<p class="text-gray-600 mb-1">目录路径:</p>
<div class="px-3 py-2 bg-gray-50 border border-gray-200 rounded-md text-gray-700 text-sm break-all">
{{ getVideoDirectory(currentVideo) || '无法获取目录路径' }}
</div>
</div>
</div>
<!-- 删除选项 -->
<div class="mb-4">
<label class="flex items-center space-x-2 cursor-pointer select-none">
<input
type="checkbox"
v-model="deleteDirectory"
class="w-4 h-4 text-[#fb7299] border-gray-300 rounded focus:ring-[#fb7299]"
>
<span>同时删除整个目录(包含所有相关文件)</span>
</label>
</div>
<!-- 视频来源提示 (针对收藏夹视频) -->
<div v-if="!currentVideo?.cid && getVideoDirectory(currentVideo)" class="mb-4 p-2 bg-amber-50 rounded-md border border-amber-200">
<p class="text-sm text-amber-700">
<span class="font-medium">提示:</span>
该视频可能来自收藏夹批量下载,将使用目录路径进行删除。
</p>
</div>
<!-- 按钮 -->
<div class="flex justify-end space-x-3 mt-6">
<button
@click="showDeleteConfirm = false"
class="px-4 py-2 text-sm font-medium text-gray-700 bg-white border border-gray-300 rounded-md hover:bg-gray-50"
>
取消
</button>
<button
@click="confirmDeleteVideo"
class="px-4 py-2 text-sm font-medium text-white bg-red-600 rounded-md hover:bg-red-700"
:disabled="isDeleting || (!currentVideo?.cid && !getVideoDirectory(currentVideo))"
>
{{ isDeleting ? '删除中...' : '确认删除' }}
</button>
</div>
</div>
</div>
</Teleport>
</div>
</template>
<script setup>
import { ref, onMounted, computed } from 'vue'
import Pagination from '../Pagination.vue'
import VideoPlayerDialog from '../VideoPlayerDialog.vue'
import { getDownloadedVideos, deleteDownloadedVideo } from '../../../api/api'
import axios from 'axios'
import { showNotify } from 'vant'
import 'vant/es/notify/style'
import SimpleSearchBar from '../SimpleSearchBar.vue'
import { openInBrowser } from '@/utils/openUrl.js'
import { normalizeImageUrl } from '@/utils/imageUrl.js'
// 定义组件选项
defineOptions({
name: 'Downloads'
})
// 定义API基础URL,与api.js中保持一致
const BASE_URL = import.meta.env.VITE_API_BASE_URL || 'http://localhost:8000'
// 状态变量
const isLoading = ref(true)
const downloads = ref({
videos: [],
total: 0,
page: 1,
limit: 20,
pages: 1
})
const searchTerm = ref('')
const currentPage = ref(1)
// 视频播放相关
const showVideoPlayer = ref(false)
const currentVideoPath = ref('')
// 删除相关
const showDeleteConfirm = ref(false)
const currentVideo = ref(null)
const deleteDirectory = ref(true)
const isDeleting = ref(false)
// 加载已下载的视频
const loadDownloadedVideos = async () => {
try {
isLoading.value = true
const response = await getDownloadedVideos(searchTerm.value, currentPage.value, 20)
if (response.data && response.data.status === 'success') {
downloads.value = {
videos: response.data.videos,
total: response.data.total,
page: response.data.page,
limit: response.data.limit,
pages: response.data.pages
}
} else {
console.error('获取下载视频失败:', response.data?.message || '未知错误')
}
} catch (error) {
console.error('请求获取下载视频列表出错:', error)
} finally {
isLoading.value = false
}
}
// 处理页码变化
const handlePageChange = (page) => {
currentPage.value = page
loadDownloadedVideos()
}
// 播放视频
const playVideo = (filePath) => {
// 先关闭播放器并重置路径
showVideoPlayer.value = false
currentVideoPath.value = ''
// 在短暂延迟后重新设置路径并打开播放器
setTimeout(() => {
currentVideoPath.value = filePath
showVideoPlayer.value = true
}, 50)
}
// 处理删除视频
const handleDeleteVideo = (video) => {
currentVideo.value = video
showDeleteConfirm.value = true
deleteDirectory.value = true
}
// 获取视频目录
const getVideoDirectory = (video) => {
// 如果视频对象已经有目录属性,直接使用
if (video.directory) return video.directory;
// 否则,尝试从第一个文件路径中提取目录
if (video.files && video.files.length > 0) {
const filePath = video.files[0].file_path;
if (filePath) {
// 提取目录路径 (去掉文件名)
const lastSlashIndex = Math.max(filePath.lastIndexOf('/'), filePath.lastIndexOf('\\'));
if (lastSlashIndex !== -1) {
return filePath.substring(0, lastSlashIndex);
}
}
}
return null;
}
// 提取短目录名
const getShortDirectory = (directory) => {
if (!directory) return '';
// 获取最后一级目录名
const parts = directory.split(/[\/\\]/);
const lastPart = parts[parts.length - 1];
// 如果路径太长,截断显示
if (directory.length > 40) {
return '...' + directory.substring(directory.length - 40);
}
return directory;
}
// 确认删除视频
const confirmDeleteVideo = async () => {
try {
isDeleting.value = true
// 确定目录路径
const directory = getVideoDirectory(currentVideo.value)
// 自动判断是否使用CID
// 如果有CID则使用CID,否则使用目录路径
const cid = currentVideo.value?.cid || null
// 如果既没有CID也没有目录路径,则无法删除
if (!cid && !directory) {
showNotify({
type: 'warning',
message: '无法获取视频信息,删除失败'
})
isDeleting.value = false
return
}
const response = await deleteDownloadedVideo(cid, deleteDirectory.value, directory)
if (response.data && response.data.status === 'success') {
showNotify({
type: 'success',
message: response.data.message
})
// 关闭对话框
showDeleteConfirm.value = false
// 重新加载列表
await loadDownloadedVideos()
} else {
throw new Error(response.data?.message || '删除视频失败')
}
} catch (error) {
showNotify({
type: 'danger',
message: error.response?.data?.message || error.message || '删除视频失败'
})
} finally {
isDeleting.value = false
}
}
// 点击视频跳转到B站
const handleVideoClick = async (video) => {
// 构建视频链接,使用bvid而不是cid
const url = `https://www.bilibili.com/video/${video.bvid}`
// 在系统默认浏览器中打开
await openInBrowser(url)
}
// 点击作者头像或名称跳转到作者页面
const handleAuthorClick = async (video) => {
if (video.author_mid) {
const url = `https://space.bilibili.com/${video.author_mid}`
await openInBrowser(url)
}
}
// 组件挂载时加载数据
onMounted(() => {
loadDownloadedVideos()
})
</script>
<style scoped>
.line-clamp-2 {
display: -webkit-box;
-webkit-box-orient: vertical;
-webkit-line-clamp: 2;
overflow: hidden;
}
.group:hover .group-hover\:block {
display: block;
}
</style>
|
2977094657/BiliHistoryFrontend
| 9,071
|
src/components/tailwind/page/MediaManager.vue
|
<template>
<div class="min-h-screen bg-gray-50/30">
<div class="py-6">
<div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
<!-- 主内容卡片 -->
<div class="bg-white rounded-lg overflow-hidden">
<!-- 标签导航 - 修改为设置页风格 -->
<div class="border-b border-gray-200">
<nav class="-mb-px flex space-x-6 px-4 overflow-x-auto" aria-label="媒体管理选项卡">
<button
@click="activeTab = 'videos'"
class="py-3 px-1 border-b-2 font-medium text-sm flex items-center space-x-2"
:class="activeTab === 'videos'
? 'border-[#fb7299] text-[#fb7299]'
: 'border-transparent text-gray-500 hover:text-gray-700 hover:border-gray-300'"
>
<svg class="w-5 h-5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 10l4.553-2.276A1 1 0 0121 8.618v6.764a1 1 0 01-1.447.894L15 14M5 18h8a2 2 0 002-2V8a2 2 0 00-2-2H5a2 2 0 00-2 2v8a2 2 0 002 2z" />
</svg>
<span>视频管理</span>
</button>
<button
@click="activeTab = 'dynamic'"
class="py-3 px-1 border-b-2 font-medium text-sm flex items-center space-x-2"
:class="activeTab === 'dynamic'
? 'border-[#fb7299] text-[#fb7299]'
: 'border-transparent text-gray-500 hover:text-gray-700 hover:border-gray-300'"
>
<span class="w-4 h-4 inline-flex items-center justify-center" aria-hidden="true">
<svg width="20" height="21" viewBox="0 0 20 21" fill="none" xmlns="http://www.w3.org/2000/svg" class="w-4 h-4">
<g clip-path="url(#clip0)">
<path d="M10 10.743C7.69883 10.743 5.83333 8.87747 5.83333 6.5763C5.83333 4.27512 7.69883 2.40964 10 2.40964V10.743Z" stroke="currentColor" stroke-width="1.6" stroke-linejoin="round"></path>
<path d="M10 10.743C10 13.0441 8.1345 14.9096 5.83333 14.9096C3.53217 14.9096 1.66667 13.0441 1.66667 10.743H10Z" stroke="currentColor" stroke-width="1.6" stroke-linejoin="round"></path>
<path d="M10 10.743C10 8.44182 11.8655 6.57632 14.1667 6.57632C16.4679 6.57632 18.3333 8.44182 18.3333 10.743H10Z" stroke="currentColor" stroke-width="1.6" stroke-linejoin="round"></path>
<path d="M9.99999 10.743C12.3012 10.743 14.1667 12.6085 14.1667 14.9096C14.1667 17.2108 12.3012 19.0763 9.99999 19.0763V10.743Z" stroke="currentColor" stroke-width="1.6" stroke-linejoin="round"></path>
</g>
<defs><clipPath id="clip0"><rect width="20" height="20" fill="currentColor" transform="matrix(-1 0 0 1 20 0.742981)"></rect></clipPath></defs>
</svg>
</span>
<span>动态下载</span>
</button>
<button
@click="activeTab = 'images'"
class="py-3 px-1 border-b-2 font-medium text-sm flex items-center space-x-2"
:class="activeTab === 'images'
? 'border-[#fb7299] text-[#fb7299]'
: 'border-transparent text-gray-500 hover:text-gray-700 hover:border-gray-300'"
>
<svg class="w-5 h-5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 16l4.586-4.586a2 2 0 012.828 0L16 16m-2-2l1.586-1.586a2 2 0 012.828 0L20 14m-6-6h.01M6 20h12a2 2 0 002-2V6a2 2 0 00-2-2H6a2 2 0 00-2 2v12a2 2 0 002 2z" />
</svg>
<span>图片管理</span>
</button>
<button
@click="activeTab = 'remarks'"
class="py-3 px-1 border-b-2 font-medium text-sm flex items-center space-x-2"
:class="activeTab === 'remarks'
? 'border-[#fb7299] text-[#fb7299]'
: 'border-transparent text-gray-500 hover:text-gray-700 hover:border-gray-300'"
>
<svg class="w-5 h-5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z" />
</svg>
<span>我的备注</span>
</button>
<button
@click="activeTab = 'comments'"
class="py-3 px-1 border-b-2 font-medium text-sm flex items-center space-x-2"
:class="activeTab === 'comments'
? 'border-[#fb7299] text-[#fb7299]'
: 'border-transparent text-gray-500 hover:text-gray-700 hover:border-gray-300'"
>
<svg class="w-5 h-5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8 10h.01M12 10h.01M16 10h.01M9 16H5a2 2 0 01-2-2V6a2 2 0 012-2h14a2 2 0 012 2v8a2 2 0 01-2 2h-5l-5 5v-5z" />
</svg>
<span>我的评论</span>
</button>
<button
@click="activeTab = 'details'"
class="py-3 px-1 border-b-2 font-medium text-sm flex items-center space-x-2"
:class="activeTab === 'details'
? 'border-[#fb7299] text-[#fb7299]'
: 'border-transparent text-gray-500 hover:text-gray-700 hover:border-gray-300'"
>
<svg class="w-5 h-5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
</svg>
<span>视频详情</span>
</button>
</nav>
</div>
<!-- 内容区域 -->
<div class="transition-all duration-300 p-5">
<!-- 动态下载 -->
<div v-if="activeTab === 'dynamic'" class="animate-fadeIn">
<DynamicDownloader />
</div>
<!-- 图片管理 -->
<div v-if="activeTab === 'images'" class="animate-fadeIn">
<Images />
</div>
<!-- 视频管理 -->
<div v-if="activeTab === 'videos'" class="animate-fadeIn">
<!-- ArtPlayer致谢 - 只在视频标签显示 -->
<div class="mb-4 flex items-center justify-center h-9 px-3 py-0 bg-[#fb7299]/5 rounded-md border border-[#fb7299]/20">
<a href="https://github.com/zhw2590582/ArtPlayer" target="_blank" rel="noopener noreferrer" class="flex items-center hover:opacity-80 transition-opacity mr-1.5">
<img src="https://artplayer.org/document/logo.png" alt="ArtPlayer Logo" class="h-3.5 mr-1.5" />
</a>
<span class="text-xs text-gray-700">视频播放通过
<a
href="https://github.com/zhw2590582/ArtPlayer"
target="_blank"
rel="noopener noreferrer"
class="text-[#fb7299] font-medium hover:underline"
>
ArtPlayer
</a>
项目实现,感谢ArtPlayer团队的开源贡献
</span>
</div>
<Downloads />
</div>
<!-- 我的备注 -->
<div v-if="activeTab === 'remarks'" class="animate-fadeIn">
<History :defaultShowRemarks="true" />
</div>
<!-- 我的评论 -->
<div v-if="activeTab === 'comments'" class="animate-fadeIn">
<Comments />
</div>
<!-- 视频详情管理 -->
<div v-if="activeTab === 'details'" class="animate-fadeIn">
<VideoDetailsManager />
</div>
</div>
</div>
</div>
</div>
</div>
</template>
<script setup>
import { ref, onMounted, watch } from 'vue'
import { useRoute } from 'vue-router'
import Images from './Images.vue'
import Downloads from './Downloads.vue'
import VideoDetailsManager from './VideoDetailsManager.vue'
import History from './History.vue'
import Comments from './Comments.vue'
import DynamicDownloader from './DynamicDownloader.vue'
const route = useRoute()
// 当前激活的标签
const activeTab = ref('videos')
// 监听路由变化以更新激活的标签
watch(
() => route.query.tab,
(tab) => {
if (tab && ['images', 'videos', 'remarks', 'comments', 'details', 'dynamic'].includes(tab)) {
activeTab.value = tab
}
},
{ immediate: true }
)
// 组件挂载时根据URL初始化标签
onMounted(() => {
const { tab } = route.query
if (tab && ['images', 'videos', 'remarks', 'comments', 'details', 'dynamic'].includes(tab)) {
activeTab.value = tab
}
})
</script>
<style scoped>
.animate-fadeIn {
animation: fadeIn 0.3s ease-in-out;
}
@keyframes fadeIn {
from { opacity: 0; }
to { opacity: 1; }
}
</style>
|
2881099/FreeSql.AdminLTE
| 2,619
|
Examples/net60_preview/Entitys/Song.cs
|
using FreeSql.DataAnnotations;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
namespace net60_preview.Entitys
{
/// <summary>
/// 音乐
/// </summary>
public class Song
{
/// <summary>
/// 主键
/// </summary>
[Column(IsIdentity = true)]
public int Id { get; set; }
/// <summary>
/// 创建时间
/// </summary>
public DateTime? Create_time { get; set; }
/// <summary>
/// 软删除
/// </summary>
public bool? Is_deleted { get; set; }
/// <summary>
/// 标题
/// </summary>
public string Title { get; set; }
/// <summary>
/// 地址
/// </summary>
public string Url { get; set; }
[JsonIgnore] public ICollection<Tag> Tags { get; set; }
[Column(IsVersion = true)]
public long versionRow { get; set; }
}
public class Song_tag
{
public int Song_id { get; set; }
[JsonIgnore] public Song Song { get; set; }
public int Tag_id { get; set; }
[JsonIgnore] public Tag Tag { get; set; }
}
/// <summary>
/// 标签
/// </summary>
public class Tag
{
/// <summary>
/// 主键
/// </summary>
[Column(IsIdentity = true)]
public int Id { get; set; }
/// <summary>
/// 父id
/// </summary>
public int? Parent_id { get; set; }
[JsonIgnore] public Tag Parent { get; set; }
/// <summary>
/// 测试字段
/// </summary>
public decimal? Ddd { get; set; }
/// <summary>
/// 名字
/// </summary>
public string Name { get; set; }
[JsonIgnore] public ICollection<Song> Songs { get; set; }
[JsonIgnore] public ICollection<Tag> Tags { get; set; }
}
/// <summary>
/// 用户管理
/// </summary>
public class User
{
[Column(IsIdentity = true)]
public int Id { get; set; }
/// <summary>
/// 用户名
/// </summary>
public string Name { get; set; }
[JsonIgnore] public ICollection<UserImage> UserImages { get; set; }
}
/// <summary>
/// 用户图片
/// </summary>
public class UserImage
{
[Column(IsIdentity = true)]
public int Id { get; set; }
/// <summary>
/// Url地址
/// </summary>
public string Url { get; set; }
/// <summary>
/// 用户id
/// </summary>
public int User_id { get; set; }
[JsonIgnore] public User User { get; set; }
}
}
|
281677160/openwrt-package
| 5,433
|
luci-app-passwall2/luasrc/view/passwall2/app_update/app_version.htm
|
<%
local api = require "luci.passwall2.api"
local com = require "luci.passwall2.com"
local version = {}
-%>
<script type="text/javascript">
//<![CDATA[
var appInfoList = new Array();
var inProgressCount = 0;
var tokenStr = '<%=token%>';
var checkUpdateText = '<%:Check update%>';
var forceUpdateText = '<%:Force update%>';
var retryText = '<%:Retry%>';
var noUpdateText = '<%:It is the latest version%>';
var updateSuccessText = '<%:Update successful%>';
var clickToUpdateText = '<%:Click to update%>';
var inProgressText = '<%:Updating...%>';
var unexpectedErrorText = '<%:Unexpected error%>';
var updateInProgressNotice = '<%:Updating, are you sure to close?%>';
var downloadingText = '<%:Downloading...%>';
var decompressioningText = '<%:Unpacking...%>';
var movingText = '<%:Moving...%>';
//window.onload = function () {};
function addPageNotice() {
if (inProgressCount === 0) {
window.onbeforeunload = function (e) {
e.returnValue = updateInProgressNotice;
return updateInProgressNotice;
};
}
inProgressCount++;
}
function removePageNotice() {
inProgressCount--;
if (inProgressCount === 0) {
window.onbeforeunload = undefined;
}
}
function onUpdateSuccess(btn) {
if (btn) {
btn.value = updateSuccessText;
btn.placeholder = updateSuccessText;
btn.disabled = true;
}
if (inProgressCount === 0) {
window.setTimeout(function () {
window.location.reload();
}, 1000);
}
}
function onRequestError(btn, errorMessage) {
btn.disabled = false;
btn.value = retryText;
var ckeckDetailElm = document.getElementById(btn.id + '-detail');
if (errorMessage && ckeckDetailElm) {
ckeckDetailElm.textContent = errorMessage
}
}
function onBtnClick(btn, app) {
if (appInfoList[app] === undefined) {
checkUpdate(btn, app);
} else {
doUpdate(btn, app);
}
}
function checkUpdate(btn, app) {
btn.disabled = true;
btn.value = inProgressText;
addPageNotice();
var ckeckDetailElm = document.getElementById(btn.id + '-detail');
if (ckeckDetailElm) {
ckeckDetailElm.textContent = "";
}
XHR.get('<%=api.url("check_")%>' + app, {
token: tokenStr,
arch: ''
}, function (x, json) {
removePageNotice();
if (json.code) {
appInfoList[app] = undefined;
onRequestError(btn, json.error);
} else {
appInfoList[app] = json;
if (json.has_update) {
btn.disabled = false;
btn.value = clickToUpdateText;
btn.placeholder = clickToUpdateText;
if (ckeckDetailElm) {
var urlNode = '';
if (json.remote_version) {
urlNode = '<em style="color:red;">' + json.remote_version + '</em>';
if (json.html_url) {
urlNode = '<a href="' + json.html_url + '" target="_blank">' + urlNode + '</a>';
}
}
ckeckDetailElm.innerHTML = urlNode;
}
} else {
btn.disabled = true;
btn.value = noUpdateText;
window['_' + app + '-force_btn'].style.display = "inline";
}
}
}, 300);
}
function doUpdate(btn, app) {
btn.disabled = true;
btn.value = downloadingText;
addPageNotice();
var appUpdateUrl = '<%=api.url("update_")%>' + app;
var appInfo = appInfoList[app];
// Download file
XHR.get(appUpdateUrl, {
token: tokenStr,
url: appInfo ? appInfo.data.browser_download_url : '',
size: appInfo ? appInfo.data.size / 1024 : null
}, function (x, json) {
if (json.code) {
removePageNotice();
onRequestError(btn, json.error);
} else if (json.zip) {
btn.value = decompressioningText;
// Extract file
XHR.get(appUpdateUrl, {
token: tokenStr,
task: 'extract',
file: json.file,
subfix: appInfo ? appInfo.type : ''
}, function (x, json) {
if (json.code) {
removePageNotice();
onRequestError(btn, json.error);
} else {
move(btn, appUpdateUrl, json.file);
}
}, 300)
} else {
move(btn, appUpdateUrl, json.file);
}
}, 300)
}
function move(btn, url, file) {
btn.value = movingText;
// Move file to target dir
XHR.get(url, {
token: tokenStr,
task: 'move',
file: file
}, function (x, json) {
removePageNotice();
if (json.code) {
onRequestError(btn, json.error);
} else {
onUpdateSuccess(btn);
}
}, 300)
}
//]]>
</script>
<div class="cbi-value">
<label class="cbi-value-title">Passwall2 <%:Version%></label>
<div class="cbi-value-field">
<div class="cbi-value-description">
<span>【 <%=api.get_version()%> 】</span>
<input class="btn cbi-button cbi-button-apply" type="button" id="passwall2-check_btn"
onclick="onBtnClick(this,'passwall2');" value="<%:Check update%>" />
<span id="passwall2-check_btn-detail"></span>
</div>
</div>
</div>
<%for k, v in pairs(com) do
version[k] = api.get_app_version(k)%>
<div class="cbi-value">
<label class="cbi-value-title"><%=v.name%>
<%:Version%>
</label>
<div class="cbi-value-field">
<div class="cbi-value-description">
<span>【 <%=version[k] ~="" and version[k] or translate("Null") %> 】</span>
<input class="btn cbi-button cbi-button-apply" type="button" id="_<%=k%>-check_btn"
onclick="onBtnClick(this,'<%=k%>');" value="<%:Check update%>" />
<input class="btn cbi-button cbi-button-apply" type="button" id="_<%=k%>-force_btn"
onclick="doUpdate(this,'<%=k%>');" value="<%:Force update%>" style="display:none"/>
<span id="_<%=k%>-check_btn-detail"></span>
</div>
</div>
</div>
<%end%>
|
281677160/openwrt-package
| 1,343
|
luci-app-passwall2/luasrc/view/passwall2/socks_auto_switch/btn.htm
|
<%
local api = require "luci.passwall2.api"
-%>
<script type="text/javascript">
//<![CDATA[
let socks_id = window.location.pathname.substring(window.location.pathname.lastIndexOf("/") + 1)
function add_node_by_key() {
var key = prompt("<%:Please enter the node keyword, pay attention to distinguish between spaces, uppercase and lowercase.%>", "");
if (key) {
window.location.href = '<%=api.url("socks_autoswitch_add_node")%>' + "?id=" + socks_id + "&key=" + key;
}
}
function remove_node_by_key() {
var key = prompt("<%:Please enter the node keyword, pay attention to distinguish between spaces, uppercase and lowercase.%>", "");
if (key) {
window.location.href = '<%=api.url("socks_autoswitch_remove_node")%>' + "?id=" + socks_id + "&key=" + key;
}
}
//]]>
</script>
<div id="cbi-<%=self.config.."-"..section.."-"..self.option%>" data-index="<%=self.index%>" data-depends="<%=pcdata(self:deplist2json(section))%>">
<label class="cbi-value-title"></label>
<div class="cbi-value-field">
<input class="btn cbi-button cbi-button-add" type="button" onclick="add_node_by_key()" value="<%:Add nodes to the standby node list by keywords%>" />
<input class="btn cbi-button cbi-button-remove" type="button" onclick="remove_node_by_key()" value="<%:Delete nodes in the standby node list by keywords%>" />
</div>
</div>
|
294coder/Efficient-MIF
| 3,008
|
Pansharpening_Hyper_SR_Matlab_Test_Package/GS/GS.m
|
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Description:
% GS fuses the upsampled MultiSpectral (MS) and PANchromatic (PAN) images by
% exploiting the Gram-Schmidt (GS) transformation.
%
% Interface:
% I_Fus_GS = GS(I_MS,I_PAN)
%
% Inputs:
% I_MS: MS image upsampled at PAN scale;
% I_PAN: PAN image.
%
% Outputs:
% I_Fus_GS: GS pasharpened image.
%
% References:
% [Laben00] C. A. Laben and B. V. Brower, Process for enhancing the spatial resolution of multispectral imagery using pan-sharpening, Eastman
% Kodak Company, Tech. Rep. US Patent # 6,011,875, 2000.
% [Aiazzi07] B. Aiazzi, S. Baronti, and M. Selva, Improving component substitution Pansharpening through multivariate regression of MS+Pan
% data, IEEE Transactions on Geoscience and Remote Sensing, vol. 45, no. 10, pp. 32303239, October 2007.
% [Vivone15] G. Vivone, L. Alparone, J. Chanussot, M. Dalla Mura, A. Garzelli, G. Licciardi, R. Restaino, and L. Wald, A Critical Comparison Among Pansharpening Algorithms,
% IEEE Transactions on Geoscience and Remote Sensing, vol. 53, no. 5, pp. 25652586, May 2015.
% [Vivone20] G. Vivone, M. Dalla Mura, A. Garzelli, R. Restaino, G. Scarpa, M.O. Ulfarsson, L. Alparone, and J. Chanussot, "A New Benchmark Based on Recent Advances in Multispectral Pansharpening: Revisiting pansharpening with classical and emerging pansharpening methods",
% IEEE Geoscience and Remote Sensing Magazine, doi: 10.1109/MGRS.2020.3019315.
% % % % % % % % % % % % %
%
% Version: 1
%
% % % % % % % % % % % % %
%
% Copyright (C) 2019
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function I_Fus_GS = GS(I_MS,I_PAN)
imageLR = double(I_MS);
imageHR = double(I_PAN);
%%% Remove means from imageLR
imageLR0 = zeros(size(I_MS));
for ii = 1 : size(I_MS,3), imageLR0(:,:,ii) = imageLR(:,:,ii) - mean2(imageLR(:,:,ii)); end
%%% Intensity
I = mean(imageLR,3);
%%% Remove mean from I
I0 = I - mean2(I);
imageHR = (imageHR - mean2(imageHR)) .* (std2(I0)./std2(imageHR)) + mean2(I0);
%%% Coefficients
g = ones(1,1,size(I_MS,3)+1);
for ii = 1 : size(I_MS,3)
h = imageLR0(:,:,ii);
c = cov(I0(:),h(:));
g(1,1,ii+1) = c(1,2)/var(I0(:));
end
%%% Detail Extraction
delta = imageHR - I0;
deltam = repmat(delta(:),[1 size(I_MS,3)+1]);
%%% Fusion
V = I0(:);
for ii = 1 : size(I_MS,3)
h = imageLR0(:,:,ii);
V = cat(2,V,h(:));
end
gm = zeros(size(V));
for ii = 1 : size(g,3)
gm(:,ii) = squeeze(g(1,1,ii)) .* ones(size(I_MS,1).*size(I_MS,2),1);
end
V_hat = V + deltam .* gm;
%%% Reshape fusion result
I_Fus_GS = reshape(V_hat(:,2:end),[size(I_MS,1) size(I_MS,2) size(I_MS,3)]);
% Final Mean Equalization
for ii = 1 : size(I_MS,3)
h = I_Fus_GS(:,:,ii);
I_Fus_GS(:,:,ii) = h - mean2(h) + mean2(imageLR(:,:,ii));
end
end
|
294coder/Efficient-MIF
| 3,378
|
Pansharpening_Hyper_SR_Matlab_Test_Package/GS/GSA.m
|
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Description:
% GSA fuses the upsampled MultiSpectral (MS) and PANchromatic (PAN) images by
% exploiting the Gram-Schmidt Adaptive (GSA) algorithm.
%
% Interface:
% I_Fus_GSA = GSA(I_MS,I_PAN,I_MS_LR,ratio)
%
% Inputs:
% I_MS: MS image upsampled at PAN scale;
% I_PAN: PAN image;
% I_MS_LR: MS image;
% ratio: Scale ratio between MS and PAN. Pre-condition: Integer value.
%
% Outputs:
% I_Fus_GSA: GSA pasharpened image.
%
% References:
% [Aiazzi07] B. Aiazzi, S. Baronti, and M. Selva, Improving component substitution Pansharpening through multivariate regression of MS+Pan
% data, IEEE Transactions on Geoscience and Remote Sensing, vol. 45, no. 10, pp. 32303239, October 2007.
% [Vivone15] G. Vivone, L. Alparone, J. Chanussot, M. Dalla Mura, A. Garzelli, G. Licciardi, R. Restaino, and L. Wald, A Critical Comparison Among Pansharpening Algorithms,
% IEEE Transactions on Geoscience and Remote Sensing, vol. 53, no. 5, pp. 25652586, May 2015.
% [Vivone20] G. Vivone, M. Dalla Mura, A. Garzelli, R. Restaino, G. Scarpa, M.O. Ulfarsson, L. Alparone, and J. Chanussot, "A New Benchmark Based on Recent Advances in Multispectral Pansharpening: Revisiting pansharpening with classical and emerging pansharpening methods",
% IEEE Geoscience and Remote Sensing Magazine, doi: 10.1109/MGRS.2020.3019315.
% % % % % % % % % % % % %
%
% Version: 1
%
% % % % % % % % % % % % %
%
% Copyright (C) 2019
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function I_Fus_GSA = GSA(I_MS,I_PAN,I_MS_LR,ratio)
imageLR = double(I_MS);
imageHR = double(I_PAN);
imageLR_LP = double(I_MS_LR);
%%% Remove means from imageLR
imageLR0 = zeros(size(I_MS));
for ii = 1 : size(I_MS,3), imageLR0(:,:,ii) = imageLR(:,:,ii) - mean2(imageLR(:,:,ii)); end
%%% Remove means from imageLR_LP
imageLR_LP0 = zeros(size(I_MS_LR));
for ii = 1 : size(I_MS_LR,3), imageLR_LP0(:,:,ii) = imageLR_LP(:,:,ii) - mean2(imageLR_LP(:,:,ii)); end
%%% Intensity
imageHR0 = imageHR - mean2(imageHR);
imageHR0 = LPfilterPlusDec(imageHR0,ratio);
alpha(1,1,:) = estimation_alpha(cat(3,imageLR_LP0,ones(size(I_MS_LR,1),size(I_MS_LR,2))),imageHR0,'global');
I = sum(cat(3,imageLR0,ones(size(I_MS,1),size(I_MS,2))) .* repmat(alpha,[size(I_MS,1) size(I_MS,2) 1]),3);
%%% Remove mean from I
I0 = I - mean2(I);
%%% Coefficients
g = ones(1,1,size(I_MS,3)+1);
for ii = 1 : size(I_MS,3)
h = imageLR0(:,:,ii);
c = cov(I0(:),h(:));
g(1,1,ii+1) = c(1,2)/var(I0(:));
end
imageHR = imageHR - mean2(imageHR);
%%% Detail Extraction
delta = imageHR - I0;
deltam = repmat(delta(:),[1 size(I_MS,3)+1]);
%%% Fusion
V = I0(:);
for ii = 1 : size(I_MS,3)
h = imageLR0(:,:,ii);
V = cat(2,V,h(:));
end
gm = zeros(size(V));
for ii = 1 : size(g,3)
gm(:,ii) = squeeze(g(1,1,ii)) .* ones(size(I_MS,1).*size(I_MS,2),1);
end
V_hat = V + deltam .* gm;
%%% Reshape fusion result
I_Fus_GSA = reshape(V_hat(:,2:end),[size(I_MS,1) size(I_MS,2) size(I_MS,3)]);
%%% Final Mean Equalization
for ii = 1 : size(I_MS,3)
h = I_Fus_GSA(:,:,ii);
I_Fus_GSA(:,:,ii) = h - mean2(h) + mean2(imageLR(:,:,ii));
end
end
|
294coder/Efficient-MIF
| 2,313
|
Pansharpening_Hyper_SR_Matlab_Test_Package/GS/GS_Segm.m
|
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Description:
% GS_Segm fuses the upsampled MultiSpectral (MS) and PANchromatic (PAN) images by
% exploiting the segmentation-based version of the Gram-Schmidt algorithm.
%
% Interface:
% PanSharpenedImage = GS_Segm(I_MS,I_PAN,I_LR_input,S)
%
% Inputs:
% I_MS: MS image upsampled at PAN scale
% I_PAN: PAN image
% I_LR_input: Low Resolution PAN Image
% S: Segmentation
%
% Outputs:
% PanSharpenedImage: Pasharpened image
%
% Reference:
% [Restaino17] R. Restaino, M. Dalla Mura, G. Vivone, J. Chanussot, Context-Adaptive Pansharpening Based on Image Segmentation,
% IEEE Transactions on Geoscience and Remote Sensing, vol. 55, no. 2, pp. 753766, February 2017.
% [Vivone20] G. Vivone, M. Dalla Mura, A. Garzelli, R. Restaino, G. Scarpa, M.O. Ulfarsson, L. Alparone, and J. Chanussot, "A New Benchmark Based on Recent Advances in Multispectral Pansharpening: Revisiting pansharpening with classical and emerging pansharpening methods",
% IEEE Geoscience and Remote Sensing Magazine, doi: 10.1109/MGRS.2020.3019315.
% % % % % % % % % % % % %
%
% Version: 1
%
% % % % % % % % % % % % %
%
% Copyright (C) 2019
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function PanSharpenedImage = GS_Segm(I_MS,I_PAN,I_LR_input,S)
I_MS = double(I_MS);
I_PAN = repmat(double(I_PAN), [1, 1, size(I_MS,3)]);
I_LR_input = double(I_LR_input);
if size(I_LR_input, 3) == 1
I_LR_input = repmat(I_LR_input, [1, 1, size(I_MS,3)]);
end
if size(I_LR_input, 3) ~= size(I_PAN, 3)
error('I_LP should have the same number of bands as PAN');
end
DetailsHRPan = I_PAN - I_LR_input;
Coeff = zeros(size(I_MS));
labels = unique(S);
for ii = 1: size(I_MS,3)
MS_Band = squeeze(I_MS(:,:,ii));
I_LR_Band = squeeze(I_LR_input(:,:,ii));
Coeff_Band = zeros(size(I_LR_Band));
for il=1:length(labels)
idx = S==labels(il);
c = cov(I_LR_Band(idx),MS_Band(idx));
Coeff_Band(idx) = c(1,2)/var(I_LR_Band(idx));
end
Coeff(:,:,ii) = Coeff_Band;
end
PanSharpenedImage = Coeff .* DetailsHRPan + I_MS;
end
|
2977094657/BiliHistoryFrontend
| 39,154
|
src/components/tailwind/page/Favorites.vue
|
<!-- 收藏夹页面 -->
<template>
<div class="min-h-screen bg-gray-50/30">
<div class="py-6">
<div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
<!-- 主内容卡片 -->
<div class="bg-white rounded-lg overflow-hidden">
<!-- 标签导航 -->
<div class="border-b border-gray-200" v-if="!showFolderContents">
<nav class="-mb-px flex space-x-6 px-4 overflow-x-auto" aria-label="收藏夹选项卡">
<button
@click="activeTab = 'created'"
class="py-3 px-1 border-b-2 font-medium text-sm flex items-center space-x-2"
:class="activeTab === 'created'
? 'border-[#fb7299] text-[#fb7299]'
: 'border-transparent text-gray-500 hover:text-gray-700 hover:border-gray-300'"
>
<svg class="w-5 h-5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 13h6m-3-3v6m-9 1V7a2 2 0 012-2h6l2 2h6a2 2 0 012 2v8a2 2 0 01-2 2H5a2 2 0 01-2-2z" />
</svg>
<span>我创建的收藏夹</span>
</button>
<button
@click="activeTab = 'collected'"
class="py-3 px-1 border-b-2 font-medium text-sm flex items-center space-x-2"
:class="activeTab === 'collected'
? 'border-[#fb7299] text-[#fb7299]'
: 'border-transparent text-gray-500 hover:text-gray-700 hover:border-gray-300'"
>
<svg class="w-5 h-5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 5a2 2 0 012-2h10a2 2 0 012 2v16l-7-3.5L5 21V5z" />
</svg>
<span>我收藏的收藏夹</span>
</button>
<button
@click="activeTab = 'local'"
class="py-3 px-1 border-b-2 font-medium text-sm flex items-center space-x-2"
:class="activeTab === 'local'
? 'border-[#fb7299] text-[#fb7299]'
: 'border-transparent text-gray-500 hover:text-gray-700 hover:border-gray-300'"
>
<svg class="w-5 h-5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8 7H5a2 2 0 00-2 2v9a2 2 0 002 2h14a2 2 0 002-2V9a2 2 0 00-2-2h-3m-1 4l-3 3m0 0l-3-3m3 3V4" />
</svg>
<span>本地收藏夹</span>
</button>
</nav>
</div>
<!-- 文件夹内容标题栏 -->
<div class="border-b border-gray-200" v-if="showFolderContents">
<div class="flex items-center justify-between px-4 py-3">
<div class="flex items-center space-x-4">
<button
@click="backToFolderList"
class="p-1 rounded-full hover:bg-gray-100 transition-colors"
>
<svg class="w-5 h-5 text-gray-600" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M10 19l-7-7m0 0l7-7m-7 7h18" />
</svg>
</button>
<h2 class="text-lg font-medium truncate">{{ currentFolder?.title || '收藏夹内容' }}</h2>
</div>
<div class="flex items-center space-x-2">
<button
v-if="activeTab !== 'local'"
@click="fetchAllContents"
class="flex items-center px-3 py-1.5 text-xs text-gray-700 bg-gray-100 hover:bg-gray-200 rounded-md transition-colors"
:disabled="fetchingAll"
>
<svg class="w-3.5 h-3.5 mr-1" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-4l-4 4m0 0l-4-4m4 4V4" />
</svg>
<span>同步到本地</span>
</button>
</div>
</div>
</div>
<!-- 内容区域 -->
<div class="transition-all duration-300 p-5">
<!-- 全局提示信息 -->
<div class="mb-4 p-3 bg-amber-50 border border-amber-200 rounded-md text-amber-700 text-sm">
<div class="flex items-start">
<svg class="w-5 h-5 text-amber-500 mt-0.5 mr-2 flex-shrink-0" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z" />
</svg>
<div>
<p class="mt-1">用户收藏夹往往非常庞大,解析时很容易触发反爬机制。如遇该问题请稍等片刻后重试。(emmm,如果视频太多的话还是建议逐个收藏夹下载……)</p>
</div>
</div>
</div>
<!-- 收藏夹列表 -->
<div class="animate-fadeIn" v-if="!showFolderContents">
<!-- 收藏夹列表显示区域 -->
<div v-if="loading" class="flex justify-center py-20">
<div class="inline-flex items-center px-4 py-2 bg-white rounded-md shadow">
<svg class="animate-spin -ml-1 mr-3 h-5 w-5 text-[#fb7299]" fill="none" viewBox="0 0 24 24">
<circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
<path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
</svg>
<span>加载中...</span>
</div>
</div>
<div v-else-if="favorites.length === 0" class="text-center py-20">
<svg class="w-16 h-16 mx-auto text-gray-300" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 5a2 2 0 012-2h10a2 2 0 012 2v16l-7-3.5L5 21V5z" />
</svg>
<p class="mt-4 text-gray-500">暂无收藏夹</p>
<!-- 在线收藏夹(需要登录) -->
<template v-if="(activeTab === 'created' || activeTab === 'collected') && !isLoggedIn">
<p class="mt-2 text-sm text-gray-400">您需要登录B站账号才能查看收藏夹</p>
<button
@click="openLoginDialog"
class="mt-4 px-4 py-2 bg-[#fb7299] text-white rounded-md hover:bg-[#fb7299]/90 transition-colors"
>
登录账号
</button>
</template>
<!-- 已登录但没有收藏夹 -->
<template v-else-if="(activeTab === 'created' || activeTab === 'collected') && isLoggedIn">
<p class="mt-2 text-sm text-gray-400">
{{ activeTab === 'created' ? '您还没有创建过收藏夹' : '您还没有收藏任何收藏夹' }}
</p>
</template>
<!-- 本地收藏夹为空 -->
<template v-else-if="activeTab === 'local'">
<p class="mt-2 text-sm text-gray-400">您的本地数据库中没有保存的收藏夹</p>
</template>
</div>
<div v-else class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-4">
<!-- 收藏夹卡片 -->
<div
v-for="folder in favorites"
:key="folder.id || folder.media_id"
class="bg-white rounded-lg overflow-hidden shadow-sm hover:shadow-md transition-shadow border border-gray-200 flex flex-col"
>
<!-- 封面图 -->
<div class="relative aspect-video bg-gray-100 overflow-hidden">
<img
:src="normalizeImageUrl(folder.cover)"
:alt="folder.title"
class="w-full h-full object-cover transition-transform duration-300 hover:scale-105"
@click="viewFolderContents(folder)"
/>
<div class="absolute bottom-0 left-0 right-0 bg-gradient-to-t from-black/70 to-transparent p-2">
<p class="text-white text-sm font-medium truncate">{{ folder.title }}</p>
<div class="flex items-center mt-1">
<span class="text-white/80 text-xs">{{ folder.media_count }}个内容</span>
</div>
</div>
</div>
<!-- 收藏夹信息 -->
<div class="p-3 flex-1 flex flex-col">
<div class="flex items-start justify-between">
<div class="flex-1">
<h3
class="font-medium text-gray-900 hover:text-[#fb7299] transition-colors cursor-pointer"
@click="viewFolderContents(folder)"
>
{{ folder.title }}
</h3>
<p class="mt-1 text-xs text-gray-500 line-clamp-2">{{ folder.intro || '无简介' }}</p>
</div>
</div>
<div class="mt-3 pt-2 border-t border-gray-100 flex items-center justify-between">
<div class="flex items-center">
<img
:src="normalizeImageUrl(folder.upper?.face || folder.creator_face)"
:alt="folder.upper?.name || folder.creator_name"
class="w-5 h-5 rounded-full"
/>
<span class="ml-1.5 text-xs text-gray-600">{{ folder.upper?.name || folder.creator_name }}</span>
</div>
<div class="flex items-center space-x-2">
<button
v-if="activeTab !== 'local'"
@click="startDownloadFolder(folder)"
class="text-xs text-blue-500 hover:bg-blue-50 px-2 py-1 rounded transition-colors"
title="下载收藏夹中的视频"
>
<svg class="w-3.5 h-3.5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-4l-4 4m0 0l-4-4m4 4V4" />
</svg>
</button>
<button
@click="viewFolderContents(folder)"
class="text-xs text-[#fb7299] hover:bg-[#fb7299]/10 px-2 py-1 rounded transition-colors"
>
查看详情
</button>
</div>
</div>
</div>
</div>
</div>
<!-- 分页控件 -->
<div v-if="favorites.length > 0 && totalPages > 1" class="mt-6 flex justify-center">
<Pagination
:current-page="currentPage"
:total-pages="totalPages"
@page-change="handlePageChange"
/>
</div>
</div>
<!-- 收藏夹内容 -->
<div v-if="showFolderContents" class="animate-fadeIn">
<div v-if="loadingContents" class="flex justify-center py-20">
<div class="inline-flex items-center px-4 py-2 bg-white rounded-md shadow">
<svg class="animate-spin -ml-1 mr-3 h-5 w-5 text-[#fb7299]" fill="none" viewBox="0 0 24 24">
<circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
<path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
</svg>
<span>加载中...</span>
</div>
</div>
<div v-else-if="folderContents.length === 0" class="py-10 text-center">
<p class="text-gray-500">该收藏夹暂无内容</p>
</div>
<div v-else>
<!-- 收藏夹操作栏 -->
<div class="mb-4 flex flex-wrap justify-between items-center bg-white/70 p-3 rounded-lg shadow-sm">
<div class="flex items-center space-x-3">
<div class="text-sm text-gray-700">共 {{ contentsTotalItems }} 个内容</div>
<div v-if="invalidVideosCount > 0" class="text-sm text-red-500">
({{ invalidVideosCount }} 个失效)
</div>
</div>
<div class="flex items-center space-x-3 mt-2 sm:mt-0">
<button
v-if="activeTab !== 'local'"
@click="startDownloadFolder(currentFolder)"
class="flex items-center px-3 py-1.5 text-xs text-blue-600 bg-blue-50 hover:bg-blue-100 rounded-md transition-colors"
>
<svg class="w-3.5 h-3.5 mr-1" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-4l-4 4m0 0l-4-4m4 4V4" />
</svg>
<span>下载收藏夹</span>
</button>
</div>
</div>
<!-- 内容列表 - 网格布局 -->
<div class="grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-4 xl:grid-cols-5 gap-3">
<div
v-for="item in folderContents"
:key="item.id || item.bvid"
class="bg-white/50 backdrop-blur-sm rounded-md overflow-hidden border border-gray-200/50 hover:border-[#fb7299] hover:shadow-sm transition-all duration-200 relative group"
>
<!-- 视频封面 -->
<div class="relative pb-[56.25%] overflow-hidden cursor-pointer group" @click="openVideo(item)">
<img
:src="normalizeImageUrl(getVideoImage(item))"
:alt="getVideoTitle(item)"
class="absolute inset-0 w-full h-full object-cover group-hover:scale-105 transition-transform duration-300"
loading="lazy"
onerror="this.src='https://i0.hdslb.com/bfs/archive/c9e72655b7c9c9c68a30d3275313c501e68427d1.jpg'"
/>
<!-- 视频时长标签 -->
<div class="absolute bottom-1 right-1 bg-black/60 backdrop-blur-sm px-1 py-0.5 rounded text-white text-[10px]">
{{ formatDuration(item.duration) }}
</div>
</div>
<!-- 视频信息 -->
<div class="p-2 flex flex-col space-y-1">
<!-- 标题 -->
<div class="line-clamp-2 text-xs text-gray-900 font-medium cursor-pointer" @click="openVideo(item)">
{{ getVideoTitle(item) }}
</div>
<!-- 作者信息 -->
<div class="flex items-center space-x-1">
<img
:src="normalizeImageUrl(getAuthorFace(item))"
:alt="getAuthorName(item)"
class="w-3.5 h-3.5 rounded-full object-cover cursor-pointer"
loading="lazy"
onerror="this.src='https://i1.hdslb.com/bfs/face/1b6f746be0d0c8324e01e618c5e85e113a8b38be.jpg'"
@click.stop="openAuthorPage(item)"
/>
<span class="text-[10px] text-gray-600 truncate hover:text-[#fb7299] cursor-pointer" @click.stop="openAuthorPage(item)">
{{ getAuthorName(item) }}
</span>
</div>
<!-- 收藏时间 -->
<div class="flex justify-between items-center text-[10px] text-gray-500">
<div class="flex items-center space-x-1">
<svg class="w-2.5 h-2.5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8 7V3m8 4V3m-9 8h10M5 21h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v12a2 2 0 002 2z" />
</svg>
<span>收藏于: {{ formatTime(item.fav_time) }}</span>
</div>
</div>
</div>
</div>
</div>
<!-- 内容分页 -->
<div v-if="contentsTotalPages > 1" class="flex justify-center mt-6">
<Pagination
:current-page="contentsPage"
:total-pages="contentsTotalPages"
@page-change="handleContentsPageChange"
/>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<!-- 登录弹窗 -->
<LoginDialog
v-model:show="showLoginDialog"
@login-success="onLoginSuccess"
/>
<!-- 全屏加载遮罩 -->
<div v-if="fetchingAll" class="fixed inset-0 bg-black/40 backdrop-blur-md flex items-center justify-center z-50">
<div class="bg-white p-6 rounded-lg max-w-xs w-full shadow-xl text-center">
<svg class="animate-spin h-10 w-10 text-[#fb7299] mx-auto mb-4" fill="none" viewBox="0 0 24 24">
<circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
<path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
</svg>
<h3 class="text-lg font-medium mb-2">正在获取全部收藏内容</h3>
<p class="text-gray-600 mb-3">请耐心等待,这可能需要一些时间</p>
<div class="w-full bg-gray-200 rounded-full h-2.5 mb-3">
<div class="bg-[#fb7299] h-2.5 rounded-full" :style="{ width: `${fetchProgress}%` }"></div>
</div>
<p class="text-sm text-gray-700">已获取 {{ currentFetchPage }} / {{ totalFetchPages }} 页</p>
</div>
</div>
<!-- 使用DownloadDialog组件 -->
<DownloadDialog
v-model:show="showDownloadDialog"
:video-info="favoriteDownloadInfo"
@download-complete="handleDownloadComplete"
/>
</div>
</template>
<script setup>
import { ref, onMounted, computed, watch, onUnmounted } from 'vue'
import { useRouter } from 'vue-router'
import { showNotify } from 'vant'
import 'vant/es/notify/style'
import 'vant/es/dialog/style'
import Pagination from '../Pagination.vue'
import LoginDialog from '../LoginDialog.vue'
import DownloadDialog from '../DownloadDialog.vue'
import {
getCreatedFavoriteFolders,
getCollectedFavoriteFolders,
getLocalFavoriteFolders,
getFavoriteContents,
getLocalFavoriteContents,
getLoginStatus
} from '@/api/api.js'
import { openInBrowser } from '@/utils/openUrl.js'
import { normalizeImageUrl } from '@/utils/imageUrl.js'
const router = useRouter()
// 状态变量
const loading = ref(false)
const favorites = ref([])
const activeTab = ref('created')
const currentPage = ref(1)
const pageSize = ref(40)
const totalItems = ref(0)
const searchKeyword = ref('')
// 收藏夹内容状态
const showFolderContents = ref(false)
const currentFolder = ref(null)
const folderContents = ref([])
const loadingContents = ref(false)
const contentsPage = ref(1)
const contentsPageSize = ref(40)
const contentsTotalItems = ref(0)
// 登录弹窗状态
const showLoginDialog = ref(false)
// 已移除修复功能相关弹窗
// 登录状态
const isLoggedIn = ref(false)
const checkingLoginStatus = ref(false)
// 获取全部收藏夹内容相关状态
const fetchingAll = ref(false)
const currentFetchPage = ref(0)
const totalFetchPages = ref(0)
const fetchProgress = ref(0)
const allFetchedContents = ref([])
// 已移除修复状态与结果
// 计算总页数
const totalPages = computed(() => {
return Math.ceil(totalItems.value / pageSize.value)
})
// 计算内容总页数
const contentsTotalPages = computed(() => {
return Math.ceil(contentsTotalItems.value / contentsPageSize.value)
})
// 监听活动标签变化
watch(activeTab, () => {
currentPage.value = 1
fetchFavorites()
})
// 组件挂载时加载数据
onMounted(() => {
checkLoginStatus()
fetchFavorites()
// 添加全局登录状态变化的监听
window.addEventListener('login-status-changed', handleLoginStatusChange)
})
// 组件卸载时移除事件监听
onUnmounted(() => {
window.removeEventListener('login-status-changed', handleLoginStatusChange)
})
// 处理登录状态变化事件
function handleLoginStatusChange(event) {
console.log('收藏页面收到登录状态变化事件:', event.detail)
if (event.detail && typeof event.detail.isLoggedIn !== 'undefined') {
isLoggedIn.value = event.detail.isLoggedIn
if (isLoggedIn.value) {
// 如果登录状态变为已登录,重新获取收藏夹
fetchFavorites()
}
} else {
// 如果事件没有包含登录状态信息,则重新检查
checkLoginStatus()
}
}
// 检查登录状态
async function checkLoginStatus() {
checkingLoginStatus.value = true
try {
const response = await getLoginStatus()
console.log('获取登录状态响应:', response.data)
if (response.data && response.data.code === 0) {
isLoggedIn.value = response.data.data.isLogin
console.log('登录状态:', isLoggedIn.value)
} else {
console.warn('登录状态响应异常:', response.data)
isLoggedIn.value = false
}
} catch (error) {
console.error('获取登录状态失败:', error)
isLoggedIn.value = false
} finally {
checkingLoginStatus.value = false
}
}
// 获取收藏夹列表
async function fetchFavorites() {
loading.value = true
favorites.value = []
try {
let response
if (activeTab.value === 'created') {
response = await getCreatedFavoriteFolders({
keyword: searchKeyword.value || undefined
})
} else if (activeTab.value === 'collected') {
response = await getCollectedFavoriteFolders({
pn: currentPage.value,
ps: pageSize.value,
keyword: searchKeyword.value || undefined
})
} else if (activeTab.value === 'local') {
response = await getLocalFavoriteFolders({
page: currentPage.value,
size: pageSize.value
})
}
if (response.data.status === 'success') {
if (activeTab.value === 'created') {
favorites.value = response.data.data.list || []
totalItems.value = response.data.data.count || 0
} else if (activeTab.value === 'collected') {
favorites.value = response.data.data.list || []
totalItems.value = response.data.data.count || 0
} else if (activeTab.value === 'local') {
favorites.value = response.data.data.list || []
totalItems.value = response.data.data.total || 0
}
// 如果收藏夹没有封面,使用第一个视频的封面
for (const folder of favorites.value) {
if (!folder.cover || folder.cover.includes('nocover')) {
// 预加载第一个视频的封面
preloadFirstVideoCover(folder)
}
}
} else {
showNotify({ type: 'danger', message: response.data.message || '获取收藏夹失败' })
}
} catch (error) {
console.error('获取收藏夹出错:', error)
showNotify({ type: 'danger', message: '获取收藏夹出错: ' + (error.message || '未知错误') })
} finally {
loading.value = false
}
}
// 预加载收藏夹的第一个视频封面
async function preloadFirstVideoCover(folder) {
try {
const folderId = folder.id || folder.media_id
if (!folderId) return
let response
if (activeTab.value === 'local') {
response = await getLocalFavoriteContents({
media_id: folderId,
page: 1,
size: 1
})
} else {
// 对于线上收藏夹,直接获取收藏夹详细信息
response = await getFavoriteContents({
media_id: folderId,
pn: 1,
ps: 1
})
// 从响应中获取收藏夹详细信息
if (response.data.status === 'success' && response.data.data && response.data.data.info) {
// 更新收藏夹信息
const info = response.data.data.info
folder.title = info.title || folder.title
folder.cover = info.cover || folder.cover
folder.intro = info.intro || folder.intro
folder.media_count = info.media_count || folder.media_count
// 更新UP主信息
if (info.upper) {
folder.upper = info.upper
}
// 获取到了详细信息,无需继续处理
return
}
}
// 如果没有获取到详细信息或是本地收藏夹,则使用第一个视频的封面
if (response.data.status === 'success') {
let contents = []
if (activeTab.value === 'local') {
contents = response.data.data.list || []
} else if (response.data.data && response.data.data.medias) {
contents = response.data.data.medias || []
} else if (response.data.data && Array.isArray(response.data.data)) {
contents = response.data.data
}
if (contents.length > 0 && contents[0].cover) {
folder.cover = contents[0].cover
}
}
} catch (error) {
console.error('获取封面出错:', error)
}
}
// 查看收藏夹内容
async function viewFolderContents(folder) {
currentFolder.value = folder
showFolderContents.value = true
contentsPage.value = 1
folderContents.value = []
// 先加载内容
const contents = await loadContents()
console.log(`收藏夹[${folder.media_id || folder.id}]加载完成,共${contents.length}个视频`)
}
// 返回到收藏夹列表
function backToFolderList() {
showFolderContents.value = false
currentFolder.value = null
folderContents.value = []
}
// 加载收藏夹内容
async function loadContents() {
if (!currentFolder.value) return
loadingContents.value = true
folderContents.value = []
try {
let response
// 确保使用正确的收藏夹ID
const folderId = currentFolder.value.media_id || currentFolder.value.id
console.log(`开始加载收藏夹[${folderId}]第${contentsPage.value}页内容`)
if (activeTab.value === 'local') {
response = await getLocalFavoriteContents({
media_id: folderId,
page: contentsPage.value,
size: contentsPageSize.value
})
if (response.data.status === 'success') {
folderContents.value = response.data.data.list || []
contentsTotalItems.value = response.data.data.total || 0
console.log(`加载到本地收藏夹内容 ${folderContents.value.length} 条`)
} else {
console.error('本地收藏夹请求失败:', response.data)
showNotify({ type: 'danger', message: response.data.message || '获取本地收藏夹内容失败' })
}
} else {
console.log('发送在线收藏夹请求:', {
media_id: folderId,
pn: contentsPage.value,
ps: contentsPageSize.value
})
response = await getFavoriteContents({
media_id: folderId,
pn: contentsPage.value,
ps: contentsPageSize.value,
keyword: searchKeyword.value || undefined
})
console.log('收到在线收藏夹响应:', response.data)
if (response.data.status === 'success') {
// 更新收藏夹信息
if (response.data.data && response.data.data.info) {
const info = response.data.data.info
// 更新当前展示的收藏夹信息
currentFolder.value.title = info.title || currentFolder.value.title
currentFolder.value.cover = info.cover || currentFolder.value.cover
currentFolder.value.intro = info.intro || currentFolder.value.intro
currentFolder.value.media_count = info.media_count || currentFolder.value.media_count
// 更新UP主信息
if (info.upper) {
currentFolder.value.upper = info.upper
}
}
// 确保我们能够正确处理不同的数据结构
if (response.data.data && response.data.data.medias) {
console.log('找到媒体数据,数量:', response.data.data.medias.length)
folderContents.value = response.data.data.medias
contentsTotalItems.value = currentFolder.value.media_count || 0
} else if (response.data.data && Array.isArray(response.data.data)) {
console.log('找到数组数据,数量:', response.data.data.length)
folderContents.value = response.data.data
contentsTotalItems.value = response.data.total || currentFolder.value.media_count || 0
} else {
console.warn('收藏夹内容数据结构异常:', response.data)
folderContents.value = []
showNotify({ type: 'warning', message: '收藏夹数据结构异常,无法显示内容' })
}
// 确保至少更新了folderContents
if (folderContents.value.length === 0) {
console.warn('无法从响应中提取内容数据')
showNotify({ type: 'warning', message: '无法从响应中提取内容数据' })
}
} else {
console.error('在线收藏夹请求失败:', response.data)
showNotify({ type: 'danger', message: response.data.message || '获取收藏夹内容失败' })
}
}
} catch (error) {
console.error('获取收藏夹内容出错:', error)
showNotify({ type: 'danger', message: '获取收藏夹内容出错: ' + (error.message || '未知错误') })
} finally {
loadingContents.value = false
}
// 返回加载的内容,便于调用者使用
return folderContents.value
}
// 打开视频
async function openVideo(video) {
// 使用BV号或视频ID打开视频,跳转到B站
const videoId = video.bvid || video.id
if (videoId) {
// 在系统默认浏览器中打开B站视频链接
await openInBrowser(`https://www.bilibili.com/video/${videoId}`)
}
}
// 处理搜索
// 处理分页变化
function handlePageChange(page) {
currentPage.value = page
fetchFavorites()
}
// 处理内容分页变化
async function handleContentsPageChange(page) {
console.log(`切换到第${page}页内容`)
contentsPage.value = page
try {
// 等待内容加载完成
await loadContents()
} catch (error) {
console.error('分页处理出错:', error)
showNotify({
type: 'danger',
message: '分页处理出错: ' + (error.message || '未知错误')
})
}
}
// 打开登录对话框
function openLoginDialog() {
showLoginDialog.value = true
}
// 登录成功回调
function onLoginSuccess() {
isLoggedIn.value = true
showNotify({ type: 'success', message: '登录成功,正在获取收藏夹数据' })
fetchFavorites()
}
// 格式化时间戳为可读格式
function formatTime(timestamp) {
if (!timestamp) return '未知'
const date = new Date(timestamp * 1000)
return date.toLocaleDateString('zh-CN', {
year: 'numeric',
month: '2-digit',
day: '2-digit'
})
}
// 格式化视频时长
function formatDuration(seconds) {
if (!seconds) return '00:00'
const minutes = Math.floor(seconds / 60)
const remainingSeconds = seconds % 60
return `${minutes.toString().padStart(2, '0')}:${remainingSeconds.toString().padStart(2, '0')}`
}
// 获取作者头像
function getAuthorFace(item) {
// 首先检查upper对象
if (item.upper && item.upper.face) {
return item.upper.face
}
// 然后检查creator_face属性(本地数据结构)
else if (item.creator_face) {
return item.creator_face
}
// 再检查upper_mid关联的信息(本地数据可能有的另一种形式)
else if (item.upper_mid && typeof item.upper_mid === 'number') {
// 如果只有mid而没有头像,返回默认头像
return 'https://i1.hdslb.com/bfs/face/1b6f746be0d0c8324e01e618c5e85e113a8b38be.jpg'
}
// 最后返回默认头像
else {
return 'https://i1.hdslb.com/bfs/face/1b6f746be0d0c8324e01e618c5e85e113a8b38be.jpg'
}
}
// 获取作者名称
function getAuthorName(item) {
// 首先检查upper对象
if (item.upper && item.upper.name) {
return item.upper.name
}
// 然后检查creator_name属性(本地数据结构)
else if (item.creator_name) {
return item.creator_name
}
// 最后返回默认名称
else {
return '未知UP主'
}
}
// 获取视频是否有修复信息
// 已移除修复信息获取逻辑
// 获取全部收藏夹内容的函数,每页请求间隔1秒
async function fetchAllContents() {
if (!currentFolder.value || fetchingAll.value) return
fetchingAll.value = true
allFetchedContents.value = []
try {
// 获取收藏夹信息以确定总页数
const folderId = currentFolder.value.media_id || currentFolder.value.id
let firstPageResponse
let fetchApi
let processResponse
console.log('开始获取全部收藏内容,收藏夹ID:', folderId, '每页大小:', contentsPageSize.value)
if (activeTab.value === 'local') {
fetchApi = (page) => getLocalFavoriteContents({
media_id: folderId,
page: page,
size: contentsPageSize.value
})
processResponse = (response, page) => {
console.log(`处理本地收藏夹第${page}页响应:`, response.data)
if (response.data.status === 'success') {
return {
contents: response.data.data.list || [],
total: response.data.data.total || 0
}
}
return { contents: [], total: 0 }
}
} else {
fetchApi = (page) => {
console.log(`请求在线收藏夹第${page}页, 参数:`, {
media_id: folderId,
pn: page,
ps: contentsPageSize.value
})
return getFavoriteContents({
media_id: folderId,
pn: page,
ps: contentsPageSize.value
})
}
processResponse = (response, page) => {
console.log(`处理在线收藏夹第${page}页响应:`, response.data)
if (response.data.status === 'success') {
// 更新收藏夹信息
if (response.data.data && response.data.data.info && page === 1) {
const info = response.data.data.info
currentFolder.value.title = info.title || currentFolder.value.title
currentFolder.value.cover = info.cover || currentFolder.value.cover
currentFolder.value.intro = info.intro || currentFolder.value.intro
currentFolder.value.media_count = info.media_count || currentFolder.value.media_count
if (info.upper) {
currentFolder.value.upper = info.upper
}
}
// 处理多种可能的数据结构
if (response.data.data && response.data.data.medias) {
console.log(`第${page}页: 找到媒体数据,数量:`, response.data.data.medias.length)
return {
contents: response.data.data.medias,
total: currentFolder.value.media_count || 0
}
} else if (response.data.data && Array.isArray(response.data.data)) {
console.log(`第${page}页: 找到数组数据,数量:`, response.data.data.length)
return {
contents: response.data.data,
total: response.data.total || currentFolder.value.media_count || 0
}
} else {
console.warn(`第${page}页: 数据结构异常:`, response.data)
return { contents: [], total: currentFolder.value.media_count || 0 }
}
}
console.error(`第${page}页: 请求失败:`, response.data)
return { contents: [], total: 0 }
}
}
// 第一页请求,获取总数量信息
console.log('获取第1页数据...')
firstPageResponse = await fetchApi(1)
const result = processResponse(firstPageResponse, 1)
const total = result.total
console.log('首页数据获取完成,总数据条目:', total)
// 计算总页数
totalFetchPages.value = Math.ceil(total / contentsPageSize.value)
console.log('计算出总页数:', totalFetchPages.value)
currentFetchPage.value = 1
fetchProgress.value = (1 / totalFetchPages.value) * 100
// 添加第一页数据
allFetchedContents.value = [...allFetchedContents.value, ...result.contents]
// 如果只有一页,则完成
if (totalFetchPages.value <= 1) {
showNotify({ type: 'success', message: '收藏夹内容获取完成!' })
fetchingAll.value = false
folderContents.value = allFetchedContents.value
return
}
// 依次请求后续页面
for (let page = 2; page <= totalFetchPages.value; page++) {
console.log(`等待1秒后获取第${page}页数据...`)
// 等待1秒
await new Promise(resolve => setTimeout(resolve, 1000))
try {
console.log(`开始获取第${page}页数据`)
const response = await fetchApi(page)
const pageResult = processResponse(response, page)
// 添加本页数据
allFetchedContents.value = [...allFetchedContents.value, ...pageResult.contents]
// 更新进度
currentFetchPage.value = page
fetchProgress.value = (page / totalFetchPages.value) * 100
console.log(`第${page}页数据获取完成,当前进度: ${fetchProgress.value.toFixed(2)}%`)
} catch (error) {
console.error(`获取第${page}页出错:`, error)
showNotify({ type: 'warning', message: `获取第${page}页出错,将继续获取下一页: ${error.message}` })
}
}
// 完成后更新数据并通知
folderContents.value = allFetchedContents.value
console.log('所有页面获取完成,总共获取到', allFetchedContents.value.length, '条内容')
showNotify({
type: 'success',
message: `已获取全部${allFetchedContents.value.length}个收藏内容!`
})
} catch (error) {
console.error('获取全部收藏夹内容出错:', error)
showNotify({ type: 'danger', message: '获取收藏夹内容出错: ' + (error.message || '未知错误') })
} finally {
fetchingAll.value = false
}
}
// 获取视频封面,优先使用修复后的封面
function getVideoImage(video) {
// 检查video对象是否存在
if (!video) return ''
console.log('获取视频封面:', video.bvid || video.avid)
// 返回原始封面
return video.cover || ''
}
// 获取视频标题,优先使用修复后的标题
function getVideoTitle(video) {
// 检查video对象是否存在
if (!video) return '未知标题'
console.log('获取视频标题:', video.bvid || video.avid)
// 返回原始标题
return video.title || '未知标题'
}
// 判断视频是否正在修复
// 已移除修复中状态判断
// 打开UP主页面
function openAuthorPage(video) {
let upId = null;
// 已移除从修复结果提取UP主ID逻辑
// 然后检查视频本身的数据
if (!upId && video.upper_mid) {
upId = video.upper_mid
} else if (!upId && video.upper && video.upper.mid) {
upId = video.upper.mid
}
// 如果找到UP主ID,跳转到B站UP主页面
if (upId) {
window.open(`https://space.bilibili.com/${upId}`, '_blank')
} else {
showNotify({ type: 'warning', message: '无法获取UP主信息' })
}
}
// 下载相关状态
const showDownloadDialog = ref(false)
const favoriteDownloadInfo = ref({
title: '',
author: '',
bvid: '',
cover: '',
cid: 0
})
// 计算无效视频数量
const invalidVideosCount = computed(() => 0)
// 开始下载收藏夹
async function startDownloadFolder(folder) {
if (!folder) return;
// 检查登录状态
if (!isLoggedIn.value) {
showNotify({ type: 'warning', message: '请先登录B站账号' });
showLoginDialog.value = true;
return;
}
// 获取完整的收藏夹视频总数
try {
// 发起一次API请求获取视频总数,仅获取第一页第一条
const response = await getFavoriteContents({
media_id: folder.id || folder.media_id,
pn: 1,
ps: 1
});
if (response.data && response.data.status === 'success' && response.data.data) {
// 更新收藏夹信息
if (response.data.data.info) {
folder.media_count = response.data.data.info.media_count || response.data.data.total || folder.media_count;
} else if (response.data.data.total) {
folder.media_count = response.data.data.total;
}
console.log(`获取到收藏夹[${folder.title}]视频总数: ${folder.media_count}`);
}
} catch (error) {
console.error('获取收藏夹信息失败:', error);
}
// 设置要下载的收藏夹信息
favoriteDownloadInfo.value = {
title: `收藏夹: ${folder.title || '未命名收藏夹'}`,
author: folder.upper?.name || folder.creator_name || '未知创建者',
bvid: `fid_${(folder.id || folder.media_id || '').toString()}`, // 使用特殊格式标识这是收藏夹ID
cover: folder.cover || '',
cid: 0,
// 添加额外信息供下载组件使用
is_favorite_folder: true,
user_id: (folder.mid || folder.creator_mid || '').toString(),
fid: (folder.id || folder.media_id || '').toString(),
// 添加视频总数信息,帮助下载对话框显示正确的总数
total_videos: folder.media_count || 0
};
// 打开下载对话框
showDownloadDialog.value = true;
}
// 处理下载完成
function handleDownloadComplete() {
showNotify({ type: 'success', message: '收藏夹下载完成' });
}
</script>
<style scoped>
.animate-fadeIn {
animation: fadeIn 0.3s ease-in-out;
}
@keyframes fadeIn {
from { opacity: 0; }
to { opacity: 1; }
}
</style>
|
2977094657/BiliHistoryFrontend
| 5,846
|
src/components/tailwind/page/Search.vue
|
<template>
<div>
<!-- 搜索框和总数显示容器 -->
<div class="sticky top-0 bg-white lg:pt-4 z-50">
<div class="bg-white">
<div class="mx-auto max-w-4xl">
<!-- 使用SearchBar组件 -->
<SearchBar
:initial-keyword="keyword"
:initial-search-type="searchType"
@search="handleSearch"
/>
<!-- 显示总条数,和输入框左端对齐 -->
<p class="p-1.5 text-lg text-gray-700 lm:text-sm">
共 <span class="text-[#fb7299]">{{ totalResults }}</span> 条数据和
<span class="text-[#fb7299]">{{ keyword }}</span> 相关
</p>
</div>
</div>
</div>
<!-- 主要内容区域 -->
<div class="mx-auto max-w-7xl sm:px-2 lg:px-8">
<!-- 使用 key 来强制组件重新渲染 -->
<div :key="page">
<!-- 视频记录列表 -->
<VideoRecord
v-for="record in records"
:key="record.id"
:record="record"
:search-keyword="keyword"
:search-type="searchType"
:remark-data="remarkData"
@remark-updated="handleRemarkUpdate"
/>
</div>
<!-- 分页功能 -->
<div class="mb-5 mt-8">
<Pagination
v-model:current-page="page"
:total-pages="totalPages"
:use-routing="true"
@update:current-page="handlePageChange"
/>
</div>
</div>
</div>
</template>
<script setup>
import { onMounted, ref, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { searchBiliHistory2024, batchGetRemarks } from '../../../api/api.js'
import SearchBar from '../SearchBar.vue'
import VideoRecord from '../VideoRecord.vue'
import Pagination from '../Pagination.vue'
import { normalizeImageUrl } from '@/utils/imageUrl.js'
// 获取路由参数
const route = useRoute()
const router = useRouter()
// 状态变量
const records = ref([])
const page = ref(1)
const size = ref(30)
const totalPages = ref(0)
const totalResults = ref(0)
const remarkData = ref({}) // 存储备注数据
// 搜索相关变量
const keyword = ref('') // 初始化为空字符串
const searchType = ref('all') // 默认为全部搜索
// 处理搜索
const handleSearch = ({ keyword: searchKeyword, type }) => {
console.log('Search - 收到搜索事件:', { searchKeyword, type })
if (searchKeyword.trim()) {
keyword.value = searchKeyword.trim()
searchType.value = type
page.value = 1
router.push({
name: 'Search',
params: { keyword: searchKeyword.trim() },
query: {
type: type
}
})
fetchSearchResults()
}
}
// 处理页码变化
const handlePageChange = async (newPage) => {
if (newPage !== page.value) {
page.value = newPage
// 清空当前记录,避免显示旧数据
records.value = []
// 更新路由
if (newPage === 1) {
await router.push({
name: 'Search',
params: { keyword: keyword.value },
query: {
type: searchType.value
}
})
} else {
await router.push({
name: 'Search',
params: { keyword: keyword.value, pageNumber: newPage },
query: {
type: searchType.value
}
})
}
await fetchSearchResults()
}
}
// 获取搜索结果
const fetchSearchResults = async () => {
try {
// 从localStorage获取是否使用本地图片源的设置
const useLocalImages = localStorage.getItem('useLocalImages') === 'true'
const response = await searchBiliHistory2024(
keyword.value, // search
searchType.value, // searchType
page.value, // page
size.value, // size
useLocalImages // 使用本地图片源
)
if (response.data.status === 'success') {
records.value = response.data.data.records
totalPages.value = Math.ceil(response.data.data.total / size.value)
totalResults.value = response.data.data.total
// 批量获取备注
if (records.value.length > 0) {
const batchRecords = records.value.map(record => ({
bvid: record.bvid,
view_at: record.view_at
}))
const remarksResponse = await batchGetRemarks(batchRecords)
if (remarksResponse.data.status === 'success') {
remarkData.value = remarksResponse.data.data
}
}
}
} catch (error) {
console.error('搜索失败:', error)
}
}
// 处理备注更新
const handleRemarkUpdate = (data) => {
const key = `${data.bvid}_${data.view_at}`
remarkData.value[key] = {
bvid: data.bvid,
view_at: data.view_at,
remark: data.remark,
remark_time: data.remark_time
}
}
// 监听 keyword 变化
watch(
() => route.params.keyword,
(newKeyword) => {
if (newKeyword !== keyword.value) {
// 确保 keyword 是字符串类型
keyword.value = Array.isArray(newKeyword) ? newKeyword[0] : String(newKeyword)
page.value = 1
records.value = [] // 清空当前记录
fetchSearchResults()
}
}
)
// 监听页码变化
watch(
() => route.params.pageNumber,
async (newPage) => {
const pageNum = Number(newPage) || 1
if (pageNum !== page.value) {
page.value = pageNum
records.value = [] // 清空当前记录
await fetchSearchResults()
}
}
)
// 监听搜索类型变化
watch(
searchType,
(newType) => {
console.log('Search - 搜索类型变化:', newType)
if (keyword.value) { // 只有在有搜索关键词时才重新搜索
records.value = [] // 清空当前记录
router.push({
name: 'Search',
params: { keyword: keyword.value },
query: {
type: newType
}
})
fetchSearchResults()
}
}
)
// 组件挂载时获取数据
onMounted(async () => {
const typeFromQuery = String(route.query.type || '')
if (typeFromQuery) {
searchType.value = typeFromQuery
}
// 设置初始关键词
const initialKeyword = Array.isArray(route.params.keyword)
? route.params.keyword[0]
: String(route.params.keyword || '')
keyword.value = initialKeyword
// 从路由参数获取页码
page.value = Number(route.params.pageNumber || 1)
await fetchSearchResults()
})
</script>
<style scoped>
/* 移除之前的sticky样式 */
</style>
|
294coder/Efficient-MIF
| 3,565
|
Pansharpening_Hyper_SR_Matlab_Test_Package/GLP/MTF_GLP.m
|
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Description:
% MTF_GLP fuses the upsampled MultiSpectral (MS) and PANchromatic (PAN) images by
% exploiting the Modulation Transfer Function - Generalized Laplacian Pyramid (MTF-GLP) algorithm.
%
% Interface:
% I_Fus_MTF_GLP = MTF_GLP(I_MS,I_PAN,sensor,ratio)
%
% Inputs:
% I_MS: MS image upsampled at PAN scale;
% I_PAN: PAN image;
% sensor: String for type of sensor (e.g. 'WV2','IKONOS');
% ratio: Scale ratio between MS and PAN. Pre-condition: Integer value.
%
% Outputs:
% I_Fus_MTF_GLP: MTF_GLP pansharpened image.
%
% References:
% [Aiazzi02] B. Aiazzi, L. Alparone, S. Baronti, and A. Garzelli, Context-driven fusion of high spatial and spectral resolution images based on
% oversampled multiresolution analysis, IEEE Transactions on Geoscience and Remote Sensing, vol. 40, no. 10, pp. 23002312, October
% 2002.
% [Aiazzi06] B. Aiazzi, L. Alparone, S. Baronti, A. Garzelli, and M. Selva, MTF-tailored multiscale fusion of high-resolution MS and Pan imagery,
% Photogrammetric Engineering and Remote Sensing, vol. 72, no. 5, pp. 591596, May 2006.
% [Vivone14a] G. Vivone, R. Restaino, M. Dalla Mura, G. Licciardi, and J. Chanussot, Contrast and error-based fusion schemes for multispectral
% image pansharpening, IEEE Geoscience and Remote Sensing Letters, vol. 11, no. 5, pp. 930934, May 2014.
% [Vivone15a] G. Vivone, L. Alparone, J. Chanussot, M. Dalla Mura, A. Garzelli, G. Licciardi, R. Restaino, and L. Wald, A Critical Comparison Among Pansharpening Algorithms,
% IEEE Transactions on Geoscience and Remote Sensing, vol. 53, no. 5, pp. 25652586, May 2015.
% [Alparone17] L. Alparone, A. Garzelli, and G. Vivone, "Intersensor statistical matching for pansharpening: Theoretical issues and practical solutions",
% IEEE Transactions on Geoscience and Remote Sensing, vol. 55, no. 8, pp. 4682-4695, 2017.
% [Vivone20] G. Vivone, M. Dalla Mura, A. Garzelli, R. Restaino, G. Scarpa, M.O. Ulfarsson, L. Alparone, and J. Chanussot, "A New Benchmark Based on Recent Advances in Multispectral Pansharpening: Revisiting pansharpening with classical and emerging pansharpening methods",
% IEEE Geoscience and Remote Sensing Magazine, doi: 10.1109/MGRS.2020.3019315.
% % % % % % % % % % % % %
%
% Version: 2
%
% % % % % % % % % % % % %
%
% Copyright (C) 2019
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function I_Fus_MTF_GLP = MTF_GLP(I_MS,I_PAN,sensor,ratio)
imageHR = double(I_PAN);
I_MS = double(I_MS);
%%% Equalization
imageHR = repmat(imageHR,[1 1 size(I_MS,3)]);
for ii = 1 : size(I_MS,3)
imageHR(:,:,ii) = (imageHR(:,:,ii) - mean2(imageHR(:,:,ii))).*(std2(I_MS(:,:,ii))./std2(LPfilterGauss(imageHR(:,:,ii),ratio))) + mean2(I_MS(:,:,ii));
end
h = genMTF(ratio, sensor, size(I_MS,3));
PAN_LP = zeros(size(I_MS));
for ii = 1 : size(I_MS,3)
PAN_LP(:,:,ii) = imfilter(imageHR(:,:,ii),real(h(:,:,ii)),'replicate');
t = imresize(PAN_LP(:,:,ii),1/ratio,'nearest');
PAN_LP(:,:,ii) = interp23tap(t,ratio);
end
I_Fus_MTF_GLP = I_MS + imageHR - PAN_LP;
end
|
294coder/Efficient-MIF
| 2,352
|
Pansharpening_Hyper_SR_Matlab_Test_Package/GLP/MTF_GLP_FS.m
|
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Description:
% MTF_GLP_FS fuses the upsampled MultiSpectral (MS) and PANchromatic (PAN) images by
% exploiting the Modulation Transfer Function - Generalized Laplacian Pyramid (MTF-GLP) and a new Full Resolution Regression-based injection model.
%
% Interface:
% I_Fus_MTF_GLP_FS = MTF_GLP_FS(I_MS,I_PAN,sensor,ratio)
%
% Inputs:
% I_MS: MS image upsampled at PAN scale;
% I_PAN: PAN image;
% sensor: String for type of sensor (e.g. 'WV2','IKONOS');
% ratio: Scale ratio between MS and PAN. Pre-condition: Integer value.
%
% Outputs:
% I_Fus_MTF_GLP_FS: Pansharpened image.
%
% Reference:
% [Vivone18] G. Vivone, R. Restaino,and J. Chanussot, "Full scale regression-based injection coefficients for panchromatic sharpening,"
% IEEE Transactions on Image Processing, vol. 27, no. 7, pp. 3418-3431, Jul. 2018.
% [Vivone20] G. Vivone, M. Dalla Mura, A. Garzelli, R. Restaino, G. Scarpa, M.O. Ulfarsson, L. Alparone, and J. Chanussot, "A New Benchmark Based on Recent Advances in Multispectral Pansharpening: Revisiting pansharpening with classical and emerging pansharpening methods",
% IEEE Geoscience and Remote Sensing Magazine, doi: 10.1109/MGRS.2020.3019315.
% % % % % % % % % % % % %
%
% Version: 1
%
% % % % % % % % % % % % %
%
% Copyright (C) 2019
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function I_Fus_MTF_GLP_FS = MTF_GLP_FS(I_MS,I_PAN,sensor,ratio)
imageHR = double(I_PAN);
I_MS = double(I_MS);
h = genMTF(ratio, sensor, size(I_MS,3));
I_Fus_MTF_GLP_FS = zeros(size(I_MS));
for ii = 1 : size(I_MS,3)
%%% Low resolution PAN image
PAN_LP = imfilter(imageHR,real(h(:,:,ii)),'replicate');
t = imresize(PAN_LP,1/ratio,'nearest');
PAN_LP = interp23tap(t,ratio);
%%% Injection coefficient for band ii
MSB = I_MS(:,:,ii);
CMSPAN = cov(MSB(:), imageHR(:));
CPANPANLR = cov(PAN_LP(:), imageHR(:));
gFS = CMSPAN(1,2)./CPANPANLR(1,2);
%%% Fusion rule
I_Fus_MTF_GLP_FS(:,:,ii) = I_MS(:,:,ii) + gFS .* (imageHR - PAN_LP);
end
end
|
294coder/Efficient-MIF
| 3,073
|
Pansharpening_Hyper_SR_Matlab_Test_Package/GLP/GS2_GLP.m
|
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Description:
% GS2_GLP fuses the upsampled MultiSpectral (MS) and PANchromatic (PAN) images by
% exploiting the Gram-Schmidt (GS) mode 2 algorithm with Generalized Laplacian Pyramid (GLP) decomposition.
%
% Interface:
% I_Fus_GS2_GLP = GS2_GLP(I_MS,I_PAN,ratio,sensor)
%
% Inputs:
% I_MS: MS image upsampled at PAN scale;
% I_PAN: PAN image;
% ratio: Scale ratio between MS and PAN. Pre-condition: Integer value;
% sensor: String for type of sensor (e.g. 'WV2','IKONOS').
%
% Outputs:
% I_Fus_GS2_GLP: GS2_GLP pasharpened image.
%
% References:
% [Aiazzi06] B. Aiazzi, L. Alparone, S. Baronti, A. Garzelli, and M. Selva, MTF-tailored multiscale fusion of high-resolution MS and Pan imagery,
% Photogrammetric Engineering and Remote Sensing, vol. 72, no. 5, pp. 591596, May 2006.
% [Alparone07] L. Alparone, L. Wald, J. Chanussot, C. Thomas, P. Gamba, and L. M. Bruce, Comparison of pansharpening algorithms: Outcome
% of the 2006 GRS-S Data Fusion Contest, IEEE Transactions on Geoscience and Remote Sensing, vol. 45, no. 10, pp. 30123021,
% October 2007.
% [Vivone15] G. Vivone, L. Alparone, J. Chanussot, M. Dalla Mura, A. Garzelli, G. Licciardi, R. Restaino, and L. Wald, A Critical Comparison Among Pansharpening Algorithms,
% IEEE Transactions on Geoscience and Remote Sensing, vol. 53, no. 5, pp. 25652586, May 2015.
% [Vivone20] G. Vivone, M. Dalla Mura, A. Garzelli, R. Restaino, G. Scarpa, M.O. Ulfarsson, L. Alparone, and J. Chanussot, "A New Benchmark Based on Recent Advances in Multispectral Pansharpening: Revisiting pansharpening with classical and emerging pansharpening methods",
% IEEE Geoscience and Remote Sensing Magazine, doi: 10.1109/MGRS.2020.3019315.
% % % % % % % % % % % % %
%
% Version: 1
%
% % % % % % % % % % % % %
%
% Copyright (C) 2019
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function I_Fus_GS2_GLP = GS2_GLP(I_MS,I_PAN,ratio,sensor)
imageLR = double(I_MS);
imageHR = double(I_PAN);
imageHR = repmat(imageHR,[1 1 size(imageLR,3)]);
h = genMTF(ratio, sensor, size(I_MS,3));
PAN_LP = zeros(size(I_MS));
for ii = 1 : size(I_MS,3)
PAN_LP(:,:,ii) = imfilter(imageHR(:,:,ii),real(h(:,:,ii)),'replicate');
t = imresize(PAN_LP(:,:,ii),1/ratio,'nearest');
PAN_LP(:,:,ii) = interp23tap(t,ratio);
end
PAN_LP = double(PAN_LP);
%%% Coefficients
g = ones(1,size(I_MS,3));
for ii = 1 : size(I_MS,3)
h = imageLR(:,:,ii);
h2 = PAN_LP(:,:,ii);
c = cov(h2(:),h(:));
g(ii) = c(1,2)/var(h2(:));
end
%%% Detail Extraction
delta = imageHR - PAN_LP;
I_Fus_GS2_GLP = zeros(size(imageLR));
for ii = 1 : size(imageLR,3)
I_Fus_GS2_GLP(:,:,ii) = imageLR(:,:,ii) + delta(:,:,ii) .* g(ii);
end
end
|
294coder/Efficient-MIF
| 3,085
|
Pansharpening_Hyper_SR_Matlab_Test_Package/GLP/MTF_GLP_HPM_Haze_min.m
|
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Description:
% Gaussian Laplacian Pyramid with high pass modulation injection model haze corrected.
%
% Interface:
% I_Fus_MTF_GLP_HPM = MTF_GLP_HPM_Haze_min(I_PAN,I_MS,sensor,ratio,decimation)
%
% Inputs:
% I_MS: MS image upsampled at PAN scale;
% I_PAN: PAN image;
% sensor: String for type of sensor (e.g. 'WV2','IKONOS');
% ratio: Scale ratio between MS and PAN. Pre-condition: Integer value;
% decimation: Flag decimation (1: decimated PAN_LP).
%
% Outputs:
% I_Fus_MTF_GLP_HPM: Pansharpened image.
%
% References:
% [Lolli17] S. Lolli, L. Alparone, A. Garzelli, and G. Vivone, "Haze correction for contrast-based multispectral pansharpening",
% IEEE Geoscience and Remote Sensing Letters, vol. 14, no. 12, pp. 2255-2259, 2017.
% [Garzelli18] A. Garzelli, B. Aiazzi, L. Alparone, S. Lolli, and G. Vivone,
% "Multispectral Pansharpening with Radiative Transfer-Based Detail-Injection Modeling for Preserving Changes in Vegetation Cover",
% MDPI Remote Sensing, vol. 10, no. 8, pp. 1 - 18, 2018.
% [Vivone20] G. Vivone, M. Dalla Mura, A. Garzelli, R. Restaino, G. Scarpa, M.O. Ulfarsson, L. Alparone, and J. Chanussot, "A New Benchmark Based on Recent Advances in Multispectral Pansharpening: Revisiting pansharpening with classical and emerging pansharpening methods",
% IEEE Geoscience and Remote Sensing Magazine, doi: 10.1109/MGRS.2020.3019315.
% % % % % % % % % % % % %
%
% Version: 1
%
% % % % % % % % % % % % %
%
% Copyright (C) 2019
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function I_Fus_MTF_GLP_HPM = MTF_GLP_HPM_Haze_min(I_MS,I_PAN,sensor,ratio,decimation)
if size(I_MS,3) == 4
prc = 1;
minMS = zeros(1,1,4);
B = I_MS(:,:,1);
G = I_MS(:,:,2);
R = I_MS(:,:,3);
NIR = I_MS(:,:,4);
minMS(1,1,1) = 0.95 * prctile(B(:),prc);
minMS(1,1,2) = 0.45 * prctile(G(:),prc);
minMS(1,1,3) = 0.40 * prctile(R(:),prc);
minMS(1,1,4) = 0.05 * prctile(NIR(:),prc);
else
minMS = zeros(1,1,size(I_MS,3));
for ii = 1 : size(I_MS, 3)
minMS(1,1,ii) = min(min(I_MS(:,:,ii)));
end
end
I_PAN_LR = LPfilterGauss(I_PAN,ratio);
w = estimation_alpha(cat(3,ones(size(I_PAN_LR)),I_MS),I_PAN_LR,'global');
wp = w' * [1;squeeze(minMS)];
L = repmat(minMS, [size(I_MS,1) size(I_MS,2)]);
Lp = wp .* ones([size(I_MS,1) size(I_MS,2)]);
imageHR = double(I_PAN);
I_MS = double(I_MS);
%%% Equalization
imageHR = repmat(imageHR,[1 1 size(I_MS,3)]);
PAN_LP = MTF(imageHR,sensor,ratio);
if decimation
for ii = 1 : size(I_MS,3)
t = imresize(PAN_LP(:,:,ii),1/ratio,'nearest');
PAN_LP(:,:,ii) = interp23tap(t,ratio);
end
end
P_PL = (imageHR - Lp) ./ (PAN_LP - Lp + eps);
MS_L = I_MS - L;
I_Fus_MTF_GLP_HPM = MS_L .* P_PL + L;
end
|
294coder/Efficient-MIF
| 3,706
|
Pansharpening_Hyper_SR_Matlab_Test_Package/GLP/MTF_GLP_HPM.m
|
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Description:
% MTF_GLP_HPM fuses the upsampled MultiSpectral (MS) and PANchromatic (PAN) images by
% exploiting the Modulation Transfer Function - Generalized Laplacian Pyramid (MTF-GLP) with High Pass Modulation (HPM) injection model algorithm.
%
% Interface:
% I_Fus_MTF_GLP_HPM = MTF_GLP_HPM(I_MS,I_PAN,sensor,ratio)
%
% Inputs:
% I_MS: MS image upsampled at PAN scale;
% I_PAN: PAN image;
% sensor: String for type of sensor (e.g. 'WV2','IKONOS');
% ratio: Scale ratio between MS and PAN. Pre-condition: Integer value.
%
% Outputs:
% I_Fus_MTF_GLP_HPM: MTF_GLP_HPM pansharpened image.
%
% References:
% [Aiazzi03] B. Aiazzi, L. Alparone, S. Baronti, A. Garzelli, and M. Selva, An MTF-based spectral distortion minimizing model for Pan-sharpening
% of very high resolution multispectral images of urban areas, in Proceedings of URBAN 2003: 2nd GRSS/ISPRS Joint Workshop on
% Remote Sensing and Data Fusion over Urban Areas, 2003, pp. 9094.
% [Aiazzi06] B. Aiazzi, L. Alparone, S. Baronti, A. Garzelli, and M. Selva, MTF-tailored multiscale fusion of high-resolution MS and Pan imagery,
% Photogrammetric Engineering and Remote Sensing, vol. 72, no. 5, pp. 591596, May 2006.
% [Vivone14a] G. Vivone, R. Restaino, M. Dalla Mura, G. Licciardi, and J. Chanussot, Contrast and error-based fusion schemes for multispectral
% image pansharpening, IEEE Geoscience and Remote Sensing Letters, vol. 11, no. 5, pp. 930934, May 2014.
% [Vivone15] G. Vivone, L. Alparone, J. Chanussot, M. Dalla Mura, A. Garzelli, G. Licciardi, R. Restaino, and L. Wald, A Critical Comparison Among Pansharpening Algorithms,
% IEEE Transactions on Geoscience and Remote Sensing, vol. 53, no. 5, pp. 25652586, May 2015.
% [Alparone17] L. Alparone, A. Garzelli, and G. Vivone, "Intersensor statistical matching for pansharpening: Theoretical issues and practical solutions",
% IEEE Transactions on Geoscience and Remote Sensing, vol. 55, no. 8, pp. 4682-4695, 2017.
% [Vivone20] G. Vivone, M. Dalla Mura, A. Garzelli, R. Restaino, G. Scarpa, M.O. Ulfarsson, L. Alparone, and J. Chanussot, "A New Benchmark Based on Recent Advances in Multispectral Pansharpening: Revisiting pansharpening with classical and emerging pansharpening methods",
% IEEE Geoscience and Remote Sensing Magazine, doi: 10.1109/MGRS.2020.3019315.
% % % % % % % % % % % % %
%
% Version: 1
%
% % % % % % % % % % % % %
%
% Copyright (C) 2019
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function I_Fus_MTF_GLP_HPM = MTF_GLP_HPM(I_MS,I_PAN,sensor,ratio)
imageHR = double(I_PAN);
I_MS = double(I_MS);
%%% Equalization
imageHR = repmat(imageHR,[1 1 size(I_MS,3)]);
for ii = 1 : size(I_MS,3)
imageHR(:,:,ii) = (imageHR(:,:,ii) - mean2(imageHR(:,:,ii))).*(std2(I_MS(:,:,ii))./std2(LPfilterGauss(imageHR(:,:,ii),ratio))) + mean2(I_MS(:,:,ii));
end
h = genMTF(ratio, sensor, size(I_MS,3));
PAN_LP = zeros(size(I_MS));
for ii = 1 : size(I_MS,3)
PAN_LP(:,:,ii) = imfilter(imageHR(:,:,ii),real(h(:,:,ii)),'replicate');
t = imresize(PAN_LP(:,:,ii),1/ratio,'nearest');
PAN_LP(:,:,ii) = interp23tap(t,ratio);
end
I_Fus_MTF_GLP_HPM = I_MS .* (imageHR ./ (PAN_LP + eps));
end
|
2881099/FreeSql.AdminLTE
| 1,093
|
Examples/net80_blazor/Admin/App.razor
|
<!DOCTYPE html>
<html lang="zh-cn">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<base href="/" />
<link rel="stylesheet" href="AdminLTE-3.2.0/plugins/fontawesome-free/css/all.min.css">
<link rel="stylesheet" href="AdminLTE-3.2.0/plugins/toastr/toastr.min.css">
<link rel="stylesheet" href="AdminLTE-3.2.0/dist/css/adminlte.min.css">
<link rel="stylesheet" href="net80_blazor.styles.css" />
<HeadOutlet @rendermode="@InteractiveServer" />
</head>
<body class="hold-transition sidebar-mini">
<Routes @rendermode="@InteractiveServer" />
<script src="AdminLTE-3.2.0/plugins/jquery/jquery.min.js"></script>
<script src="AdminLTE-3.2.0/plugins/bootstrap/js/bootstrap.bundle.min.js"></script>
<script src="AdminLTE-3.2.0/plugins/toastr/toastr.min.js"></script>
<script src="AdminLTE-3.2.0/plugins/sweetalert2/sweetalert2.all.min.js"></script>
<script src="AdminLTE-3.2.0/dist/js/adminlte.min.js"></script>
<script src="_framework/blazor.web.js"></script>
</body>
</html>
|
2977094657/BiliHistoryFrontend
| 10,181
|
src/components/tailwind/page/Remarks.vue
|
<template>
<div>
<!-- 页面标题 -->
<div class="flex items-center justify-between mb-8">
<div class="flex items-center space-x-3 text-gray-900">
<svg class="w-7 h-7 text-[#fb7299]" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z" />
</svg>
<h1 class="text-2xl font-medium">我的备注</h1>
</div>
<div class="text-sm text-gray-500">
共 {{ total }} 条备注
</div>
</div>
<!-- 备注列表 -->
<div v-if="remarkRecords.length > 0" class="grid grid-cols-1 gap-6">
<div v-for="record in remarkRecords"
:key="record.bvid + record.view_at"
class="bg-white rounded-lg shadow-sm hover:shadow-md transition-all duration-300">
<div class="flex p-4 space-x-6">
<!-- 左侧:视频信息 -->
<div class="w-64 flex-shrink-0">
<!-- 视频封面 -->
<div class="relative w-full aspect-video overflow-hidden rounded-lg mb-3">
<img
:src="normalizeImageUrl(record.cover)"
:class="{ 'blur-md': isPrivacyMode }"
class="w-full h-full object-cover"
alt=""
/>
<!-- 视频时长 -->
<div class="absolute bottom-2 right-2 bg-black/70 text-white text-xs px-2 py-1 rounded">
{{ formatDuration(record.duration) }}
</div>
<!-- 观看进度条 -->
<div class="absolute bottom-0 left-0 w-full h-1 bg-gray-200">
<div
class="h-full bg-[#fb7299]"
:style="{ width: getProgressWidth(record.progress, record.duration) }"
></div>
</div>
</div>
<!-- 视频标题 -->
<h3 class="text-sm font-medium text-gray-900 mb-2 line-clamp-2 hover:line-clamp-none"
:class="{ 'blur-sm': isPrivacyMode }"
v-html="isPrivacyMode ? '******' : record.title">
</h3>
<!-- UP主信息和时间 -->
<div class="flex items-center space-x-2 mb-2">
<img
:src="normalizeImageUrl(record.author_face)"
:class="{ 'blur-md': isPrivacyMode }"
class="w-4 h-4 rounded-full"
alt=""
/>
<span class="text-xs text-gray-600"
:class="{ 'blur-sm': isPrivacyMode }"
v-text="isPrivacyMode ? '******' : record.author_name">
</span>
</div>
<div class="flex items-center justify-between text-xs text-gray-400">
<span>{{ formatTimestamp(record.view_at) }}</span>
<button
@click="openVideo(record)"
class="inline-flex items-center space-x-1 text-[#fb7299] hover:text-[#fb7299]/80 transition-colors duration-200"
>
<svg class="w-3 h-3" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M14.752 11.168l-3.197-2.132A1 1 0 0010 9.87v4.263a1 1 0 001.555.832l3.197-2.132a1 1 0 000-1.664z" />
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
</svg>
<span>查看视频</span>
</button>
</div>
</div>
<!-- 右侧:备注内容 -->
<div class="flex-1 min-w-0 relative">
<van-field
v-model="record.remark"
:disabled="isPrivacyMode"
@blur="handleRemarkUpdate(record)"
type="textarea"
rows="8"
:autosize="{ minHeight: 160 }"
:placeholder="'添加备注...'"
class="remarks-field !bg-transparent"
/>
<div v-if="record.remark_time" class="absolute bottom-1 right-2 text-xs text-gray-400">
最后更新: {{ formatRemarkTime(record.remark_time) }}
</div>
</div>
</div>
</div>
</div>
<!-- 空状态显示 -->
<div v-else class="flex flex-col items-center justify-center py-16 bg-white rounded-lg">
<svg class="w-20 h-20 text-gray-300 mb-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.5" d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z" />
</svg>
<h3 class="text-xl font-medium text-gray-600 mb-2">暂无备注</h3>
<p class="text-gray-500 mb-6">当你添加备注后,将在这里显示</p>
<button
class="px-4 py-2 bg-[#fb7299] text-white rounded-md hover:bg-[#fb7299]/90 transition-colors duration-200 flex items-center space-x-2"
@click="$router.push('/')">
<svg class="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 19l-7-7 7-7" />
</svg>
<span>返回视频列表</span>
</button>
</div>
<!-- 分页组件 -->
<div v-if="remarkRecords.length > 0" class="mt-8">
<Pagination
:current-page="page"
:total-pages="totalPages"
:use-routing="false"
@page-change="handlePageChange"
/>
</div>
</div>
</template>
<script setup>
import { ref, onMounted } from 'vue'
import { usePrivacyStore } from '../../../store/privacy'
import { getAllRemarks, updateVideoRemark, batchGetRemarks } from '../../../api/api'
import { showNotify } from 'vant'
import Pagination from '../Pagination.vue'
import { normalizeImageUrl } from '@/utils/imageUrl.js'
const { isPrivacyMode } = usePrivacyStore()
// 状态管理
const page = ref(1)
const totalPages = ref(1)
const total = ref(0)
const remarkRecords = ref([])
// 获取备注列表
const fetchRemarks = async () => {
try {
const response = await getAllRemarks(page.value, 12) // 每页显示12条
if (response.data.status === 'success') {
const records = response.data.data.records
// 构建批量查询请求
const batchRecords = records.map(record => ({
bvid: record.bvid,
view_at: record.view_at
}))
// 批量获取备注信息
const remarksResponse = await batchGetRemarks(batchRecords)
if (remarksResponse.data.status === 'success') {
remarkRecords.value = records.map(record => {
const key = `${record.bvid}_${record.view_at}`
const remarkData = remarksResponse.data.data[key] || {}
return {
...record,
remark: remarkData.remark || '',
remark_time: remarkData.remark_time,
originalRemark: remarkData.remark || '' // 保存原始备注内容
}
})
}
totalPages.value = Math.ceil(response.data.data.total / response.data.data.size)
total.value = response.data.data.total
} else {
throw new Error(response.data.message || '获取备注列表失败')
}
} catch (error) {
showNotify({
type: 'danger',
message: error.message
})
}
}
// 处理分页变化
const handlePageChange = (newPage) => {
page.value = newPage
fetchRemarks()
}
// 打开视频
const openVideo = (record) => {
const url = `https://www.bilibili.com/video/${record.bvid}`
window.open(url, '_blank')
}
// 格式化时间戳
const formatTimestamp = (timestamp) => {
const date = new Date(timestamp * 1000)
return date.toLocaleString('zh-CN', {
year: 'numeric',
month: '2-digit',
day: '2-digit',
hour: '2-digit',
minute: '2-digit'
})
}
// 格式化时长
const formatDuration = (seconds) => {
if (seconds === -1) return '已看完'
const minutes = String(Math.floor(seconds / 60)).padStart(2, '0')
const secs = String(seconds % 60).padStart(2, '0')
return `${minutes}:${secs}`
}
// 获取进度条宽度
const getProgressWidth = (progress, duration) => {
if (progress === -1) return '100%'
if (duration === 0) return '0%'
return `${(progress / duration) * 100}%`
}
// 格式化备注时间
const formatRemarkTime = (timestamp) => {
if (!timestamp) return ''
const date = new Date(timestamp * 1000)
return date.toLocaleString('zh-CN', {
year: 'numeric',
month: '2-digit',
day: '2-digit',
hour: '2-digit',
minute: '2-digit'
})
}
// 处理备注更新
const handleRemarkUpdate = async (record) => {
const newValue = record.remark
if (newValue === record.originalRemark) return
try {
const response = await updateVideoRemark(
record.bvid,
record.view_at,
newValue
)
if (response.data.status === 'success') {
record.originalRemark = newValue
record.remark_time = response.data.data.remark_time // 更新备注时间
showNotify({
type: 'success',
message: '备注已更新'
})
} else {
throw new Error(response.data.message)
}
} catch (error) {
showNotify({
type: 'danger',
message: error.message
})
// 恢复原值
record.remark = record.originalRemark
}
}
// 组件挂载时获取数据
onMounted(() => {
fetchRemarks()
})
// 默认导出
defineOptions({
name: 'Remarks'
})
</script>
<style scoped>
.line-clamp-2 {
display: -webkit-box;
-webkit-box-orient: vertical;
-webkit-line-clamp: 2;
overflow: hidden;
}
:deep(.remarks-field) {
height: 100%;
}
:deep(.remarks-field .van-field__control) {
padding: 12px 16px;
background-color: rgba(251, 114, 153, 0.03);
border-radius: 8px;
font-size: 14px;
line-height: 1.6;
color: #4b5563;
transition: all 0.2s ease;
resize: none;
min-height: 160px !important;
border: 1px solid transparent;
}
:deep(.remarks-field .van-field__control:hover) {
background-color: rgba(251, 114, 153, 0.05);
}
:deep(.remarks-field .van-field__control:focus) {
background-color: rgba(251, 114, 153, 0.05);
border-color: #fb7299;
box-shadow: 0 0 0 2px rgba(251, 114, 153, 0.1);
outline: none;
}
:deep(.remarks-field .van-field__control::placeholder) {
color: #9ca3af;
}
:deep(.remarks-field.van-field) {
padding: 0;
border: none;
}
:deep(.van-field__error-message) {
display: none;
}
</style>
|
294coder/Efficient-MIF
| 2,214
|
Pansharpening_Hyper_SR_Matlab_Test_Package/GLP/MTF_GLP_HPM_R.m
|
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Description:
% A Regression-Based High-Pass Modulation Pansharpening Approach (Global Version)
%
% Interface:
% I_Fus_MTF_GLP_HPM_R = MTF_GLP_HPM_R(I_MS,I_PAN,sensor,ratio)
%
% Inputs:
% I_MS: MS image upsampled at PAN scale;
% I_PAN: PAN image;
% sensor: String for type of sensor (e.g. 'WV2','IKONOS');
% ratio: Scale ratio between MS and PAN. Pre-condition: Integer value.
%
% Outputs:
% I_Fus_MTF_GLP_HPM_R: Pansharpened image.
%
% Reference:
% [Vivone18] G. Vivone, R. Restaino, and J. Chanussot, "A regression-based high-pass modulation pansharpening approach,"
% IEEE Transactions on Geoscience and Remote Sensing, vol. 56, no. 2, pp. 984-996, Feb. 2018.
% [Vivone20] G. Vivone, M. Dalla Mura, A. Garzelli, R. Restaino, G. Scarpa, M.O. Ulfarsson, L. Alparone, and J. Chanussot, "A New Benchmark Based on Recent Advances in Multispectral Pansharpening: Revisiting pansharpening with classical and emerging pansharpening methods",
% IEEE Geoscience and Remote Sensing Magazine, doi: 10.1109/MGRS.2020.3019315.
% % % % % % % % % % % % %
%
% Version: 1
%
% % % % % % % % % % % % %
%
% Copyright (C) 2019
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function I_Fus_MTF_GLP_HPM_R = MTF_GLP_HPM_R(I_MS,I_PAN,sensor,ratio)
imageHR = double(I_PAN);
I_MS = double(I_MS);
h = genMTF(ratio, sensor, size(I_MS,3));
I_Fus_MTF_GLP_HPM_R = zeros(size(I_MS));
for ii = 1 : size(I_MS,3)
%%% Low resolution PAN image
PAN_LP = imfilter(imageHR,real(h(:,:,ii)),'replicate');
t = imresize(PAN_LP,1/ratio,'nearest');
PAN_LP = interp23tap(t,ratio);
%%%% Regression coefficients
MSB = I_MS(:,:,ii);
C = cov(MSB(:),PAN_LP(:));
g = C(1,2)./C(2,2);
cb = mean(MSB(:))./g - mean(imageHR(:));
%%% Fusion rule
I_Fus_MTF_GLP_HPM_R(:,:,ii) = I_MS(:,:,ii) .* (imageHR + cb) ./ (PAN_LP + cb + eps);
end
end
|
294coder/Efficient-MIF
| 2,342
|
Pansharpening_Hyper_SR_Matlab_Test_Package/BDSD/BDSD_PC.m
|
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Description:
% BDSD_PC fuses the upsampled MultiSpectral (MS) and PANchromatic (PAN) images by
% exploiting the Band-Dependent Spatial-Detail (BDSD) model solving an optimization constrained problem.
%
% Interface:
% I_Fus_BDSD = BDSD_PC(I_MS,I_PAN,ratio,S,sensor)
%
% Inputs:
% I_MS: MS image upsampled at PAN scale;
% I_PAN: PAN image;
% ratio: Scale ratio between MS and PAN. Pre-condition: Integer value;
% sensor: String for type of sensor (e.g. 'WV2', 'IKONOS').
%
% Output:
% I_Fus_BDSD: BDSD_PC pansharpened image.
%
% Reference:
% [Vivone19] G. Vivone, Robust Band-Dependent Spatial-Detail Approaches for Panchromatic Sharpening,
% IEEE Transactions on Geoscience and Remote Sensing, 2019.
% [Vivone20] G. Vivone, M. Dalla Mura, A. Garzelli, R. Restaino, G. Scarpa, M.O. Ulfarsson, L. Alparone, and J. Chanussot, "A New Benchmark Based on Recent Advances in Multispectral Pansharpening: Revisiting pansharpening with classical and emerging pansharpening methods",
% IEEE Geoscience and Remote Sensing Magazine, doi: 10.1109/MGRS.2020.3019315.
% % % % % % % % % % % % %
%
% Version: 1
%
% % % % % % % % % % % % %
%
% Copyright (C) 2019
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function I_Fus_BDSD = BDSD_PC(I_MS,I_PAN,ratio,sensor)
I_MS = double(I_MS);
I_PAN = double(I_PAN);
opts1 = optimset('display','off');
I_GT = imresize(I_MS,1/ratio);%,'nearest');
I_MS_LR = MTF(I_GT,sensor,ratio);
I_PAN_LR = imresize(MTF_PAN(I_PAN,sensor,ratio),1/ratio,'nearest');
I_Fus_BDSD = zeros(size(I_MS));
gamma = zeros(size(I_MS,3)+1,size(I_MS,3));
for ii = 1 : size(I_MS,3)
h1 = I_GT(:,:,ii);
h2 = I_MS_LR(:,:,ii);
H = [I_PAN_LR(:), reshape(I_MS_LR,[size(I_MS_LR,1)*size(I_MS_LR,2), size(I_MS_LR,3)])];
A = eye(size(I_MS,3)+1);
A(1,1) = -1;
gamma(:,ii) = lsqlin(H,h1(:)-h2(:),A,zeros(1,size(I_MS,3)+1),[],[],[],[],[],opts1);
I_Fus_BDSD(:,:,ii) = I_MS(:,:,ii) + reshape([I_PAN(:),reshape(I_MS,[size(I_MS,1)*size(I_MS,2), size(I_MS,3)])]*gamma(:,ii),[size(I_MS,1) size(I_MS,2)]);
end
end
|
294coder/Efficient-MIF
| 4,060
|
Pansharpening_Hyper_SR_Matlab_Test_Package/BDSD/BDSD.m
|
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Description:
% BDSD fuses the upsampled MultiSpectral (MS) and PANchromatic (PAN) images by
% exploiting the Band-Dependent Spatial-Detail (BDSD) algorithm.
%
% Interface:
% I_Fus_BDSD = BDSD(I_MS,I_PAN,ratio,S,sensor)
%
% Inputs:
% I_MS: MS image upsampled at PAN scale;
% I_PAN: PAN image;
% ratio: Scale ratio between MS and PAN. Pre-condition: Integer value;
% S: Local estimation on SxS distinct blocks (typically 128x128);
% sensor: String for type of sensor (e.g. 'WV2', 'IKONOS').
%
% Output:
% I_Fus_BDSD: BDSD pansharpened image.
%
% References:
% [Garzelli08] A. Garzelli, F. Nencini, and L. Capobianco, Optimal MMSE pan sharpening of very high resolution multispectral images,
% IEEE Transactions on Geoscience and Remote Sensing, vol. 46, no. 1, pp. 228236, January 2008.
% [Vivone15] G. Vivone, L. Alparone, J. Chanussot, M. Dalla Mura, A. Garzelli, G. Licciardi, R. Restaino, and L. Wald, A Critical Comparison Among Pansharpening Algorithms,
% IEEE Transactions on Geoscience and Remote Sensing, vol. 53, no. 5, pp. 25652586, May 2015.
% [Vivone20] G. Vivone, M. Dalla Mura, A. Garzelli, R. Restaino, G. Scarpa, M.O. Ulfarsson, L. Alparone, and J. Chanussot, "A New Benchmark Based on Recent Advances in Multispectral Pansharpening: Revisiting pansharpening with classical and emerging pansharpening methods",
% IEEE Geoscience and Remote Sensing Magazine, doi: 10.1109/MGRS.2020.3019315.
% % % % % % % % % % % % %
%
% Version: 1
%
% % % % % % % % % % % % %
%
% Copyright (C) 2019
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function I_Fus_BDSD = BDSD(I_MS,I_PAN,ratio,S,sensor)
%%%
% Control of input parameters and initialization
%%%
if (S > 1)
if(rem(S,2) && S >1)
fprintf(1,'\n\n ');
error('block size for local estimation must be even')
end
if(rem(S,ratio))
fprintf(1,'\n\n ');
error('block size must be multiple of ratio')
end
[N,M] = size(I_PAN);
if(rem(N,S)||rem(M,S))
fprintf(1,'\n\n ');
error('x and y dims of pan must be multiple of the block size')
end
end
I_MS = double(I_MS);
I_PAN = double(I_PAN);
%%%
% Reduced resolution
%%%
pan_LP = MTF_PAN(I_PAN,sensor,ratio);
pan_LP_d = pan_LP(3:ratio:end,3:ratio:end);
ms_orig = imresize(I_MS,1/ratio);
ms_LP_d = MTF(ms_orig,sensor,ratio);
%%%
% Parameter estimation at reduced resolution
%%%
in3 = cat(3,ms_LP_d,ms_orig,pan_LP_d);
fun_eg = @(bs) estimate_gamma_cube(bs.data,S,ratio);
gamma = blockproc(in3,[S/ratio S/ratio],fun_eg);
%%%
% Fusion
%%%
in3 = cat(3,I_MS,I_PAN,gamma);
fun_Hi = @(bs) compH_inject(bs.data,S);
I_Fus_BDSD = blockproc(in3,[S S],fun_Hi);
%%%_______________________________________________________________
%%%
function gamma = estimate_gamma_cube(in3,S,ratio)
Nb = (size(in3,3)-1)/2;
hs_LP_d = in3(:,:,1:Nb);
hs_orig = in3(:,:,Nb+1:2*Nb);
pan_LP_d = in3(:,:,2*Nb+1);
% Compute Hd
Hd = zeros(S*S/ratio/ratio,Nb+1);
for k=1:Nb
b = hs_LP_d(:,:,k);
Hd(:,k) = b(:);
end
Hd(:,Nb+1) = pan_LP_d(:);
% Estimate gamma
B = (Hd'*Hd)\Hd';
gamma = zeros(Nb+1,Nb);
for k=1:Nb
b = hs_orig(:,:,k);
bd = hs_LP_d(:,:,k);
gamma(:,k) = B *(b(:)-bd(:));
end
gamma = padarray(gamma,[S-Nb-1 S-Nb],0,'post');
%%%_______________________________________________________________
%%%
function ms_en = compH_inject(in3,S)
Nb = size(in3,3)-2;
hs = in3(:,:,1:Nb);
pan = in3(:,:,Nb+1);
gamma = in3(:,:,Nb+2);
% Compute H
[N,M,Nb] = size(hs);
H = zeros(S*S,Nb+1);
for k=1:Nb
b = hs(:,:,k);
H(:,k) = b(:);
end
H(:,Nb+1) = pan(:);
% Inject
g = gamma(1:Nb+1,1:Nb);
ms_en = zeros(N,M,Nb);
for k=1:Nb
b = hs(:,:,k);
b_en = b(:) + H * g(:,k);
ms_en(:,:,k) = reshape(b_en,N,M);
end
|
2881099/FreeSql.AdminLTE
| 3,167
|
Examples/net80_blazor/Admin/AdminModel.cs
|
namespace net80_blazor.Admin
{
class SharedInfo
{
}
public class ItemSelected<T>
{
public T Item { get; set; }
public bool Selected { get; set; }
public ItemSelected(T item) => Item = item;
}
public class QueryOptions
{
public QueryOptions() { }
public QueryOptions(SearchFilterInfo[] filters) => Filters = filters;
public string SearchText { get; set; }
public SearchFilterInfo[] Filters { get; set; }
long _total;
public long Total
{
get => _total;
set
{
if (value < 0) value = 0;
if (value != _total)
{
_total = value;
MaxPageNumber = (int)Math.Ceiling(1.0 * _total / _pageSize);
if (_pageNumber > MaxPageNumber) _pageNumber = MaxPageNumber;
}
}
}
int _pageNumber = 1;
public int PageNumber
{
get => _pageNumber;
set
{
if (value <= 0) value = 1;
if (value > MaxPageNumber) value = MaxPageNumber;
_pageNumber = value;
}
}
int _pageSize = 20;
public int PageSize
{
get => _pageSize;
set
{
if (value <= 0) value = 1;
if (value != _pageSize)
{
_pageSize = value;
MaxPageNumber = (int)Math.Ceiling(1.0 * _total / _pageSize);
if (MaxPageNumber <= 0) MaxPageNumber = 1;
if (_pageNumber > MaxPageNumber) _pageNumber = MaxPageNumber;
}
}
}
public int MaxPageNumber { get; private set; }
public string PageNumberQueryStringName { get; set; } = "page";
public string SearchTextQueryStringName { get; set; } = "search";
public Func<Task> InvokeQueryAsync { get; set; }
}
public class SearchFilterInfo
{
public string Label { get; set; }
public string QueryStringName { get; set; }
public bool Multiple { get; set; }
public ItemSelected<string>[] Texts { get; set; }
public string[] Values { get; set; }
public bool HasValue => Texts.Where(a => a.Selected).Any();
public T[] SelectedValues<T>() => Texts.Select((a, b) => a.Selected ? Values[b] : null).Where(a => a != null).Select(a => a.ConvertTo<T>()).ToArray();
public T SelectedValue<T>() => SelectedValues<T>().FirstOrDefault();
public SearchFilterInfo(string label, string queryStringName, string texts, string values) : this(label, queryStringName, false, texts, values) { }
public SearchFilterInfo(string label, string queryStringName, bool multiple, string texts, string values)
{
Label = label;
QueryStringName = queryStringName;
Multiple = multiple;
Texts = texts.Split(',').Select(a => new ItemSelected<string>(a)).ToArray();
Values = values.Split(',');
}
}
}
|
Subsets and Splits
HTML Files in Train Set
Retrieves all records from the dataset where the file path ends with .html or .htm, providing a basic filter for HTML files.
SQL Console for nick007x/github-code-2025
Retrieves 200 file paths that end with '.html' or '.htm', providing a basic overview of HTML files in the dataset.
Top HTML Files
The query retrieves a sample of HTML file paths, providing basic filtering but limited analytical value.
CSharp Repositories Excluding Unity
Retrieves all records for repositories that contain C# files but are not related to Unity, providing a basic filter of the dataset.
C# File Count per Repository
Counts the total number of C# files across distinct repositories, providing a basic measure of C# file presence.
SQL Console for nick007x/github-code-2025
Lists unique repository IDs containing C# files, providing basic filtering to understand which repositories have C# code.
Select Groovy Files: Train Set
Retrieves the first 1000 entries from the 'train' dataset where the file path ends with '.groovy', providing a basic sample of Groovy files.
GitHub Repos with WiFiClientSecure
Finds specific file paths in repositories that contain particular code snippets related to WiFiClientSecure and ChatGPT, providing basic filtering of relevant files.