feat: 优化收藏逻辑 本地和线上同步 添加批量下载

This commit is contained in:
alger
2025-01-11 18:38:34 +08:00
parent 8f7d6fbb8d
commit 866fec6ee3
3 changed files with 279 additions and 34 deletions

View File

@@ -4,6 +4,9 @@
:class="{ 'song-mini': mini, 'song-list': list }"
@contextmenu.prevent="handleContextMenu"
>
<div v-if="selectable" class="song-item-select" @click.stop="toggleSelect">
<n-checkbox :checked="selected" />
</div>
<n-image
v-if="item.picUrl"
ref="songImg"
@@ -93,11 +96,15 @@ const props = withDefaults(
mini?: boolean;
list?: boolean;
favorite?: boolean;
selectable?: boolean;
selected?: boolean;
}>(),
{
mini: false,
list: false,
favorite: true
favorite: true,
selectable: false,
selected: false
}
);
@@ -191,7 +198,7 @@ const downloadMusic = async () => {
}
};
const emits = defineEmits(['play']);
const emits = defineEmits(['play', 'select']);
const songImageRef = useTemplateRef('songImg');
const imageLoad = async () => {
@@ -236,6 +243,11 @@ const toggleFavorite = async (e: Event) => {
store.commit('addToFavorite', props.item.id);
}
};
// 切换选择状态
const toggleSelect = () => {
emits('select', props.item.id, !props.selected);
};
</script>
<style lang="scss" scoped>
@@ -308,6 +320,10 @@ const toggleFavorite = async (e: Event) => {
}
}
}
&-select {
@apply mr-3 cursor-pointer;
}
}
.song-mini {

View File

@@ -103,23 +103,33 @@ const mutations = {
}
},
async addToFavorite(state: State, songId: number) {
try {
state.user && localStorage.getItem('token') && (await likeSong(songId, true));
if (!state.favoriteList.includes(songId)) {
state.favoriteList = [songId, ...state.favoriteList];
localStorage.setItem('favoriteList', JSON.stringify(state.favoriteList));
// 先添加到本地
if (!state.favoriteList.includes(songId)) {
state.favoriteList = [songId, ...state.favoriteList];
localStorage.setItem('favoriteList', JSON.stringify(state.favoriteList));
}
// 如果用户已登录,尝试同步到服务器
if (state.user && localStorage.getItem('token')) {
try {
await likeSong(songId, true);
} catch (error) {
console.error('同步收藏到服务器失败,但已保存在本地:', error);
}
} catch (error) {
console.error('收藏歌曲失败:', error);
}
},
async removeFromFavorite(state: State, songId: number) {
try {
state.user && localStorage.getItem('token') && (await likeSong(songId, false));
state.favoriteList = state.favoriteList.filter((id) => id !== songId);
localStorage.setItem('favoriteList', JSON.stringify(state.favoriteList));
} catch (error) {
console.error('取消收藏歌曲失败:', error);
// 先从本地移除
state.favoriteList = state.favoriteList.filter((id) => id !== songId);
localStorage.setItem('favoriteList', JSON.stringify(state.favoriteList));
// 如果用户已登录,尝试同步到服务器
if (state.user && localStorage.getItem('token')) {
try {
await likeSong(songId, false);
} catch (error) {
console.error('同步取消收藏到服务器失败,但已在本地移除:', error);
}
}
},
togglePlayMode(state: State) {
@@ -161,22 +171,32 @@ const actions = {
applyTheme(state.theme);
},
async initializeFavoriteList({ state }: { state: State }) {
try {
if (state.user && localStorage.getItem('token')) {
// 先获取本地收藏列表
const localFavoriteList = localStorage.getItem('favoriteList');
const localList: number[] = localFavoriteList ? JSON.parse(localFavoriteList) : [];
// 如果用户已登录,尝试获取服务器收藏列表并合并
if (state.user && localStorage.getItem('token')) {
try {
const res = await getLikedList();
if (res.data?.ids) {
state.favoriteList = res.data.ids.reverse();
localStorage.setItem('favoriteList', JSON.stringify(state.favoriteList));
}
} else {
const localFavoriteList = localStorage.getItem('favoriteList');
if (localFavoriteList) {
state.favoriteList = JSON.parse(localFavoriteList);
// 合并本地和服务器的收藏列表,去重
const serverList = res.data.ids.reverse();
const mergedList = Array.from(new Set([...localList, ...serverList]));
state.favoriteList = mergedList;
} else {
state.favoriteList = localList;
}
} catch (error) {
console.error('获取服务器收藏列表失败,使用本地数据:', error);
state.favoriteList = localList;
}
} catch (error) {
console.error('获取收藏列表失败:', error);
} else {
state.favoriteList = localList;
}
// 更新本地存储
localStorage.setItem('favoriteList', JSON.stringify(state.favoriteList));
}
};

View File

@@ -1,8 +1,51 @@
<template>
<div v-if="isComponent ? favoriteSongs.length : true" class="favorite-page">
<div class="favorite-header" :class="setAnimationClass('animate__fadeInLeft')">
<h2>我的收藏</h2>
<div class="favorite-count"> {{ favoriteList.length }} </div>
<div class="favorite-header-left">
<h2>我的收藏</h2>
<div class="favorite-count"> {{ favoriteList.length }} </div>
</div>
<div v-if="!isComponent" class="favorite-header-right">
<n-button
v-if="!isSelecting"
secondary
type="primary"
size="small"
class="select-btn"
@click="startSelect"
>
<template #icon>
<i class="iconfont ri-checkbox-multiple-line"></i>
</template>
批量下载
</n-button>
<div v-else class="select-controls">
<n-checkbox
class="select-all-checkbox"
:checked="isAllSelected"
:indeterminate="isIndeterminate"
@update:checked="handleSelectAll"
>
全选
</n-checkbox>
<n-button-group class="operation-btns">
<n-button
type="primary"
size="small"
:loading="isDownloading"
:disabled="selectedSongs.length === 0"
class="download-btn"
@click="handleBatchDownload"
>
<template #icon>
<i class="iconfont ri-download-line"></i>
</template>
下载 ({{ selectedSongs.length }})
</n-button>
<n-button size="small" class="cancel-btn" @click="cancelSelect"> 取消 </n-button>
</n-button-group>
</div>
</div>
</div>
<div class="favorite-main" :class="setAnimationClass('animate__bounceInRight')">
<n-scrollbar ref="scrollbarRef" class="favorite-content" @scroll="handleScroll">
@@ -17,7 +60,10 @@
:favorite="!isComponent"
:class="setAnimationClass('animate__bounceInLeft')"
:style="getItemAnimationDelay(index)"
:selectable="isSelecting"
:selected="selectedSongs.includes(song.id)"
@play="handlePlay"
@select="handleSelect"
/>
<div v-if="isComponent" class="favorite-list-more text-center">
<n-button text type="primary" @click="handleMore">查看更多</n-button>
@@ -35,22 +81,112 @@
</template>
<script setup lang="ts">
import { useMessage } from 'naive-ui';
import { computed, onMounted, ref, watch } from 'vue';
import { useRouter } from 'vue-router';
import { useStore } from 'vuex';
import { getMusicDetail } from '@/api/music';
import SongItem from '@/components/common/SongItem.vue';
import { getSongUrl } from '@/hooks/MusicListHook';
import type { SongResult } from '@/type/music';
import { setAnimationClass, setAnimationDelay } from '@/utils';
const store = useStore();
const message = useMessage();
const favoriteList = computed(() => store.state.favoriteList);
const favoriteSongs = ref<SongResult[]>([]);
const loading = ref(false);
const noMore = ref(false);
const scrollbarRef = ref();
// 多选相关
const isSelecting = ref(false);
const selectedSongs = ref<number[]>([]);
const isDownloading = ref(false);
// 开始多选
const startSelect = () => {
isSelecting.value = true;
selectedSongs.value = [];
};
// 取消多选
const cancelSelect = () => {
isSelecting.value = false;
selectedSongs.value = [];
};
// 处理选择
const handleSelect = (songId: number, selected: boolean) => {
if (selected) {
selectedSongs.value.push(songId);
} else {
selectedSongs.value = selectedSongs.value.filter((id) => id !== songId);
}
};
// 批量下载
const handleBatchDownload = async () => {
if (isDownloading.value) {
message.warning('正在下载中,请稍候...');
return;
}
if (selectedSongs.value.length === 0) {
message.warning('请先选择要下载的歌曲');
return;
}
try {
isDownloading.value = true;
const loadingMessage = message.loading('正在下载中...', { duration: 0 });
let successCount = 0;
let failCount = 0;
// 移除旧的监听器
window.electron.ipcRenderer.removeAllListeners('music-download-complete');
// 添加新的监听器
window.electron.ipcRenderer.on('music-download-complete', (_, result) => {
if (result.success) {
successCount++;
} else if (!result.canceled) {
failCount++;
}
// 当所有下载完成时
if (successCount + failCount === selectedSongs.value.length) {
isDownloading.value = false;
loadingMessage.destroy();
message.success(`下载完成:成功 ${successCount} 首,失败 ${failCount}`);
cancelSelect();
}
});
// 开始下载选中的歌曲
for (const songId of selectedSongs.value) {
const song = favoriteSongs.value.find((s) => s.id === songId);
if (!song) continue;
const url = await getSongUrl(song.id, song);
if (!url) {
failCount++;
continue;
}
window.electron.ipcRenderer.send('download-music', {
url,
filename: `${song.name} - ${(song.ar || song.song?.artists)?.map((a) => a.name).join(',')}`
});
}
} catch (error) {
isDownloading.value = false;
message.destroyAll();
message.error('下载失败');
}
};
// 无限滚动相关
const pageSize = 16;
const currentPage = ref(1);
@@ -146,6 +282,26 @@ const router = useRouter();
const handleMore = () => {
router.push('/favorite');
};
// 全选相关
const isAllSelected = computed(() => {
return (
favoriteSongs.value.length > 0 && selectedSongs.value.length === favoriteSongs.value.length
);
});
const isIndeterminate = computed(() => {
return selectedSongs.value.length > 0 && selectedSongs.value.length < favoriteSongs.value.length;
});
// 处理全选/取消全选
const handleSelectAll = (checked: boolean) => {
if (checked) {
selectedSongs.value = favoriteSongs.value.map((song) => song.id);
} else {
selectedSongs.value = [];
}
};
</script>
<style lang="scss" scoped>
@@ -154,15 +310,68 @@ const handleMore = () => {
@apply bg-light dark:bg-black;
.favorite-header {
@apply flex items-center justify-between flex-shrink-0 px-4;
@apply flex items-center justify-between flex-shrink-0 px-4 pb-2;
h2 {
@apply text-xl font-bold pb-2;
@apply text-gray-900 dark:text-white;
&-left {
@apply flex items-center gap-4;
h2 {
@apply text-xl font-bold;
@apply text-gray-900 dark:text-white;
}
.favorite-count {
@apply text-gray-500 dark:text-gray-400 text-sm;
}
}
.favorite-count {
@apply text-gray-500 dark:text-gray-400 text-sm;
&-right {
@apply flex items-center;
.select-btn {
@apply rounded-full px-4 h-8;
@apply transition-all duration-300 ease-in-out;
@apply hover:bg-primary hover:text-white;
@apply dark:border-gray-600;
.iconfont {
@apply mr-1 text-lg;
}
}
.select-controls {
@apply flex items-center gap-3;
@apply bg-gray-50 dark:bg-gray-800;
@apply rounded-full px-3 py-1;
@apply border border-gray-200 dark:border-gray-700;
@apply transition-all duration-300;
.select-all-checkbox {
@apply text-sm text-gray-900 dark:text-gray-200;
}
.operation-btns {
@apply flex items-center gap-2 ml-2;
.download-btn {
@apply rounded-full px-4 h-7;
@apply bg-primary text-white;
@apply hover:bg-primary-dark;
@apply disabled:opacity-50 disabled:cursor-not-allowed;
.iconfont {
@apply mr-1 text-lg;
}
}
.cancel-btn {
@apply rounded-full px-4 h-7;
@apply text-gray-600 dark:text-gray-300;
@apply hover:bg-gray-100 dark:hover:bg-gray-700;
@apply border-gray-300 dark:border-gray-600;
}
}
}
}
}