1. 小程序端
2. 视频优化
This commit is contained in:
1
.gitignore
vendored
1
.gitignore
vendored
@@ -10,3 +10,4 @@ client/dist
|
||||
/server/nl-blog
|
||||
/client/dist.zip
|
||||
/nl_blog线上.sql
|
||||
/client/node_modules/
|
||||
|
||||
1
.idea/vcs.xml
generated
1
.idea/vcs.xml
generated
@@ -2,5 +2,6 @@
|
||||
<project version="4">
|
||||
<component name="VcsDirectoryMappings">
|
||||
<mapping directory="$PROJECT_DIR$" vcs="Git" />
|
||||
<mapping directory="$PROJECT_DIR$/blog-wot-uniapp" vcs="Git" />
|
||||
</component>
|
||||
</project>
|
||||
1
client/node_modules/tailwindcss/stubs/.gitignore
generated
vendored
1
client/node_modules/tailwindcss/stubs/.gitignore
generated
vendored
@@ -1 +0,0 @@
|
||||
!*
|
||||
6
client/node_modules/tailwindcss/stubs/.prettierrc.json
generated
vendored
6
client/node_modules/tailwindcss/stubs/.prettierrc.json
generated
vendored
@@ -1,6 +0,0 @@
|
||||
{
|
||||
"printWidth": 120,
|
||||
"semi": false,
|
||||
"singleQuote": true,
|
||||
"trailingComma": "es5"
|
||||
}
|
||||
1062
client/node_modules/tailwindcss/stubs/config.full.js
generated
vendored
1062
client/node_modules/tailwindcss/stubs/config.full.js
generated
vendored
File diff suppressed because it is too large
Load Diff
7
client/node_modules/tailwindcss/stubs/config.simple.js
generated
vendored
7
client/node_modules/tailwindcss/stubs/config.simple.js
generated
vendored
@@ -1,7 +0,0 @@
|
||||
module.exports = {
|
||||
content: [],
|
||||
theme: {
|
||||
extend: {},
|
||||
},
|
||||
plugins: [],
|
||||
}
|
||||
6
client/node_modules/tailwindcss/stubs/postcss.config.cjs
generated
vendored
6
client/node_modules/tailwindcss/stubs/postcss.config.cjs
generated
vendored
@@ -1,6 +0,0 @@
|
||||
module.exports = {
|
||||
plugins: {
|
||||
tailwindcss: {},
|
||||
autoprefixer: {},
|
||||
},
|
||||
}
|
||||
6
client/node_modules/tailwindcss/stubs/postcss.config.js
generated
vendored
6
client/node_modules/tailwindcss/stubs/postcss.config.js
generated
vendored
@@ -1,6 +0,0 @@
|
||||
export default {
|
||||
plugins: {
|
||||
tailwindcss: {},
|
||||
autoprefixer: {},
|
||||
},
|
||||
}
|
||||
2
client/node_modules/tailwindcss/stubs/tailwind.config.cjs
generated
vendored
2
client/node_modules/tailwindcss/stubs/tailwind.config.cjs
generated
vendored
@@ -1,2 +0,0 @@
|
||||
/** @type {import('tailwindcss').Config} */
|
||||
module.exports = __CONFIG__
|
||||
2
client/node_modules/tailwindcss/stubs/tailwind.config.js
generated
vendored
2
client/node_modules/tailwindcss/stubs/tailwind.config.js
generated
vendored
@@ -1,2 +0,0 @@
|
||||
/** @type {import('tailwindcss').Config} */
|
||||
export default __CONFIG__
|
||||
3
client/node_modules/tailwindcss/stubs/tailwind.config.ts
generated
vendored
3
client/node_modules/tailwindcss/stubs/tailwind.config.ts
generated
vendored
@@ -1,3 +0,0 @@
|
||||
import type { Config } from 'tailwindcss'
|
||||
|
||||
export default __CONFIG__ satisfies Config
|
||||
6413
client/pnpm-lock.yaml
generated
6413
client/pnpm-lock.yaml
generated
File diff suppressed because it is too large
Load Diff
@@ -90,6 +90,7 @@ const isFullWidthPage = computed(() => {
|
||||
|| path.startsWith('/blog/')
|
||||
|| path.startsWith('/works/')
|
||||
|| path.startsWith('/columns')
|
||||
|| path.startsWith('/videos/')
|
||||
})
|
||||
|
||||
// 应用网站配置到页面标题和meta标签
|
||||
|
||||
@@ -165,7 +165,6 @@ const uploadFile = async (file: File) => {
|
||||
if (props.categoryId) {
|
||||
formData.append('categoryId', props.categoryId.toString())
|
||||
}
|
||||
formData.append('storageType', 'aliyun')
|
||||
|
||||
const result = await parseApiResponse<{ fileUrl: string }>(await authFetch(`${API_BASE}/admin/attachments/upload`, {
|
||||
method: 'POST',
|
||||
|
||||
@@ -366,7 +366,6 @@ const uploadSingleFile = async (file: File): Promise<string | null> => {
|
||||
if (props.categoryId) {
|
||||
formData.append('categoryId', props.categoryId.toString())
|
||||
}
|
||||
formData.append('storageType', 'aliyun')
|
||||
|
||||
const result = await parseApiResponse<{ fileUrl: string }>(await authFetch(`${API_BASE}/admin/attachments/upload`, {
|
||||
method: 'POST',
|
||||
|
||||
@@ -46,7 +46,6 @@ const uploadFile = async (file: File) => {
|
||||
const formData = new FormData()
|
||||
formData.append('file', file)
|
||||
if (props.categoryId) formData.append('categoryId', props.categoryId.toString())
|
||||
formData.append('storageType', 'aliyun')
|
||||
const result = await parseApiResponse<{ fileUrl: string }>(
|
||||
await authFetch(`${API_BASE}/admin/attachments/upload`, { method: 'POST', headers: {}, body: formData })
|
||||
)
|
||||
|
||||
@@ -14,7 +14,6 @@ export function useMdMediaUpload(editorRef: Ref<ExposeParam | undefined>) {
|
||||
const formData = new FormData()
|
||||
formData.append('file', file)
|
||||
formData.append('categoryId', '1')
|
||||
formData.append('storageType', 'aliyun')
|
||||
|
||||
const response = await authFetch('/api/admin/attachments/upload', {
|
||||
method: 'POST',
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
<template>
|
||||
<section class="page-section block">
|
||||
<div class="max-w-6xl mx-auto pb-12 md:pb-20">
|
||||
<section class="page-section block w-full">
|
||||
<div class="max-w-[90rem] mx-auto w-full pt-20 md:pt-32 px-4 md:px-6 pb-12 md:pb-20">
|
||||
<button @click="router.push('/videos')" class="mb-8 text-art-muted hover:text-art-text flex items-center gap-2 text-sm">
|
||||
<Icon name="arrow-left" :size="16" /> 返回视频
|
||||
</button>
|
||||
|
||||
@@ -1,28 +1,71 @@
|
||||
<template>
|
||||
<section class="page-section block">
|
||||
<div class="max-w-6xl mx-auto pb-12 md:pb-20">
|
||||
<section class="page-section block w-full">
|
||||
<div class="max-w-[90rem] mx-auto w-full pt-20 md:pt-32 px-4 md:px-6 pb-12 md:pb-20">
|
||||
<button @click="$router.back()" class="mb-8 text-art-muted hover:text-art-text flex items-center gap-2 text-sm">
|
||||
<Icon name="arrow-left" :size="16" /> 返回
|
||||
</button>
|
||||
|
||||
<div v-if="loading" class="flex justify-center py-20"><div class="animate-spin h-10 w-10 border-t-2 border-art-accent rounded-full"></div></div>
|
||||
<div v-if="loading" class="flex justify-center py-20">
|
||||
<div class="animate-spin h-10 w-10 border-t-2 border-art-accent rounded-full" />
|
||||
</div>
|
||||
<div v-else-if="error" class="text-red-400 text-center py-12">
|
||||
<p class="mb-4">{{ error }}</p>
|
||||
<button
|
||||
type="button"
|
||||
class="px-4 py-2 border border-art-border rounded-full text-sm text-art-text hover:border-art-accent transition-colors"
|
||||
@click="load"
|
||||
>重试</button>
|
||||
>
|
||||
重试
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<template v-else-if="video">
|
||||
<h1 class="font-serif text-3xl md:text-4xl text-art-text mb-6">{{ video.title }}</h1>
|
||||
|
||||
<!-- 播放区:未挂载前封面;挂载后 DPlayer + 暂停时大按钮遮罩 -->
|
||||
<div
|
||||
v-if="video.videoUrl"
|
||||
ref="playerRef"
|
||||
class="w-full aspect-video rounded-xl overflow-hidden bg-black mb-6"
|
||||
></div>
|
||||
class="w-full aspect-video rounded-xl overflow-hidden bg-black mb-6 relative"
|
||||
>
|
||||
<!-- DPlayer 容器:playerReady 后始终保留,暂停不销毁 -->
|
||||
<div
|
||||
v-show="playerReady"
|
||||
ref="playerRef"
|
||||
class="absolute inset-0 w-full h-full"
|
||||
/>
|
||||
|
||||
<!-- 大播放按钮:初始 / 暂停时显示;点击开始或继续播 -->
|
||||
<div
|
||||
v-if="showPlayOverlay"
|
||||
class="absolute inset-0 z-20 cursor-pointer group"
|
||||
role="button"
|
||||
tabindex="0"
|
||||
aria-label="播放视频"
|
||||
@click="onOverlayPlay"
|
||||
@keydown.enter.prevent="onOverlayPlay"
|
||||
@keydown.space.prevent="onOverlayPlay"
|
||||
>
|
||||
<img
|
||||
v-if="!playerReady && coverSrc"
|
||||
:src="coverSrc"
|
||||
class="w-full h-full object-cover"
|
||||
alt=""
|
||||
/>
|
||||
<div
|
||||
v-else-if="!playerReady"
|
||||
class="w-full h-full bg-black/60"
|
||||
/>
|
||||
<div
|
||||
class="absolute inset-0 transition-colors"
|
||||
:class="playerReady ? 'bg-black/40' : 'bg-black/35 group-hover:bg-black/25'"
|
||||
/>
|
||||
<div
|
||||
class="absolute top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2 w-20 h-20 md:w-24 md:h-24 rounded-full border border-white/40 bg-black/40 backdrop-blur-md flex items-center justify-center transition-transform group-hover:scale-105 group-active:scale-95 z-10"
|
||||
>
|
||||
<Icon name="play" :size="32" class="text-white ml-1" />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div
|
||||
v-else
|
||||
class="w-full aspect-video rounded-xl overflow-hidden bg-black/40 border border-art-border flex items-center justify-center mb-6"
|
||||
@@ -39,10 +82,11 @@
|
||||
<router-link
|
||||
:to="`/videos/albums/${video.albumContext.albumId}`"
|
||||
class="text-xs text-art-accent hover:underline"
|
||||
>返回专辑</router-link>
|
||||
>
|
||||
返回专辑
|
||||
</router-link>
|
||||
</div>
|
||||
<div class="flex gap-3 overflow-x-auto pb-2">
|
||||
<!-- 前序视频 -->
|
||||
<div
|
||||
v-for="pv in video.albumContext.prevVideos"
|
||||
:key="'prev-' + pv.id"
|
||||
@@ -54,14 +98,14 @@
|
||||
</div>
|
||||
<p class="text-xs text-art-muted mt-1 line-clamp-2 group-hover:text-art-text">{{ pv.title }}</p>
|
||||
</div>
|
||||
<!-- 当前视频高亮 -->
|
||||
<div class="shrink-0 w-36">
|
||||
<div class="aspect-video rounded-lg overflow-hidden border-2 border-art-accent bg-black/40">
|
||||
<img v-if="video.cover" :src="video.cover" class="w-full h-full object-cover" alt="" />
|
||||
</div>
|
||||
<p class="text-xs text-art-accent mt-1 line-clamp-2 font-medium">正在播放</p>
|
||||
<p class="text-xs text-art-accent mt-1 line-clamp-2 font-medium">
|
||||
{{ playerReady && !showPlayOverlay ? '正在播放' : '当前视频' }}
|
||||
</p>
|
||||
</div>
|
||||
<!-- 后续视频 -->
|
||||
<div
|
||||
v-for="nv in video.albumContext.nextVideos"
|
||||
:key="'next-' + nv.id"
|
||||
@@ -89,7 +133,11 @@
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { ref, onMounted, onBeforeUnmount, watch, nextTick } from 'vue'
|
||||
/**
|
||||
* 视频详情:封面大按钮点播;暂停时再次显示大按钮(不销毁播放器)。
|
||||
* 恢复 rounded-xl / rounded-lg 与 w-full,避免 PC 端观感变窄变生硬。
|
||||
*/
|
||||
import { ref, computed, onMounted, onBeforeUnmount, watch, nextTick } from 'vue'
|
||||
import { useRoute, useRouter } from 'vue-router'
|
||||
import DPlayer from 'dplayer'
|
||||
import 'dplayer/dist/DPlayer.min.css'
|
||||
@@ -101,31 +149,86 @@ const router = useRouter()
|
||||
const loading = ref(true)
|
||||
const error = ref('')
|
||||
const video = ref<VideoDetailItem | null>(null)
|
||||
/** 已挂载 DPlayer */
|
||||
const playerReady = ref(false)
|
||||
/** 初始或暂停时显示大播放按钮 */
|
||||
const showPlayOverlay = ref(true)
|
||||
const playerRef = ref<HTMLElement | null>(null)
|
||||
let dp: DPlayer | null = null
|
||||
|
||||
/** 销毁 DPlayer 实例 */
|
||||
const destroyPlayer = () => {
|
||||
if (dp) { dp.destroy(); dp = null }
|
||||
const coverSrc = computed(() => video.value?.poster || video.value?.cover || '')
|
||||
|
||||
/** 销毁 DPlayer,释放资源 */
|
||||
function destroyPlayer() {
|
||||
if (dp) {
|
||||
dp.destroy()
|
||||
dp = null
|
||||
}
|
||||
playerReady.value = false
|
||||
}
|
||||
|
||||
/** 创建 DPlayer 播放器 */
|
||||
const initPlayer = async () => {
|
||||
destroyPlayer()
|
||||
if (!playerRef.value || !video.value?.videoUrl) return
|
||||
await nextTick()
|
||||
dp = new DPlayer({
|
||||
container: playerRef.value,
|
||||
video: { url: video.value.videoUrl, pic: video.value.poster || video.value.cover },
|
||||
theme: '#d4b383',
|
||||
lang: 'zh-cn',
|
||||
/** 绑定 play/pause,驱动大按钮显隐 */
|
||||
function bindPlayerEvents(player: DPlayer) {
|
||||
player.on('play', () => {
|
||||
showPlayOverlay.value = false
|
||||
})
|
||||
player.on('pause', () => {
|
||||
showPlayOverlay.value = true
|
||||
})
|
||||
}
|
||||
|
||||
/** 加载视频详情 */
|
||||
const load = async () => {
|
||||
/** 首次创建播放器并播放 */
|
||||
async function initPlayer() {
|
||||
destroyPlayer()
|
||||
playerReady.value = true
|
||||
await nextTick()
|
||||
if (!playerRef.value || !video.value?.videoUrl) {
|
||||
playerReady.value = false
|
||||
return
|
||||
}
|
||||
dp = new DPlayer({
|
||||
container: playerRef.value,
|
||||
video: {
|
||||
url: video.value.videoUrl,
|
||||
pic: video.value.poster || video.value.cover,
|
||||
},
|
||||
autoplay: false,
|
||||
theme: '#d4b383',
|
||||
lang: 'zh-cn',
|
||||
})
|
||||
bindPlayerEvents(dp)
|
||||
try {
|
||||
dp.play()
|
||||
showPlayOverlay.value = false
|
||||
} catch {
|
||||
showPlayOverlay.value = true
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 点击大按钮:未就绪则初始化;已就绪则继续 play。
|
||||
* 用户手势触发,利于移动端绕过自动播限制。
|
||||
*/
|
||||
async function onOverlayPlay() {
|
||||
if (!video.value?.videoUrl) return
|
||||
if (!playerReady.value || !dp) {
|
||||
showPlayOverlay.value = false
|
||||
await initPlayer()
|
||||
return
|
||||
}
|
||||
try {
|
||||
dp.play()
|
||||
showPlayOverlay.value = false
|
||||
} catch {
|
||||
showPlayOverlay.value = true
|
||||
}
|
||||
}
|
||||
|
||||
/** 加载视频详情;切换条目时重置播放态 */
|
||||
async function load() {
|
||||
loading.value = true
|
||||
error.value = ''
|
||||
showPlayOverlay.value = true
|
||||
destroyPlayer()
|
||||
try {
|
||||
video.value = await fetchVideo(route.params.id as string)
|
||||
@@ -137,17 +240,17 @@ const load = async () => {
|
||||
}
|
||||
}
|
||||
|
||||
watch([video, playerRef, loading], async ([v, el, isLoading]) => {
|
||||
if (isLoading || !v?.videoUrl || !el) return
|
||||
await nextTick()
|
||||
initPlayer()
|
||||
}, { flush: 'post' })
|
||||
|
||||
onMounted(load)
|
||||
watch(() => route.params.id, load)
|
||||
onBeforeUnmount(destroyPlayer)
|
||||
onBeforeUnmount(() => {
|
||||
destroyPlayer()
|
||||
showPlayOverlay.value = true
|
||||
})
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
:deep(.dplayer) { width: 100% !important; height: 100% !important; }
|
||||
:deep(.dplayer) {
|
||||
width: 100% !important;
|
||||
height: 100% !important;
|
||||
}
|
||||
</style>
|
||||
|
||||
@@ -1,197 +1,339 @@
|
||||
<template>
|
||||
<section id="videos" class="page-section block animate-slide-down">
|
||||
<div class="max-w-6xl mx-auto pb-12 md:pb-20">
|
||||
<div class="mb-12">
|
||||
<div class="max-w-6xl mx-auto w-full pb-12 md:pb-20">
|
||||
<div class="mb-10">
|
||||
<h2 class="font-serif text-5xl italic text-art-text mb-4">视频</h2>
|
||||
<p class="text-art-muted">精选视频内容与系列专辑。</p>
|
||||
</div>
|
||||
|
||||
<!-- 分类 Tab 快捷筛选 -->
|
||||
<div class="flex flex-wrap gap-2 mb-8">
|
||||
<!-- 主 Tab:默认全部视频,分类/专辑收进第二页 -->
|
||||
<nav class="flex items-end gap-8 mb-10 border-b border-art-border" aria-label="视频浏览切换">
|
||||
<button
|
||||
type="button"
|
||||
class="px-4 py-1.5 rounded-full text-sm border transition-colors"
|
||||
:class="activeCategory === 0 ? 'border-art-accent text-art-accent bg-art-accent/10' : 'border-art-border text-art-muted hover:text-art-text'"
|
||||
@click="selectCategory(0)"
|
||||
>全部</button>
|
||||
class="relative pb-3 text-sm tracking-wide transition-colors"
|
||||
:class="mainTab === 'videos' ? 'text-art-text' : 'text-art-muted hover:text-art-text'"
|
||||
@click="switchMainTab('videos')"
|
||||
>
|
||||
全部视频
|
||||
<span
|
||||
v-if="mainTab === 'videos'"
|
||||
class="absolute left-0 right-0 -bottom-px h-0.5 bg-art-accent"
|
||||
/>
|
||||
</button>
|
||||
<button
|
||||
v-for="cat in categories"
|
||||
:key="cat.id"
|
||||
type="button"
|
||||
class="px-4 py-1.5 rounded-full text-sm border transition-colors"
|
||||
:class="activeCategory === cat.id ? 'border-art-accent text-art-accent bg-art-accent/10' : 'border-art-border text-art-muted hover:text-art-text'"
|
||||
@click="selectCategory(cat.id)"
|
||||
>{{ cat.name }}</button>
|
||||
</div>
|
||||
class="relative pb-3 text-sm tracking-wide transition-colors"
|
||||
:class="mainTab === 'browse' ? 'text-art-text' : 'text-art-muted hover:text-art-text'"
|
||||
@click="switchMainTab('browse')"
|
||||
>
|
||||
分类 & 专辑
|
||||
<span
|
||||
v-if="mainTab === 'browse'"
|
||||
class="absolute left-0 right-0 -bottom-px h-0.5 bg-art-accent"
|
||||
/>
|
||||
</button>
|
||||
</nav>
|
||||
|
||||
<!-- 分类概览卡片 -->
|
||||
<div v-if="categories.length" class="mb-14">
|
||||
<h3 class="font-mono text-xs text-art-muted uppercase tracking-widest mb-6">分类</h3>
|
||||
<div class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4">
|
||||
<div
|
||||
v-for="cat in categories"
|
||||
:key="'card-' + cat.id"
|
||||
class="group p-5 rounded-xl border cursor-pointer transition-colors"
|
||||
:class="activeCategory === cat.id ? 'border-art-accent/50 bg-art-accent/5' : 'border-art-border hover:border-art-accent/30 hover:bg-art-text/5'"
|
||||
@click="selectCategory(cat.id)"
|
||||
>
|
||||
<h4 class="text-art-text font-medium group-hover:text-art-accent transition-colors">{{ cat.name }}</h4>
|
||||
<p v-if="cat.description" class="text-xs text-art-muted mt-2 line-clamp-2">{{ cat.description }}</p>
|
||||
<div class="flex gap-4 mt-3 text-xs text-art-muted">
|
||||
<span>{{ cat.videoCount ?? 0 }} 个视频</span>
|
||||
<span>{{ cat.albumCount ?? 0 }} 个专辑</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div v-if="loading" class="flex justify-center py-20">
|
||||
<div class="animate-spin h-10 w-10 border-t-2 border-art-accent rounded-full" />
|
||||
</div>
|
||||
<div v-else-if="!loading && !error" class="mb-10 text-center text-art-muted text-sm py-6 border border-dashed border-art-border rounded-xl">
|
||||
暂无视频分类,请先在后台创建分类
|
||||
</div>
|
||||
|
||||
<div v-if="loading" class="flex justify-center py-20"><div class="animate-spin h-10 w-10 border-t-2 border-art-accent rounded-full"></div></div>
|
||||
|
||||
<div v-else-if="error" class="text-center py-12">
|
||||
<p class="text-red-400 mb-4">{{ error }}</p>
|
||||
<button
|
||||
type="button"
|
||||
class="px-4 py-2 border border-art-border rounded-full text-sm text-art-text hover:border-art-accent hover:text-art-accent transition-colors"
|
||||
@click="loadAll"
|
||||
>重试</button>
|
||||
@click="retry"
|
||||
>
|
||||
重试
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<template v-else>
|
||||
<!-- 专辑 -->
|
||||
<div v-if="albums.length" class="mb-16">
|
||||
<h3 class="font-mono text-xs text-art-muted uppercase tracking-widest mb-6">专辑</h3>
|
||||
<div class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-6">
|
||||
<div
|
||||
v-for="album in albums"
|
||||
:key="album.id"
|
||||
class="group rounded-xl overflow-hidden border border-art-border hover:border-art-accent/40 transition-colors"
|
||||
>
|
||||
<div
|
||||
class="aspect-video bg-gray-900 overflow-hidden cursor-pointer"
|
||||
@click="router.push(`/videos/albums/${album.id}`)"
|
||||
<!-- Tab 面板:out-in 淡入上移,切换时不走全页 loading 以免打断动画 -->
|
||||
<Transition v-else name="videos-tab" mode="out-in">
|
||||
<div :key="mainTab" class="videos-tab-panel">
|
||||
<!-- 全部视频 -->
|
||||
<template v-if="mainTab === 'videos'">
|
||||
<div v-if="categories.length" class="mb-8">
|
||||
<label class="sr-only" for="video-cat-filter">按分类筛选</label>
|
||||
<select
|
||||
id="video-cat-filter"
|
||||
class="bg-transparent border-0 border-b border-art-border text-sm text-art-text py-1.5 pr-8 focus:outline-none focus:border-art-accent cursor-pointer"
|
||||
:value="activeCategory"
|
||||
@change="onVideoFilterChange"
|
||||
>
|
||||
<img v-if="album.cover" :src="album.cover" class="w-full h-full object-cover group-hover:scale-105 transition-transform duration-500" alt="" />
|
||||
</div>
|
||||
<!-- 专辑预览视频缩略图 -->
|
||||
<div
|
||||
v-if="album.previewVideos?.length"
|
||||
class="flex gap-1 px-2 py-2 bg-black/30 border-t border-art-border overflow-x-auto"
|
||||
>
|
||||
<div
|
||||
v-for="pv in album.previewVideos"
|
||||
:key="pv.id"
|
||||
class="shrink-0 w-16 h-10 rounded overflow-hidden cursor-pointer border border-transparent hover:border-art-accent/50"
|
||||
@click.stop="router.push(`/videos/${pv.id}`)"
|
||||
>
|
||||
<img v-if="pv.cover" :src="pv.cover" class="w-full h-full object-cover" alt="" />
|
||||
<div v-else class="w-full h-full bg-art-text/5 flex items-center justify-center">
|
||||
<Icon name="play" :size="12" class="text-art-muted" />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="p-4 cursor-pointer" @click="router.push(`/videos/albums/${album.id}`)">
|
||||
<h4 class="text-art-text font-medium group-hover:text-art-accent transition-colors">{{ album.name }}</h4>
|
||||
<p class="text-xs text-art-muted mt-1">
|
||||
{{ album.videoCount ?? 0 }} 个视频
|
||||
<span v-if="album.latestVideoUpdatedAt" class="ml-2">· 更新于 {{ album.latestVideoUpdatedAt }}</span>
|
||||
</p>
|
||||
<p v-if="album.categoryName" class="text-xs text-art-muted/70 mt-1">{{ album.categoryName }}</p>
|
||||
</div>
|
||||
<option :value="0">全部分类</option>
|
||||
<option v-for="cat in categories" :key="cat.id" :value="cat.id">{{ cat.name }}</option>
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div v-else class="mb-10 text-center text-art-muted text-sm py-8 border border-dashed border-art-border rounded-xl">
|
||||
暂无专辑
|
||||
</div>
|
||||
|
||||
<!-- 最新视频 -->
|
||||
<div>
|
||||
<h3 class="font-mono text-xs text-art-muted uppercase tracking-widest mb-6">最新视频</h3>
|
||||
<div class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-6">
|
||||
<div
|
||||
v-for="video in videos"
|
||||
:key="video.id"
|
||||
class="group cursor-pointer rounded-xl overflow-hidden border border-art-border hover:border-art-accent/40 transition-colors"
|
||||
@click="router.push(`/videos/${video.id}`)"
|
||||
>
|
||||
<div class="aspect-video bg-black/40 relative overflow-hidden">
|
||||
<img v-if="video.cover" :src="video.cover" class="w-full h-full object-cover" alt="" />
|
||||
<div class="absolute inset-0 flex items-center justify-center bg-black/30 group-hover:bg-black/10 transition-colors">
|
||||
<div class="w-12 h-12 rounded-full border border-art-border flex items-center justify-center">
|
||||
<Icon name="play" :size="20" class="text-art-text ml-0.5" />
|
||||
<div v-if="panelLoading" class="flex justify-center py-16">
|
||||
<div class="animate-spin h-8 w-8 border-t-2 border-art-accent rounded-full" />
|
||||
</div>
|
||||
<template v-else>
|
||||
<div class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-6">
|
||||
<div
|
||||
v-for="video in videos"
|
||||
:key="video.id"
|
||||
class="group cursor-pointer rounded-xl overflow-hidden border border-art-border hover:border-art-accent/40 transition-colors"
|
||||
@click="router.push(`/videos/${video.id}`)"
|
||||
>
|
||||
<div class="aspect-video bg-black/40 relative overflow-hidden">
|
||||
<img v-if="video.cover" :src="video.cover" class="w-full h-full object-cover" alt="" />
|
||||
<div class="absolute inset-0 flex items-center justify-center bg-black/30 group-hover:bg-black/10 transition-colors">
|
||||
<div class="w-12 h-12 rounded-full border border-art-border flex items-center justify-center">
|
||||
<Icon name="play" :size="20" class="text-art-text ml-0.5" />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="p-4">
|
||||
<h4 class="text-art-text font-medium line-clamp-2">{{ video.title }}</h4>
|
||||
<p class="text-xs text-art-muted mt-1">
|
||||
{{ video.categoryName || '未分类' }}
|
||||
<span v-if="video.createdAt" class="ml-2">· 发布于 {{ video.createdAt }}</span>
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="p-4">
|
||||
<h4 class="text-art-text font-medium line-clamp-2">{{ video.title }}</h4>
|
||||
<p class="text-xs text-art-muted mt-1">
|
||||
{{ video.categoryName || '未分类' }}
|
||||
<span v-if="video.createdAt" class="ml-2">· 发布于 {{ video.createdAt }}</span>
|
||||
</p>
|
||||
<div v-if="videos.length === 0" class="text-center py-12 text-art-muted rounded-xl border border-dashed border-art-border">
|
||||
暂无视频
|
||||
</div>
|
||||
</template>
|
||||
</template>
|
||||
|
||||
<!-- 分类 & 专辑 -->
|
||||
<template v-else>
|
||||
<div v-if="categories.length" class="mb-12">
|
||||
<h3 class="font-mono text-xs text-art-muted uppercase tracking-widest mb-6">分类</h3>
|
||||
<div class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4">
|
||||
<div
|
||||
class="group p-5 rounded-xl border cursor-pointer transition-colors"
|
||||
:class="activeCategory === 0 ? 'border-art-accent/50 bg-art-accent/5' : 'border-art-border hover:border-art-accent/30 hover:bg-art-text/5'"
|
||||
@click="selectBrowseCategory(0)"
|
||||
>
|
||||
<h4 class="text-art-text font-medium">全部专辑</h4>
|
||||
<p class="text-xs text-art-muted mt-2">查看所有分类下的专辑</p>
|
||||
</div>
|
||||
<div
|
||||
v-for="cat in categories"
|
||||
:key="'card-' + cat.id"
|
||||
class="group p-5 rounded-xl border cursor-pointer transition-colors"
|
||||
:class="activeCategory === cat.id ? 'border-art-accent/50 bg-art-accent/5' : 'border-art-border hover:border-art-accent/30 hover:bg-art-text/5'"
|
||||
@click="selectBrowseCategory(cat.id)"
|
||||
>
|
||||
<h4 class="text-art-text font-medium group-hover:text-art-accent transition-colors">{{ cat.name }}</h4>
|
||||
<p v-if="cat.description" class="text-xs text-art-muted mt-2 line-clamp-2">{{ cat.description }}</p>
|
||||
<div class="flex gap-4 mt-3 text-xs text-art-muted">
|
||||
<span>{{ cat.videoCount ?? 0 }} 个视频</span>
|
||||
<span>{{ cat.albumCount ?? 0 }} 个专辑</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div v-if="videos.length === 0" class="text-center py-12 text-art-muted">暂无视频</div>
|
||||
<div
|
||||
v-else
|
||||
class="mb-10 text-center text-art-muted text-sm py-6 border border-dashed border-art-border rounded-xl"
|
||||
>
|
||||
暂无视频分类,请先在后台创建分类
|
||||
</div>
|
||||
|
||||
<div v-if="panelLoading" class="flex justify-center py-16">
|
||||
<div class="animate-spin h-8 w-8 border-t-2 border-art-accent rounded-full" />
|
||||
</div>
|
||||
<template v-else>
|
||||
<div v-if="albums.length">
|
||||
<h3 class="font-mono text-xs text-art-muted uppercase tracking-widest mb-6">专辑</h3>
|
||||
<div class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-6">
|
||||
<div
|
||||
v-for="album in albums"
|
||||
:key="album.id"
|
||||
class="group rounded-xl overflow-hidden border border-art-border hover:border-art-accent/40 transition-colors"
|
||||
>
|
||||
<div
|
||||
class="aspect-video bg-gray-900 overflow-hidden cursor-pointer"
|
||||
@click="router.push(`/videos/albums/${album.id}`)"
|
||||
>
|
||||
<img
|
||||
v-if="album.cover"
|
||||
:src="album.cover"
|
||||
class="w-full h-full object-cover group-hover:scale-105 transition-transform duration-500"
|
||||
alt=""
|
||||
/>
|
||||
</div>
|
||||
<div
|
||||
v-if="album.previewVideos?.length"
|
||||
class="flex gap-1 px-2 py-2 bg-black/30 border-t border-art-border overflow-x-auto"
|
||||
>
|
||||
<div
|
||||
v-for="pv in album.previewVideos"
|
||||
:key="pv.id"
|
||||
class="shrink-0 w-16 h-10 rounded overflow-hidden cursor-pointer border border-transparent hover:border-art-accent/50"
|
||||
@click.stop="router.push(`/videos/${pv.id}`)"
|
||||
>
|
||||
<img v-if="pv.cover" :src="pv.cover" class="w-full h-full object-cover" alt="" />
|
||||
<div v-else class="w-full h-full bg-art-text/5 flex items-center justify-center">
|
||||
<Icon name="play" :size="12" class="text-art-muted" />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="p-4 cursor-pointer" @click="router.push(`/videos/albums/${album.id}`)">
|
||||
<h4 class="text-art-text font-medium group-hover:text-art-accent transition-colors">{{ album.name }}</h4>
|
||||
<p class="text-xs text-art-muted mt-1">
|
||||
{{ album.videoCount ?? 0 }} 个视频
|
||||
<span v-if="album.latestVideoUpdatedAt" class="ml-2">· 更新于 {{ album.latestVideoUpdatedAt }}</span>
|
||||
</p>
|
||||
<p v-if="album.categoryName" class="text-xs text-art-muted/70 mt-1">{{ album.categoryName }}</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div
|
||||
v-else
|
||||
class="text-center text-art-muted text-sm py-10 border border-dashed border-art-border rounded-xl"
|
||||
>
|
||||
暂无专辑
|
||||
</div>
|
||||
</template>
|
||||
</template>
|
||||
</div>
|
||||
</template>
|
||||
</Transition>
|
||||
</div>
|
||||
</section>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
/**
|
||||
* 前台视频页:双主 Tab + 卡片圆角边框(对齐改前视觉)+ Tab 切换过渡。
|
||||
*/
|
||||
import { ref, onMounted } from 'vue'
|
||||
import { useRouter } from 'vue-router'
|
||||
import { fetchVideoCategories, fetchVideoAlbums, fetchVideos, type VideoCategory, type VideoAlbum, type VideoItem } from '../services/api'
|
||||
import {
|
||||
fetchVideoCategories,
|
||||
fetchVideoAlbums,
|
||||
fetchVideos,
|
||||
type VideoCategory,
|
||||
type VideoAlbum,
|
||||
type VideoItem,
|
||||
} from '../services/api'
|
||||
import { useScrollAnimation } from '../composables/useScrollAnimation'
|
||||
import Icon from '../components/Icon.vue'
|
||||
|
||||
const router = useRouter()
|
||||
/** 首屏全页 loading */
|
||||
const loading = ref(false)
|
||||
/** Tab 内局部 loading,避免打断 Transition */
|
||||
const panelLoading = ref(false)
|
||||
const error = ref('')
|
||||
const categories = ref<VideoCategory[]>([])
|
||||
const albums = ref<VideoAlbum[]>([])
|
||||
const videos = ref<VideoItem[]>([])
|
||||
const mainTab = ref<'videos' | 'browse'>('videos')
|
||||
const activeCategory = ref(0)
|
||||
|
||||
const { initObserver } = useScrollAnimation()
|
||||
|
||||
/** 切换分类并重新加载数据 */
|
||||
const selectCategory = (catId: number) => {
|
||||
activeCategory.value = catId
|
||||
loadData()
|
||||
/** 切换主 Tab;数据用 panelLoading,保证面板过渡可见 */
|
||||
async function switchMainTab(tab: 'videos' | 'browse') {
|
||||
if (mainTab.value === tab) return
|
||||
mainTab.value = tab
|
||||
if (tab === 'videos') await loadVideos(true)
|
||||
else await loadAlbums(true)
|
||||
}
|
||||
|
||||
/** 加载专辑与视频列表 */
|
||||
const loadData = async () => {
|
||||
loading.value = true
|
||||
function onVideoFilterChange(e: Event) {
|
||||
const val = Number((e.target as HTMLSelectElement).value) || 0
|
||||
activeCategory.value = val
|
||||
loadVideos(true)
|
||||
}
|
||||
|
||||
function selectBrowseCategory(catId: number) {
|
||||
activeCategory.value = catId
|
||||
loadAlbums(true)
|
||||
}
|
||||
|
||||
/** @param silent 为 true 时用面板内 loading,不盖住 Tab 过渡 */
|
||||
async function loadVideos(silent = false) {
|
||||
if (silent) panelLoading.value = true
|
||||
else loading.value = true
|
||||
error.value = ''
|
||||
try {
|
||||
const catId = activeCategory.value || undefined
|
||||
albums.value = await fetchVideoAlbums(catId)
|
||||
videos.value = await fetchVideos(catId)
|
||||
} catch (err) {
|
||||
error.value = '加载失败,请稍后重试'
|
||||
console.error('加载视频列表失败:', err)
|
||||
} finally {
|
||||
loading.value = false
|
||||
panelLoading.value = false
|
||||
await initObserver()
|
||||
}
|
||||
}
|
||||
|
||||
/** 加载分类并刷新列表 */
|
||||
const loadAll = async () => {
|
||||
async function loadAlbums(silent = false) {
|
||||
if (silent) panelLoading.value = true
|
||||
else loading.value = true
|
||||
error.value = ''
|
||||
try {
|
||||
const catId = activeCategory.value || undefined
|
||||
albums.value = await fetchVideoAlbums(catId)
|
||||
} catch (err) {
|
||||
error.value = '加载失败,请稍后重试'
|
||||
console.error('加载专辑失败:', err)
|
||||
} finally {
|
||||
loading.value = false
|
||||
panelLoading.value = false
|
||||
await initObserver()
|
||||
}
|
||||
}
|
||||
|
||||
async function loadAll() {
|
||||
loading.value = true
|
||||
error.value = ''
|
||||
try {
|
||||
categories.value = await fetchVideoCategories()
|
||||
videos.value = await fetchVideos()
|
||||
} catch (err) {
|
||||
error.value = '加载分类失败,请稍后重试'
|
||||
console.error('加载视频分类失败:', err)
|
||||
return
|
||||
error.value = '加载失败,请稍后重试'
|
||||
console.error('加载视频页失败:', err)
|
||||
} finally {
|
||||
loading.value = false
|
||||
await initObserver()
|
||||
}
|
||||
}
|
||||
|
||||
function retry() {
|
||||
if (mainTab.value === 'videos') {
|
||||
if (!categories.value.length) loadAll()
|
||||
else loadVideos()
|
||||
} else {
|
||||
loadAlbums()
|
||||
}
|
||||
await loadData()
|
||||
}
|
||||
|
||||
onMounted(loadAll)
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.sr-only {
|
||||
position: absolute;
|
||||
width: 1px;
|
||||
height: 1px;
|
||||
padding: 0;
|
||||
margin: -1px;
|
||||
overflow: hidden;
|
||||
clip: rect(0, 0, 0, 0);
|
||||
white-space: nowrap;
|
||||
border: 0;
|
||||
}
|
||||
.videos-tab-enter-active,
|
||||
.videos-tab-leave-active {
|
||||
transition: opacity 0.2s ease-out, transform 0.2s ease-out;
|
||||
}
|
||||
.videos-tab-enter-from {
|
||||
opacity: 0;
|
||||
transform: translateY(6px);
|
||||
}
|
||||
.videos-tab-leave-to {
|
||||
opacity: 0;
|
||||
transform: translateY(-4px);
|
||||
}
|
||||
</style>
|
||||
|
||||
@@ -293,7 +293,6 @@ const uploadFileWithFile = async (file: File) => {
|
||||
if (uploadCategoryId.value > 0) {
|
||||
formData.append('categoryId', uploadCategoryId.value.toString())
|
||||
}
|
||||
formData.append('storageType', 'aliyun')
|
||||
|
||||
await parseApiResponse(await authFetch(`${API_BASE}/admin/attachments/upload`, {
|
||||
method: 'POST',
|
||||
|
||||
@@ -549,7 +549,6 @@ const uploadMediaFile = async (file: File): Promise<string | null> => {
|
||||
const formData = new FormData()
|
||||
formData.append('file', file)
|
||||
formData.append('categoryId', '1')
|
||||
formData.append('storageType', 'aliyun')
|
||||
|
||||
const response = await authFetch('/api/admin/attachments/upload', {
|
||||
method: 'POST',
|
||||
|
||||
3
client/src/types/dplayer.d.ts
vendored
3
client/src/types/dplayer.d.ts
vendored
@@ -12,6 +12,9 @@ declare module 'dplayer' {
|
||||
}
|
||||
export default class DPlayer {
|
||||
constructor(options: DPlayerOptions)
|
||||
play(): void
|
||||
pause(): void
|
||||
destroy(): void
|
||||
on(event: string, handler: (...args: unknown[]) => void): void
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"fmt"
|
||||
"log"
|
||||
"os"
|
||||
@@ -17,37 +18,102 @@ var DB *gorm.DB
|
||||
// JWTSecret is the secret key used for signing JWT tokens
|
||||
var JWTSecret = "your-secret-key" // Default value, should be set via JWT_SECRET environment variable in production
|
||||
|
||||
// LoadEnvFile 从可执行文件同级目录加载 .env 文件
|
||||
func LoadEnvFile() {
|
||||
// 获取可执行文件路径
|
||||
execPath, err := os.Executable()
|
||||
// utf8BOM 用于剥离 Windows 编辑器常写入的 UTF-8 BOM,否则 godotenv 会解析失败
|
||||
var utf8BOM = []byte{0xEF, 0xBB, 0xBF}
|
||||
|
||||
// tryLoadEnv 尝试加载指定路径的 .env;成功则记录日志并返回 true。
|
||||
// 会先去掉 UTF-8 BOM,再按 godotenv 默认语义:不覆盖已存在的 OS 环境变量。
|
||||
func tryLoadEnv(path string) bool {
|
||||
if path == "" {
|
||||
return false
|
||||
}
|
||||
raw, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
log.Printf("Warning: Failed to get executable path: %v. Using current working directory.", err)
|
||||
// 如果获取可执行文件路径失败,使用当前工作目录
|
||||
if err := godotenv.Load(".env"); err != nil {
|
||||
log.Printf("Info: .env file not found in current directory: %v", err)
|
||||
} else {
|
||||
log.Println("Loaded .env file from current directory")
|
||||
return false
|
||||
}
|
||||
raw = bytes.TrimPrefix(raw, utf8BOM)
|
||||
envMap, err := godotenv.Parse(bytes.NewReader(raw))
|
||||
if err != nil {
|
||||
log.Printf("Warning: found .env at %s but failed to parse: %v", path, err)
|
||||
return false
|
||||
}
|
||||
applied := 0
|
||||
for k, v := range envMap {
|
||||
if os.Getenv(k) == "" {
|
||||
_ = os.Setenv(k, v)
|
||||
applied++
|
||||
}
|
||||
return
|
||||
}
|
||||
log.Printf("Loaded .env file from %s (%d keys applied)", path, applied)
|
||||
return true
|
||||
}
|
||||
|
||||
// collectEnvCandidates 收集候选 .env 路径:可执行文件旁、cwd、cwd/server、向上 3 级
|
||||
func collectEnvCandidates() []string {
|
||||
seen := map[string]struct{}{}
|
||||
var list []string
|
||||
add := func(p string) {
|
||||
abs, err := filepath.Abs(p)
|
||||
if err != nil {
|
||||
abs = p
|
||||
}
|
||||
if _, ok := seen[abs]; ok {
|
||||
return
|
||||
}
|
||||
seen[abs] = struct{}{}
|
||||
list = append(list, abs)
|
||||
}
|
||||
|
||||
// 获取可执行文件所在目录
|
||||
execDir := filepath.Dir(execPath)
|
||||
envPath := filepath.Join(execDir, ".env")
|
||||
|
||||
// 检查 .env 文件是否存在
|
||||
if _, err := os.Stat(envPath); os.IsNotExist(err) {
|
||||
log.Printf("Info: .env file not found at %s, using environment variables or defaults", envPath)
|
||||
return
|
||||
}
|
||||
|
||||
// 加载 .env 文件
|
||||
if err := godotenv.Load(envPath); err != nil {
|
||||
log.Printf("Warning: Failed to load .env file from %s: %v", envPath, err)
|
||||
if execPath, err := os.Executable(); err == nil {
|
||||
add(filepath.Join(filepath.Dir(execPath), ".env"))
|
||||
} else {
|
||||
log.Printf("Loaded .env file from %s", envPath)
|
||||
log.Printf("Warning: Failed to get executable path: %v", err)
|
||||
}
|
||||
|
||||
cwd, err := os.Getwd()
|
||||
if err != nil {
|
||||
log.Printf("Warning: Failed to get working directory: %v", err)
|
||||
cwd = "."
|
||||
}
|
||||
add(filepath.Join(cwd, ".env"))
|
||||
add(filepath.Join(cwd, "server", ".env")) // 从仓库根启动时
|
||||
|
||||
// 向上最多 3 级父目录查找 .env 与 server/.env
|
||||
dir := cwd
|
||||
for i := 0; i < 3; i++ {
|
||||
parent := filepath.Dir(dir)
|
||||
if parent == dir {
|
||||
break
|
||||
}
|
||||
dir = parent
|
||||
add(filepath.Join(dir, ".env"))
|
||||
add(filepath.Join(dir, "server", ".env"))
|
||||
}
|
||||
return list
|
||||
}
|
||||
|
||||
// LoadEnvFile 依次尝试多个路径加载 .env(后加载补缺,不覆盖已有 OS 环境变量)
|
||||
func LoadEnvFile() {
|
||||
loadedPaths := []string{}
|
||||
for _, p := range collectEnvCandidates() {
|
||||
if tryLoadEnv(p) {
|
||||
loadedPaths = append(loadedPaths, p)
|
||||
}
|
||||
}
|
||||
|
||||
if len(loadedPaths) == 0 {
|
||||
log.Println("Info: no .env loaded; relying on process environment variables")
|
||||
} else {
|
||||
log.Printf("Env load summary: %d file(s) loaded", len(loadedPaths))
|
||||
}
|
||||
|
||||
appID := os.Getenv("WECHAT_APP_ID")
|
||||
secret := os.Getenv("WECHAT_APP_SECRET")
|
||||
log.Printf(
|
||||
"WeChat env: APP_ID_set=%v SECRET_set=%v",
|
||||
appID != "",
|
||||
secret != "",
|
||||
)
|
||||
}
|
||||
|
||||
func InitDB() {
|
||||
|
||||
@@ -5,6 +5,7 @@ import (
|
||||
"log"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/niangaodev/art-code/models"
|
||||
@@ -31,12 +32,21 @@ func AdminUploadAttachment(c *gin.Context) {
|
||||
}
|
||||
}
|
||||
|
||||
// 获取存储类型:Env 齐全时默认 aliyun
|
||||
defaultStorage := "local"
|
||||
if utils.HasAliyunEnvConfig() {
|
||||
defaultStorage = "aliyun"
|
||||
// 存储类型解析:客户端显式传入 > 数据库启用配置 > Aliyun Env > local
|
||||
storageType := strings.TrimSpace(c.PostForm("storageType"))
|
||||
var ossConfig *models.OSSConfig
|
||||
usedEnvConfig := false
|
||||
|
||||
if storageType == "" {
|
||||
if cfg, cfgErr := repositories.GetActiveOSSConfig(""); cfgErr == nil && cfg != nil {
|
||||
storageType = cfg.StorageType
|
||||
ossConfig = cfg // 复用,避免下方再查
|
||||
} else if utils.HasAliyunEnvConfig() {
|
||||
storageType = "aliyun"
|
||||
} else {
|
||||
storageType = "local"
|
||||
}
|
||||
}
|
||||
storageType := c.DefaultPostForm("storageType", defaultStorage)
|
||||
|
||||
// 打开文件
|
||||
src, err := file.Open()
|
||||
@@ -51,10 +61,8 @@ func AdminUploadAttachment(c *gin.Context) {
|
||||
StorageType: storageType,
|
||||
}
|
||||
|
||||
var ossConfig *models.OSSConfig
|
||||
usedEnvConfig := false
|
||||
|
||||
if storageType == "aliyun" {
|
||||
// 仅在无库配置时才用 Env 阿里云(库配置优先)
|
||||
if storageType == "aliyun" && ossConfig == nil {
|
||||
if envCfg, ok := utils.LoadAliyunConfigFromEnv(); ok {
|
||||
config = envCfg
|
||||
usedEnvConfig = true
|
||||
@@ -62,10 +70,12 @@ func AdminUploadAttachment(c *gin.Context) {
|
||||
}
|
||||
|
||||
if !usedEnvConfig && storageType != "local" {
|
||||
ossConfig, err = repositories.GetActiveOSSConfig(storageType)
|
||||
if err != nil || ossConfig == nil {
|
||||
utils.Error(c, 400, "OSS config not found or not active")
|
||||
return
|
||||
if ossConfig == nil {
|
||||
ossConfig, err = repositories.GetActiveOSSConfig(storageType)
|
||||
if err != nil || ossConfig == nil {
|
||||
utils.Error(c, 400, "OSS config not found or not active")
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
// 根据存储类型从专用字段或通用字段读取配置
|
||||
|
||||
@@ -224,6 +224,28 @@ func GetPost(c *gin.Context) {
|
||||
}()
|
||||
}
|
||||
|
||||
// AdminGetPost 后台按 ID 获取文章详情(含未发布),供编辑表单加载
|
||||
func AdminGetPost(c *gin.Context) {
|
||||
idStr := c.Param("id")
|
||||
var id uint
|
||||
if _, err := fmt.Sscanf(idStr, "%d", &id); err != nil {
|
||||
utils.Error(c, 400, "Invalid post ID")
|
||||
return
|
||||
}
|
||||
|
||||
post, err := repositories.GetPostByIDAdmin(id)
|
||||
if err != nil {
|
||||
utils.ServerError(c, err)
|
||||
return
|
||||
}
|
||||
if post == nil {
|
||||
utils.Error(c, 404, "Post not found")
|
||||
return
|
||||
}
|
||||
|
||||
utils.Success(c, repositories.BuildPostResponse(post, true))
|
||||
}
|
||||
|
||||
// 获取所有文章(包括未发布的,后台用)
|
||||
func AdminGetPosts(c *gin.Context) {
|
||||
page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
|
||||
|
||||
@@ -27,6 +27,7 @@ func main() {
|
||||
repositories.MigratePostUserID()
|
||||
repositories.MigrateUserAvatar()
|
||||
repositories.MigrateUserProfileFields()
|
||||
repositories.MigrateUserWxOpenID()
|
||||
repositories.MigrateVideoModule()
|
||||
repositories.MigratePptTemplates()
|
||||
repositories.MigrateOSSConfigFields()
|
||||
@@ -118,6 +119,16 @@ func main() {
|
||||
api.POST("/inquiries", handlers.SubmitInquiry)
|
||||
api.GET("/email-suffixes", handlers.GetEmailSuffixes)
|
||||
|
||||
// 微信小程序静默登录
|
||||
api.POST("/auth/wx-login", handlers.WxLogin)
|
||||
|
||||
// 需登录:游客合并到管理员账号
|
||||
authUser := api.Group("")
|
||||
authUser.Use(middleware.AuthMiddleware())
|
||||
{
|
||||
authUser.POST("/auth/merge-account", handlers.MergeAccount)
|
||||
}
|
||||
|
||||
// 用户公开资料
|
||||
api.GET("/users/:id/profile", handlers.GetUserProfile)
|
||||
api.GET("/users/:id/posts", handlers.GetUserPosts)
|
||||
@@ -205,6 +216,7 @@ func main() {
|
||||
|
||||
// 文章管理
|
||||
authAdmin.GET("/posts", middleware.PermissionMiddleware("posts", "read"), handlers.AdminGetPosts)
|
||||
authAdmin.GET("/posts/:id", middleware.PermissionMiddleware("posts", "read"), handlers.AdminGetPost)
|
||||
authAdmin.POST("/posts", middleware.PermissionMiddleware("posts", "create"), handlers.AdminCreatePost)
|
||||
authAdmin.PUT("/posts/:id", middleware.PermissionMiddleware("posts", "update"), handlers.AdminUpdatePost)
|
||||
authAdmin.PATCH("/posts/:id/relations", middleware.PermissionMiddleware("posts", "update"), handlers.AdminUpdatePostRelations) // 更新文章关联关系
|
||||
|
||||
@@ -16,6 +16,7 @@ type User struct {
|
||||
Phone string `json:"phone" gorm:"column:phone"`
|
||||
Wechat string `json:"wechat" gorm:"column:wechat"`
|
||||
WechatQrcode string `json:"wechatQrcode" gorm:"column:wechat_qrcode"`
|
||||
WxOpenID string `json:"-" gorm:"column:wx_openid;uniqueIndex"`
|
||||
Password string `json:"password,omitempty" gorm:"-"` // Virtual field for input
|
||||
PasswordHash string `json:"-" gorm:"column:password_hash"`
|
||||
RoleID uint `json:"roleId" gorm:"column:role_id"`
|
||||
@@ -109,3 +110,8 @@ type LoginResponse struct {
|
||||
User UserResponse `json:"user"`
|
||||
Expire int64 `json:"expire"`
|
||||
}
|
||||
|
||||
// WxLoginRequest 微信小程序登录
|
||||
type WxLoginRequest struct {
|
||||
Code string `json:"code" binding:"required"`
|
||||
}
|
||||
|
||||
@@ -54,9 +54,10 @@ func CreateAccessLog(log *models.AccessLog) error {
|
||||
}
|
||||
|
||||
// UVTrendData UV趋势数据
|
||||
// Count 的 SQL 别名与 gorm column 均为 value,与 json 对齐,避免 Scan 落成 0
|
||||
type UVTrendData struct {
|
||||
Date string `json:"date"`
|
||||
Count int `json:"value"`
|
||||
Count int `json:"value" gorm:"column:value"`
|
||||
YoY float64 `json:"yoy"`
|
||||
MoM float64 `json:"mom"`
|
||||
}
|
||||
@@ -83,7 +84,7 @@ func GetDailyUV(startDate, endDate string) ([]UVTrendData, error) {
|
||||
|
||||
// 查询数据库
|
||||
query := config.DB.Model(&models.UserAccessLog{}).
|
||||
Select("FROM_UNIXTIME(access_time, '%Y-%m-%d') as date, COUNT(DISTINCT user_ip) as count").
|
||||
Select("FROM_UNIXTIME(access_time, '%Y-%m-%d') as date, COUNT(DISTINCT user_ip) as value").
|
||||
Where("access_time >= ?", startTime.Unix()).
|
||||
Where("access_time <= ?", endTime.Unix())
|
||||
|
||||
|
||||
@@ -197,6 +197,16 @@ func MigrateUserProfileFields() {
|
||||
}
|
||||
}
|
||||
|
||||
// MigrateUserWxOpenID adds wx_openid for mini-program silent login.
|
||||
func MigrateUserWxOpenID() {
|
||||
if columnExists("users", "wx_openid") {
|
||||
return
|
||||
}
|
||||
log.Printf("Adding users.wx_openid...")
|
||||
execSQL("ALTER TABLE `users` ADD COLUMN `wx_openid` VARCHAR(64) NULL DEFAULT NULL COMMENT '微信小程序openid' AFTER `wechat_qrcode`")
|
||||
execSQL("CREATE UNIQUE INDEX `idx_users_wx_openid` ON `users` (`wx_openid`)")
|
||||
}
|
||||
|
||||
// MigrateVideoModule 创建视频模块表及作品视频字段
|
||||
func MigrateVideoModule() {
|
||||
log.Printf("Migrating video module...")
|
||||
|
||||
@@ -15,9 +15,10 @@ import (
|
||||
)
|
||||
|
||||
// TrendData 趋势数据
|
||||
// Count 的 SQL 别名与 gorm column 均为 value,与 json 对齐,避免 Scan 落成 0
|
||||
type TrendData struct {
|
||||
Date string `json:"date"`
|
||||
Count int `json:"value"`
|
||||
Count int `json:"value" gorm:"column:value"`
|
||||
YoY float64 `json:"yoy"`
|
||||
MoM float64 `json:"mom"`
|
||||
}
|
||||
@@ -621,7 +622,7 @@ func GetNewPostsTrend(startDate, endDate string) ([]TrendData, error) {
|
||||
|
||||
// 查询数据库
|
||||
query := config.DB.Model(&models.Post{}).
|
||||
Select("FROM_UNIXTIME(created_at, '%Y-%m-%d') as date, COUNT(*) as count").
|
||||
Select("FROM_UNIXTIME(created_at, '%Y-%m-%d') as date, COUNT(*) as value").
|
||||
Where("deleted_at = ?", 0).
|
||||
Where("created_at >= ?", startTime.Unix()).
|
||||
Where("created_at <= ?", endTime.Unix())
|
||||
|
||||
@@ -29,6 +29,29 @@ func GetUserByUsername(username string) (*models.User, error) {
|
||||
return &user, nil
|
||||
}
|
||||
|
||||
// GetUserByWxOpenID 根据微信 openid 获取用户
|
||||
func GetUserByWxOpenID(openid string) (*models.User, error) {
|
||||
if openid == "" {
|
||||
return nil, nil
|
||||
}
|
||||
var user models.User
|
||||
err := config.DB.Model(&models.User{}).
|
||||
Select("users.*, COALESCE(roles.name, users.role) as role").
|
||||
Joins("LEFT JOIN roles ON users.role_id = roles.id").
|
||||
Where("users.wx_openid = ? AND users.deleted_at = ?", openid, 0).
|
||||
First(&user).Error
|
||||
|
||||
if err != nil {
|
||||
if err == gorm.ErrRecordNotFound {
|
||||
return nil, nil
|
||||
}
|
||||
log.Printf("Error getting user by wx_openid: %v", err)
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &user, nil
|
||||
}
|
||||
|
||||
// GetUserByID 根据ID获取用户
|
||||
func GetUserByID(id uint) (*models.User, error) {
|
||||
var user models.User
|
||||
@@ -179,6 +202,36 @@ func UpdateUserPassword(id uint, passwordHash string) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// ClearUserWxOpenID 清空用户微信 openid(写 NULL,避免 unique 索引与空串冲突)
|
||||
func ClearUserWxOpenID(id uint) error {
|
||||
err := config.DB.Model(&models.User{}).
|
||||
Where("id = ?", id).
|
||||
Updates(map[string]interface{}{
|
||||
"wx_openid": nil,
|
||||
"updated_at": time.Now().Unix(),
|
||||
}).Error
|
||||
if err != nil {
|
||||
log.Printf("Error clearing user wx_openid: %v", err)
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// SetUserWxOpenID 将微信 openid 绑定到指定用户
|
||||
func SetUserWxOpenID(id uint, openid string) error {
|
||||
err := config.DB.Model(&models.User{}).
|
||||
Where("id = ? AND deleted_at = ?", id, 0).
|
||||
Updates(map[string]interface{}{
|
||||
"wx_openid": openid,
|
||||
"updated_at": time.Now().Unix(),
|
||||
}).Error
|
||||
if err != nil {
|
||||
log.Printf("Error setting user wx_openid: %v", err)
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// DeleteUser 删除用户 (Soft Delete)
|
||||
func DeleteUser(id uint) error {
|
||||
err := config.DB.Model(&models.User{}).
|
||||
|
||||
Reference in New Issue
Block a user