| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566 |
- import { VideoItem } from '../viewmodel/VideoItem';
- import { LengthMetrics, SegmentButton, SegmentButtonItemTuple, SegmentButtonOptions,
- SymbolGlyphModifier } from '@kit.ArkUI';
- import {
- PreferencesUtil, ToastUtil, StrUtil
- } from '@pura/harmony-utils';
- import {
- ButtonFancyModifier,
- SymbolGlyphFancyModifier,
- ShadowModifier
- } from '../common/util/AttributeModifierUtil';
- import { CommonConstants } from '../common/constants/CommonConstants';
- import { WebDavAccount } from '../viewmodel/WebDavAccount';
- import Logger from '../common/util/Logger';
- import { RemoteDriveType } from '../common/enums/RemoteDriveType';
- import { navidromeRestApi, NavidromeRestAlbum, NavidromeRestArtist, NavidromeRestSong } from '../common/network/NavidromeRestApi';
- import { Utility } from '../common/util/Utility';
- import { Constants } from '../Constants';
- import { EventConstants } from '../common/constants/EventConstants';
- import { emitter } from '@kit.BasicServicesKit';
- import { setNavidromePlaylist } from '../common/util/NavidromePlaylistStore';
- import { navidromeApi, NavidromeSong } from '../common/network/NavidromeApi';
- import { ServerLogUtil } from '../common/util/ServerLogUtil';
- import { RemoteDriveManager } from '../common/util/RemoteDriveManager';
- const NAVIDROME_PLAYLIST_ID = 'navidrome-playlist';
- const NAVIDROME_SEARCH_LIMIT = 500;
- interface PlaylistEventData {
- playlistId: string;
- playlistName: string;
- songCount: number;
- startIndex: number;
- isJump: boolean;
- songFilePaths: string[];
- }
- enum NavFilterType {
- None = 0,
- Artist = 1,
- Album = 2
- }
- interface CachePreviewInfo {
- cacheRoot: string;
- examplePath: string;
- }
- @Component
- export struct NavidromePage {
- @Link mType: number;
- @Link offsetX: number;
- @Link isShowDrawer: boolean;
- @State isNoJumpToHome: boolean = false //网盘播放不跳转首页
- @StorageProp('bottomSafeHeight') bottomSafeHeight: number = 0;
- @Prop @Watch('onSwitchAccount') selectedAccount: WebDavAccount;
- @StorageProp('currentTheme') currentTheme: number = 0;
- @State selectedTab: number = 0; // 0: 全部, 1: 艺术家, 2: 专辑
- @State allVideos: VideoItem[] = [];
- @State artists: NavidromeRestArtist[] = [];
- @State albums: NavidromeRestAlbum[] = [];
- @State loading: boolean = false;
- @State songNextStart: number | null = 0;
- @State artistNextStart: number | null = 0;
- @State albumNextStart: number | null = 0;
- @State isSongPageLoading: boolean = false;
- @State isArtistPageLoading: boolean = false;
- @State isAlbumPageLoading: boolean = false;
- @StorageProp('isDarkMode') isDarkMode: boolean = false;
- @StorageLink('currentSong') currentSong: VideoItem | undefined = undefined;
- @StorageProp('topRectHeight') topRectHeight: number = 0;
- @State @Watch('onTabSelectedIndexesChanged') tabSelectedIndexes: number[] = [0];
- @StorageProp('themeColor') themeColor: string =
- PreferencesUtil.getStringSync('THEME_COLOR', CommonConstants.DEFAULT_THEME_COLOR);
- private tabs: string[] = ['全部', '艺术家', '专辑'];
- private loadTicket: number = 0;
- @State filterType: NavFilterType = NavFilterType.None;
- @State filterLabel: string = '';
- @State filterId: string = '';
- @State filterSongs: VideoItem[] = [];
- @State isFilterLoading: boolean = false;
- private coverUrlCache: Map<string, string> = new Map();
- private albumCoverLookup: Map<string, string> = new Map();
- private searchTicket: number = 0;
- private createTabOptions(): SegmentButtonOptions {
- const buttons = [
- { text: '全部' },
- { text: '艺术家' },
- { text: '专辑' }
- ] as SegmentButtonItemTuple;
- return SegmentButtonOptions.capsule({
- buttons,
- direction: Direction.Ltr,
- buttonPadding: { top: 10, bottom: 10 },
- backgroundColor: $r('app.color.index_background'),
- selectedBackgroundColor: $r('app.color.start_window_background'),
- selectedFontColor: $r('app.color.text_color'),
- fontSize: 14,
- selectedFontSize: 15,
- localizedTextPadding: {
- end: LengthMetrics.vp(20),
- start: LengthMetrics.vp(20)
- }
- });
- }
- private getCachePreviewInfo(account: WebDavAccount): CachePreviewInfo | null {
- try {
- const manager = RemoteDriveManager.getInstance();
- const context = manager.context;
- if (!context) {
- return null;
- }
- const baseDir = context.filesDir ?? context.cacheDir;
- if (!baseDir) {
- return null;
- }
- const accountId = account.id?.toString() || 'default';
- const cacheRoot = `${baseDir}/remote_cache/webdav/${accountId}`;
- const examplePath = `${cacheRoot}/navidrome_preview.cache`;
- return { cacheRoot, examplePath };
- } catch (error) {
- Logger.error('NavidromePage', `获取缓存预览路径失败: ${(error as Error).message}`);
- return null;
- }
- }
- // 搜索和排序相关状态
- @State isSearchMode: boolean = false;
- @State searchText: string = ''; // 用户输入内容
- @State filteredList: Array<VideoItem> = []; // 过滤后的歌曲结果
- @State sortType: number = 0; // 排序类型 0:名称升序 1:名称降序 2:时间升序 3:时间降序 4:大小升序 5:大小降序
- @State isSearchLoading: boolean = false;
- // SegmentButton选项
- @State tabOptions: SegmentButtonOptions = this.createTabOptions();
- //当胶囊按钮的选择发生变化时调用此函数
- onTabSelectedIndexesChanged() {
- this.selectedTab = this.tabSelectedIndexes[0];
- console.info('heanup', `Selected tab: ${this.tabs[this.selectedTab]}`);
-
- // 从艺术家或专辑切换回全部时,清除筛选状态
- if (this.selectedTab === 0 && this.filterType !== NavFilterType.None) {
- // 不清除筛选,保持筛选状态
- } else if (this.selectedTab !== 0) {
- // 切换到艺术家或专辑标签页时,清除筛选和搜索状态
- this.clearFilter();
- this.isSearchMode = false;
- this.searchText = '';
- this.filteredList = [];
- this.isSearchLoading = false;
- this.searchTicket++;
- }
- }
- //切换不同的NavidromePage
- async onSwitchAccount() {
- await this.refreshNavidromeData(true);
- }
- aboutToAppear() {
- this.isNoJumpToHome = PreferencesUtil.getBooleanSync('isNoJumpToHome', true)
- this.sortType = PreferencesUtil.getNumberSync('navidromeSortType', 0);
- this.refreshNavidromeData();
- }
- private async refreshNavidromeData(showToastWhenMissing: boolean = false): Promise<void> {
- const account = this.resolveActiveAccount();
- if (!account) {
- this.resetData();
- if (showToastWhenMissing) {
- ToastUtil.showToast('请先选择 Navidrome 账号');
- }
- return;
- }
- // 记录日志开关状态
- void ServerLogUtil.info('NavidromeLoad', `日志状态: ${ServerLogUtil.getLogUploadStatus()}`);
- // 记录账号信息和缓存路径
- await this.logAccountCacheInfo(account);
- await this.loadNavidromeLibrary(account);
- this.doSortType(this.sortType)
- }
- private resolveActiveAccount(): WebDavAccount | undefined {
- if (!this.selectedAccount) {
- return undefined;
- }
- if (this.selectedAccount.webType !== RemoteDriveType.Navidrome) {
- return undefined;
- }
- if (!this.selectedAccount.host || this.selectedAccount.host.length === 0) {
- return undefined;
- }
- return this.selectedAccount;
- }
- private resetData(): void {
- this.allVideos = [];
- this.artists = [];
- this.albums = [];
- this.clearFilter();
- this.coverUrlCache.clear();
- this.albumCoverLookup.clear();
- this.songNextStart = 0;
- this.artistNextStart = 0;
- this.albumNextStart = 0;
- this.isSongPageLoading = false;
- this.isArtistPageLoading = false;
- this.isAlbumPageLoading = false;
- }
- private async loadNavidromeLibrary(account: WebDavAccount): Promise<void> {
- const ticket = ++this.loadTicket;
- this.loading = true;
- this.resetData();
- void ServerLogUtil.info('NavidromeLoad', '开始加载 Navidrome 数据库');
- void ServerLogUtil.info('NavidromeLoad', `服务器: ${ServerLogUtil.sanitizeAccount(account)}`);
- void ServerLogUtil.info('NavidromeLoad', `封面URL缓存已清空,当前缓存数量: ${this.coverUrlCache.size}`);
- try {
- await this.logAccountCacheInfo(account);
- await Promise.all([
- this.loadNextSongPage(account, ticket),
- this.loadNextArtistPage(account, ticket),
- this.loadNextAlbumPage(account, ticket)
- ]);
- if (ticket !== this.loadTicket) {
- return;
- }
- void ServerLogUtil.info('NavidromeLoad', `首次加载完成: 歌曲 ${this.allVideos.length} / 艺术家 ${this.artists.length} / 专辑 ${this.albums.length}`);
- await this.logCacheStatistics(account);
- } catch (error) {
- if (ticket === this.loadTicket) {
- void ServerLogUtil.error('NavidromeLoad', `数据加载失败: ${(error as Error).message}`);
- void ServerLogUtil.error('NavidromeLoad', `失败时服务器信息: ${ServerLogUtil.sanitizeAccount(account)}`);
- ToastUtil.showToast((error as Error).message ?? 'Navidrome 数据加载失败');
- }
- } finally {
- if (ticket === this.loadTicket) {
- this.loading = false;
- void ServerLogUtil.info('NavidromeLoad', '加载流程结束');
- }
- }
- }
- private async loadNextSongPage(account: WebDavAccount, ticket?: number): Promise<void> {
- if (this.songNextStart === null || this.isSongPageLoading) {
- return;
- }
- const currentTicket = ticket ?? this.loadTicket;
- this.isSongPageLoading = true;
- try {
- const response = await navidromeRestApi.fetchSongPage(account, this.songNextStart);
- if (currentTicket !== this.loadTicket) {
- return;
- }
- const chunk = response.data ?? [];
- if (chunk.length === 0) {
- this.songNextStart = null;
- return;
- }
- const videos = await this.convertSongsToVideoItems(chunk, account);
- if (currentTicket !== this.loadTicket) {
- return;
- }
- this.allVideos = [...this.allVideos, ...videos];
- this.songNextStart = response.nextStart;
- void ServerLogUtil.info('NavidromeLoad', `歌曲列表追加: 本次 ${videos.length} 首, 总数 ${this.allVideos.length}`);
- } finally {
- this.isSongPageLoading = false;
- }
- }
- private async loadNextArtistPage(account: WebDavAccount, ticket?: number): Promise<void> {
- if (this.artistNextStart === null || this.isArtistPageLoading) {
- return;
- }
- const currentTicket = ticket ?? this.loadTicket;
- this.isArtistPageLoading = true;
- try {
- const response = await navidromeRestApi.fetchArtistPage(account, this.artistNextStart);
- if (currentTicket !== this.loadTicket) {
- return;
- }
- const chunk = response.data ?? [];
- if (chunk.length === 0) {
- this.artistNextStart = null;
- return;
- }
- const coverMap = await this.buildArtistCoverMap(chunk, account);
- if (currentTicket !== this.loadTicket) {
- return;
- }
- const processed = chunk.map(artist => {
- artist.coverUrl = coverMap.get(artist.id);
- return artist;
- });
- this.artists = [...this.artists, ...processed];
- this.artistNextStart = response.nextStart;
- void ServerLogUtil.info('ArtistCover', `艺术家列表追加: 本次 ${processed.length} 位, 总数 ${this.artists.length}`);
- } finally {
- this.isArtistPageLoading = false;
- }
- }
- private async loadNextAlbumPage(account: WebDavAccount, ticket?: number): Promise<void> {
- if (this.albumNextStart === null || this.isAlbumPageLoading) {
- return;
- }
- const currentTicket = ticket ?? this.loadTicket;
- this.isAlbumPageLoading = true;
- try {
- const response = await navidromeRestApi.fetchAlbumPage(account, this.albumNextStart);
- if (currentTicket !== this.loadTicket) {
- return;
- }
- const chunk = response.data ?? [];
- if (chunk.length === 0) {
- this.albumNextStart = null;
- return;
- }
- const coverMap = await this.buildAlbumCoverMap(chunk, account);
- if (currentTicket !== this.loadTicket) {
- return;
- }
- coverMap.forEach((value, key) => {
- if (value) {
- this.albumCoverLookup.set(key, value);
- }
- });
- const processed = chunk.map(album => {
- album.coverUrl = coverMap.get(album.id);
- return album;
- });
- this.albums = [...this.albums, ...processed];
- this.albumNextStart = response.nextStart;
- void ServerLogUtil.info('AlbumCover', `专辑列表追加: 本次 ${processed.length} 张, 总数 ${this.albums.length}`);
- } finally {
- this.isAlbumPageLoading = false;
- }
- }
- private async handleReachEnd(): Promise<void> {
- if (this.loading) {
- return;
- }
- if (this.selectedTab === 0 && this.filterType !== NavFilterType.None) {
- return;
- }
- const account = this.selectedAccount;
- if (!account) {
- return;
- }
- switch (this.selectedTab) {
- case 0:
- await this.loadNextSongPage(account);
- break;
- case 1:
- await this.loadNextArtistPage(account);
- break;
- case 2:
- await this.loadNextAlbumPage(account);
- break;
- default:
- break;
- }
- }
- private async buildAlbumCoverMap(albums: NavidromeRestAlbum[], account: WebDavAccount): Promise<Map<string, string>> {
- const map = new Map<string, string>();
- const tasks: Promise<void>[] = [];
- let directCoverCount = 0;
- let generatedCoverCount = 0;
- let failedCoverCount = 0;
- void ServerLogUtil.info('AlbumCover', `开始处理 ${albums.length} 张专辑的封面`);
- for (let i = 0; i < albums.length; i++) {
- const album = albums[i];
- tasks.push((async () => {
- try {
- // 尝试获取直接嵌入的封面路径
- const directUrl = this.resolveEmbedCover(account, album.embedArtPath ?? album.coverArtPath);
- if (directUrl) {
- map.set(album.id, directUrl);
- directCoverCount++;
- void ServerLogUtil.debug('AlbumCover', `专辑 ${album.name} 使用直接封面: ${directUrl}`);
- return;
- }
- // 生成封面URL
- const coverId = album.coverArt ?? album.coverArtId ?? (album.id ? `al-${album.id}` : undefined);
- const url = await this.buildCoverUrl(account, coverId);
- if (url) {
- map.set(album.id, url);
- generatedCoverCount++;
- void ServerLogUtil.debug('AlbumCover', `专辑 ${album.name} 生成封面URL: ${coverId} -> ${url}`);
- } else {
- failedCoverCount++;
- void ServerLogUtil.warn('AlbumCover', `专辑 ${album.name} 无可用封面: ${JSON.stringify({coverArt: album.coverArt, coverArtId: album.coverArtId, id: album.id})}`);
- }
- } catch (error) {
- failedCoverCount++;
- void ServerLogUtil.warn('AlbumCover', `专辑 ${album.name} 封面解析失败: ${(error as Error).message}`);
- }
- })());
- }
- await Promise.all(tasks);
- void ServerLogUtil.info('AlbumCover', `专辑封面处理完成: 直接嵌入 ${directCoverCount}, 生成URL ${generatedCoverCount}, 失败 ${failedCoverCount}`);
- return map;
- }
- private async buildArtistCoverMap(artists: NavidromeRestArtist[], account: WebDavAccount): Promise<Map<string, string>> {
- const map = new Map<string, string>();
- const tasks: Promise<void>[] = [];
- let directCoverCount = 0;
- let generatedCoverCount = 0;
- let failedCoverCount = 0;
- void ServerLogUtil.info('ArtistCover', `开始处理 ${artists.length} 位艺术家的封面`);
- for (let i = 0; i < artists.length; i++) {
- const artist = artists[i];
- tasks.push((async () => {
- try {
- // 尝试获取已有图片URL
- const directUrl = artist.mediumImageUrl ?? artist.largeImageUrl ?? this.resolveEmbedCover(account, artist.coverArtPath);
- if (directUrl) {
- map.set(artist.id, directUrl);
- directCoverCount++;
- void ServerLogUtil.debug('ArtistCover', `艺术家 ${artist.name} 使用已有图片: ${directUrl}`);
- return;
- }
- // 生成封面URL
- const coverId = artist.coverArt ?? artist.coverArtId ?? (artist.id ? `ar-${artist.id}` : undefined);
- const url = await this.buildCoverUrl(account, coverId, 256);
- if (url) {
- map.set(artist.id, url);
- generatedCoverCount++;
- void ServerLogUtil.debug('ArtistCover', `艺术家 ${artist.name} 生成封面URL: ${coverId} -> ${url}`);
- } else {
- failedCoverCount++;
- void ServerLogUtil.warn('ArtistCover', `艺术家 ${artist.name} 无可用封面: ${JSON.stringify({coverArt: artist.coverArt, coverArtId: artist.coverArtId, id: artist.id})}`);
- }
- } catch (error) {
- failedCoverCount++;
- void ServerLogUtil.warn('ArtistCover', `艺术家 ${artist.name} 封面解析失败: ${(error as Error).message}`);
- }
- })());
- }
- await Promise.all(tasks);
- void ServerLogUtil.info('ArtistCover', `艺术家封面处理完成: 直接链接 ${directCoverCount}, 生成URL ${generatedCoverCount}, 失败 ${failedCoverCount}`);
- return map;
- }
- private convertApiSongsToRestSongs(songs: NavidromeSong[]): NavidromeRestSong[] {
- return songs.map((song: NavidromeSong): NavidromeRestSong => ({
- id: song.id,
- title: song.title,
- artist: song.artist,
- artistId: song.artistId,
- album: song.album,
- albumId: song.albumId,
- duration: song.duration,
- bitRate: song.bitRate,
- suffix: song.suffix,
- size: song.size,
- createdAt: song.created,
- genre: song.genre,
- track: song.track,
- year: song.year,
- contentType: song.contentType,
- coverArt: song.coverArt,
- coverArtId: song.coverArt
- }));
- }
- private async convertSongsToVideoItems(songs: NavidromeRestSong[], account: WebDavAccount): Promise<VideoItem[]> {
- const tasks: Promise<VideoItem>[] = [];
- let successCount = 0;
- let failedCount = 0;
- void ServerLogUtil.info('SongConvert', `开始转换 ${songs.length} 首歌曲为 VideoItem`);
- for (let i = 0; i < songs.length; i++) {
- const song = songs[i];
- tasks.push((async () => {
- try {
- let coverUrl: string | undefined;
- try {
- coverUrl = await this.resolveSongCover(song, account);
- } catch (error) {
- void ServerLogUtil.warn('SongConvert', `歌曲 ${song.title} 封面解析失败: ${(error as Error).message}`);
- }
- const videoItem = this.convertSongToVideoItem(song, account, coverUrl);
- successCount++;
- // 记录前几首歌的详细信息用于调试
- if (i < 3) {
- void ServerLogUtil.debug('SongConvert', `歌曲 ${i + 1}: ${videoItem.name}, 封面: ${coverUrl ? '有' : '无'}, 路径: ${videoItem.filePath}`);
- }
- return videoItem;
- } catch (error) {
- failedCount++;
- void ServerLogUtil.error('SongConvert', `歌曲 ${song.title} 转换失败: ${(error as Error).message}`);
- throw new Error(`歌曲 ${song.title} 转换失败: ${(error as Error).message}`);
- }
- })());
- }
- const results = await Promise.all(tasks);
- void ServerLogUtil.info('SongConvert', `歌曲转换完成: 成功 ${successCount}, 失败 ${failedCount}`);
- return results;
- }
- private async resolveSongCover(song: NavidromeRestSong, account: WebDavAccount): Promise<string | undefined> {
- if (song.albumId) {
- const albumCover = song.albumId ? this.albumCoverLookup.get(song.albumId) : undefined;
- if (albumCover) {
- return albumCover;
- }
- }
- const directUrl = this.resolveEmbedCover(account, song.embedArtPath ?? song.coverArtPath);
- if (directUrl) {
- return directUrl;
- }
- const coverId = song.coverArt ?? song.coverArtId ?? song.id;
- return this.buildCoverUrl(account, coverId);
- }
- private async buildCoverUrl(account: WebDavAccount, coverId?: string, size: number = 300): Promise<string | undefined> {
- if (!coverId || coverId.trim().length === 0) {
- return undefined;
- }
- const normalizedId = coverId.trim();
- const cacheKey = `${normalizedId}_${size}`;
- const cached = this.coverUrlCache.get(cacheKey);
- if (cached) {
- void ServerLogUtil.debug('CoverCache', `封面URL缓存命中: ${cacheKey} -> ${cached}`);
- return cached;
- }
- void ServerLogUtil.debug('CoverCache', `生成封面URL: ${coverId} (尺寸: ${size})`);
- const url = await navidromeApi.buildCoverArtUrl(account, normalizedId, size);
- if (url) {
- this.coverUrlCache.set(cacheKey, url);
- void ServerLogUtil.debug('CoverCache', `封面URL已缓存: ${cacheKey} -> ${url}`);
- } else {
- void ServerLogUtil.warn('CoverCache', `封面URL生成失败: ${coverId} (尺寸: ${size})`);
- }
- return url;
- }
- /**
- * 记录账号缓存信息
- */
- private async logAccountCacheInfo(account: WebDavAccount): Promise<void> {
- try {
- void ServerLogUtil.info('AccountInfo', `账号信息: ${ServerLogUtil.sanitizeAccount(account)}`);
- // 记录缓存路径信息
- const cachePreview = this.getCachePreviewInfo(account);
- if (cachePreview) {
- void ServerLogUtil.info('AccountInfo', `Navidrome缓存目录结构:`);
- void ServerLogUtil.info('AccountInfo', `- 缓存根目录: ${cachePreview.cacheRoot}`);
- void ServerLogUtil.info('AccountInfo', `- 示例缓存路径: ${cachePreview.examplePath}`);
- } else {
- void ServerLogUtil.warn('AccountInfo', '无法预览缓存目录:上下文或根目录不可用');
- }
- // 记录封面缓存状态
- void ServerLogUtil.info('AccountInfo', `当前封面URL缓存数量: ${this.coverUrlCache.size}`);
- if (this.coverUrlCache.size > 0) {
- const cacheKeys = Array.from(this.coverUrlCache.keys()).slice(0, 10);
- void ServerLogUtil.debug('AccountInfo', `封面缓存示例: ${cacheKeys.join(', ')}`);
- }
- } catch (error) {
- void ServerLogUtil.error('AccountInfo', `记录账号信息失败: ${(error as Error).message}`);
- }
- }
- /**
- * 记录缓存统计信息
- */
- private async logCacheStatistics(account: WebDavAccount): Promise<void> {
- try {
- void ServerLogUtil.info('CacheStats', '=== Navidrome 缓存统计 ===');
- void ServerLogUtil.info('CacheStats', `封面URL缓存: ${this.coverUrlCache.size} 个条目`);
- void ServerLogUtil.info('CacheStats', `已加载歌曲: ${this.allVideos.length} 首`);
- void ServerLogUtil.info('CacheStats', `已处理艺术家: ${this.artists.length} 位`);
- void ServerLogUtil.info('CacheStats', `已处理专辑: ${this.albums.length} 张`);
- // 计算封面统计
- const songsWithCover = this.allVideos.filter(song => song.pixelMapPath && song.pixelMapPath.length > 0).length;
- const albumsWithCover = this.albums.filter(album => album.coverUrl && album.coverUrl.length > 0).length;
- const artistsWithCover = this.artists.filter(artist => artist.coverUrl && artist.coverUrl.length > 0).length;
- void ServerLogUtil.info('CacheStats', `封面统计:`);
- void ServerLogUtil.info('CacheStats', `- 歌曲有封面: ${songsWithCover}/${this.allVideos.length} (${Math.round(songsWithCover / this.allVideos.length * 100)}%)`);
- void ServerLogUtil.info('CacheStats', `- 专辑有封面: ${albumsWithCover}/${this.albums.length} (${Math.round(albumsWithCover / this.albums.length * 100)}%)`);
- void ServerLogUtil.info('CacheStats', `- 艺术家有封面: ${artistsWithCover}/${this.artists.length} (${Math.round(artistsWithCover / this.artists.length * 100)}%)`);
- } catch (error) {
- void ServerLogUtil.error('CacheStats', `记录缓存统计失败: ${(error as Error).message}`);
- }
- }
- private resolveEmbedCover(account: WebDavAccount, path?: string): string | undefined {
- return navidromeRestApi.resolveResourceUrl(account, path);
- }
- private convertSongToVideoItem(song: NavidromeRestSong, account: WebDavAccount, coverUrl?: string): VideoItem {
- const title = song.title ?? Constants.UNKNOWN_TITLE;
- const videoItem = new VideoItem(
- title,
- song.id,
- `navidrome://${account.id ?? 0}/${song.id}`,
- CommonConstants.TYPE_NAVIDROME,
- song.size ?? 0,
- song.createdAt ?? '',
- Utility.formatFSize(song.size ?? 0),
- undefined,
- song.artist ?? Constants.UNKNOWN_ARTIST,
- song.album ?? '',
- `${title}${song.suffix ? '.' + song.suffix : ''}`
- );
- const durationStr = this.formatSongDuration(song.duration);
- if (durationStr) {
- videoItem.duration = durationStr;
- }
- videoItem.size = Utility.formatFSize(song.size ?? 0);
- videoItem.bit_rate = song.bitRate ? song.bitRate.toString() : undefined;
- videoItem.genre = song.genre;
- videoItem.webdav_account_id = account.id?.toString();
- videoItem.remote_rel_path = song.id;
- videoItem.navArtistId = song.artistId;
- videoItem.navAlbumId = song.albumId;
- videoItem.pixelMapPath = coverUrl;
-
- // 调试日志:检查歌曲的 albumId 和 artistId
- if (this.allVideos.length < 3) {
- Logger.info('heanup', `歌曲 ${title}: artistId=${song.artistId}, albumId=${song.albumId}, artist=${song.artist}, album=${song.album}`);
- }
- if (song.track !== undefined && song.track !== null) {
- videoItem.track = song.track.toString();
- }
- if (song.year !== undefined && song.year !== null) {
- videoItem.year = song.year.toString();
- }
- if (song.contentType) {
- videoItem.mimeType = song.contentType;
- }
- return videoItem;
- }
- private formatSongDuration(durationSeconds?: number): string | undefined {
- if (durationSeconds === undefined || durationSeconds === null || durationSeconds < 0) {
- return undefined;
- }
- const totalSeconds = Math.floor(durationSeconds);
- const minutes = Math.floor(totalSeconds / 60);
- const seconds = totalSeconds % 60;
- const pad = (value: number) => value.toString().padStart(2, '0');
- return `${pad(minutes)}:${pad(seconds)}`;
- }
- @Builder
- topTitleBar() {
- Column() {
- Row({ space: 6 }) {
- // 标题或搜索框
- if (!this.isSearchMode) {
- // 左侧返回按钮
- Button({ type: ButtonType.Circle, stateEffect: true }) {
- SymbolGlyph($r('sys.symbol.sort'))
- .attributeModifier(new SymbolGlyphFancyModifier(25, '', ''))
- }
- .attributeModifier(new ButtonFancyModifier(40, 40))
- .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.6 })
- .animation({ duration: 300, curve: Curve.Ease })
- .onClick(() => {
- this.getUIContext().animateTo({ duration: 555 }, () => {
- // 动画闭包内控制Image组件的出现和消失
- this.isShowDrawer = !this.isShowDrawer
- this.offsetX = 0
- })
- })
- .attributeModifier(new ShadowModifier())
- .zIndex(0)
- Text(this.selectedAccount.name)
- .margin({ left: 3, right: 10 })
- .fontColor($r('app.color.text_color'))
- .fontSize(18)
- .maxLines(1)
- .textOverflow({ overflow: TextOverflow.MARQUEE })
- .layoutWeight(1)
- .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.6 })
- .onClick(() => {
- // 可以添加标题点击事件
- })
- .animation({ duration: 300, curve: Curve.Ease })
- } else {
- Button({ type: ButtonType.Circle, stateEffect: true }) {
- SymbolGlyph($r('sys.symbol.chevron_left'))
- .attributeModifier(new SymbolGlyphFancyModifier(24, '', ''))
- }
- .attributeModifier(new ButtonFancyModifier(40, 40))
- .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.6 })
- .animation({ duration: 300, curve: Curve.Ease })
- .onClick(() => {
- this.isSearchMode = false;
- void this.onSearchInput('');
- })
- .attributeModifier(new ShadowModifier())
- .zIndex(0)
- }
- // 搜索框
- Search({ value: this.searchText, placeholder: '搜索标题、艺术家...' })
- .searchButton('搜索', { fontColor: this.themeColor })
- .searchIcon({
- src: $r('sys.media.ohos_ic_public_search_filled')
- })
- .cancelButton({
- style: CancelButtonStyle.CONSTANT,
- icon: {
- src: $r('sys.media.ohos_ic_public_cancel_filled')
- }
- })
- .layoutWeight(1)
- .height(35)
- .maxLength(20)
- .backgroundColor(this.isDarkMode?Color.Black:'#F5F5F5')
- .placeholderColor(Color.Grey)
- .placeholderFont({ size: 14, weight: 400 })
- .textFont({ size: 14, weight: 400 })
- .onSubmit((value: string) => {
- void this.onSearchInput(value);
- })
- .onChange((value: string) => {
- void this.onSearchInput(value);
- })
- .visibility(this.isSearchMode?Visibility.Visible:Visibility.None)
- .animation({ duration: 300, curve: Curve.Ease })
- // 搜索/排序按钮
- if (!this.isSearchMode) {
- // 搜索按钮
- Button({ type: ButtonType.Circle, stateEffect: true }) {
- SymbolGlyph($r('sys.symbol.magnifyingglass'))
- .attributeModifier(new SymbolGlyphFancyModifier(25, '', ''))
- }
- .attributeModifier(new ButtonFancyModifier(40, 40))
- .animation({ duration: 300, curve: Curve.Ease })
- .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.6 })
- .attributeModifier(new ShadowModifier())
- .zIndex(0)
- .visibility(this.selectedTab==0?Visibility.Visible:Visibility.None)
- .onClick(() => {
- this.isSearchMode = true;
- if (!this.isSearchLoading && this.searchText.length === 0) {
- this.filteredList = [];
- }
- })
- // 排序按钮
- Button({ type: ButtonType.Circle, stateEffect: true }) {
- SymbolGlyph($r('sys.symbol.list_number'))
- .attributeModifier(new SymbolGlyphFancyModifier(25, '', ''))
- }
- .attributeModifier(new ButtonFancyModifier(40, 40))
- .animation({ duration: 300, curve: Curve.Ease })
- .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.6 })
- .bindMenu(this.SortMenuBuilder)
- .attributeModifier(new ShadowModifier())
- .zIndex(0)
- }
- }
- .width('100%')
- .height(55)
- .padding({ left: 15, right: 15 })
- .justifyContent(FlexAlign.SpaceBetween)
- .alignItems(VerticalAlign.Center)
- // 分段按钮
- SegmentButton({
- options: this.tabOptions,
- selectedIndexes: $tabSelectedIndexes
- })
- .width('100%')
- .padding({ left: 25, right: 25, top: 5, bottom: 5 })
- }
- .width('100%')
- .padding({ top: this.topRectHeight + 5 })
- // .backgroundColor($r('app.color.start_window_background'))
- }
- @Builder
- SortMenuBuilder() {
- Menu() {
- MenuItem({
- symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.text_and_arrow_up')),
- content: $r('app.string.sort_by_name')
- })
- .onClick(async () => {
- this.doSortType(0);
- PreferencesUtil.put("navidromeSortType", 0);
- })
- MenuItem({
- symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.text_and_arrow_down')),
- content: '按名称降序'
- })
- .onClick(async () => {
- this.doSortType(1);
- PreferencesUtil.put("navidromeSortType", 1);
- })
- MenuItem({
- symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.clock')),
- content: '按艺术家升序'
- })
- .onClick(async () => {
- this.doSortType(2);
- PreferencesUtil.put("navidromeSortType", 2);
- })
- MenuItem({
- symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.timer')),
- content: '按艺术家降序'
- })
- .onClick(async () => {
- this.doSortType(3);
- PreferencesUtil.put("navidromeSortType", 3);
- })
- MenuItem({
- symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.text_and_arrow_up')),
- content: '按专辑升序'
- })
- .onClick(async () => {
- this.doSortType(4);
- PreferencesUtil.put("navidromeSortType", 4);
- })
- MenuItem({
- symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.text_and_arrow_down')),
- content: '按专辑降序'
- })
- .onClick(async () => {
- this.doSortType(5);
- PreferencesUtil.put("navidromeSortType", 5);
- })
- }
- }
- doSortType(index: number) {
- this.sortType = index;
- const songs = this.isSearchMode && this.searchText.length > 0 ? this.filteredList : this.allVideos;
- const sortTypeNames = ['名称升序', '名称降序', '艺术家升序', '艺术家降序', '专辑升序', '专辑降序'];
- const sortTypeName = sortTypeNames[index] || '未知排序';
- // 记录排序操作
- void ServerLogUtil.info('NavidromeSort', `应用排序: ${sortTypeName} (${index})`);
- void ServerLogUtil.info('NavidromeSort', `排序范围: ${songs.length} 首歌曲 (${this.isSearchMode ? '搜索结果' : '全部歌曲'})`);
- const startTime = Date.now();
- // 对歌曲列表进行排序
- switch (index) {
- case 0: // 名称升序
- Utility.doSortListAscending(songs,false)
- break;
- case 1: // 名称降序
- Utility.doSortListDescending(songs,true)
- break;
- case 2: // 艺术家升序
- songs.sort((a, b) => {
- // 处理艺术家可能为undefined的字符串比较
- const artistA = a.artist?.trim() || ''; // 可选添加 trim() 处理空格
- const artistB = b.artist?.trim() || '';
- return artistA.localeCompare(artistB);
- });
- break;
- case 3: // 艺术家降序
- songs.sort((a, b) => {
- // 处理艺术家可能为undefined的字符串比较
- const artistA = a.artist?.trim() || ''; // 可选添加 trim() 处理空格
- const artistB = b.artist?.trim() || '';
- return artistB.localeCompare(artistA);
- });
- break;
- case 4: // 专辑升序
- songs.sort((a, b) => {
- const albumA = a.album?.trim() || ''; // 可选添加 trim() 处理空格
- const albumB = b.album?.trim() || '';
- return albumA.localeCompare(albumB);
- });
- break;
- case 5: // 专辑降序
- songs.sort((a, b) => {
- const albumA = a.album?.trim() || ''; // 可选添加 trim() 处理空格
- const albumB = b.album?.trim() || '';
- return albumB.localeCompare(albumA);
- });
- break;
- }
- const sortTime = Date.now() - startTime;
- // 更新显示列表
- if (this.isSearchMode) {
- this.filteredList = [...songs];
- }
- // 记录排序结果
- void ServerLogUtil.info('NavidromeSort', `排序完成: ${sortTypeName}`);
- void ServerLogUtil.info('NavidromeSort', `- 排序耗时: ${sortTime}ms`);
- void ServerLogUtil.debug('NavidromeSort', `排序结果示例: ${songs.slice(0, 3).map(s => `${s.name} (${s.artist})`).join(', ')}`);
- }
- // 实时搜索逻辑(改为远程API搜索)
- private async onSearchInput(value: string): Promise<void> {
- const keyword = value.trim();
- this.searchText = keyword;
- const ticket = ++this.searchTicket;
- void ServerLogUtil.debug('NavidromeSearch', `搜索输入: "${value}" -> "${keyword}"`);
- if (keyword.length === 0) {
- this.filteredList = [];
- this.isSearchLoading = false;
- void ServerLogUtil.info('NavidromeSearch', '搜索已清空,显示所有歌曲');
- return;
- }
- if (!this.isSearchMode) {
- this.isSearchMode = true;
- }
- const account = this.resolveActiveAccount();
- if (!account) {
- this.filteredList = [];
- this.isSearchLoading = false;
- ToastUtil.showToast('Navidrome账号不可用');
- return;
- }
- this.isSearchLoading = true;
- this.filteredList = [];
- const startTime = Date.now();
- void ServerLogUtil.info('NavidromeSearch', `开始远程搜索: "${keyword}"`);
- try {
- const songs = await navidromeApi.searchSongs(account, keyword, NAVIDROME_SEARCH_LIMIT);
- if (ticket !== this.searchTicket) {
- return;
- }
- const searchTime = Date.now() - startTime;
- if (!songs || songs.length === 0) {
- this.filteredList = [];
- void ServerLogUtil.warn('NavidromeSearch', `搜索无结果: "${keyword}"`);
- void ServerLogUtil.info('NavidromeSearch', `- 搜索耗时: ${searchTime}ms`);
- return;
- }
- const restSongs = this.convertApiSongsToRestSongs(songs);
- const videoItems = await this.convertSongsToVideoItems(restSongs, account);
- if (ticket !== this.searchTicket) {
- return;
- }
- this.filteredList = videoItems;
- this.doSortType(this.sortType);
- void ServerLogUtil.info('NavidromeSearch', `搜索完成: "${keyword}"`);
- void ServerLogUtil.info('NavidromeSearch', `- 搜索耗时: ${searchTime}ms`);
- void ServerLogUtil.info('NavidromeSearch', `- 匹配结果: ${videoItems.length}`);
- void ServerLogUtil.debug('NavidromeSearch', `搜索结果示例: ${videoItems.slice(0, 3).map(s => `${s.name} (${s.artist})`).join(', ')}`);
- } catch (error) {
- if (ticket !== this.searchTicket) {
- return;
- }
- this.filteredList = [];
- const message = (error as Error).message ?? 'Navidrome 搜索失败';
- ToastUtil.showToast(message);
- void ServerLogUtil.error('NavidromeSearch', `搜索失败: ${message}`);
- void ServerLogUtil.info('NavidromeSearch', `- 搜索耗时: ${Date.now() - startTime}ms`);
- } finally {
- if (ticket === this.searchTicket) {
- this.isSearchLoading = false;
- }
- }
- }
- private getCurrentCount(): number {
- switch (this.selectedTab) {
- case 1:
- return this.artists.length;
- case 2:
- return this.albums.length;
- default:
- return this.getVisibleSongs().length;
- }
- }
- private getEmptyTitle(): string {
- switch (this.selectedTab) {
- case 1:
- return '暂无艺术家';
- case 2:
- return '暂无专辑';
- default:
- if (this.isSearchMode && this.searchText.length > 0) {
- return this.isSearchLoading ? '正在搜索远程歌曲' : '没有匹配的远程歌曲';
- }
- if (this.filterType !== NavFilterType.None && this.isFilterLoading) {
- return '正在加载筛选结果';
- }
- return this.filterType === NavFilterType.None ? '暂无音乐' : '该筛选下暂无歌曲';
- }
- }
- private getEmptySubtitle(): string {
- switch (this.selectedTab) {
- case 1:
- return '当前筛选没有找到艺术家';
- case 2:
- return '当前筛选没有找到专辑';
- default:
- if (this.isSearchMode && this.searchText.length > 0) {
- return this.isSearchLoading ? '请稍候,正在通过 API 搜索' : '换个关键词再试试吧';
- }
- if (this.filterType !== NavFilterType.None && this.isFilterLoading) {
- return '请稍候...';
- }
- return this.filterType === NavFilterType.None ? '当前分类下没有找到音乐文件' : '请尝试调整筛选条件';
- }
- }
- @Builder
- buildSongItem(song: VideoItem, index: number) {
- Button({ type: ButtonType.Capsule, stateEffect: true }) {
- Row({ space: 12 }) {
- // 歌曲封面
- Image(song.pixelMapPath ? song.pixelMapPath : $r('app.media.music_red'))
- .width(52)
- .height(52)
- .borderRadius(9)
- .sourceSize({ width: 38, height: 38 })
- .draggable(false)
- .interpolation(ImageInterpolation.High)// 用于重采样后的抗锯齿
- .autoResize(true) // 重采样,可减少内存占用
- .alt($r('app.media.music_red'))
- .fillColor(song.pixelMapPath ? undefined : this.themeColor)
- .objectFit(ImageFit.Cover)
- .margin({ left: 20 })
- .shadow({
- radius: StrUtil.isEmpty(song.pixelMapPath) ?6:14,
- type: ShadowType.BLUR,
- color: 'on_primary'
- })
- .onClick(() => {
- this.playSong(song, index, true);
- })
- // 歌曲信息
- Column({ space: 4 }) {
- Text(song.name)
- .fontSize(15)
- .fontColor(this.currentSong?.filePath == song.filePath ? this.themeColor : $r('app.color.index_tab_font_color'))
- .maxLines(1)
- .textOverflow({ overflow: TextOverflow.Ellipsis })
- Row() {
- Text((song.artist ?? '') + " ")
- .fontSize(13)
- .fontColor(this.currentSong?.filePath == song.filePath ? this.themeColor : $r('app.color.index_tab_font_color'))
- .opacity(0.6)
- .maxLines(1)
- .visibility(song.artist ? Visibility.Visible : Visibility.None)
- .textOverflow({ overflow: TextOverflow.Ellipsis })
- Text(this.buildSongMetaLine(song))
- .fontSize(13)
- .fontColor(this.currentSong?.filePath == song.filePath ? this.themeColor : $r('app.color.index_tab_font_color'))
- .opacity(0.6)
- .maxLines(1)
- .textOverflow({ overflow: TextOverflow.Ellipsis })
- }
- .width('90%')
- }
- .alignItems(HorizontalAlign.Start)
- .layoutWeight(1)
- .padding({ right: 20 })
- Column() {
- ImageAnimator()
- .images(CommonConstants.IMAGE_FRAME_INFO)// 动画数组
- .duration(1000)// 持续
- .state(AnimationStatus.Running)// 动画状态
- .fillMode(FillMode.Forwards)
- .visibility(this.currentSong?.filePath == song.filePath ? Visibility.Visible :
- Visibility.None)
- .width(18)
- .margin({ right: 12, top: 8, bottom: 8 })
- .height(18)
- .iterations(-1) // 播放次数
- }
- }
- }
- .width('100%')
- .padding(12)
- .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.8 })
- .backgroundColor(Color.Transparent)
- .onClick(() => {
- this.playSong(song, index);
- })
- }
- @Builder
- buildArtistItem(artist: NavidromeRestArtist) {
- Button({ type: ButtonType.Capsule, stateEffect: true }) {
- Row({ space: 12 }) {
- Image(artist.coverUrl ?? $r('app.media.music_red'))
- .width(48)
- .height(48)
- .borderRadius(10)
- .draggable(false)
- .interpolation(ImageInterpolation.High)// 用于重采样后的抗锯齿
- .autoResize(true) // 重采样,可减少内存占用
- // .sourceSize({ width: 38, height: 38 })
- .fillColor(artist.coverUrl ? undefined : this.themeColor)
- .objectFit(ImageFit.Cover)
- .margin({ left: 20 })
- Column({ space: 4 }) {
- Text(artist.name ?? Constants.UNKNOWN_ARTIST)
- .fontSize(15)
- .fontColor($r('app.color.index_tab_font_color'))
- .maxLines(1)
- .textAlign(TextAlign.Start)
- .textOverflow({ overflow: TextOverflow.Ellipsis })
- Text(this.buildArtistMetaLine(artist))
- .fontSize(13)
- .fontColor($r('app.color.index_tab_font_color'))
- .opacity(0.6)
- .maxLines(1)
- .textOverflow({ overflow: TextOverflow.Ellipsis })
- }
- .alignItems(HorizontalAlign.Start)
- .padding({ right: 20 })
- }
- .width('100%')
- }
- .width('100%')
- .padding(12)
- .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.85 })
- .backgroundColor(Color.Transparent)
- .onClick(() => {
- this.onArtistSelected(artist);
- })
- }
- @Builder
- buildAlbumItem(album: NavidromeRestAlbum) {
- Button({ type: ButtonType.Capsule, stateEffect: true }) {
- Row({ space: 12 }) {
- Image(album.coverUrl ?? $r('app.media.music_red'))
- .width(48)
- .height(48)
- .borderRadius(10)
- .clip(true)
- .draggable(false)
- // .interpolation(ImageInterpolation.High)// 用于重采样后的抗锯齿
- // .autoResize(true) // 重采样,可减少内存占用
- .sourceSize({ width: 38, height: 38 })
- .fillColor(album.coverUrl ? undefined : this.themeColor)
- .objectFit(ImageFit.Cover)
- .margin({ left: 20 })
- Column({ space: 4 }) {
- Text(album.name ?? '未知专辑')
- .fontSize(15)
- .fontColor($r('app.color.index_tab_font_color'))
- .maxLines(1)
- .textAlign(TextAlign.Start)
- .textOverflow({ overflow: TextOverflow.Ellipsis })
- Row() {
- Text(album.artist ?? Constants.UNKNOWN_ARTIST)
- .fontSize(13)
- .fontColor($r('app.color.index_tab_font_color'))
- .opacity(0.6)
- .maxLines(1)
- .textOverflow({ overflow: TextOverflow.Ellipsis })
- Text(this.buildAlbumMetaLine(album))
- .fontSize(13)
- .fontColor($r('app.color.index_tab_font_color'))
- .opacity(0.6)
- .maxLines(1)
- .textOverflow({ overflow: TextOverflow.Ellipsis })
- }
- }
- .alignItems(HorizontalAlign.Start)
- .padding({ right: 20 })
- }
- .width('100%')
- }
- .width('100%')
- .padding(12)
- .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.85 })
- .backgroundColor(Color.Transparent)
- .onClick(() => {
- this.onAlbumSelected(album);
- })
- }
- private buildSongMetaLine(song: VideoItem): string {
- const parts: string[] = [];
- if (song.duration) {
- parts.push(song.duration as string);
- }
- // if (song.size) {
- // parts.push(song.size as string);
- // }
- // if (parts.length === 0 && song.cTime) {
- // parts.push(song.cTime as string);
- // }
- return parts.join(' · ');
- }
- private buildArtistMetaLine(artist: NavidromeRestArtist): string {
- const albumCount = artist.albumCount ?? 0;
- const songCount = artist.songCount ?? 0;
- const playCount = artist.playCount ?? 0;
- return `专辑 ${albumCount} · 歌曲 ${songCount} `;
- }
- private buildAlbumMetaLine(album: NavidromeRestAlbum): string {
- const parts: string[] = [];
- if (album.duration !== undefined) {
- const duration = this.formatSongDuration(album.duration);
- if (duration) {
- parts.push(' '+duration);
- }
- }
- if (album.minYear) {
- parts.push(`发行 ${album.minYear}`);
- }
- return parts.join(' · ');
- }
- private getVisibleSongs(): VideoItem[] {
- if (this.isSearchMode) {
- return this.searchText.length > 0 ? this.filteredList : this.allVideos;
- }
- if (this.filterType !== NavFilterType.None) {
- return this.filterSongs;
- }
- return this.allVideos;
- }
- private onArtistSelected(artist: NavidromeRestArtist): void {
- if (!artist || !artist.id) {
- return;
- }
- void this.applyFilter(NavFilterType.Artist, artist.id, artist.name ?? Constants.UNKNOWN_ARTIST);
- }
- private onAlbumSelected(album: NavidromeRestAlbum): void {
- if (!album || !album.id) {
- return;
- }
- void this.applyFilter(NavFilterType.Album, album.id, album.name ?? '未知专辑');
- }
- private async applyFilter(type: NavFilterType, id: string, label: string): Promise<void> {
- // 记录筛选操作
- void ServerLogUtil.info('NavidromeFilter', `应用筛选:`);
- void ServerLogUtil.info('NavidromeFilter', `- 类型: ${type} (${type === NavFilterType.Artist ? '艺术家' : type === NavFilterType.Album ? '专辑' : '无'})`);
- void ServerLogUtil.info('NavidromeFilter', `- ID: ${id}`);
- void ServerLogUtil.info('NavidromeFilter', `- 标签: ${label}`);
- void ServerLogUtil.info('NavidromeFilter', `- 筛选前总歌曲数: ${this.allVideos.length}`);
- // 先更新状态
- this.filterType = type;
- this.filterId = id;
- this.filterLabel = label;
- // 退出搜索模式,确保显示筛选结果
- this.isSearchMode = false;
- this.searchText = '';
- this.filteredList = [];
- this.isSearchLoading = false;
- this.searchTicket++;
- this.filterSongs = [];
- this.isFilterLoading = true;
- // 调试日志:检查筛选结果
- void this.loadSongsForFilter().catch((error: Error) => {
- void ServerLogUtil.error('NavidromeFilter', `筛选歌曲加载失败: ${error.message}`);
- ToastUtil.showToast(error.message || '筛选数据加载失败');
- });
- // 然后执行动画切换标签页
- this.getUIContext().animateTo({ duration: 555 }, () => {
- this.selectedTab = 0;
- this.tabSelectedIndexes = [0];
- })
- }
- private async loadSongsForFilter(): Promise<void> {
- if (this.filterType === NavFilterType.None || !this.filterId) {
- this.filterSongs = [];
- this.isFilterLoading = false;
- return;
- }
- const account = this.resolveActiveAccount();
- if (!account) {
- this.filterSongs = [];
- this.isFilterLoading = false;
- throw new Error('Navidrome账号不可用');
- }
- const expectedFilterId = this.filterId;
- const expectedFilterType = this.filterType;
- try {
- let songs: NavidromeRestSong[] = [];
- if (this.filterType === NavFilterType.Artist) {
- songs = await navidromeRestApi.fetchSongsByArtist(account, this.filterId);
- } else if (this.filterType === NavFilterType.Album) {
- songs = await navidromeRestApi.fetchSongsByAlbum(account, this.filterId);
- }
- const videoItems = await this.convertSongsToVideoItems(songs, account);
- if (expectedFilterId !== this.filterId || expectedFilterType !== this.filterType) {
- return;
- }
- this.filterSongs = videoItems;
- if (videoItems.length === 0) {
- void ServerLogUtil.warn('NavidromeFilter', '筛选下暂无歌曲');
- } else {
- void ServerLogUtil.info('NavidromeFilter', `筛选歌曲加载完成: ${videoItems.length} 首`);
- }
- } finally {
- this.isFilterLoading = false;
- }
- }
- private clearFilter(): void {
- this.filterType = NavFilterType.None;
- this.filterId = '';
- this.filterLabel = '';
- this.filterSongs = [];
- this.isFilterLoading = false;
- }
- private playSong(song: VideoItem, index: number, isJump: boolean = false): void {
- try {
- if (!this.allVideos || this.allVideos.length === 0) {
- ToastUtil.showToast('暂无可播放的歌曲');
- return;
- }
- const account = this.resolveActiveAccount();
- if (!account || !account.id) {
- ToastUtil.showToast('Navidrome账号信息不完整,无法播放');
- return;
- }
- // 记录播放详细信息
- void ServerLogUtil.info('NavidromePlay', `开始播放歌曲: ${song.name} (#${index})`);
- void ServerLogUtil.info('NavidromePlay', `歌曲信息:`);
- void ServerLogUtil.info('NavidromePlay', `- ID: ${song.id}`);
- void ServerLogUtil.info('NavidromePlay', `- 艺术家: ${song.artist || '未知'}`);
- void ServerLogUtil.info('NavidromePlay', `- 专辑: ${song.album || '未知'}`);
- void ServerLogUtil.info('NavidromePlay', `- 文件大小: ${song.size || '未知'}`);
- void ServerLogUtil.info('NavidromePlay', `- 时长: ${song.duration || '未知'}`);
- void ServerLogUtil.info('NavidromePlay', `- 封面: ${song.pixelMapPath ? '有' : '无'}`);
- void ServerLogUtil.info('NavidromePlay', `- 播放路径: ${song.filePath}`);
- const playlistSource = this.getVisibleSongs().length > 0 ? this.getVisibleSongs() : this.allVideos;
- const targetIndex = playlistSource.findIndex(item => item.id === song.id);
- const startIndex = targetIndex >= 0 ? targetIndex : Math.min(index, Math.max(playlistSource.length - 1, 0));
- void ServerLogUtil.info('NavidromePlay', `播放列表设置: 起始索引 ${startIndex}, 总数 ${playlistSource.length}`);
- setNavidromePlaylist(playlistSource, startIndex);
- const playlistData: PlaylistEventData = {
- playlistId: NAVIDROME_PLAYLIST_ID,
- playlistName: `Navidrome - ${account.name ?? '未知账户'}`,
- songCount: playlistSource.length,
- startIndex,
- isJump: isJump,//设置true会弹出播放页
- songFilePaths: playlistSource.map(item => item.filePath)
- };
- const eventPlaylistPlay: emitter.InnerEvent = { eventId: EventConstants.EVENT_PLAYLIST_PLAY };
- emitter.emit(eventPlaylistPlay, { data: playlistData });
- void ServerLogUtil.info('NavidromePlay', `播放事件已发送`);
- void ServerLogUtil.debug('NavidromePlay', `播放事件详情: 列表ID=${playlistData.playlistId}, 列表名称=${playlistData.playlistName}, 歌曲数=${playlistData.songCount}, 起始索引=${playlistData.startIndex}, 是否跳转=${playlistData.isJump}`);
- if(!this.isNoJumpToHome){
- void ServerLogUtil.debug('NavidromePlay', '跳转到首页播放器');
- // 跳转到首页播放器
- this.getUIContext()?.animateTo({ duration: 555 }, () => {
- this.mType = 0
- })
- }
- } catch (error) {
- const err = error as Error;
- void ServerLogUtil.error('NavidromePlay', `播放失败: ${err.message}`);
- void ServerLogUtil.error('NavidromePlay', `失败歌曲信息: ${song.name} (${song.id})`);
- ToastUtil.showToast('播放失败');
- }
- }
- @Builder
- buildContentView(){
- // 主内容区域
- if (this.loading) {
- Column() {
- LoadingProgress()
- .width(50)
- .height(50)
- .color($r('app.color.title_bar_bg'))
- Text('加载中...')
- .margin({ top: 10 })
- .fontSize(14)
- .fontColor($r('app.color.index_tab_unselected_font_color'))
- }
- .width('100%')
- .layoutWeight(1)
- .justifyContent(FlexAlign.Center)
- } else {
- if (this.selectedTab === 0 && this.filterType !== NavFilterType.None) {
- Row({ space: 8 }) {
- Text(`筛选:${this.filterLabel}`)
- .fontSize(13)
- .fontColor(this.themeColor)
- .layoutWeight(1)
- Button('清除筛选')
- .type(ButtonType.Capsule)
- .backgroundColor(this.themeColor)
- .fontSize(12)
- .onClick(() => this.clearFilter())
- }
- .width('90%')
- .padding({ left: 16, right: 16, top: 12, bottom: 2 })
- }
- if (this.isSearchMode && this.selectedTab === 0 && this.searchText.length > 0 && this.isSearchLoading) {
- Column() {
- LoadingProgress()
- .width(40)
- .height(40)
- .color(this.themeColor)
- Text('正在通过 API 搜索歌曲...')
- .margin({ top: 12 })
- .fontSize(14)
- .fontColor($r('app.color.index_tab_unselected_font_color'))
- }
- .width('100%')
- .layoutWeight(1)
- } else if (this.selectedTab === 0 && this.filterType !== NavFilterType.None && this.isFilterLoading) {
- Column() {
- LoadingProgress()
- .width(40)
- .height(40)
- .color(this.themeColor)
- Text('正在加载筛选歌曲...')
- .margin({ top: 12 })
- .fontSize(14)
- .fontColor($r('app.color.index_tab_unselected_font_color'))
- }
- .width('100%')
- .layoutWeight(1)
- } else {
- List({ space: 8 }) {
- if (this.selectedTab === 0) {
- ForEach(this.getVisibleSongs(), (item: VideoItem, index: number) => {
- ListItem() {
- this.buildSongItem(item, index)
- }
- }, (item: VideoItem) => item.id)
- } else if (this.selectedTab === 1) {
- ForEach(this.artists, (artist: NavidromeRestArtist) => {
- ListItem() {
- this.buildArtistItem(artist)
- }
- }, (artist: NavidromeRestArtist) => artist.id)
- } else {
- ForEach(this.albums, (album: NavidromeRestAlbum) => {
- ListItem() {
- this.buildAlbumItem(album)
- }
- }, (album: NavidromeRestAlbum) => album.id)
- }
- }
- .width('100%')
- .layoutWeight(1)
- .cachedCount(3)
- .padding({ top: 5, bottom: 5 })
- .listDirection(Axis.Vertical)
- .contentEndOffset(this.bottomSafeHeight+70)
- .scrollBar(BarState.Auto)
- .edgeEffect(EdgeEffect.Spring)
- .onReachEnd(() => {
- void this.handleReachEnd();
- })
- }
- // 空状态
- if (this.getCurrentCount() === 0 && !(this.selectedTab === 0 && this.filterType !== NavFilterType.None && this.isFilterLoading) && !(this.isSearchMode && this.searchText.length > 0 && this.isSearchLoading)) {
- Column() {
- Image($r('app.media.music_red'))
- .width(80)
- .height(80)
- .opacity(0.6)
- Text(this.getEmptyTitle())
- .margin({ top: 16 })
- .fontSize(16)
- .fontColor($r('app.color.index_tab_unselected_font_color'))
- Text(this.getEmptySubtitle())
- .margin({ top: 8 })
- .fontSize(14)
- .fontColor($r('app.color.index_tab_unselected_font_color'))
- }
- .width('100%')
- .layoutWeight(1)
- .justifyContent(FlexAlign.Center)
- }
- }
- }
- build() {
- Stack() {
- Column() {
- this.buildContentView();
- }
- .padding({top:this.topRectHeight+98})
- Column() {
- this.topTitleBar()
- }
- }
- .alignContent(Alignment.Top)
- .width('100%')
- .height('100%')
- }
- }
|