| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468 |
- 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, NavidromeRestPlaylist } 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';
- import { SettingPage } from '../pages/SettingPage';
- import { jellyfinApi, JellyfinAlbum, JellyfinArtist, JellyfinSong } from '../common/network/JellyfinApi';
- import { embyApi, EmbyAlbum, EmbyArtist, EmbySong } from '../common/network/EmbyApi';
- import { getRemoteDriveDisplayLabel } from '../common/util/RemoteDriveLabel';
- 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,
- Playlist = 3
- }
- interface CachePreviewInfo {
- cacheRoot: string;
- examplePath: string;
- }
- interface LibraryInfo {
- type: number;
- scheme: string;
- }
- @Component
- export struct NavidromePage {
- @State isShowTitleBar: boolean = true //是否显示分类导航条
- private scroller: Scroller = new Scroller()
- private prevOffsetY: number = 0; // 记录上一次的Y轴偏移量
- @State autoHideTitle: boolean = true //滚动自动隐藏标题栏
- @State isCustomizeBg: boolean = false //自定义背景界面
- @StorageProp('isLandscape') isLandscape: boolean = false;
- @State blurValue: number = 0 //背景模糊
- @State bgBrightness: number = 0 //背景亮度
- @State customizeBgPath: string | undefined = '';
- @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 playlists: NavidromeRestPlaylist[] = [];
- @State loading: boolean = false;
- @State songNextStart: number | null = 0;
- @State artistNextStart: number | null = 0;
- @State albumNextStart: number | null = 0;
- @State playlistNextStart: number | null = 0;
- @State isSongPageLoading: boolean = false;
- @State isArtistPageLoading: boolean = false;
- @State isAlbumPageLoading: boolean = false;
- @State isPlaylistPageLoading: boolean = false;
- // 新增:详情视图状态
- @Link isDetailView: boolean; // 是否在艺术家/专辑详情视图
- @State previousTab: number = 0; // 进入详情视图前的标签页索引
- @StorageProp('isDarkMode') isDarkMode: boolean = false;
- @StorageLink('currentSong') currentSong: VideoItem | undefined = undefined;
- @StorageProp('topSafeHeight') topSafeHeight: 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 readonly REMOTE_PAGE_SIZE: number = 200;
- private jellyfinSongIdSeen: Set<string> = new Set();
- private embySongIdSeen: Set<string> = new Set();
- private jellyfinSongKeySeen: Set<string> = new Set();
- private embySongKeySeen: Set<string> = new Set();
- private isNavidromeAccount(account: WebDavAccount): boolean {
- return account.webType === RemoteDriveType.Navidrome;
- }
- private isJellyfinAccount(account: WebDavAccount): boolean {
- return account.webType === RemoteDriveType.Jellyfin;
- }
- private isEmbyAccount(account: WebDavAccount): boolean {
- return account.webType === RemoteDriveType.Emby;
- }
- private createTabOptions(): SegmentButtonOptions {
- const buttons = [
- { text: '全部' },
- { 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;
- private readonly REMOTE_SEARCH_LIMIT: number = 500;
- // SegmentButton选项
- @State tabOptions: SegmentButtonOptions = this.createTabOptions();
- //当胶囊按钮的选择发生变化时调用此函数
- onTabSelectedIndexesChanged() {
- this.selectedTab = this.tabSelectedIndexes[0];
- console.info('heanup', `Selected tab: ${this.tabs[this.selectedTab]}`);
- // 如果在详情视图模式下切换标签页,退出详情视图并清除筛选
- if (this.isDetailView) {
- this.isDetailView = false;
- this.clearFilter();
- }
- // 从艺术家或专辑切换回全部时,清除筛选状态
- 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);
- }
- initSetting(){
- this.isCustomizeBg = PreferencesUtil.getBooleanSync(SettingPage.IS_CUSTOMIZE_BG, false)
- this.customizeBgPath = PreferencesUtil.getStringSync(SettingPage.IS_CUSTOMIZE_BG_PATH, '')
- this.blurValue = PreferencesUtil.getNumberSync(SettingPage.CUSTOMIZE_BG_BLUR, 0)
- this.bgBrightness = PreferencesUtil.getNumberSync(SettingPage.BG_BRIGHTNESS, 0)
- this.isNoJumpToHome = PreferencesUtil.getBooleanSync('isNoJumpToHome', true)
- this.sortType = PreferencesUtil.getNumberSync('navidromeSortType', 0);
- this.isShowTitleBar = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_TITLTBAR, true)
- this.autoHideTitle = PreferencesUtil.getBooleanSync('autoHideTitle', true)
- }
- aboutToAppear() {
- this.initSetting()
- let eventSetting: emitter.InnerEvent = { eventId: 333 }
- // 监听广播事件(通用设置配置更新)
- emitter.on(eventSetting, (eventData: emitter.EventData) => {
- this.initSetting()
- });
- // 监听手势返回事件
- let eventBackSwipeBack: emitter.InnerEvent = { eventId: EventConstants.EVENT_SWIPE_BACK_NAVID }
- emitter.on(eventBackSwipeBack, (eventData: emitter.EventData) => {
- console.info('heanup', 'NavidromePage 收到 EVENT_SWIPE_BACK_NAVID 事件');
- // 如果在详情视图模式,退出详情视图
- if (this.isDetailView) {
- this.getUIContext().animateTo({ duration: 555 }, () => {
- this.isDetailView = false;
- this.clearFilter();
- })
- }
- });
- this.refreshNavidromeData();
- }
- private async refreshNavidromeData(showToastWhenMissing: boolean = false): Promise<void> {
- const account = this.resolveActiveAccount();
- if (!account) {
- this.resetData();
- if (showToastWhenMissing) {
- ToastUtil.showToast('请先选择媒体库账号');
- }
- return;
- }
- // 记录日志开关状态
- void ServerLogUtil.info('NavidromeLoad', `日志状态: ${ServerLogUtil.getLogUploadStatus()}`);
- // 记录账号信息和缓存路径
- await this.logAccountCacheInfo(account);
- await this.loadMediaLibrary(account);
- this.doSortType(this.sortType)
- }
- private resolveActiveAccount(): WebDavAccount | undefined {
- if (!this.selectedAccount) {
- return undefined;
- }
- if (!this.isNavidromeAccount(this.selectedAccount)
- && !this.isJellyfinAccount(this.selectedAccount)
- && !this.isEmbyAccount(this.selectedAccount)) {
- 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.playlists = [];
- this.jellyfinSongIdSeen.clear();
- this.embySongIdSeen.clear();
- this.jellyfinSongKeySeen.clear();
- this.embySongKeySeen.clear();
- this.clearFilter();
- this.coverUrlCache.clear();
- this.albumCoverLookup.clear();
- this.songNextStart = 0;
- this.artistNextStart = 0;
- this.albumNextStart = 0;
- this.playlistNextStart = 0;
- this.isSongPageLoading = false;
- this.isArtistPageLoading = false;
- this.isAlbumPageLoading = false;
- this.isPlaylistPageLoading = false;
- }
- private async loadMediaLibrary(account: WebDavAccount): Promise<void> {
- if (this.isNavidromeAccount(account)) {
- await this.loadNavidromeLibrary(account);
- return;
- }
- if (this.isJellyfinAccount(account)) {
- await this.loadJellyfinLibrary(account);
- return;
- }
- if (this.isEmbyAccount(account)) {
- await this.loadEmbyLibrary(account);
- }
- }
- 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),
- this.loadNextPlaylistPage(account, ticket)
- ]);
- if (ticket !== this.loadTicket) {
- return;
- }
- void ServerLogUtil.info('NavidromeLoad', `首次加载完成: 歌曲 ${this.allVideos.length} / 艺术家 ${this.artists.length} / 专辑 ${this.albums.length} / 歌单 ${this.playlists.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 loadJellyfinLibrary(account: WebDavAccount): Promise<void> {
- const ticket = ++this.loadTicket;
- this.loading = true;
- this.resetData();
- void ServerLogUtil.info('NavidromeLoad', '开始加载 Jellyfin 媒体库');
- void ServerLogUtil.info('NavidromeLoad', `服务器: ${ServerLogUtil.sanitizeAccount(account)}`);
- try {
- this.songNextStart = 0;
- this.artistNextStart = 0;
- this.albumNextStart = 0;
- this.playlistNextStart = null;
- await Promise.all([
- this.loadNextJellyfinSongPage(account, ticket),
- this.loadNextJellyfinArtistPage(account, ticket),
- this.loadNextJellyfinAlbumPage(account, ticket)
- ]);
- if (ticket === this.loadTicket) {
- void ServerLogUtil.info('NavidromeLoad', `Jellyfin 首屏完成: 歌曲 ${this.allVideos.length} / 艺术家 ${this.artists.length} / 专辑 ${this.albums.length}`);
- }
- } catch (error) {
- if (ticket === this.loadTicket) {
- void ServerLogUtil.error('NavidromeLoad', `Jellyfin 数据加载失败: ${(error as Error).message}`);
- ToastUtil.showToast((error as Error).message ?? 'Jellyfin 数据加载失败');
- }
- } finally {
- if (ticket === this.loadTicket) {
- this.loading = false;
- }
- }
- }
- private async loadEmbyLibrary(account: WebDavAccount): Promise<void> {
- const ticket = ++this.loadTicket;
- this.loading = true;
- this.resetData();
- void ServerLogUtil.info('NavidromeLoad', '开始加载 Emby 媒体库');
- void ServerLogUtil.info('NavidromeLoad', `服务器: ${ServerLogUtil.sanitizeAccount(account)}`);
- try {
- this.songNextStart = 0;
- this.artistNextStart = 0;
- this.albumNextStart = 0;
- this.playlistNextStart = null;
- await Promise.all([
- this.loadNextEmbySongPage(account, ticket),
- this.loadNextEmbyArtistPage(account, ticket),
- this.loadNextEmbyAlbumPage(account, ticket)
- ]);
- if (ticket === this.loadTicket) {
- void ServerLogUtil.info('NavidromeLoad', `Emby 首屏完成: 歌曲 ${this.allVideos.length} / 艺术家 ${this.artists.length} / 专辑 ${this.albums.length}`);
- }
- } catch (error) {
- if (ticket === this.loadTicket) {
- void ServerLogUtil.error('NavidromeLoad', `Emby 数据加载失败: ${(error as Error).message}`);
- ToastUtil.showToast((error as Error).message ?? 'Emby 数据加载失败');
- }
- } finally {
- if (ticket === this.loadTicket) {
- this.loading = false;
- }
- }
- }
- 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];
- // 打印前20条数据
- // const previewCount = Math.min(20, this.allVideos.length);
- // console.info(`onecold allVideos: ${this.allVideos.length}, 打印前${previewCount}条:`);
- // for (let i = 0; i < previewCount; i++) {
- // const all = this.allVideos[i];
- // console.info(`onecold allVideos[${i}]:`, JSON.stringify({
- // id: all.id,
- // name: all.name,
- // pixelMapPath: all.pixelMapPath
- // }));
- // }
- 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];
- // console.info('onecold 帮我打印这个artists的前20条数据');
- // 打印前20条艺术家数据
- // const previewCount = Math.min(20, this.artists.length);
- // console.info(`onecold artists总数: ${this.artists.length}, 打印前${previewCount}条:`);
- // for (let i = 0; i < previewCount; i++) {
- // const artist = this.artists[i];
- // console.info(`onecold artist[${i}]:`, JSON.stringify({
- // id: artist.id,
- // name: artist.name,
- // albumCount: artist.albumCount,
- // songCount: artist.songCount,
- // coverUrl: artist.coverUrl
- // }));
- // }
- 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 loadNextJellyfinSongPage(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 jellyfinApi.getSongsPage(account, this.songNextStart, this.REMOTE_PAGE_SIZE);
- if (currentTicket !== this.loadTicket) {
- return;
- }
- const uniqueItems: JellyfinSong[] = [];
- for (let i = 0; i < response.items.length; i++) {
- const item = response.items[i];
- if (!item.id) {
- continue;
- }
- const key = this.buildSongDedupKey(item.title, item.artist, item.album, item.durationSeconds);
- if (this.jellyfinSongIdSeen.has(item.id) || this.jellyfinSongKeySeen.has(key)) {
- continue;
- }
- this.jellyfinSongIdSeen.add(item.id);
- this.jellyfinSongKeySeen.add(key);
- uniqueItems.push(item);
- }
- const restSongs = this.convertJellyfinSongsToRestSongs(uniqueItems);
- const videoItems = await this.convertSongsToVideoItems(restSongs, account);
- if (currentTicket !== this.loadTicket) {
- return;
- }
- this.allVideos = this.dedupRemoteSongsByKey([...this.allVideos, ...videoItems]);
- this.songNextStart = response.nextStart;
- void ServerLogUtil.info('NavidromeLoad', `Jellyfin 歌曲追加: 本次 ${videoItems.length} 首, 总数 ${this.allVideos.length}`);
- } finally {
- this.isSongPageLoading = false;
- }
- }
- private async loadNextJellyfinArtistPage(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 jellyfinApi.getArtistsPage(account, this.artistNextStart, this.REMOTE_PAGE_SIZE);
- if (currentTicket !== this.loadTicket) {
- return;
- }
- const processed = await this.convertJellyfinArtistsToRest(response.items, account);
- if (currentTicket !== this.loadTicket) {
- return;
- }
- this.artists = [...this.artists, ...processed];
- this.artistNextStart = response.nextStart;
- void ServerLogUtil.info('NavidromeLoad', `Jellyfin 艺术家追加: 本次 ${processed.length} 位, 总数 ${this.artists.length}`);
- } finally {
- this.isArtistPageLoading = false;
- }
- }
- private async loadNextJellyfinAlbumPage(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 jellyfinApi.getAlbumsPage(account, this.albumNextStart, this.REMOTE_PAGE_SIZE);
- if (currentTicket !== this.loadTicket) {
- return;
- }
- const processed = await this.convertJellyfinAlbumsToRest(response.items, account);
- if (currentTicket !== this.loadTicket) {
- return;
- }
- this.albums = [...this.albums, ...processed];
- this.albumNextStart = response.nextStart;
- void ServerLogUtil.info('NavidromeLoad', `Jellyfin 专辑追加: 本次 ${processed.length} 张, 总数 ${this.albums.length}`);
- } finally {
- this.isAlbumPageLoading = false;
- }
- }
- private async loadNextEmbySongPage(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 embyApi.getSongsPage(account, this.songNextStart, this.REMOTE_PAGE_SIZE);
- if (currentTicket !== this.loadTicket) {
- return;
- }
- const uniqueItems: EmbySong[] = [];
- for (let i = 0; i < response.items.length; i++) {
- const item = response.items[i];
- if (!item.id) {
- continue;
- }
- const key = this.buildSongDedupKey(item.title, item.artist, item.album, item.durationSeconds);
- if (this.embySongIdSeen.has(item.id) || this.embySongKeySeen.has(key)) {
- continue;
- }
- this.embySongIdSeen.add(item.id);
- this.embySongKeySeen.add(key);
- uniqueItems.push(item);
- }
- const restSongs = this.convertEmbySongsToRestSongs(uniqueItems);
- const videoItems = await this.convertSongsToVideoItems(restSongs, account);
- if (currentTicket !== this.loadTicket) {
- return;
- }
- this.allVideos = this.dedupRemoteSongsByKey([...this.allVideos, ...videoItems]);
- this.songNextStart = response.nextStart;
- void ServerLogUtil.info('NavidromeLoad', `Emby 歌曲追加: 本次 ${videoItems.length} 首, 总数 ${this.allVideos.length}`);
- } finally {
- this.isSongPageLoading = false;
- }
- }
- private async loadNextEmbyArtistPage(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 embyApi.getArtistsPage(account, this.artistNextStart, this.REMOTE_PAGE_SIZE);
- if (currentTicket !== this.loadTicket) {
- return;
- }
- const processed = await this.convertEmbyArtistsToRest(response.items, account);
- if (currentTicket !== this.loadTicket) {
- return;
- }
- this.artists = [...this.artists, ...processed];
- this.artistNextStart = response.nextStart;
- void ServerLogUtil.info('NavidromeLoad', `Emby 艺术家追加: 本次 ${processed.length} 位, 总数 ${this.artists.length}`);
- } finally {
- this.isArtistPageLoading = false;
- }
- }
- private async loadNextEmbyAlbumPage(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 embyApi.getAlbumsPage(account, this.albumNextStart, this.REMOTE_PAGE_SIZE);
- if (currentTicket !== this.loadTicket) {
- return;
- }
- const processed = await this.convertEmbyAlbumsToRest(response.items, account);
- if (currentTicket !== this.loadTicket) {
- return;
- }
- this.albums = [...this.albums, ...processed];
- this.albumNextStart = response.nextStart;
- void ServerLogUtil.info('NavidromeLoad', `Emby 专辑追加: 本次 ${processed.length} 张, 总数 ${this.albums.length}`);
- } finally {
- this.isAlbumPageLoading = false;
- }
- }
- private async loadNextPlaylistPage(account: WebDavAccount, ticket?: number): Promise<void> {
- if (this.playlistNextStart === null || this.isPlaylistPageLoading) {
- return;
- }
- const currentTicket = ticket ?? this.loadTicket;
- this.isPlaylistPageLoading = true;
- try {
- const response = await navidromeRestApi.fetchPlaylistPage(account, this.playlistNextStart);
- if (currentTicket !== this.loadTicket) {
- return;
- }
- const chunk = response.data ?? [];
- if (chunk.length === 0) {
- this.playlistNextStart = null;
- return;
- }
- this.playlists = [...this.playlists, ...chunk];
- this.playlistNextStart = response.nextStart;
- void ServerLogUtil.info('NavidromeLoad', `歌单列表追加: 本次 ${chunk.length} 个, 总数 ${this.playlists.length}`);
- } finally {
- this.isPlaylistPageLoading = 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;
- }
- if (this.isNavidromeAccount(account)) {
- switch (this.selectedTab) {
- case 0:
- await this.loadNextSongPage(account);
- break;
- case 1:
- await this.loadNextArtistPage(account);
- break;
- case 2:
- await this.loadNextAlbumPage(account);
- break;
- case 3:
- await this.loadNextPlaylistPage(account);
- break;
- default:
- break;
- }
- return;
- }
- if (this.isJellyfinAccount(account)) {
- switch (this.selectedTab) {
- case 0:
- await this.loadNextJellyfinSongPage(account);
- break;
- case 1:
- await this.loadNextJellyfinArtistPage(account);
- break;
- case 2:
- await this.loadNextJellyfinAlbumPage(account);
- break;
- default:
- break;
- }
- return;
- }
- if (this.isEmbyAccount(account)) {
- switch (this.selectedTab) {
- case 0:
- await this.loadNextEmbySongPage(account);
- break;
- case 1:
- await this.loadNextEmbyArtistPage(account);
- break;
- case 2:
- await this.loadNextEmbyAlbumPage(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('NavidromePageCover', `📀 开始处理 ${albums.length} 张专辑的封面 - 账号: ${ServerLogUtil.sanitizeAccount(account)}`);
- for (let i = 0; i < albums.length; i++) {
- const album = albums[i];
- void ServerLogUtil.debug('NavidromePageCover', `处理专辑 [${i + 1}/${albums.length}] - id: ${album.id}, name: ${album.name}`);
- tasks.push((async () => {
- try {
- // 注意: embedArtPath 和 coverArtPath 可能指向音频文件而非封面图片
- // 所以这里不能直接使用,需要通过 buildCoverUrl 生成正确的封面URL
- // const directUrl = this.resolveEmbedCover(account, album.embedArtPath ?? album.coverArtPath);
- // if (directUrl) {
- // map.set(album.id, directUrl);
- // directCoverCount++;
- // void ServerLogUtil.info('NavidromePageCover', `✅ 专辑使用直接封面 - name: ${album.name}, url: ${directUrl}`);
- // return;
- // }
- // 生成封面URL
- const coverId = album.coverArt ?? album.coverArtId ?? (album.id ? `al-${album.id}` : undefined);
- void ServerLogUtil.debug('NavidromePageCover', `专辑封面ID - name: ${album.name}, coverArt: ${album.coverArt}, coverArtId: ${album.coverArtId}, 最终coverId: ${coverId}`);
- const url = await this.buildCoverUrl(account, coverId);
- if (url) {
- map.set(album.id, url);
- generatedCoverCount++;
- void ServerLogUtil.info('NavidromePageCover', `✅ 专辑生成封面成功 - name: ${album.name}, coverId: ${coverId}, url: ${url}`);
- } else {
- failedCoverCount++;
- void ServerLogUtil.error('NavidromePageCover', `❌ 专辑封面失败 - name: ${album.name}, coverId: ${coverId}, 原始数据: ${JSON.stringify({coverArt: album.coverArt, coverArtId: album.coverArtId, id: album.id})}`);
- }
- } catch (error) {
- failedCoverCount++;
- void ServerLogUtil.error('NavidromePageCover', `❌ 专辑封面解析异常 - name: ${album.name}, error: ${(error as Error).message}`);
- }
- })());
- }
- await Promise.all(tasks);
- void ServerLogUtil.info('NavidromePageCover', `📊 专辑封面处理完成 - 总数: ${albums.length}, 直接嵌入: ${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('NavidromePageCover', `🎤 开始处理 ${artists.length} 位艺术家的封面 - 账号: ${ServerLogUtil.sanitizeAccount(account)}`);
- for (let i = 0; i < artists.length; i++) {
- const artist = artists[i];
- void ServerLogUtil.debug('NavidromePageCover', `处理艺术家 [${i + 1}/${artists.length}] - id: ${artist.id}, name: ${artist.name}`);
- 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.info('NavidromePageCover', `✅ 艺术家使用已有图片 - name: ${artist.name}, url: ${directUrl}`);
- return;
- }
- // 生成封面URL
- const coverId = artist.coverArt ?? artist.coverArtId ?? (artist.id ? `ar-${artist.id}` : undefined);
- void ServerLogUtil.debug('NavidromePageCover', `艺术家封面ID - name: ${artist.name}, coverArt: ${artist.coverArt}, coverArtId: ${artist.coverArtId}, 最终coverId: ${coverId}`);
- const url = await this.buildCoverUrl(account, coverId, 256);
- if (url) {
- map.set(artist.id, url);
- generatedCoverCount++;
- void ServerLogUtil.info('NavidromePageCover', `✅ 艺术家生成封面成功 - name: ${artist.name}, coverId: ${coverId}, url: ${url}`);
- } else {
- failedCoverCount++;
- void ServerLogUtil.error('NavidromePageCover', `❌ 艺术家封面失败 - name: ${artist.name}, coverId: ${coverId}, 原始数据: ${JSON.stringify({coverArt: artist.coverArt, coverArtId: artist.coverArtId, id: artist.id})}`);
- }
- } catch (error) {
- failedCoverCount++;
- void ServerLogUtil.error('NavidromePageCover', `❌ 艺术家封面解析异常 - name: ${artist.name}, error: ${(error as Error).message}`);
- }
- })());
- }
- await Promise.all(tasks);
- void ServerLogUtil.info('NavidromePageCover', `📊 艺术家封面处理完成 - 总数: ${artists.length}, 直接链接: ${directCoverCount}, 生成URL: ${generatedCoverCount}, 失败: ${failedCoverCount}`);
- return map;
- }
- private async buildRemoteCoverMap(ids: string[], account: WebDavAccount): Promise<Map<string, string>> {
- const map = new Map<string, string>();
- const tasks = ids.map(async (id) => {
- if (!id) {
- return;
- }
- try {
- const url = await this.buildCoverUrl(account, id, 300);
- if (url) {
- map.set(id, url);
- }
- } catch (error) {
- void ServerLogUtil.warn('CoverCache', `远程封面生成失败: ${id} ${(error as Error).message}`);
- }
- });
- await Promise.all(tasks);
- return map;
- }
- private async convertJellyfinArtistsToRest(artists: JellyfinArtist[], account: WebDavAccount): Promise<NavidromeRestArtist[]> {
- const results: NavidromeRestArtist[] = [];
- for (let i = 0; i < artists.length; i++) {
- const artist = artists[i];
- const coverUrl = await this.buildCoverUrl(account, artist.id, 300);
- const restArtist: NavidromeRestArtist = {
- id: artist.id,
- name: artist.name,
- albumCount: artist.albumCount,
- songCount: artist.songCount,
- coverUrl: coverUrl
- };
- results.push(restArtist);
- }
- return results;
- }
- private async convertEmbyArtistsToRest(artists: EmbyArtist[], account: WebDavAccount): Promise<NavidromeRestArtist[]> {
- const results: NavidromeRestArtist[] = [];
- for (let i = 0; i < artists.length; i++) {
- const artist = artists[i];
- const coverUrl = await this.buildCoverUrl(account, artist.id, 300);
- const restArtist: NavidromeRestArtist = {
- id: artist.id,
- name: artist.name,
- albumCount: artist.albumCount,
- songCount: artist.songCount,
- coverUrl: coverUrl
- };
- results.push(restArtist);
- }
- return results;
- }
- private async convertJellyfinAlbumsToRest(albums: JellyfinAlbum[], account: WebDavAccount): Promise<NavidromeRestAlbum[]> {
- const results: NavidromeRestAlbum[] = [];
- for (let i = 0; i < albums.length; i++) {
- const album = albums[i];
- const coverUrl = await this.buildCoverUrl(account, album.id, 300);
- const restAlbum: NavidromeRestAlbum = {
- id: album.id,
- name: album.name,
- artist: album.artist,
- minYear: album.year,
- coverUrl: coverUrl
- };
- results.push(restAlbum);
- }
- return results;
- }
- private async convertEmbyAlbumsToRest(albums: EmbyAlbum[], account: WebDavAccount): Promise<NavidromeRestAlbum[]> {
- const results: NavidromeRestAlbum[] = [];
- for (let i = 0; i < albums.length; i++) {
- const album = albums[i];
- const coverUrl = await this.buildCoverUrl(account, album.id, 300);
- const restAlbum: NavidromeRestAlbum = {
- id: album.id,
- name: album.name,
- artist: album.artist,
- minYear: album.year,
- coverUrl: coverUrl
- };
- results.push(restAlbum);
- }
- return results;
- }
- private convertJellyfinSongsToRestSongs(songs: JellyfinSong[]): NavidromeRestSong[] {
- return songs.map(song => {
- const restSong: NavidromeRestSong = {
- id: song.id,
- title: song.title,
- album: song.album,
- albumId: song.albumId,
- artist: song.artist,
- artistId: song.artistId,
- duration: song.durationSeconds,
- bitRate: song.bitRate,
- suffix: song.suffix,
- size: song.size,
- track: song.track,
- year: song.year,
- coverArt: song.albumId ?? song.id
- };
- return restSong;
- });
- }
- private convertEmbySongsToRestSongs(songs: EmbySong[]): NavidromeRestSong[] {
- return songs.map(song => {
- const restSong: NavidromeRestSong = {
- id: song.id,
- title: song.title,
- album: song.album,
- albumId: song.albumId,
- artist: song.artist,
- artistId: song.artistId,
- duration: song.durationSeconds,
- bitRate: song.bitRate,
- suffix: song.suffix,
- size: song.size,
- track: song.track,
- year: song.year,
- coverArt: song.albumId ?? song.id
- };
- return restSong;
- });
- }
- private async fetchAllJellyfinArtistSongs(account: WebDavAccount, artistId: string): Promise<JellyfinSong[]> {
- const results: JellyfinSong[] = [];
- let startIndex = 0;
- while (true) {
- const response = await jellyfinApi.getArtistSongs(account, artistId, startIndex, this.REMOTE_PAGE_SIZE);
- results.push(...response.items);
- if (response.nextStart === null) {
- break;
- }
- startIndex = response.nextStart;
- }
- return results;
- }
- private async fetchAllEmbyArtistSongs(account: WebDavAccount, artistId: string): Promise<EmbySong[]> {
- const results: EmbySong[] = [];
- let startIndex = 0;
- while (true) {
- const response = await embyApi.getArtistSongs(account, artistId, startIndex, this.REMOTE_PAGE_SIZE);
- results.push(...response.items);
- if (response.nextStart === null) {
- break;
- }
- startIndex = response.nextStart;
- }
- return results;
- }
- private buildSongDedupKey(title?: string, artist?: string, album?: string, durationSeconds?: number): string {
- const safeTitle = title ?? '';
- const safeArtist = artist ?? '';
- const safeAlbum = album ?? '';
- const safeDuration = durationSeconds !== undefined && durationSeconds !== null ? durationSeconds.toString() : '';
- return `${safeTitle}__${safeArtist}__${safeAlbum}__${safeDuration}`.toLowerCase();
- }
- private buildSongKeyFromItem(item: VideoItem): string {
- const safeTitle = item.name ?? '';
- const safeArtist = item.artist ?? '';
- const safeAlbum = item.album ?? '';
- const safeDuration = item.duration ?? '';
- return `${safeTitle}__${safeArtist}__${safeAlbum}__${safeDuration}`.toLowerCase();
- }
- private dedupRemoteSongsByKey(items: VideoItem[]): VideoItem[] {
- const map = new Map<string, VideoItem>();
- for (let i = 0; i < items.length; i++) {
- const item = items[i];
- const key = this.buildSongKeyFromItem(item);
- const existing = map.get(key);
- if (!existing) {
- map.set(key, item);
- continue;
- }
- const existingHasAlbumId = StrUtil.isNotEmpty(existing.navAlbumId);
- const currentHasAlbumId = StrUtil.isNotEmpty(item.navAlbumId);
- if (!existingHasAlbumId && currentHasAlbumId) {
- map.set(key, item);
- }
- }
- return Array.from(map.values());
- }
- 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> {
- void ServerLogUtil.debug('NavidromePageCover', `🎵 解析歌曲封面 - title: ${song.title}, albumId: ${song.albumId}, id: ${song.id}`);
- // 注释掉这个代码可以解决NavidRome部分账号没有封面问题
- // if (this.isNavidromeAccount(account) && song.albumId) {
- // const albumCover = song.albumId ? this.albumCoverLookup.get(song.albumId) : undefined;
- // if (albumCover) {
- // void ServerLogUtil.debug('NavidromePageCover', `✅ 歌曲使用专辑封面缓存 - title: ${song.title}, albumCover: ${albumCover}`);
- // return albumCover;
- // }
- // }
- if (!this.isNavidromeAccount(account)) {
- const fallbackId = song.albumId ?? song.id;
- void ServerLogUtil.debug('NavidromePageCover', `歌曲使用非Navidrome账号封面 - title: ${song.title}, fallbackId: ${fallbackId}`);
- return this.buildCoverUrl(account, fallbackId);
- }
- const directUrl = this.resolveEmbedCover(account, song.embedArtPath ?? song.coverArtPath);
- if (directUrl) {
- void ServerLogUtil.info('NavidromePageCover', `✅ 歌曲使用直接封面 - title: ${song.title}, url: ${directUrl}`);
- return directUrl;
- }
- const coverId = song.coverArt ?? song.coverArtId ?? song.id;
- void ServerLogUtil.debug('NavidromePageCover', `歌曲生成封面URL - title: ${song.title}, coverArt: ${song.coverArt}, coverArtId: ${song.coverArtId}, 最终coverId: ${coverId}`);
- return this.buildCoverUrl(account, coverId);
- }
- private async buildCoverUrl(account: WebDavAccount, coverId?: string, size: number = 300): Promise<string | undefined> {
- void ServerLogUtil.info('NavidromePageCover', `开始构建封面URL - coverId: ${coverId}, size: ${size}, 账号: ${ServerLogUtil.sanitizeAccount(account)}`);
- if (!coverId || coverId.trim().length === 0) {
- void ServerLogUtil.warn('NavidromePageCover', `封面ID为空,跳过构建 - coverId: "${coverId}"`);
- return undefined;
- }
- const normalizedId = coverId.trim();
- const cacheKey = `${normalizedId}_${size}`;
- if (this.isNavidromeAccount(account)) {
- const cached = this.coverUrlCache.get(cacheKey);
- if (cached) {
- void ServerLogUtil.info('NavidromePageCover', `✅ 缓存命中 - coverId: ${coverId}, size: ${size}, url: ${cached}`);
- return cached;
- }
- }
- void ServerLogUtil.info('NavidromePageCover', `⚡ 调用API生成封面URL - coverId: ${coverId}, size: ${size}`);
- let url: string | undefined = undefined;
- try {
- if (this.isNavidromeAccount(account)) {
- void ServerLogUtil.debug('NavidromePageCover', `[开始] 调用 navidromeApi.buildCoverArtUrl - coverId: ${normalizedId}, size: ${size}`);
- void ServerLogUtil.debug('NavidromePageCover', `[账号信息] host=${account.host}, port=${account.port}, enableHttps=${account.enableHttps}`);
- void ServerLogUtil.debug('NavidromePageCover', `[账号信息] basePath=${account.navidromeBasePath}`);
- url = await navidromeApi.buildCoverArtUrl(account, normalizedId, size);
- void ServerLogUtil.debug('NavidromePageCover', `[完成] navidromeApi.buildCoverArtUrl 返回 - coverId: ${normalizedId}, 返回值: "${url}"`);
- if (url) {
- void ServerLogUtil.info('NavidromePageCover', `✅ API返回URL成功 - coverId: ${coverId}, url: ${url}`);
- } else {
- void ServerLogUtil.warn('NavidromePageCover', `⚠️ API返回空值 - coverId: ${coverId}`);
- }
- } else if (this.isJellyfinAccount(account)) {
- void ServerLogUtil.debug('NavidromePageCover', `调用 jellyfinApi.buildPrimaryImageUrl - coverId: ${normalizedId}, size: ${size}`);
- url = await jellyfinApi.buildPrimaryImageUrl(account, normalizedId, size, size);
- } else if (this.isEmbyAccount(account)) {
- void ServerLogUtil.debug('NavidromePageCover', `调用 embyApi.buildPrimaryImageUrl - coverId: ${normalizedId}, size: ${size}`);
- url = await embyApi.buildPrimaryImageUrl(account, normalizedId, size, size);
- }
- if (url && this.isNavidromeAccount(account)) {
- this.coverUrlCache.set(cacheKey, url);
- void ServerLogUtil.info('NavidromePageCover', `✅ 封面URL生成成功并已缓存 - coverId: ${coverId}, url: ${url}`);
- void ServerLogUtil.debug('NavidromePageCover', `缓存键值 - cacheKey: ${cacheKey}`);
- } else if (!url) {
- void ServerLogUtil.error('NavidromePageCover', `❌ 封面URL生成失败(返回空) - coverId: ${coverId}, size: ${size}`);
- } else {
- void ServerLogUtil.info('NavidromePageCover', `✅ 封面URL生成成功(非Navidrome账号) - coverId: ${coverId}, url: ${url}`);
- }
- } catch (error) {
- const err = error as Error;
- void ServerLogUtil.error('NavidromePageCover', `❌ 封面URL生成异常 - coverId: ${coverId}, error: ${err.message}`);
- void ServerLogUtil.error('NavidromePageCover', `错误类型: ${err.name || 'Unknown'}`);
- void ServerLogUtil.error('NavidromePageCover', `错误堆栈: ${err.stack || '无'}`);
- }
- 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 {
- if (!this.isNavidromeAccount(account)) {
- return undefined;
- }
- return navidromeRestApi.resolveResourceUrl(account, path);
- }
- private resolveLibraryInfo(account: WebDavAccount): LibraryInfo {
- if (this.isJellyfinAccount(account)) {
- return { type: CommonConstants.TYPE_JELLYFIN, scheme: 'jellyfin' } as LibraryInfo;
- }
- if (this.isEmbyAccount(account)) {
- return { type: CommonConstants.TYPE_EMBY, scheme: 'emby' } as LibraryInfo;
- }
- return { type: CommonConstants.TYPE_NAVIDROME, scheme: 'navidrome' } as LibraryInfo;
- }
- private convertSongToVideoItem(song: NavidromeRestSong, account: WebDavAccount, coverUrl?: string): VideoItem {
- const title = song.title ?? Constants.UNKNOWN_TITLE;
- const libraryInfo = this.resolveLibraryInfo(account);
- // 调试日志:记录从playlist或其他API获取的歌曲的id字段
- void ServerLogUtil.debug('SongConvert', `转换歌曲: ${title}`);
- void ServerLogUtil.debug('SongConvert', `- song.id: ${song.id}`);
- void ServerLogUtil.debug('SongConvert', `- song.artistId: ${song.artistId}`);
- void ServerLogUtil.debug('SongConvert', `- song.albumId: ${song.albumId}`);
- void ServerLogUtil.debug('SongConvert', `- song.lyrics: ${song.lyrics}`);
- const videoItem = new VideoItem(
- title,
- song.id,
- `${libraryInfo.scheme}://${account.id ?? 0}/${song.id}`,
- libraryInfo.type,
- 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;
- videoItem.lyricContent = song.lyrics;
- // 调试日志:检查歌曲的 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;
- }
- // 记录最终生成的VideoItem路径
- void ServerLogUtil.debug('SongConvert', `- VideoItem.filePath: ${videoItem.filePath}`);
- void ServerLogUtil.debug('SongConvert', `- VideoItem.remote_rel_path: ${videoItem.remote_rel_path}`);
- 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) {
- // 详情视图模式下显示返回按钮
- if (this.isDetailView) {
- 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.isDetailView = false;
- this.clearFilter();
- })
- .attributeModifier(new ShadowModifier())
- .zIndex(0)
- Text(this.filterLabel)
- .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 })
- .animation({ duration: 300, curve: Curve.Ease })
- } else {
- // 正常模式:侧边栏按钮和账号名
- 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.topSafeHeight + 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('媒体库账号不可用');
- return;
- }
- this.isSearchLoading = true;
- this.filteredList = [];
- const startTime = Date.now();
- void ServerLogUtil.info('NavidromeSearch', `开始远程搜索: "${keyword}"`);
- try {
- let restSongs: NavidromeRestSong[] = [];
- if (this.isNavidromeAccount(account)) {
- const songs = await navidromeApi.searchSongs(account, keyword, NAVIDROME_SEARCH_LIMIT);
- restSongs = this.convertApiSongsToRestSongs(songs);
- } else if (this.isJellyfinAccount(account)) {
- const response = await jellyfinApi.searchSongs(account, keyword, 0, this.REMOTE_SEARCH_LIMIT);
- restSongs = this.convertJellyfinSongsToRestSongs(response.items);
- } else if (this.isEmbyAccount(account)) {
- const response = await embyApi.searchSongs(account, keyword, 0, this.REMOTE_SEARCH_LIMIT);
- restSongs = this.convertEmbySongsToRestSongs(response.items);
- }
- if (ticket !== this.searchTicket) {
- return;
- }
- const searchTime = Date.now() - startTime;
- if (!restSongs || restSongs.length === 0) {
- this.filteredList = [];
- void ServerLogUtil.warn('NavidromeSearch', `搜索无结果: "${keyword}"`);
- void ServerLogUtil.info('NavidromeSearch', `- 搜索耗时: ${searchTime}ms`);
- return;
- }
- 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;
- case 3:
- return this.playlists.length;
- default:
- return this.getVisibleSongs().length;
- }
- }
- private getEmptyTitle(): string {
- switch (this.selectedTab) {
- case 1:
- return '暂无艺术家';
- case 2:
- return '暂无专辑';
- case 3:
- 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 '当前筛选没有找到专辑';
- case 3:
- 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.alt'))
- .width(52)
- .height(52)
- .borderRadius(9)
- .sourceSize({ width: 38, height: 38 })
- .draggable(false)
- .interpolation(ImageInterpolation.High)// 用于重采样后的抗锯齿
- .autoResize(true) // 重采样,可减少内存占用
- .alt($r('app.media.alt'))
- .fillColor(song.pixelMapPath ? undefined : this.themeColor)
- .objectFit(ImageFit.Cover)
- .margin({ left: 20 })
- .animation({
- duration: 500,
- curve: Curve.Friction // 可选动画曲线
- })
- .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.alt'))
- .width(48)
- .height(48)
- .borderRadius(10)
- .draggable(false)
- .alt($r('app.media.alt'))
- // .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 })
- .visibility((artist.albumCount ?? 0) === 0 && (artist.songCount ?? 0) === 0 ? Visibility.None : Visibility.Visible)
- }
- .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.alt'))
- .width(48)
- .height(48)
- .borderRadius(10)
- .clip(true)
- .alt($r('app.media.alt'))
- .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);
- })
- }
- @Builder
- buildPlaylistItem(playlist: NavidromeRestPlaylist) {
- Button({ type: ButtonType.Capsule, stateEffect: true }) {
- Row({ space: 12 }) {
- Image($r('app.media.alt'))
- .width(48)
- .height(48)
- .borderRadius(10)
- .alt($r('app.media.alt'))
- .draggable(false)
- .sourceSize({ width: 38, height: 38 })
- .fillColor(this.themeColor)
- .objectFit(ImageFit.Cover)
- .margin({ left: 20 })
- Column({ space: 4 }) {
- Text(playlist.name ?? '未知歌单')
- .fontSize(15)
- .fontColor($r('app.color.index_tab_font_color'))
- .maxLines(1)
- .textAlign(TextAlign.Start)
- .textOverflow({ overflow: TextOverflow.Ellipsis })
- Text(this.buildPlaylistMetaLine(playlist))
- .fontSize(13)
- .fontColor($r('app.color.index_tab_font_color'))
- .opacity(0.6)
- .maxLines(1)
- .textOverflow({ overflow: TextOverflow.Ellipsis })
- // if (playlist.ownerName) {
- // Text(playlist.ownerName)
- // .fontSize(12)
- // .fontColor($r('app.color.index_tab_font_color'))
- // .opacity(0.5)
- // .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.onPlaylistSelected(playlist);
- })
- }
- 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;
- // 如果专辑和歌曲数都为0,不显示元数据信息
- if (albumCount === 0 && songCount === 0) {
- return '';
- }
- 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 buildPlaylistMetaLine(playlist: NavidromeRestPlaylist): string {
- const parts: string[] = [];
- if (playlist.songCount !== undefined) {
- parts.push(`${playlist.songCount} 首歌`);
- }
- if (playlist.duration !== undefined) {
- const duration = this.formatSongDuration(playlist.duration);
- if (duration) {
- parts.push(duration);
- }
- }
- 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;
- }
- this.isShowTitleBar = true;
- // 保存当前标签页,进入详情视图
- this.previousTab = this.selectedTab;
- this.isDetailView = true;
- // 应用筛选但不切换标签页
- void this.applyFilter(NavFilterType.Artist, artist.id, artist.name ?? Constants.UNKNOWN_ARTIST);
- }
- private onAlbumSelected(album: NavidromeRestAlbum): void {
- if (!album || !album.id) {
- return;
- }
- this.isShowTitleBar = true;
- // 保存当前标签页,进入详情视图
- this.previousTab = this.selectedTab;
- this.isDetailView = true;
- // 应用筛选但不切换标签页
- void this.applyFilter(NavFilterType.Album, album.id, album.name ?? '未知专辑');
- }
- private onPlaylistSelected(playlist: NavidromeRestPlaylist): void {
- if (!playlist || !playlist.id) {
- return;
- }
- this.isShowTitleBar = true;
- // 保存当前标签页,进入详情视图
- this.previousTab = this.selectedTab;
- this.isDetailView = true;
- // 应用筛选但不切换标签页
- void this.applyFilter(NavFilterType.Playlist, playlist.id, playlist.name ?? '未知歌单');
- }
- private async applyFilter(type: NavFilterType, id: string, label: string): Promise<void> {
- // 记录筛选操作
- void ServerLogUtil.info('NavidromeFilter', `应用筛选:`);
- const typeText = type === NavFilterType.Artist ? '艺术家' : type === NavFilterType.Album ? '专辑' : type === NavFilterType.Playlist ? '歌单' : '无';
- void ServerLogUtil.info('NavidromeFilter', `- 类型: ${type} (${typeText})`);
- 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(label).catch((error: Error) => {
- void ServerLogUtil.error('NavidromeFilter', `筛选歌曲加载失败: ${error.message}`);
- ToastUtil.showToast(error.message || '筛选数据加载失败');
- });
- // 不再自动切换标签页,保持在详情视图模式
- }
- private async loadSongsForFilter(label:string): 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('媒体库账号不可用');
- }
- if (!this.isNavidromeAccount(account)) {
- if (this.filterType === NavFilterType.Playlist) {
- this.filterSongs = [];
- this.isFilterLoading = false;
- ToastUtil.showToast('当前媒体库不支持歌单');
- return;
- }
- let restSongs: NavidromeRestSong[] = [];
- if (this.filterType === NavFilterType.Artist) {
- if (this.isJellyfinAccount(account)) {
- const songs = await this.fetchAllJellyfinArtistSongs(account, this.filterId);
- restSongs = this.convertJellyfinSongsToRestSongs(songs);
- } else if (this.isEmbyAccount(account)) {
- const songs = await this.fetchAllEmbyArtistSongs(account, this.filterId);
- restSongs = this.convertEmbySongsToRestSongs(songs);
- }
- } else if (this.filterType === NavFilterType.Album) {
- if (this.isJellyfinAccount(account)) {
- const songs = await jellyfinApi.getAlbumSongs(account, this.filterId);
- restSongs = this.convertJellyfinSongsToRestSongs(songs);
- } else if (this.isEmbyAccount(account)) {
- const songs = await embyApi.getAlbumSongs(account, this.filterId);
- restSongs = this.convertEmbySongsToRestSongs(songs);
- }
- }
- const videoItems = await this.convertSongsToVideoItems(restSongs, account);
- this.filterSongs = videoItems;
- this.isFilterLoading = false;
- return;
- }
- const expectedFilterId = this.filterId;
- const expectedFilterType = this.filterType;
- try {
- let songs: NavidromeRestSong[] = [];
- if (this.filterType === NavFilterType.Artist) {
- songs = await navidromeRestApi.fetchSongsByArtist(account, this.filterId,label);
- } else if (this.filterType === NavFilterType.Album) {
- songs = await navidromeRestApi.fetchSongsByAlbum(account, this.filterId,label);
- } else if (this.filterType === NavFilterType.Playlist) {
- songs = await navidromeRestApi.fetchSongsByPlaylist(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;
- // 退出详情视图
- this.isDetailView = 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('媒体库账号信息不完整,无法播放');
- 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: `${getRemoteDriveDisplayLabel(account.webType)} - ${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)
- .padding({top:this.topSafeHeight+98})
- .justifyContent(FlexAlign.Center)
- } else {
- 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({scroller:this.scroller, space: 8 }) {
- // 详情视图模式下显示筛选后的歌曲,否则根据标签页显示对应内容
- if (this.selectedTab === 0||this.isDetailView) {
- 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 if (this.selectedTab === 2) {
- ForEach(this.albums, (album: NavidromeRestAlbum) => {
- ListItem() {
- this.buildAlbumItem(album)
- }
- }, (album: NavidromeRestAlbum) => album.id)
- } else if (this.selectedTab === 3) {
- ForEach(this.playlists, (playlist: NavidromeRestPlaylist) => {
- ListItem() {
- this.buildPlaylistItem(playlist)
- }
- }, (playlist: NavidromeRestPlaylist) => playlist.id)
- }
- }
- .onScrollFrameBegin((offset: number) => {
- // 获取当前滚动偏移量
- if(this.autoHideTitle){
- const currentOffsetY = this.scroller.currentOffset().yOffset;
- // 判断滚动方向
- if (currentOffsetY > this.prevOffsetY) {
- this.isShowTitleBar = false
- } else if (currentOffsetY < this.prevOffsetY) {
- this.isShowTitleBar = true
- }
- // 更新前一次偏移量
- this.prevOffsetY = currentOffsetY;
- }
- return { offsetRemain: offset };
- })
- .width('100%')
- .height('100%')
- .layoutWeight(1)
- .cachedCount(3)
- .padding({ top: 5, bottom: 5 })
- .listDirection(Axis.Vertical)
- .contentEndOffset(this.bottomSafeHeight+70)
- .contentStartOffset(this.topSafeHeight + 98)
- .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() {
- SymbolGlyph($r('sys.symbol.music_fill'))
- .fontSize(50)
- .opacity(0.3)
- 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%')
- .height('100%')
- .justifyContent(FlexAlign.Center)
- }
- }
- }
- build() {
- Stack() {
- Column() {
- this.buildContentView()
- }
- .height('100%')
- Column() {
- this.topTitleBar()
- }
- .visibility(this.isShowTitleBar?Visibility.Visible:
- this.autoHideTitle?Visibility.None:Visibility.Visible)
- .animation({
- duration: 500,
- curve: Curve.Friction // 可选动画曲线
- })
- }
- .alignContent(Alignment.Top)
- .width('100%')
- .height('100%')
- .backgroundImage(this.isCustomizeBg?this.customizeBgPath:$r('app.color.start_window_background'))
- .backgroundImageSize(this.isLandscape?{width:'100%'}:{ height: '100%'})
- .backgroundImagePosition(Alignment.Center)
- .backdropBlur(this.blurValue)
- .backgroundBrightness({rate:this.isCustomizeBg?0.1:0,lightUpDegree:this.bgBrightness})
- .expandSafeArea([SafeAreaType.SYSTEM], [SafeAreaEdge.BOTTOM])
- }
- }
|