NavidromePage.ets 84 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297
  1. import { VideoItem } from '../viewmodel/VideoItem';
  2. import { LengthMetrics, SegmentButton, SegmentButtonItemTuple, SegmentButtonOptions,
  3. SymbolGlyphModifier } from '@kit.ArkUI';
  4. import {
  5. PreferencesUtil, ToastUtil, StrUtil
  6. } from '@pura/harmony-utils';
  7. import {
  8. ButtonFancyModifier,
  9. SymbolGlyphFancyModifier,
  10. ShadowModifier
  11. } from '../common/util/AttributeModifierUtil';
  12. import { CommonConstants } from '../common/constants/CommonConstants';
  13. import { WebDavAccount } from '../viewmodel/WebDavAccount';
  14. import Logger from '../common/util/Logger';
  15. import { RemoteDriveType } from '../common/enums/RemoteDriveType';
  16. import { navidromeRestApi, NavidromeRestAlbum, NavidromeRestArtist, NavidromeRestSong, NavidromeRestPlaylist } from '../common/network/NavidromeRestApi';
  17. import { Utility } from '../common/util/Utility';
  18. import { Constants } from '../Constants';
  19. import { EventConstants } from '../common/constants/EventConstants';
  20. import { emitter } from '@kit.BasicServicesKit';
  21. import { setNavidromePlaylist } from '../common/util/NavidromePlaylistStore';
  22. import { navidromeApi, NavidromeSong } from '../common/network/NavidromeApi';
  23. import { ServerLogUtil } from '../common/util/ServerLogUtil';
  24. import { RemoteDriveManager } from '../common/util/RemoteDriveManager';
  25. import { SettingPage } from '../pages/SettingPage';
  26. import { jellyfinApi, JellyfinAlbum, JellyfinArtist, JellyfinSong } from '../common/network/JellyfinApi';
  27. import { embyApi, EmbyAlbum, EmbyArtist, EmbySong } from '../common/network/EmbyApi';
  28. import { getRemoteDriveDisplayLabel } from '../common/util/RemoteDriveLabel';
  29. const NAVIDROME_PLAYLIST_ID = 'navidrome-playlist';
  30. const NAVIDROME_SEARCH_LIMIT = 500;
  31. interface PlaylistEventData {
  32. playlistId: string;
  33. playlistName: string;
  34. songCount: number;
  35. startIndex: number;
  36. isJump: boolean;
  37. songFilePaths: string[];
  38. }
  39. enum NavFilterType {
  40. None = 0,
  41. Artist = 1,
  42. Album = 2,
  43. Playlist = 3
  44. }
  45. interface CachePreviewInfo {
  46. cacheRoot: string;
  47. examplePath: string;
  48. }
  49. interface LibraryInfo {
  50. type: number;
  51. scheme: string;
  52. }
  53. @Component
  54. export struct NavidromePage {
  55. @State isShowTitleBar: boolean = true //是否显示分类导航条
  56. private scroller: Scroller = new Scroller()
  57. private prevOffsetY: number = 0; // 记录上一次的Y轴偏移量
  58. @State autoHideTitle: boolean = true //滚动自动隐藏标题栏
  59. @State isCustomizeBg: boolean = false //自定义背景界面
  60. @StorageProp('isLandscape') isLandscape: boolean = false;
  61. @State blurValue: number = 0 //背景模糊
  62. @State bgBrightness: number = 0 //背景亮度
  63. @State customizeBgPath: string | undefined = '';
  64. @Link mType: number;
  65. @Link offsetX: number;
  66. @Link isShowDrawer: boolean;
  67. @State isNoJumpToHome: boolean = false //网盘播放不跳转首页
  68. @StorageProp('bottomSafeHeight') bottomSafeHeight: number = 0;
  69. @Prop @Watch('onSwitchAccount') selectedAccount: WebDavAccount;
  70. @StorageProp('currentTheme') currentTheme: number = 0;
  71. @State selectedTab: number = 0; // 0: 全部, 1: 艺术家, 2: 专辑
  72. @State allVideos: VideoItem[] = [];
  73. @State artists: NavidromeRestArtist[] = [];
  74. @State albums: NavidromeRestAlbum[] = [];
  75. @State playlists: NavidromeRestPlaylist[] = [];
  76. @State loading: boolean = false;
  77. @State songNextStart: number | null = 0;
  78. @State artistNextStart: number | null = 0;
  79. @State albumNextStart: number | null = 0;
  80. @State playlistNextStart: number | null = 0;
  81. @State isSongPageLoading: boolean = false;
  82. @State isArtistPageLoading: boolean = false;
  83. @State isAlbumPageLoading: boolean = false;
  84. @State isPlaylistPageLoading: boolean = false;
  85. // 新增:详情视图状态
  86. @State isDetailView: boolean = false; // 是否在艺术家/专辑详情视图
  87. @State previousTab: number = 0; // 进入详情视图前的标签页索引
  88. @StorageProp('isDarkMode') isDarkMode: boolean = false;
  89. @StorageLink('currentSong') currentSong: VideoItem | undefined = undefined;
  90. @StorageProp('topSafeHeight') topSafeHeight: number = 0;
  91. @State @Watch('onTabSelectedIndexesChanged') tabSelectedIndexes: number[] = [0];
  92. @StorageProp('themeColor') themeColor: string =
  93. PreferencesUtil.getStringSync('THEME_COLOR', CommonConstants.DEFAULT_THEME_COLOR);
  94. private tabs: string[] = ['全部', '艺术家', '专辑', '歌单'];
  95. private loadTicket: number = 0;
  96. @State filterType: NavFilterType = NavFilterType.None;
  97. @State filterLabel: string = '';
  98. @State filterId: string = '';
  99. @State filterSongs: VideoItem[] = [];
  100. @State isFilterLoading: boolean = false;
  101. private coverUrlCache: Map<string, string> = new Map();
  102. private albumCoverLookup: Map<string, string> = new Map();
  103. private searchTicket: number = 0;
  104. private readonly REMOTE_PAGE_SIZE: number = 200;
  105. private isNavidromeAccount(account: WebDavAccount): boolean {
  106. return account.webType === RemoteDriveType.Navidrome;
  107. }
  108. private isJellyfinAccount(account: WebDavAccount): boolean {
  109. return account.webType === RemoteDriveType.Jellyfin;
  110. }
  111. private isEmbyAccount(account: WebDavAccount): boolean {
  112. return account.webType === RemoteDriveType.Emby;
  113. }
  114. private createTabOptions(): SegmentButtonOptions {
  115. const buttons = [
  116. { text: '全部' },
  117. { text: '艺术家' },
  118. { text: '专辑' },
  119. { text: '歌单' }
  120. ] as SegmentButtonItemTuple;
  121. return SegmentButtonOptions.capsule({
  122. buttons,
  123. direction: Direction.Ltr,
  124. buttonPadding: { top: 10, bottom: 10 },
  125. backgroundColor: $r('app.color.index_background'),
  126. selectedBackgroundColor: $r('app.color.start_window_background'),
  127. selectedFontColor: $r('app.color.text_color'),
  128. fontSize: 14,
  129. selectedFontSize: 15,
  130. localizedTextPadding: {
  131. end: LengthMetrics.vp(20),
  132. start: LengthMetrics.vp(20)
  133. }
  134. });
  135. }
  136. private getCachePreviewInfo(account: WebDavAccount): CachePreviewInfo | null {
  137. try {
  138. const manager = RemoteDriveManager.getInstance();
  139. const context = manager.context;
  140. if (!context) {
  141. return null;
  142. }
  143. const baseDir = context.filesDir ?? context.cacheDir;
  144. if (!baseDir) {
  145. return null;
  146. }
  147. const accountId = account.id?.toString() || 'default';
  148. const cacheRoot = `${baseDir}/remote_cache/webdav/${accountId}`;
  149. const examplePath = `${cacheRoot}/navidrome_preview.cache`;
  150. return { cacheRoot, examplePath };
  151. } catch (error) {
  152. Logger.error('NavidromePage', `获取缓存预览路径失败: ${(error as Error).message}`);
  153. return null;
  154. }
  155. }
  156. // 搜索和排序相关状态
  157. @State isSearchMode: boolean = false;
  158. @State searchText: string = ''; // 用户输入内容
  159. @State filteredList: Array<VideoItem> = []; // 过滤后的歌曲结果
  160. @State sortType: number = 0; // 排序类型 0:名称升序 1:名称降序 2:时间升序 3:时间降序 4:大小升序 5:大小降序
  161. @State isSearchLoading: boolean = false;
  162. private readonly REMOTE_SEARCH_LIMIT: number = 500;
  163. // SegmentButton选项
  164. @State tabOptions: SegmentButtonOptions = this.createTabOptions();
  165. //当胶囊按钮的选择发生变化时调用此函数
  166. onTabSelectedIndexesChanged() {
  167. this.selectedTab = this.tabSelectedIndexes[0];
  168. console.info('heanup', `Selected tab: ${this.tabs[this.selectedTab]}`);
  169. // 如果在详情视图模式下切换标签页,退出详情视图并清除筛选
  170. if (this.isDetailView) {
  171. this.isDetailView = false;
  172. this.clearFilter();
  173. }
  174. // 从艺术家或专辑切换回全部时,清除筛选状态
  175. if (this.selectedTab === 0 && this.filterType !== NavFilterType.None) {
  176. // 不清除筛选,保持筛选状态
  177. } else if (this.selectedTab !== 0) {
  178. // 切换到艺术家或专辑标签页时,清除筛选和搜索状态
  179. this.clearFilter();
  180. this.isSearchMode = false;
  181. this.searchText = '';
  182. this.filteredList = [];
  183. this.isSearchLoading = false;
  184. this.searchTicket++;
  185. }
  186. }
  187. //切换不同的NavidromePage
  188. async onSwitchAccount() {
  189. await this.refreshNavidromeData(true);
  190. }
  191. initSetting(){
  192. this.isCustomizeBg = PreferencesUtil.getBooleanSync(SettingPage.IS_CUSTOMIZE_BG, false)
  193. this.customizeBgPath = PreferencesUtil.getStringSync(SettingPage.IS_CUSTOMIZE_BG_PATH, '')
  194. this.blurValue = PreferencesUtil.getNumberSync(SettingPage.CUSTOMIZE_BG_BLUR, 0)
  195. this.bgBrightness = PreferencesUtil.getNumberSync(SettingPage.BG_BRIGHTNESS, 0)
  196. this.isNoJumpToHome = PreferencesUtil.getBooleanSync('isNoJumpToHome', true)
  197. this.sortType = PreferencesUtil.getNumberSync('navidromeSortType', 0);
  198. this.isShowTitleBar = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_TITLTBAR, true)
  199. this.autoHideTitle = PreferencesUtil.getBooleanSync('autoHideTitle', true)
  200. }
  201. aboutToAppear() {
  202. this.initSetting()
  203. let eventSetting: emitter.InnerEvent = { eventId: 333 }
  204. // 监听广播事件(通用设置配置更新)
  205. emitter.on(eventSetting, (eventData: emitter.EventData) => {
  206. this.initSetting()
  207. });
  208. this.refreshNavidromeData();
  209. }
  210. private async refreshNavidromeData(showToastWhenMissing: boolean = false): Promise<void> {
  211. const account = this.resolveActiveAccount();
  212. if (!account) {
  213. this.resetData();
  214. if (showToastWhenMissing) {
  215. ToastUtil.showToast('请先选择媒体库账号');
  216. }
  217. return;
  218. }
  219. // 记录日志开关状态
  220. void ServerLogUtil.info('NavidromeLoad', `日志状态: ${ServerLogUtil.getLogUploadStatus()}`);
  221. // 记录账号信息和缓存路径
  222. await this.logAccountCacheInfo(account);
  223. await this.loadMediaLibrary(account);
  224. this.doSortType(this.sortType)
  225. }
  226. private resolveActiveAccount(): WebDavAccount | undefined {
  227. if (!this.selectedAccount) {
  228. return undefined;
  229. }
  230. if (!this.isNavidromeAccount(this.selectedAccount)
  231. && !this.isJellyfinAccount(this.selectedAccount)
  232. && !this.isEmbyAccount(this.selectedAccount)) {
  233. return undefined;
  234. }
  235. if (!this.selectedAccount.host || this.selectedAccount.host.length === 0) {
  236. return undefined;
  237. }
  238. return this.selectedAccount;
  239. }
  240. private resetData(): void {
  241. this.allVideos = [];
  242. this.artists = [];
  243. this.albums = [];
  244. this.playlists = [];
  245. this.clearFilter();
  246. this.coverUrlCache.clear();
  247. this.albumCoverLookup.clear();
  248. this.songNextStart = 0;
  249. this.artistNextStart = 0;
  250. this.albumNextStart = 0;
  251. this.playlistNextStart = 0;
  252. this.isSongPageLoading = false;
  253. this.isArtistPageLoading = false;
  254. this.isAlbumPageLoading = false;
  255. this.isPlaylistPageLoading = false;
  256. }
  257. private async loadMediaLibrary(account: WebDavAccount): Promise<void> {
  258. if (this.isNavidromeAccount(account)) {
  259. await this.loadNavidromeLibrary(account);
  260. return;
  261. }
  262. if (this.isJellyfinAccount(account)) {
  263. await this.loadJellyfinLibrary(account);
  264. return;
  265. }
  266. if (this.isEmbyAccount(account)) {
  267. await this.loadEmbyLibrary(account);
  268. }
  269. }
  270. private async loadNavidromeLibrary(account: WebDavAccount): Promise<void> {
  271. const ticket = ++this.loadTicket;
  272. this.loading = true;
  273. this.resetData();
  274. void ServerLogUtil.info('NavidromeLoad', '开始加载 Navidrome 数据库');
  275. void ServerLogUtil.info('NavidromeLoad', `服务器: ${ServerLogUtil.sanitizeAccount(account)}`);
  276. void ServerLogUtil.info('NavidromeLoad', `封面URL缓存已清空,当前缓存数量: ${this.coverUrlCache.size}`);
  277. try {
  278. await this.logAccountCacheInfo(account);
  279. await Promise.all([
  280. this.loadNextSongPage(account, ticket),
  281. this.loadNextArtistPage(account, ticket),
  282. this.loadNextAlbumPage(account, ticket),
  283. this.loadNextPlaylistPage(account, ticket)
  284. ]);
  285. if (ticket !== this.loadTicket) {
  286. return;
  287. }
  288. void ServerLogUtil.info('NavidromeLoad', `首次加载完成: 歌曲 ${this.allVideos.length} / 艺术家 ${this.artists.length} / 专辑 ${this.albums.length} / 歌单 ${this.playlists.length}`);
  289. await this.logCacheStatistics(account);
  290. } catch (error) {
  291. if (ticket === this.loadTicket) {
  292. void ServerLogUtil.error('NavidromeLoad', `数据加载失败: ${(error as Error).message}`);
  293. void ServerLogUtil.error('NavidromeLoad', `失败时服务器信息: ${ServerLogUtil.sanitizeAccount(account)}`);
  294. ToastUtil.showToast((error as Error).message ?? 'Navidrome 数据加载失败');
  295. }
  296. } finally {
  297. if (ticket === this.loadTicket) {
  298. this.loading = false;
  299. void ServerLogUtil.info('NavidromeLoad', '加载流程结束');
  300. }
  301. }
  302. }
  303. private async loadJellyfinLibrary(account: WebDavAccount): Promise<void> {
  304. const ticket = ++this.loadTicket;
  305. this.loading = true;
  306. this.resetData();
  307. void ServerLogUtil.info('NavidromeLoad', '开始加载 Jellyfin 媒体库');
  308. void ServerLogUtil.info('NavidromeLoad', `服务器: ${ServerLogUtil.sanitizeAccount(account)}`);
  309. try {
  310. this.songNextStart = 0;
  311. this.artistNextStart = 0;
  312. this.albumNextStart = 0;
  313. await Promise.all([
  314. this.loadNextJellyfinSongPage(account, ticket),
  315. this.loadNextJellyfinArtistPage(account, ticket),
  316. this.loadNextJellyfinAlbumPage(account, ticket)
  317. ]);
  318. if (ticket === this.loadTicket) {
  319. void ServerLogUtil.info('NavidromeLoad', `Jellyfin 首屏完成: 歌曲 ${this.allVideos.length} / 艺术家 ${this.artists.length} / 专辑 ${this.albums.length}`);
  320. }
  321. } catch (error) {
  322. if (ticket === this.loadTicket) {
  323. void ServerLogUtil.error('NavidromeLoad', `Jellyfin 数据加载失败: ${(error as Error).message}`);
  324. ToastUtil.showToast((error as Error).message ?? 'Jellyfin 数据加载失败');
  325. }
  326. } finally {
  327. if (ticket === this.loadTicket) {
  328. this.loading = false;
  329. }
  330. }
  331. }
  332. private async loadEmbyLibrary(account: WebDavAccount): Promise<void> {
  333. const ticket = ++this.loadTicket;
  334. this.loading = true;
  335. this.resetData();
  336. void ServerLogUtil.info('NavidromeLoad', '开始加载 Emby 媒体库');
  337. void ServerLogUtil.info('NavidromeLoad', `服务器: ${ServerLogUtil.sanitizeAccount(account)}`);
  338. try {
  339. this.songNextStart = 0;
  340. this.artistNextStart = 0;
  341. this.albumNextStart = 0;
  342. await Promise.all([
  343. this.loadNextEmbySongPage(account, ticket),
  344. this.loadNextEmbyArtistPage(account, ticket),
  345. this.loadNextEmbyAlbumPage(account, ticket)
  346. ]);
  347. if (ticket === this.loadTicket) {
  348. void ServerLogUtil.info('NavidromeLoad', `Emby 首屏完成: 歌曲 ${this.allVideos.length} / 艺术家 ${this.artists.length} / 专辑 ${this.albums.length}`);
  349. }
  350. } catch (error) {
  351. if (ticket === this.loadTicket) {
  352. void ServerLogUtil.error('NavidromeLoad', `Emby 数据加载失败: ${(error as Error).message}`);
  353. ToastUtil.showToast((error as Error).message ?? 'Emby 数据加载失败');
  354. }
  355. } finally {
  356. if (ticket === this.loadTicket) {
  357. this.loading = false;
  358. }
  359. }
  360. }
  361. private async loadNextSongPage(account: WebDavAccount, ticket?: number): Promise<void> {
  362. if (this.songNextStart === null || this.isSongPageLoading) {
  363. return;
  364. }
  365. const currentTicket = ticket ?? this.loadTicket;
  366. this.isSongPageLoading = true;
  367. try {
  368. const response = await navidromeRestApi.fetchSongPage(account, this.songNextStart);
  369. if (currentTicket !== this.loadTicket) {
  370. return;
  371. }
  372. const chunk = response.data ?? [];
  373. if (chunk.length === 0) {
  374. this.songNextStart = null;
  375. return;
  376. }
  377. const videos = await this.convertSongsToVideoItems(chunk, account);
  378. if (currentTicket !== this.loadTicket) {
  379. return;
  380. }
  381. this.allVideos = [...this.allVideos, ...videos];
  382. this.songNextStart = response.nextStart;
  383. void ServerLogUtil.info('NavidromeLoad', `歌曲列表追加: 本次 ${videos.length} 首, 总数 ${this.allVideos.length}`);
  384. } finally {
  385. this.isSongPageLoading = false;
  386. }
  387. }
  388. private async loadNextArtistPage(account: WebDavAccount, ticket?: number): Promise<void> {
  389. if (this.artistNextStart === null || this.isArtistPageLoading) {
  390. return;
  391. }
  392. const currentTicket = ticket ?? this.loadTicket;
  393. this.isArtistPageLoading = true;
  394. try {
  395. const response = await navidromeRestApi.fetchArtistPage(account, this.artistNextStart);
  396. if (currentTicket !== this.loadTicket) {
  397. return;
  398. }
  399. const chunk = response.data ?? [];
  400. if (chunk.length === 0) {
  401. this.artistNextStart = null;
  402. return;
  403. }
  404. const coverMap = await this.buildArtistCoverMap(chunk, account);
  405. if (currentTicket !== this.loadTicket) {
  406. return;
  407. }
  408. const processed = chunk.map(artist => {
  409. artist.coverUrl = coverMap.get(artist.id);
  410. return artist;
  411. });
  412. this.artists = [...this.artists, ...processed];
  413. console.info('onecold 帮我打印这个artists的前20条数据');
  414. // 打印前20条艺术家数据
  415. const previewCount = Math.min(20, this.artists.length);
  416. console.info(`onecold artists总数: ${this.artists.length}, 打印前${previewCount}条:`);
  417. for (let i = 0; i < previewCount; i++) {
  418. const artist = this.artists[i];
  419. console.info(`onecold artist[${i}]:`, JSON.stringify({
  420. id: artist.id,
  421. name: artist.name,
  422. albumCount: artist.albumCount,
  423. songCount: artist.songCount,
  424. coverUrl: artist.coverUrl
  425. }));
  426. }
  427. this.artistNextStart = response.nextStart;
  428. void ServerLogUtil.info('ArtistCover', `艺术家列表追加: 本次 ${processed.length} 位, 总数 ${this.artists.length}`);
  429. } finally {
  430. this.isArtistPageLoading = false;
  431. }
  432. }
  433. private async loadNextAlbumPage(account: WebDavAccount, ticket?: number): Promise<void> {
  434. if (this.albumNextStart === null || this.isAlbumPageLoading) {
  435. return;
  436. }
  437. const currentTicket = ticket ?? this.loadTicket;
  438. this.isAlbumPageLoading = true;
  439. try {
  440. const response = await navidromeRestApi.fetchAlbumPage(account, this.albumNextStart);
  441. if (currentTicket !== this.loadTicket) {
  442. return;
  443. }
  444. const chunk = response.data ?? [];
  445. if (chunk.length === 0) {
  446. this.albumNextStart = null;
  447. return;
  448. }
  449. const coverMap = await this.buildAlbumCoverMap(chunk, account);
  450. if (currentTicket !== this.loadTicket) {
  451. return;
  452. }
  453. coverMap.forEach((value, key) => {
  454. if (value) {
  455. this.albumCoverLookup.set(key, value);
  456. }
  457. });
  458. const processed = chunk.map(album => {
  459. album.coverUrl = coverMap.get(album.id);
  460. return album;
  461. });
  462. this.albums = [...this.albums, ...processed];
  463. this.albumNextStart = response.nextStart;
  464. void ServerLogUtil.info('AlbumCover', `专辑列表追加: 本次 ${processed.length} 张, 总数 ${this.albums.length}`);
  465. } finally {
  466. this.isAlbumPageLoading = false;
  467. }
  468. }
  469. private async loadNextJellyfinSongPage(account: WebDavAccount, ticket?: number): Promise<void> {
  470. if (this.songNextStart === null || this.isSongPageLoading) {
  471. return;
  472. }
  473. const currentTicket = ticket ?? this.loadTicket;
  474. this.isSongPageLoading = true;
  475. try {
  476. const response = await jellyfinApi.getSongsPage(account, this.songNextStart, this.REMOTE_PAGE_SIZE);
  477. if (currentTicket !== this.loadTicket) {
  478. return;
  479. }
  480. const restSongs = this.convertJellyfinSongsToRestSongs(response.items);
  481. const videoItems = await this.convertSongsToVideoItems(restSongs, account);
  482. if (currentTicket !== this.loadTicket) {
  483. return;
  484. }
  485. this.allVideos = [...this.allVideos, ...videoItems];
  486. this.songNextStart = response.nextStart;
  487. void ServerLogUtil.info('NavidromeLoad', `Jellyfin 歌曲追加: 本次 ${videoItems.length} 首, 总数 ${this.allVideos.length}`);
  488. } finally {
  489. this.isSongPageLoading = false;
  490. }
  491. }
  492. private async loadNextJellyfinArtistPage(account: WebDavAccount, ticket?: number): Promise<void> {
  493. if (this.artistNextStart === null || this.isArtistPageLoading) {
  494. return;
  495. }
  496. const currentTicket = ticket ?? this.loadTicket;
  497. this.isArtistPageLoading = true;
  498. try {
  499. const response = await jellyfinApi.getArtistsPage(account, this.artistNextStart, this.REMOTE_PAGE_SIZE);
  500. if (currentTicket !== this.loadTicket) {
  501. return;
  502. }
  503. const processed = await this.convertJellyfinArtistsToRest(response.items, account);
  504. if (currentTicket !== this.loadTicket) {
  505. return;
  506. }
  507. this.artists = [...this.artists, ...processed];
  508. this.artistNextStart = response.nextStart;
  509. void ServerLogUtil.info('NavidromeLoad', `Jellyfin 艺术家追加: 本次 ${processed.length} 位, 总数 ${this.artists.length}`);
  510. } finally {
  511. this.isArtistPageLoading = false;
  512. }
  513. }
  514. private async loadNextJellyfinAlbumPage(account: WebDavAccount, ticket?: number): Promise<void> {
  515. if (this.albumNextStart === null || this.isAlbumPageLoading) {
  516. return;
  517. }
  518. const currentTicket = ticket ?? this.loadTicket;
  519. this.isAlbumPageLoading = true;
  520. try {
  521. const response = await jellyfinApi.getAlbumsPage(account, this.albumNextStart, this.REMOTE_PAGE_SIZE);
  522. if (currentTicket !== this.loadTicket) {
  523. return;
  524. }
  525. const processed = await this.convertJellyfinAlbumsToRest(response.items, account);
  526. if (currentTicket !== this.loadTicket) {
  527. return;
  528. }
  529. this.albums = [...this.albums, ...processed];
  530. this.albumNextStart = response.nextStart;
  531. void ServerLogUtil.info('NavidromeLoad', `Jellyfin 专辑追加: 本次 ${processed.length} 张, 总数 ${this.albums.length}`);
  532. } finally {
  533. this.isAlbumPageLoading = false;
  534. }
  535. }
  536. private async loadNextEmbySongPage(account: WebDavAccount, ticket?: number): Promise<void> {
  537. if (this.songNextStart === null || this.isSongPageLoading) {
  538. return;
  539. }
  540. const currentTicket = ticket ?? this.loadTicket;
  541. this.isSongPageLoading = true;
  542. try {
  543. const response = await embyApi.getSongsPage(account, this.songNextStart, this.REMOTE_PAGE_SIZE);
  544. if (currentTicket !== this.loadTicket) {
  545. return;
  546. }
  547. const restSongs = this.convertEmbySongsToRestSongs(response.items);
  548. const videoItems = await this.convertSongsToVideoItems(restSongs, account);
  549. if (currentTicket !== this.loadTicket) {
  550. return;
  551. }
  552. this.allVideos = [...this.allVideos, ...videoItems];
  553. this.songNextStart = response.nextStart;
  554. void ServerLogUtil.info('NavidromeLoad', `Emby 歌曲追加: 本次 ${videoItems.length} 首, 总数 ${this.allVideos.length}`);
  555. } finally {
  556. this.isSongPageLoading = false;
  557. }
  558. }
  559. private async loadNextEmbyArtistPage(account: WebDavAccount, ticket?: number): Promise<void> {
  560. if (this.artistNextStart === null || this.isArtistPageLoading) {
  561. return;
  562. }
  563. const currentTicket = ticket ?? this.loadTicket;
  564. this.isArtistPageLoading = true;
  565. try {
  566. const response = await embyApi.getArtistsPage(account, this.artistNextStart, this.REMOTE_PAGE_SIZE);
  567. if (currentTicket !== this.loadTicket) {
  568. return;
  569. }
  570. const processed = await this.convertEmbyArtistsToRest(response.items, account);
  571. if (currentTicket !== this.loadTicket) {
  572. return;
  573. }
  574. this.artists = [...this.artists, ...processed];
  575. this.artistNextStart = response.nextStart;
  576. void ServerLogUtil.info('NavidromeLoad', `Emby 艺术家追加: 本次 ${processed.length} 位, 总数 ${this.artists.length}`);
  577. } finally {
  578. this.isArtistPageLoading = false;
  579. }
  580. }
  581. private async loadNextEmbyAlbumPage(account: WebDavAccount, ticket?: number): Promise<void> {
  582. if (this.albumNextStart === null || this.isAlbumPageLoading) {
  583. return;
  584. }
  585. const currentTicket = ticket ?? this.loadTicket;
  586. this.isAlbumPageLoading = true;
  587. try {
  588. const response = await embyApi.getAlbumsPage(account, this.albumNextStart, this.REMOTE_PAGE_SIZE);
  589. if (currentTicket !== this.loadTicket) {
  590. return;
  591. }
  592. const processed = await this.convertEmbyAlbumsToRest(response.items, account);
  593. if (currentTicket !== this.loadTicket) {
  594. return;
  595. }
  596. this.albums = [...this.albums, ...processed];
  597. this.albumNextStart = response.nextStart;
  598. void ServerLogUtil.info('NavidromeLoad', `Emby 专辑追加: 本次 ${processed.length} 张, 总数 ${this.albums.length}`);
  599. } finally {
  600. this.isAlbumPageLoading = false;
  601. }
  602. }
  603. private async loadNextPlaylistPage(account: WebDavAccount, ticket?: number): Promise<void> {
  604. if (this.playlistNextStart === null || this.isPlaylistPageLoading) {
  605. return;
  606. }
  607. const currentTicket = ticket ?? this.loadTicket;
  608. this.isPlaylistPageLoading = true;
  609. try {
  610. const response = await navidromeRestApi.fetchPlaylistPage(account, this.playlistNextStart);
  611. if (currentTicket !== this.loadTicket) {
  612. return;
  613. }
  614. const chunk = response.data ?? [];
  615. if (chunk.length === 0) {
  616. this.playlistNextStart = null;
  617. return;
  618. }
  619. this.playlists = [...this.playlists, ...chunk];
  620. this.playlistNextStart = response.nextStart;
  621. void ServerLogUtil.info('NavidromeLoad', `歌单列表追加: 本次 ${chunk.length} 个, 总数 ${this.playlists.length}`);
  622. } finally {
  623. this.isPlaylistPageLoading = false;
  624. }
  625. }
  626. private async handleReachEnd(): Promise<void> {
  627. if (this.loading) {
  628. return;
  629. }
  630. if (this.selectedTab === 0 && this.filterType !== NavFilterType.None) {
  631. return;
  632. }
  633. const account = this.selectedAccount;
  634. if (!account) {
  635. return;
  636. }
  637. if (this.isNavidromeAccount(account)) {
  638. switch (this.selectedTab) {
  639. case 0:
  640. await this.loadNextSongPage(account);
  641. break;
  642. case 1:
  643. await this.loadNextArtistPage(account);
  644. break;
  645. case 2:
  646. await this.loadNextAlbumPage(account);
  647. break;
  648. case 3:
  649. await this.loadNextPlaylistPage(account);
  650. break;
  651. default:
  652. break;
  653. }
  654. return;
  655. }
  656. if (this.isJellyfinAccount(account)) {
  657. switch (this.selectedTab) {
  658. case 0:
  659. await this.loadNextJellyfinSongPage(account);
  660. break;
  661. case 1:
  662. await this.loadNextJellyfinArtistPage(account);
  663. break;
  664. case 2:
  665. await this.loadNextJellyfinAlbumPage(account);
  666. break;
  667. default:
  668. break;
  669. }
  670. return;
  671. }
  672. if (this.isEmbyAccount(account)) {
  673. switch (this.selectedTab) {
  674. case 0:
  675. await this.loadNextEmbySongPage(account);
  676. break;
  677. case 1:
  678. await this.loadNextEmbyArtistPage(account);
  679. break;
  680. case 2:
  681. await this.loadNextEmbyAlbumPage(account);
  682. break;
  683. default:
  684. break;
  685. }
  686. }
  687. }
  688. private async buildAlbumCoverMap(albums: NavidromeRestAlbum[], account: WebDavAccount): Promise<Map<string, string>> {
  689. const map = new Map<string, string>();
  690. const tasks: Promise<void>[] = [];
  691. let directCoverCount = 0;
  692. let generatedCoverCount = 0;
  693. let failedCoverCount = 0;
  694. void ServerLogUtil.info('AlbumCover', `开始处理 ${albums.length} 张专辑的封面`);
  695. for (let i = 0; i < albums.length; i++) {
  696. const album = albums[i];
  697. tasks.push((async () => {
  698. try {
  699. // 尝试获取直接嵌入的封面路径
  700. const directUrl = this.resolveEmbedCover(account, album.embedArtPath ?? album.coverArtPath);
  701. if (directUrl) {
  702. map.set(album.id, directUrl);
  703. directCoverCount++;
  704. void ServerLogUtil.debug('AlbumCover', `专辑 ${album.name} 使用直接封面: ${directUrl}`);
  705. return;
  706. }
  707. // 生成封面URL
  708. const coverId = album.coverArt ?? album.coverArtId ?? (album.id ? `al-${album.id}` : undefined);
  709. const url = await this.buildCoverUrl(account, coverId);
  710. if (url) {
  711. map.set(album.id, url);
  712. generatedCoverCount++;
  713. void ServerLogUtil.debug('AlbumCover', `专辑 ${album.name} 生成封面URL: ${coverId} -> ${url}`);
  714. } else {
  715. failedCoverCount++;
  716. void ServerLogUtil.warn('AlbumCover', `专辑 ${album.name} 无可用封面: ${JSON.stringify({coverArt: album.coverArt, coverArtId: album.coverArtId, id: album.id})}`);
  717. }
  718. } catch (error) {
  719. failedCoverCount++;
  720. void ServerLogUtil.warn('AlbumCover', `专辑 ${album.name} 封面解析失败: ${(error as Error).message}`);
  721. }
  722. })());
  723. }
  724. await Promise.all(tasks);
  725. void ServerLogUtil.info('AlbumCover', `专辑封面处理完成: 直接嵌入 ${directCoverCount}, 生成URL ${generatedCoverCount}, 失败 ${failedCoverCount}`);
  726. return map;
  727. }
  728. private async buildArtistCoverMap(artists: NavidromeRestArtist[], account: WebDavAccount): Promise<Map<string, string>> {
  729. const map = new Map<string, string>();
  730. const tasks: Promise<void>[] = [];
  731. let directCoverCount = 0;
  732. let generatedCoverCount = 0;
  733. let failedCoverCount = 0;
  734. void ServerLogUtil.info('ArtistCover', `开始处理 ${artists.length} 位艺术家的封面`);
  735. for (let i = 0; i < artists.length; i++) {
  736. const artist = artists[i];
  737. tasks.push((async () => {
  738. try {
  739. // 尝试获取已有图片URL
  740. const directUrl = artist.mediumImageUrl ?? artist.largeImageUrl ?? this.resolveEmbedCover(account, artist.coverArtPath);
  741. if (directUrl) {
  742. map.set(artist.id, directUrl);
  743. directCoverCount++;
  744. void ServerLogUtil.debug('ArtistCover', `艺术家 ${artist.name} 使用已有图片: ${directUrl}`);
  745. return;
  746. }
  747. // 生成封面URL
  748. const coverId = artist.coverArt ?? artist.coverArtId ?? (artist.id ? `ar-${artist.id}` : undefined);
  749. const url = await this.buildCoverUrl(account, coverId, 256);
  750. if (url) {
  751. map.set(artist.id, url);
  752. generatedCoverCount++;
  753. void ServerLogUtil.debug('ArtistCover', `艺术家 ${artist.name} 生成封面URL: ${coverId} -> ${url}`);
  754. } else {
  755. failedCoverCount++;
  756. void ServerLogUtil.warn('ArtistCover', `艺术家 ${artist.name} 无可用封面: ${JSON.stringify({coverArt: artist.coverArt, coverArtId: artist.coverArtId, id: artist.id})}`);
  757. }
  758. } catch (error) {
  759. failedCoverCount++;
  760. void ServerLogUtil.warn('ArtistCover', `艺术家 ${artist.name} 封面解析失败: ${(error as Error).message}`);
  761. }
  762. })());
  763. }
  764. await Promise.all(tasks);
  765. void ServerLogUtil.info('ArtistCover', `艺术家封面处理完成: 直接链接 ${directCoverCount}, 生成URL ${generatedCoverCount}, 失败 ${failedCoverCount}`);
  766. return map;
  767. }
  768. private async buildRemoteCoverMap(ids: string[], account: WebDavAccount): Promise<Map<string, string>> {
  769. const map = new Map<string, string>();
  770. const tasks = ids.map(async (id) => {
  771. if (!id) {
  772. return;
  773. }
  774. try {
  775. const url = await this.buildCoverUrl(account, id, 300);
  776. if (url) {
  777. map.set(id, url);
  778. }
  779. } catch (error) {
  780. void ServerLogUtil.warn('CoverCache', `远程封面生成失败: ${id} ${(error as Error).message}`);
  781. }
  782. });
  783. await Promise.all(tasks);
  784. return map;
  785. }
  786. private async convertJellyfinArtistsToRest(artists: JellyfinArtist[], account: WebDavAccount): Promise<NavidromeRestArtist[]> {
  787. const results: NavidromeRestArtist[] = [];
  788. for (let i = 0; i < artists.length; i++) {
  789. const artist = artists[i];
  790. const coverUrl = await this.buildCoverUrl(account, artist.id, 300);
  791. const restArtist: NavidromeRestArtist = {
  792. id: artist.id,
  793. name: artist.name,
  794. coverUrl: coverUrl
  795. };
  796. results.push(restArtist);
  797. }
  798. return results;
  799. }
  800. private async convertEmbyArtistsToRest(artists: EmbyArtist[], account: WebDavAccount): Promise<NavidromeRestArtist[]> {
  801. const results: NavidromeRestArtist[] = [];
  802. for (let i = 0; i < artists.length; i++) {
  803. const artist = artists[i];
  804. const coverUrl = await this.buildCoverUrl(account, artist.id, 300);
  805. const restArtist: NavidromeRestArtist = {
  806. id: artist.id,
  807. name: artist.name,
  808. coverUrl: coverUrl
  809. };
  810. results.push(restArtist);
  811. }
  812. return results;
  813. }
  814. private async convertJellyfinAlbumsToRest(albums: JellyfinAlbum[], account: WebDavAccount): Promise<NavidromeRestAlbum[]> {
  815. const results: NavidromeRestAlbum[] = [];
  816. for (let i = 0; i < albums.length; i++) {
  817. const album = albums[i];
  818. const coverUrl = await this.buildCoverUrl(account, album.id, 300);
  819. const restAlbum: NavidromeRestAlbum = {
  820. id: album.id,
  821. name: album.name,
  822. artist: album.artist,
  823. minYear: album.year,
  824. coverUrl: coverUrl
  825. };
  826. results.push(restAlbum);
  827. }
  828. return results;
  829. }
  830. private async convertEmbyAlbumsToRest(albums: EmbyAlbum[], account: WebDavAccount): Promise<NavidromeRestAlbum[]> {
  831. const results: NavidromeRestAlbum[] = [];
  832. for (let i = 0; i < albums.length; i++) {
  833. const album = albums[i];
  834. const coverUrl = await this.buildCoverUrl(account, album.id, 300);
  835. const restAlbum: NavidromeRestAlbum = {
  836. id: album.id,
  837. name: album.name,
  838. artist: album.artist,
  839. minYear: album.year,
  840. coverUrl: coverUrl
  841. };
  842. results.push(restAlbum);
  843. }
  844. return results;
  845. }
  846. private convertJellyfinSongsToRestSongs(songs: JellyfinSong[]): NavidromeRestSong[] {
  847. return songs.map(song => {
  848. const restSong: NavidromeRestSong = {
  849. id: song.id,
  850. title: song.title,
  851. album: song.album,
  852. albumId: song.albumId,
  853. artist: song.artist,
  854. artistId: song.artistId,
  855. duration: song.durationSeconds,
  856. bitRate: song.bitRate,
  857. suffix: song.suffix,
  858. size: song.size,
  859. track: song.track,
  860. year: song.year,
  861. coverArt: song.albumId ?? song.id
  862. };
  863. return restSong;
  864. });
  865. }
  866. private convertEmbySongsToRestSongs(songs: EmbySong[]): NavidromeRestSong[] {
  867. return songs.map(song => {
  868. const restSong: NavidromeRestSong = {
  869. id: song.id,
  870. title: song.title,
  871. album: song.album,
  872. albumId: song.albumId,
  873. artist: song.artist,
  874. artistId: song.artistId,
  875. duration: song.durationSeconds,
  876. bitRate: song.bitRate,
  877. suffix: song.suffix,
  878. size: song.size,
  879. track: song.track,
  880. year: song.year,
  881. coverArt: song.albumId ?? song.id
  882. };
  883. return restSong;
  884. });
  885. }
  886. private async fetchAllJellyfinArtistSongs(account: WebDavAccount, artistId: string): Promise<JellyfinSong[]> {
  887. const results: JellyfinSong[] = [];
  888. let startIndex = 0;
  889. while (true) {
  890. const response = await jellyfinApi.getArtistSongs(account, artistId, startIndex, this.REMOTE_PAGE_SIZE);
  891. results.push(...response.items);
  892. if (response.nextStart === null) {
  893. break;
  894. }
  895. startIndex = response.nextStart;
  896. }
  897. return results;
  898. }
  899. private async fetchAllEmbyArtistSongs(account: WebDavAccount, artistId: string): Promise<EmbySong[]> {
  900. const results: EmbySong[] = [];
  901. let startIndex = 0;
  902. while (true) {
  903. const response = await embyApi.getArtistSongs(account, artistId, startIndex, this.REMOTE_PAGE_SIZE);
  904. results.push(...response.items);
  905. if (response.nextStart === null) {
  906. break;
  907. }
  908. startIndex = response.nextStart;
  909. }
  910. return results;
  911. }
  912. private convertApiSongsToRestSongs(songs: NavidromeSong[]): NavidromeRestSong[] {
  913. return songs.map((song: NavidromeSong): NavidromeRestSong => ({
  914. id: song.id,
  915. title: song.title,
  916. artist: song.artist,
  917. artistId: song.artistId,
  918. album: song.album,
  919. albumId: song.albumId,
  920. duration: song.duration,
  921. bitRate: song.bitRate,
  922. suffix: song.suffix,
  923. size: song.size,
  924. createdAt: song.created,
  925. genre: song.genre,
  926. track: song.track,
  927. year: song.year,
  928. contentType: song.contentType,
  929. coverArt: song.coverArt,
  930. coverArtId: song.coverArt
  931. }));
  932. }
  933. private async convertSongsToVideoItems(songs: NavidromeRestSong[], account: WebDavAccount): Promise<VideoItem[]> {
  934. const tasks: Promise<VideoItem>[] = [];
  935. let successCount = 0;
  936. let failedCount = 0;
  937. void ServerLogUtil.info('SongConvert', `开始转换 ${songs.length} 首歌曲为 VideoItem`);
  938. for (let i = 0; i < songs.length; i++) {
  939. const song = songs[i];
  940. tasks.push((async () => {
  941. try {
  942. let coverUrl: string | undefined;
  943. try {
  944. coverUrl = await this.resolveSongCover(song, account);
  945. } catch (error) {
  946. void ServerLogUtil.warn('SongConvert', `歌曲 ${song.title} 封面解析失败: ${(error as Error).message}`);
  947. }
  948. const videoItem = this.convertSongToVideoItem(song, account, coverUrl);
  949. successCount++;
  950. // 记录前几首歌的详细信息用于调试
  951. if (i < 3) {
  952. void ServerLogUtil.debug('SongConvert', `歌曲 ${i + 1}: ${videoItem.name}, 封面: ${coverUrl ? '有' : '无'}, 路径: ${videoItem.filePath}`);
  953. }
  954. return videoItem;
  955. } catch (error) {
  956. failedCount++;
  957. void ServerLogUtil.error('SongConvert', `歌曲 ${song.title} 转换失败: ${(error as Error).message}`);
  958. throw new Error(`歌曲 ${song.title} 转换失败: ${(error as Error).message}`);
  959. }
  960. })());
  961. }
  962. const results = await Promise.all(tasks);
  963. void ServerLogUtil.info('SongConvert', `歌曲转换完成: 成功 ${successCount}, 失败 ${failedCount}`);
  964. return results;
  965. }
  966. private async resolveSongCover(song: NavidromeRestSong, account: WebDavAccount): Promise<string | undefined> {
  967. if (this.isNavidromeAccount(account) && song.albumId) {
  968. const albumCover = song.albumId ? this.albumCoverLookup.get(song.albumId) : undefined;
  969. if (albumCover) {
  970. return albumCover;
  971. }
  972. }
  973. if (!this.isNavidromeAccount(account)) {
  974. const fallbackId = song.albumId ?? song.id;
  975. return this.buildCoverUrl(account, fallbackId);
  976. }
  977. const directUrl = this.resolveEmbedCover(account, song.embedArtPath ?? song.coverArtPath);
  978. if (directUrl) {
  979. return directUrl;
  980. }
  981. const coverId = song.coverArt ?? song.coverArtId ?? song.id;
  982. return this.buildCoverUrl(account, coverId);
  983. }
  984. private async buildCoverUrl(account: WebDavAccount, coverId?: string, size: number = 300): Promise<string | undefined> {
  985. if (!coverId || coverId.trim().length === 0) {
  986. return undefined;
  987. }
  988. const normalizedId = coverId.trim();
  989. const cacheKey = `${normalizedId}_${size}`;
  990. if (this.isNavidromeAccount(account)) {
  991. const cached = this.coverUrlCache.get(cacheKey);
  992. if (cached) {
  993. void ServerLogUtil.debug('CoverCache', `封面URL缓存命中: ${cacheKey} -> ${cached}`);
  994. return cached;
  995. }
  996. }
  997. void ServerLogUtil.debug('CoverCache', `生成封面URL: ${coverId} (尺寸: ${size})`);
  998. let url: string | undefined = undefined;
  999. if (this.isNavidromeAccount(account)) {
  1000. url = await navidromeApi.buildCoverArtUrl(account, normalizedId, size);
  1001. } else if (this.isJellyfinAccount(account)) {
  1002. url = await jellyfinApi.buildPrimaryImageUrl(account, normalizedId, size, size);
  1003. } else if (this.isEmbyAccount(account)) {
  1004. url = await embyApi.buildPrimaryImageUrl(account, normalizedId, size, size);
  1005. }
  1006. if (url && this.isNavidromeAccount(account)) {
  1007. this.coverUrlCache.set(cacheKey, url);
  1008. void ServerLogUtil.debug('CoverCache', `封面URL已缓存: ${cacheKey} -> ${url}`);
  1009. } else {
  1010. void ServerLogUtil.warn('CoverCache', `封面URL生成失败: ${coverId} (尺寸: ${size})`);
  1011. }
  1012. return url;
  1013. }
  1014. /**
  1015. * 记录账号缓存信息
  1016. */
  1017. private async logAccountCacheInfo(account: WebDavAccount): Promise<void> {
  1018. try {
  1019. void ServerLogUtil.info('AccountInfo', `账号信息: ${ServerLogUtil.sanitizeAccount(account)}`);
  1020. // 记录缓存路径信息
  1021. const cachePreview = this.getCachePreviewInfo(account);
  1022. if (cachePreview) {
  1023. void ServerLogUtil.info('AccountInfo', `Navidrome缓存目录结构:`);
  1024. void ServerLogUtil.info('AccountInfo', `- 缓存根目录: ${cachePreview.cacheRoot}`);
  1025. void ServerLogUtil.info('AccountInfo', `- 示例缓存路径: ${cachePreview.examplePath}`);
  1026. } else {
  1027. void ServerLogUtil.warn('AccountInfo', '无法预览缓存目录:上下文或根目录不可用');
  1028. }
  1029. // 记录封面缓存状态
  1030. void ServerLogUtil.info('AccountInfo', `当前封面URL缓存数量: ${this.coverUrlCache.size}`);
  1031. if (this.coverUrlCache.size > 0) {
  1032. const cacheKeys = Array.from(this.coverUrlCache.keys()).slice(0, 10);
  1033. void ServerLogUtil.debug('AccountInfo', `封面缓存示例: ${cacheKeys.join(', ')}`);
  1034. }
  1035. } catch (error) {
  1036. void ServerLogUtil.error('AccountInfo', `记录账号信息失败: ${(error as Error).message}`);
  1037. }
  1038. }
  1039. /**
  1040. * 记录缓存统计信息
  1041. */
  1042. private async logCacheStatistics(account: WebDavAccount): Promise<void> {
  1043. try {
  1044. void ServerLogUtil.info('CacheStats', '=== Navidrome 缓存统计 ===');
  1045. void ServerLogUtil.info('CacheStats', `封面URL缓存: ${this.coverUrlCache.size} 个条目`);
  1046. void ServerLogUtil.info('CacheStats', `已加载歌曲: ${this.allVideos.length} 首`);
  1047. void ServerLogUtil.info('CacheStats', `已处理艺术家: ${this.artists.length} 位`);
  1048. void ServerLogUtil.info('CacheStats', `已处理专辑: ${this.albums.length} 张`);
  1049. // 计算封面统计
  1050. const songsWithCover = this.allVideos.filter(song => song.pixelMapPath && song.pixelMapPath.length > 0).length;
  1051. const albumsWithCover = this.albums.filter(album => album.coverUrl && album.coverUrl.length > 0).length;
  1052. const artistsWithCover = this.artists.filter(artist => artist.coverUrl && artist.coverUrl.length > 0).length;
  1053. void ServerLogUtil.info('CacheStats', `封面统计:`);
  1054. void ServerLogUtil.info('CacheStats', `- 歌曲有封面: ${songsWithCover}/${this.allVideos.length} (${Math.round(songsWithCover / this.allVideos.length * 100)}%)`);
  1055. void ServerLogUtil.info('CacheStats', `- 专辑有封面: ${albumsWithCover}/${this.albums.length} (${Math.round(albumsWithCover / this.albums.length * 100)}%)`);
  1056. void ServerLogUtil.info('CacheStats', `- 艺术家有封面: ${artistsWithCover}/${this.artists.length} (${Math.round(artistsWithCover / this.artists.length * 100)}%)`);
  1057. } catch (error) {
  1058. void ServerLogUtil.error('CacheStats', `记录缓存统计失败: ${(error as Error).message}`);
  1059. }
  1060. }
  1061. private resolveEmbedCover(account: WebDavAccount, path?: string): string | undefined {
  1062. if (!this.isNavidromeAccount(account)) {
  1063. return undefined;
  1064. }
  1065. return navidromeRestApi.resolveResourceUrl(account, path);
  1066. }
  1067. private resolveLibraryInfo(account: WebDavAccount): LibraryInfo {
  1068. if (this.isJellyfinAccount(account)) {
  1069. return { type: CommonConstants.TYPE_JELLYFIN, scheme: 'jellyfin' } as LibraryInfo;
  1070. }
  1071. if (this.isEmbyAccount(account)) {
  1072. return { type: CommonConstants.TYPE_EMBY, scheme: 'emby' } as LibraryInfo;
  1073. }
  1074. return { type: CommonConstants.TYPE_NAVIDROME, scheme: 'navidrome' } as LibraryInfo;
  1075. }
  1076. private convertSongToVideoItem(song: NavidromeRestSong, account: WebDavAccount, coverUrl?: string): VideoItem {
  1077. const title = song.title ?? Constants.UNKNOWN_TITLE;
  1078. const libraryInfo = this.resolveLibraryInfo(account);
  1079. const videoItem = new VideoItem(
  1080. title,
  1081. song.id,
  1082. `${libraryInfo.scheme}://${account.id ?? 0}/${song.id}`,
  1083. libraryInfo.type,
  1084. song.size ?? 0,
  1085. song.createdAt ?? '',
  1086. Utility.formatFSize(song.size ?? 0),
  1087. undefined,
  1088. song.artist ?? Constants.UNKNOWN_ARTIST,
  1089. song.album ?? '',
  1090. `${title}${song.suffix ? '.' + song.suffix : ''}`
  1091. );
  1092. const durationStr = this.formatSongDuration(song.duration);
  1093. if (durationStr) {
  1094. videoItem.duration = durationStr;
  1095. }
  1096. videoItem.size = Utility.formatFSize(song.size ?? 0);
  1097. videoItem.bit_rate = song.bitRate ? song.bitRate.toString() : undefined;
  1098. videoItem.genre = song.genre;
  1099. videoItem.webdav_account_id = account.id?.toString();
  1100. videoItem.remote_rel_path = song.id;
  1101. videoItem.navArtistId = song.artistId;
  1102. videoItem.navAlbumId = song.albumId;
  1103. videoItem.pixelMapPath = coverUrl;
  1104. // 调试日志:检查歌曲的 albumId 和 artistId
  1105. if (this.allVideos.length < 3) {
  1106. Logger.info('heanup', `歌曲 ${title}: artistId=${song.artistId}, albumId=${song.albumId}, artist=${song.artist}, album=${song.album}`);
  1107. }
  1108. if (song.track !== undefined && song.track !== null) {
  1109. videoItem.track = song.track.toString();
  1110. }
  1111. if (song.year !== undefined && song.year !== null) {
  1112. videoItem.year = song.year.toString();
  1113. }
  1114. if (song.contentType) {
  1115. videoItem.mimeType = song.contentType;
  1116. }
  1117. return videoItem;
  1118. }
  1119. private formatSongDuration(durationSeconds?: number): string | undefined {
  1120. if (durationSeconds === undefined || durationSeconds === null || durationSeconds < 0) {
  1121. return undefined;
  1122. }
  1123. const totalSeconds = Math.floor(durationSeconds);
  1124. const minutes = Math.floor(totalSeconds / 60);
  1125. const seconds = totalSeconds % 60;
  1126. const pad = (value: number) => value.toString().padStart(2, '0');
  1127. return `${pad(minutes)}:${pad(seconds)}`;
  1128. }
  1129. @Builder
  1130. topTitleBar() {
  1131. Column() {
  1132. Row({ space: 6 }) {
  1133. // 标题或搜索框
  1134. if (!this.isSearchMode) {
  1135. // 详情视图模式下显示返回按钮
  1136. if (this.isDetailView) {
  1137. Button({ type: ButtonType.Circle, stateEffect: true }) {
  1138. SymbolGlyph($r('sys.symbol.chevron_left'))
  1139. .attributeModifier(new SymbolGlyphFancyModifier(24, '', ''))
  1140. }
  1141. .attributeModifier(new ButtonFancyModifier(40, 40))
  1142. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.6 })
  1143. .animation({ duration: 300, curve: Curve.Ease })
  1144. .onClick(() => {
  1145. // 返回到之前的标签页
  1146. this.isDetailView = false;
  1147. this.clearFilter();
  1148. })
  1149. .attributeModifier(new ShadowModifier())
  1150. .zIndex(0)
  1151. Text(this.filterLabel)
  1152. .margin({ left: 3, right: 10 })
  1153. .fontColor($r('app.color.text_color'))
  1154. .fontSize(18)
  1155. .maxLines(1)
  1156. .textOverflow({ overflow: TextOverflow.MARQUEE })
  1157. .layoutWeight(1)
  1158. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.6 })
  1159. .animation({ duration: 300, curve: Curve.Ease })
  1160. } else {
  1161. // 正常模式:侧边栏按钮和账号名
  1162. Button({ type: ButtonType.Circle, stateEffect: true }) {
  1163. SymbolGlyph($r('sys.symbol.sort'))
  1164. .attributeModifier(new SymbolGlyphFancyModifier(25, '', ''))
  1165. }
  1166. .attributeModifier(new ButtonFancyModifier(40, 40))
  1167. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.6 })
  1168. .animation({ duration: 300, curve: Curve.Ease })
  1169. .onClick(() => {
  1170. this.getUIContext().animateTo({ duration: 555 }, () => {
  1171. // 动画闭包内控制Image组件的出现和消失
  1172. this.isShowDrawer = !this.isShowDrawer
  1173. this.offsetX = 0
  1174. })
  1175. })
  1176. .attributeModifier(new ShadowModifier())
  1177. .zIndex(0)
  1178. Text(this.selectedAccount.name)
  1179. .margin({ left: 3, right: 10 })
  1180. .fontColor($r('app.color.text_color'))
  1181. .fontSize(18)
  1182. .maxLines(1)
  1183. .textOverflow({ overflow: TextOverflow.MARQUEE })
  1184. .layoutWeight(1)
  1185. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.6 })
  1186. .onClick(() => {
  1187. // 可以添加标题点击事件
  1188. })
  1189. .animation({ duration: 300, curve: Curve.Ease })
  1190. }
  1191. } else {
  1192. Button({ type: ButtonType.Circle, stateEffect: true }) {
  1193. SymbolGlyph($r('sys.symbol.chevron_left'))
  1194. .attributeModifier(new SymbolGlyphFancyModifier(24, '', ''))
  1195. }
  1196. .attributeModifier(new ButtonFancyModifier(40, 40))
  1197. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.6 })
  1198. .animation({ duration: 300, curve: Curve.Ease })
  1199. .onClick(() => {
  1200. this.isSearchMode = false;
  1201. void this.onSearchInput('');
  1202. })
  1203. .attributeModifier(new ShadowModifier())
  1204. .zIndex(0)
  1205. }
  1206. // 搜索框
  1207. Search({ value: this.searchText, placeholder: '搜索标题、艺术家...' })
  1208. .searchButton('搜索', { fontColor: this.themeColor })
  1209. .searchIcon({
  1210. src: $r('sys.media.ohos_ic_public_search_filled')
  1211. })
  1212. .cancelButton({
  1213. style: CancelButtonStyle.CONSTANT,
  1214. icon: {
  1215. src: $r('sys.media.ohos_ic_public_cancel_filled')
  1216. }
  1217. })
  1218. .layoutWeight(1)
  1219. .height(35)
  1220. .maxLength(20)
  1221. .backgroundColor(this.isDarkMode?Color.Black:'#F5F5F5')
  1222. .placeholderColor(Color.Grey)
  1223. .placeholderFont({ size: 14, weight: 400 })
  1224. .textFont({ size: 14, weight: 400 })
  1225. .onSubmit((value: string) => {
  1226. void this.onSearchInput(value);
  1227. })
  1228. .onChange((value: string) => {
  1229. void this.onSearchInput(value);
  1230. })
  1231. .visibility(this.isSearchMode?Visibility.Visible:Visibility.None)
  1232. .animation({ duration: 300, curve: Curve.Ease })
  1233. // 搜索/排序按钮
  1234. if (!this.isSearchMode) {
  1235. // 搜索按钮
  1236. Button({ type: ButtonType.Circle, stateEffect: true }) {
  1237. SymbolGlyph($r('sys.symbol.magnifyingglass'))
  1238. .attributeModifier(new SymbolGlyphFancyModifier(25, '', ''))
  1239. }
  1240. .attributeModifier(new ButtonFancyModifier(40, 40))
  1241. .animation({ duration: 300, curve: Curve.Ease })
  1242. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.6 })
  1243. .attributeModifier(new ShadowModifier())
  1244. .zIndex(0)
  1245. .visibility(this.selectedTab==0?Visibility.Visible:Visibility.None)
  1246. .onClick(() => {
  1247. this.isSearchMode = true;
  1248. if (!this.isSearchLoading && this.searchText.length === 0) {
  1249. this.filteredList = [];
  1250. }
  1251. })
  1252. // 排序按钮
  1253. Button({ type: ButtonType.Circle, stateEffect: true }) {
  1254. SymbolGlyph($r('sys.symbol.list_number'))
  1255. .attributeModifier(new SymbolGlyphFancyModifier(25, '', ''))
  1256. }
  1257. .attributeModifier(new ButtonFancyModifier(40, 40))
  1258. .animation({ duration: 300, curve: Curve.Ease })
  1259. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.6 })
  1260. .bindMenu(this.SortMenuBuilder)
  1261. .attributeModifier(new ShadowModifier())
  1262. .zIndex(0)
  1263. }
  1264. }
  1265. .width('100%')
  1266. .height(55)
  1267. .padding({ left: 15, right: 15 })
  1268. .justifyContent(FlexAlign.SpaceBetween)
  1269. .alignItems(VerticalAlign.Center)
  1270. // 分段按钮
  1271. SegmentButton({
  1272. options: this.tabOptions,
  1273. selectedIndexes: $tabSelectedIndexes
  1274. })
  1275. .width('100%')
  1276. .padding({ left: 25, right: 25, top: 5, bottom: 5 })
  1277. }
  1278. .width('100%')
  1279. .padding({ top: this.topSafeHeight + 5 })
  1280. // .backgroundColor($r('app.color.start_window_background'))
  1281. }
  1282. @Builder
  1283. SortMenuBuilder() {
  1284. Menu() {
  1285. MenuItem({
  1286. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.text_and_arrow_up')),
  1287. content: $r('app.string.sort_by_name')
  1288. })
  1289. .onClick(async () => {
  1290. this.doSortType(0);
  1291. PreferencesUtil.put("navidromeSortType", 0);
  1292. })
  1293. MenuItem({
  1294. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.text_and_arrow_down')),
  1295. content: '按名称降序'
  1296. })
  1297. .onClick(async () => {
  1298. this.doSortType(1);
  1299. PreferencesUtil.put("navidromeSortType", 1);
  1300. })
  1301. MenuItem({
  1302. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.clock')),
  1303. content: '按艺术家升序'
  1304. })
  1305. .onClick(async () => {
  1306. this.doSortType(2);
  1307. PreferencesUtil.put("navidromeSortType", 2);
  1308. })
  1309. MenuItem({
  1310. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.timer')),
  1311. content: '按艺术家降序'
  1312. })
  1313. .onClick(async () => {
  1314. this.doSortType(3);
  1315. PreferencesUtil.put("navidromeSortType", 3);
  1316. })
  1317. MenuItem({
  1318. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.text_and_arrow_up')),
  1319. content: '按专辑升序'
  1320. })
  1321. .onClick(async () => {
  1322. this.doSortType(4);
  1323. PreferencesUtil.put("navidromeSortType", 4);
  1324. })
  1325. MenuItem({
  1326. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.text_and_arrow_down')),
  1327. content: '按专辑降序'
  1328. })
  1329. .onClick(async () => {
  1330. this.doSortType(5);
  1331. PreferencesUtil.put("navidromeSortType", 5);
  1332. })
  1333. }
  1334. }
  1335. doSortType(index: number) {
  1336. this.sortType = index;
  1337. const songs = this.isSearchMode && this.searchText.length > 0 ? this.filteredList : this.allVideos;
  1338. const sortTypeNames = ['名称升序', '名称降序', '艺术家升序', '艺术家降序', '专辑升序', '专辑降序'];
  1339. const sortTypeName = sortTypeNames[index] || '未知排序';
  1340. // 记录排序操作
  1341. void ServerLogUtil.info('NavidromeSort', `应用排序: ${sortTypeName} (${index})`);
  1342. void ServerLogUtil.info('NavidromeSort', `排序范围: ${songs.length} 首歌曲 (${this.isSearchMode ? '搜索结果' : '全部歌曲'})`);
  1343. const startTime = Date.now();
  1344. // 对歌曲列表进行排序
  1345. switch (index) {
  1346. case 0: // 名称升序
  1347. Utility.doSortListAscending(songs,false)
  1348. break;
  1349. case 1: // 名称降序
  1350. Utility.doSortListDescending(songs,true)
  1351. break;
  1352. case 2: // 艺术家升序
  1353. songs.sort((a, b) => {
  1354. // 处理艺术家可能为undefined的字符串比较
  1355. const artistA = a.artist?.trim() || ''; // 可选添加 trim() 处理空格
  1356. const artistB = b.artist?.trim() || '';
  1357. return artistA.localeCompare(artistB);
  1358. });
  1359. break;
  1360. case 3: // 艺术家降序
  1361. songs.sort((a, b) => {
  1362. // 处理艺术家可能为undefined的字符串比较
  1363. const artistA = a.artist?.trim() || ''; // 可选添加 trim() 处理空格
  1364. const artistB = b.artist?.trim() || '';
  1365. return artistB.localeCompare(artistA);
  1366. });
  1367. break;
  1368. case 4: // 专辑升序
  1369. songs.sort((a, b) => {
  1370. const albumA = a.album?.trim() || ''; // 可选添加 trim() 处理空格
  1371. const albumB = b.album?.trim() || '';
  1372. return albumA.localeCompare(albumB);
  1373. });
  1374. break;
  1375. case 5: // 专辑降序
  1376. songs.sort((a, b) => {
  1377. const albumA = a.album?.trim() || ''; // 可选添加 trim() 处理空格
  1378. const albumB = b.album?.trim() || '';
  1379. return albumB.localeCompare(albumA);
  1380. });
  1381. break;
  1382. }
  1383. const sortTime = Date.now() - startTime;
  1384. // 更新显示列表
  1385. if (this.isSearchMode) {
  1386. this.filteredList = [...songs];
  1387. }
  1388. // 记录排序结果
  1389. void ServerLogUtil.info('NavidromeSort', `排序完成: ${sortTypeName}`);
  1390. void ServerLogUtil.info('NavidromeSort', `- 排序耗时: ${sortTime}ms`);
  1391. void ServerLogUtil.debug('NavidromeSort', `排序结果示例: ${songs.slice(0, 3).map(s => `${s.name} (${s.artist})`).join(', ')}`);
  1392. }
  1393. // 实时搜索逻辑(改为远程API搜索)
  1394. private async onSearchInput(value: string): Promise<void> {
  1395. const keyword = value.trim();
  1396. this.searchText = keyword;
  1397. const ticket = ++this.searchTicket;
  1398. void ServerLogUtil.debug('NavidromeSearch', `搜索输入: "${value}" -> "${keyword}"`);
  1399. if (keyword.length === 0) {
  1400. this.filteredList = [];
  1401. this.isSearchLoading = false;
  1402. void ServerLogUtil.info('NavidromeSearch', '搜索已清空,显示所有歌曲');
  1403. return;
  1404. }
  1405. if (!this.isSearchMode) {
  1406. this.isSearchMode = true;
  1407. }
  1408. const account = this.resolveActiveAccount();
  1409. if (!account) {
  1410. this.filteredList = [];
  1411. this.isSearchLoading = false;
  1412. ToastUtil.showToast('媒体库账号不可用');
  1413. return;
  1414. }
  1415. this.isSearchLoading = true;
  1416. this.filteredList = [];
  1417. const startTime = Date.now();
  1418. void ServerLogUtil.info('NavidromeSearch', `开始远程搜索: "${keyword}"`);
  1419. try {
  1420. let restSongs: NavidromeRestSong[] = [];
  1421. if (this.isNavidromeAccount(account)) {
  1422. const songs = await navidromeApi.searchSongs(account, keyword, NAVIDROME_SEARCH_LIMIT);
  1423. restSongs = this.convertApiSongsToRestSongs(songs);
  1424. } else if (this.isJellyfinAccount(account)) {
  1425. const response = await jellyfinApi.searchSongs(account, keyword, 0, this.REMOTE_SEARCH_LIMIT);
  1426. restSongs = this.convertJellyfinSongsToRestSongs(response.items);
  1427. } else if (this.isEmbyAccount(account)) {
  1428. const response = await embyApi.searchSongs(account, keyword, 0, this.REMOTE_SEARCH_LIMIT);
  1429. restSongs = this.convertEmbySongsToRestSongs(response.items);
  1430. }
  1431. if (ticket !== this.searchTicket) {
  1432. return;
  1433. }
  1434. const searchTime = Date.now() - startTime;
  1435. if (!restSongs || restSongs.length === 0) {
  1436. this.filteredList = [];
  1437. void ServerLogUtil.warn('NavidromeSearch', `搜索无结果: "${keyword}"`);
  1438. void ServerLogUtil.info('NavidromeSearch', `- 搜索耗时: ${searchTime}ms`);
  1439. return;
  1440. }
  1441. const videoItems = await this.convertSongsToVideoItems(restSongs, account);
  1442. if (ticket !== this.searchTicket) {
  1443. return;
  1444. }
  1445. this.filteredList = videoItems;
  1446. this.doSortType(this.sortType);
  1447. void ServerLogUtil.info('NavidromeSearch', `搜索完成: "${keyword}"`);
  1448. void ServerLogUtil.info('NavidromeSearch', `- 搜索耗时: ${searchTime}ms`);
  1449. void ServerLogUtil.info('NavidromeSearch', `- 匹配结果: ${videoItems.length}`);
  1450. void ServerLogUtil.debug('NavidromeSearch', `搜索结果示例: ${videoItems.slice(0, 3).map(s => `${s.name} (${s.artist})`).join(', ')}`);
  1451. } catch (error) {
  1452. if (ticket !== this.searchTicket) {
  1453. return;
  1454. }
  1455. this.filteredList = [];
  1456. const message = (error as Error).message ?? 'Navidrome 搜索失败';
  1457. ToastUtil.showToast(message);
  1458. void ServerLogUtil.error('NavidromeSearch', `搜索失败: ${message}`);
  1459. void ServerLogUtil.info('NavidromeSearch', `- 搜索耗时: ${Date.now() - startTime}ms`);
  1460. } finally {
  1461. if (ticket === this.searchTicket) {
  1462. this.isSearchLoading = false;
  1463. }
  1464. }
  1465. }
  1466. private getCurrentCount(): number {
  1467. switch (this.selectedTab) {
  1468. case 1:
  1469. return this.artists.length;
  1470. case 2:
  1471. return this.albums.length;
  1472. case 3:
  1473. return this.playlists.length;
  1474. default:
  1475. return this.getVisibleSongs().length;
  1476. }
  1477. }
  1478. private getEmptyTitle(): string {
  1479. switch (this.selectedTab) {
  1480. case 1:
  1481. return '暂无艺术家';
  1482. case 2:
  1483. return '暂无专辑';
  1484. case 3:
  1485. return '暂无歌单';
  1486. default:
  1487. if (this.isSearchMode && this.searchText.length > 0) {
  1488. return this.isSearchLoading ? '正在搜索远程歌曲' : '没有匹配的远程歌曲';
  1489. }
  1490. if (this.filterType !== NavFilterType.None && this.isFilterLoading) {
  1491. return '正在加载筛选结果';
  1492. }
  1493. return this.filterType === NavFilterType.None ? '暂无音乐' : '该筛选下暂无歌曲';
  1494. }
  1495. }
  1496. private getEmptySubtitle(): string {
  1497. switch (this.selectedTab) {
  1498. case 1:
  1499. return '当前筛选没有找到艺术家';
  1500. case 2:
  1501. return '当前筛选没有找到专辑';
  1502. case 3:
  1503. return '当前筛选没有找到歌单';
  1504. default:
  1505. if (this.isSearchMode && this.searchText.length > 0) {
  1506. return this.isSearchLoading ? '请稍候,正在通过 API 搜索' : '换个关键词再试试吧';
  1507. }
  1508. if (this.filterType !== NavFilterType.None && this.isFilterLoading) {
  1509. return '请稍候...';
  1510. }
  1511. return this.filterType === NavFilterType.None ? '当前分类下没有找到音乐文件' : '请尝试调整筛选条件';
  1512. }
  1513. }
  1514. @Builder
  1515. buildSongItem(song: VideoItem, index: number) {
  1516. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  1517. Row({ space: 12 }) {
  1518. // 歌曲封面
  1519. Image(song.pixelMapPath ? song.pixelMapPath : $r('app.media.alt'))
  1520. .width(52)
  1521. .height(52)
  1522. .borderRadius(9)
  1523. .sourceSize({ width: 38, height: 38 })
  1524. .draggable(false)
  1525. .interpolation(ImageInterpolation.High)// 用于重采样后的抗锯齿
  1526. .autoResize(true) // 重采样,可减少内存占用
  1527. .alt($r('app.media.alt'))
  1528. .fillColor(song.pixelMapPath ? undefined : this.themeColor)
  1529. .objectFit(ImageFit.Cover)
  1530. .margin({ left: 20 })
  1531. .animation({
  1532. duration: 500,
  1533. curve: Curve.Friction // 可选动画曲线
  1534. })
  1535. .shadow({
  1536. radius: StrUtil.isEmpty(song.pixelMapPath) ?6:14,
  1537. type: ShadowType.BLUR,
  1538. color: 'on_primary'
  1539. })
  1540. .onClick(() => {
  1541. this.playSong(song, index, true);
  1542. })
  1543. // 歌曲信息
  1544. Column({ space: 4 }) {
  1545. Text(song.name)
  1546. .fontSize(15)
  1547. .fontColor(this.currentSong?.filePath == song.filePath ? this.themeColor : $r('app.color.index_tab_font_color'))
  1548. .maxLines(1)
  1549. .textOverflow({ overflow: TextOverflow.Ellipsis })
  1550. Row() {
  1551. Text((song.artist ?? '') + " ")
  1552. .fontSize(13)
  1553. .fontColor(this.currentSong?.filePath == song.filePath ? this.themeColor : $r('app.color.index_tab_font_color'))
  1554. .opacity(0.6)
  1555. .maxLines(1)
  1556. .visibility(song.artist ? Visibility.Visible : Visibility.None)
  1557. .textOverflow({ overflow: TextOverflow.Ellipsis })
  1558. Text(this.buildSongMetaLine(song))
  1559. .fontSize(13)
  1560. .fontColor(this.currentSong?.filePath == song.filePath ? this.themeColor : $r('app.color.index_tab_font_color'))
  1561. .opacity(0.6)
  1562. .maxLines(1)
  1563. .textOverflow({ overflow: TextOverflow.Ellipsis })
  1564. }
  1565. .width('90%')
  1566. }
  1567. .alignItems(HorizontalAlign.Start)
  1568. .layoutWeight(1)
  1569. .padding({ right: 20 })
  1570. Column() {
  1571. ImageAnimator()
  1572. .images(CommonConstants.IMAGE_FRAME_INFO)// 动画数组
  1573. .duration(1000)// 持续
  1574. .state(AnimationStatus.Running)// 动画状态
  1575. .fillMode(FillMode.Forwards)
  1576. .visibility(this.currentSong?.filePath == song.filePath ? Visibility.Visible :
  1577. Visibility.None)
  1578. .width(18)
  1579. .margin({ right: 12, top: 8, bottom: 8 })
  1580. .height(18)
  1581. .iterations(-1) // 播放次数
  1582. }
  1583. }
  1584. }
  1585. .width('100%')
  1586. .padding(12)
  1587. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.8 })
  1588. .backgroundColor(Color.Transparent)
  1589. .onClick(() => {
  1590. this.playSong(song, index);
  1591. })
  1592. }
  1593. @Builder
  1594. buildArtistItem(artist: NavidromeRestArtist) {
  1595. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  1596. Row({ space: 12 }) {
  1597. Image(artist.coverUrl ?? $r('app.media.alt'))
  1598. .width(48)
  1599. .height(48)
  1600. .borderRadius(10)
  1601. .draggable(false)
  1602. .alt($r('app.media.alt'))
  1603. // .interpolation(ImageInterpolation.High)// 用于重采样后的抗锯齿
  1604. // .autoResize(true) // 重采样,可减少内存占用
  1605. .sourceSize({ width: 38, height: 38 })
  1606. .fillColor(artist.coverUrl ? undefined : this.themeColor)
  1607. .objectFit(ImageFit.Cover)
  1608. .margin({ left: 20 })
  1609. Column({ space: 4 }) {
  1610. Text(artist.name ?? Constants.UNKNOWN_ARTIST)
  1611. .fontSize(15)
  1612. .fontColor($r('app.color.index_tab_font_color'))
  1613. .maxLines(1)
  1614. .textAlign(TextAlign.Start)
  1615. .textOverflow({ overflow: TextOverflow.Ellipsis })
  1616. Text(this.buildArtistMetaLine(artist))
  1617. .fontSize(13)
  1618. .fontColor($r('app.color.index_tab_font_color'))
  1619. .opacity(0.6)
  1620. .maxLines(1)
  1621. .textOverflow({ overflow: TextOverflow.Ellipsis })
  1622. }
  1623. .alignItems(HorizontalAlign.Start)
  1624. .padding({ right: 20 })
  1625. }
  1626. .width('100%')
  1627. }
  1628. .width('100%')
  1629. .padding(12)
  1630. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.85 })
  1631. .backgroundColor(Color.Transparent)
  1632. .onClick(() => {
  1633. this.onArtistSelected(artist);
  1634. })
  1635. }
  1636. @Builder
  1637. buildAlbumItem(album: NavidromeRestAlbum) {
  1638. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  1639. Row({ space: 12 }) {
  1640. Image(album.coverUrl ?? $r('app.media.alt'))
  1641. .width(48)
  1642. .height(48)
  1643. .borderRadius(10)
  1644. .clip(true)
  1645. .alt($r('app.media.alt'))
  1646. .draggable(false)
  1647. // .interpolation(ImageInterpolation.High)// 用于重采样后的抗锯齿
  1648. // .autoResize(true) // 重采样,可减少内存占用
  1649. .sourceSize({ width: 38, height: 38 })
  1650. .fillColor(album.coverUrl ? undefined : this.themeColor)
  1651. .objectFit(ImageFit.Cover)
  1652. .margin({ left: 20 })
  1653. Column({ space: 4 }) {
  1654. Text(album.name ?? '未知专辑')
  1655. .fontSize(15)
  1656. .fontColor($r('app.color.index_tab_font_color'))
  1657. .maxLines(1)
  1658. .textAlign(TextAlign.Start)
  1659. .textOverflow({ overflow: TextOverflow.Ellipsis })
  1660. Row() {
  1661. Text(album.artist ?? Constants.UNKNOWN_ARTIST)
  1662. .fontSize(13)
  1663. .fontColor($r('app.color.index_tab_font_color'))
  1664. .opacity(0.6)
  1665. .maxLines(1)
  1666. .textOverflow({ overflow: TextOverflow.Ellipsis })
  1667. Text(this.buildAlbumMetaLine(album))
  1668. .fontSize(13)
  1669. .fontColor($r('app.color.index_tab_font_color'))
  1670. .opacity(0.6)
  1671. .maxLines(1)
  1672. .textOverflow({ overflow: TextOverflow.Ellipsis })
  1673. }
  1674. }
  1675. .alignItems(HorizontalAlign.Start)
  1676. .padding({ right: 20 })
  1677. }
  1678. .width('100%')
  1679. }
  1680. .width('100%')
  1681. .padding(12)
  1682. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.85 })
  1683. .backgroundColor(Color.Transparent)
  1684. .onClick(() => {
  1685. this.onAlbumSelected(album);
  1686. })
  1687. }
  1688. @Builder
  1689. buildPlaylistItem(playlist: NavidromeRestPlaylist) {
  1690. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  1691. Row({ space: 12 }) {
  1692. Image($r('app.media.alt'))
  1693. .width(48)
  1694. .height(48)
  1695. .borderRadius(10)
  1696. .alt($r('app.media.alt'))
  1697. .draggable(false)
  1698. .sourceSize({ width: 38, height: 38 })
  1699. .fillColor(this.themeColor)
  1700. .objectFit(ImageFit.Cover)
  1701. .margin({ left: 20 })
  1702. Column({ space: 4 }) {
  1703. Text(playlist.name ?? '未知歌单')
  1704. .fontSize(15)
  1705. .fontColor($r('app.color.index_tab_font_color'))
  1706. .maxLines(1)
  1707. .textAlign(TextAlign.Start)
  1708. .textOverflow({ overflow: TextOverflow.Ellipsis })
  1709. Text(this.buildPlaylistMetaLine(playlist))
  1710. .fontSize(13)
  1711. .fontColor($r('app.color.index_tab_font_color'))
  1712. .opacity(0.6)
  1713. .maxLines(1)
  1714. .textOverflow({ overflow: TextOverflow.Ellipsis })
  1715. if (playlist.ownerName) {
  1716. Text(playlist.ownerName)
  1717. .fontSize(12)
  1718. .fontColor($r('app.color.index_tab_font_color'))
  1719. .opacity(0.5)
  1720. .maxLines(1)
  1721. .textOverflow({ overflow: TextOverflow.Ellipsis })
  1722. }
  1723. }
  1724. .alignItems(HorizontalAlign.Start)
  1725. .padding({ right: 20 })
  1726. }
  1727. .width('100%')
  1728. }
  1729. .width('100%')
  1730. .padding(12)
  1731. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.85 })
  1732. .backgroundColor(Color.Transparent)
  1733. .onClick(() => {
  1734. this.onPlaylistSelected(playlist);
  1735. })
  1736. }
  1737. private buildSongMetaLine(song: VideoItem): string {
  1738. const parts: string[] = [];
  1739. if (song.duration) {
  1740. parts.push(song.duration as string);
  1741. }
  1742. // if (song.size) {
  1743. // parts.push(song.size as string);
  1744. // }
  1745. // if (parts.length === 0 && song.cTime) {
  1746. // parts.push(song.cTime as string);
  1747. // }
  1748. return parts.join(' · ');
  1749. }
  1750. private buildArtistMetaLine(artist: NavidromeRestArtist): string {
  1751. const albumCount = artist.albumCount ?? 0;
  1752. const songCount = artist.songCount ?? 0;
  1753. const playCount = artist.playCount ?? 0;
  1754. return `专辑 ${albumCount} · 歌曲 ${songCount} `;
  1755. }
  1756. private buildAlbumMetaLine(album: NavidromeRestAlbum): string {
  1757. const parts: string[] = [];
  1758. if (album.duration !== undefined) {
  1759. const duration = this.formatSongDuration(album.duration);
  1760. if (duration) {
  1761. parts.push(' '+duration);
  1762. }
  1763. }
  1764. if (album.minYear) {
  1765. parts.push(`发行 ${album.minYear}`);
  1766. }
  1767. return parts.join(' · ');
  1768. }
  1769. private buildPlaylistMetaLine(playlist: NavidromeRestPlaylist): string {
  1770. const parts: string[] = [];
  1771. if (playlist.songCount !== undefined) {
  1772. parts.push(`${playlist.songCount} 首歌`);
  1773. }
  1774. if (playlist.duration !== undefined) {
  1775. const duration = this.formatSongDuration(playlist.duration);
  1776. if (duration) {
  1777. parts.push(duration);
  1778. }
  1779. }
  1780. return parts.join(' · ');
  1781. }
  1782. private getVisibleSongs(): VideoItem[] {
  1783. if (this.isSearchMode) {
  1784. return this.searchText.length > 0 ? this.filteredList : this.allVideos;
  1785. }
  1786. if (this.filterType !== NavFilterType.None) {
  1787. return this.filterSongs;
  1788. }
  1789. return this.allVideos;
  1790. }
  1791. private onArtistSelected(artist: NavidromeRestArtist): void {
  1792. if (!artist || !artist.id) {
  1793. return;
  1794. }
  1795. this.isShowTitleBar = true;
  1796. // 保存当前标签页,进入详情视图
  1797. this.previousTab = this.selectedTab;
  1798. this.isDetailView = true;
  1799. // 应用筛选但不切换标签页
  1800. void this.applyFilter(NavFilterType.Artist, artist.id, artist.name ?? Constants.UNKNOWN_ARTIST);
  1801. }
  1802. private onAlbumSelected(album: NavidromeRestAlbum): void {
  1803. if (!album || !album.id) {
  1804. return;
  1805. }
  1806. this.isShowTitleBar = true;
  1807. // 保存当前标签页,进入详情视图
  1808. this.previousTab = this.selectedTab;
  1809. this.isDetailView = true;
  1810. // 应用筛选但不切换标签页
  1811. void this.applyFilter(NavFilterType.Album, album.id, album.name ?? '未知专辑');
  1812. }
  1813. private onPlaylistSelected(playlist: NavidromeRestPlaylist): void {
  1814. if (!playlist || !playlist.id) {
  1815. return;
  1816. }
  1817. this.isShowTitleBar = true;
  1818. // 保存当前标签页,进入详情视图
  1819. this.previousTab = this.selectedTab;
  1820. this.isDetailView = true;
  1821. // 应用筛选但不切换标签页
  1822. void this.applyFilter(NavFilterType.Playlist, playlist.id, playlist.name ?? '未知歌单');
  1823. }
  1824. private async applyFilter(type: NavFilterType, id: string, label: string): Promise<void> {
  1825. // 记录筛选操作
  1826. void ServerLogUtil.info('NavidromeFilter', `应用筛选:`);
  1827. const typeText = type === NavFilterType.Artist ? '艺术家' : type === NavFilterType.Album ? '专辑' : type === NavFilterType.Playlist ? '歌单' : '无';
  1828. void ServerLogUtil.info('NavidromeFilter', `- 类型: ${type} (${typeText})`);
  1829. void ServerLogUtil.info('NavidromeFilter', `- ID: ${id}`);
  1830. void ServerLogUtil.info('NavidromeFilter', `- 标签: ${label}`);
  1831. void ServerLogUtil.info('NavidromeFilter', `- 筛选前总歌曲数: ${this.allVideos.length}`);
  1832. // 先更新状态
  1833. this.filterType = type;
  1834. this.filterId = id;
  1835. this.filterLabel = label;
  1836. // 退出搜索模式,确保显示筛选结果
  1837. this.isSearchMode = false;
  1838. this.searchText = '';
  1839. this.filteredList = [];
  1840. this.isSearchLoading = false;
  1841. this.searchTicket++;
  1842. this.filterSongs = [];
  1843. this.isFilterLoading = true;
  1844. // 调试日志:检查筛选结果
  1845. void this.loadSongsForFilter(label).catch((error: Error) => {
  1846. void ServerLogUtil.error('NavidromeFilter', `筛选歌曲加载失败: ${error.message}`);
  1847. ToastUtil.showToast(error.message || '筛选数据加载失败');
  1848. });
  1849. // 不再自动切换标签页,保持在详情视图模式
  1850. }
  1851. private async loadSongsForFilter(label:string): Promise<void> {
  1852. if (this.filterType === NavFilterType.None || !this.filterId) {
  1853. this.filterSongs = [];
  1854. this.isFilterLoading = false;
  1855. return;
  1856. }
  1857. const account = this.resolveActiveAccount();
  1858. if (!account) {
  1859. this.filterSongs = [];
  1860. this.isFilterLoading = false;
  1861. throw new Error('媒体库账号不可用');
  1862. }
  1863. if (!this.isNavidromeAccount(account)) {
  1864. let restSongs: NavidromeRestSong[] = [];
  1865. if (this.filterType === NavFilterType.Artist) {
  1866. if (this.isJellyfinAccount(account)) {
  1867. const songs = await this.fetchAllJellyfinArtistSongs(account, this.filterId);
  1868. restSongs = this.convertJellyfinSongsToRestSongs(songs);
  1869. } else if (this.isEmbyAccount(account)) {
  1870. const songs = await this.fetchAllEmbyArtistSongs(account, this.filterId);
  1871. restSongs = this.convertEmbySongsToRestSongs(songs);
  1872. }
  1873. } else if (this.filterType === NavFilterType.Album) {
  1874. if (this.isJellyfinAccount(account)) {
  1875. const songs = await jellyfinApi.getAlbumSongs(account, this.filterId);
  1876. restSongs = this.convertJellyfinSongsToRestSongs(songs);
  1877. } else if (this.isEmbyAccount(account)) {
  1878. const songs = await embyApi.getAlbumSongs(account, this.filterId);
  1879. restSongs = this.convertEmbySongsToRestSongs(songs);
  1880. }
  1881. }
  1882. const videoItems = await this.convertSongsToVideoItems(restSongs, account);
  1883. this.filterSongs = videoItems;
  1884. this.isFilterLoading = false;
  1885. return;
  1886. }
  1887. const expectedFilterId = this.filterId;
  1888. const expectedFilterType = this.filterType;
  1889. try {
  1890. let songs: NavidromeRestSong[] = [];
  1891. if (this.filterType === NavFilterType.Artist) {
  1892. songs = await navidromeRestApi.fetchSongsByArtist(account, this.filterId,label);
  1893. } else if (this.filterType === NavFilterType.Album) {
  1894. songs = await navidromeRestApi.fetchSongsByAlbum(account, this.filterId,label);
  1895. } else if (this.filterType === NavFilterType.Playlist) {
  1896. songs = await navidromeRestApi.fetchSongsByPlaylist(account, this.filterId);
  1897. }
  1898. const videoItems = await this.convertSongsToVideoItems(songs, account);
  1899. if (expectedFilterId !== this.filterId || expectedFilterType !== this.filterType) {
  1900. return;
  1901. }
  1902. this.filterSongs = videoItems;
  1903. if (videoItems.length === 0) {
  1904. void ServerLogUtil.warn('NavidromeFilter', '筛选下暂无歌曲');
  1905. } else {
  1906. void ServerLogUtil.info('NavidromeFilter', `筛选歌曲加载完成: ${videoItems.length} 首`);
  1907. }
  1908. } finally {
  1909. this.isFilterLoading = false;
  1910. }
  1911. }
  1912. private clearFilter(): void {
  1913. this.filterType = NavFilterType.None;
  1914. this.filterId = '';
  1915. this.filterLabel = '';
  1916. this.filterSongs = [];
  1917. this.isFilterLoading = false;
  1918. // 退出详情视图
  1919. this.isDetailView = false;
  1920. }
  1921. private playSong(song: VideoItem, index: number, isJump: boolean = false): void {
  1922. try {
  1923. if (!this.allVideos || this.allVideos.length === 0) {
  1924. ToastUtil.showToast('暂无可播放的歌曲');
  1925. return;
  1926. }
  1927. const account = this.resolveActiveAccount();
  1928. if (!account || !account.id) {
  1929. ToastUtil.showToast('媒体库账号信息不完整,无法播放');
  1930. return;
  1931. }
  1932. // 记录播放详细信息
  1933. void ServerLogUtil.info('NavidromePlay', `开始播放歌曲: ${song.name} (#${index})`);
  1934. void ServerLogUtil.info('NavidromePlay', `歌曲信息:`);
  1935. void ServerLogUtil.info('NavidromePlay', `- ID: ${song.id}`);
  1936. void ServerLogUtil.info('NavidromePlay', `- 艺术家: ${song.artist || '未知'}`);
  1937. void ServerLogUtil.info('NavidromePlay', `- 专辑: ${song.album || '未知'}`);
  1938. void ServerLogUtil.info('NavidromePlay', `- 文件大小: ${song.size || '未知'}`);
  1939. void ServerLogUtil.info('NavidromePlay', `- 时长: ${song.duration || '未知'}`);
  1940. void ServerLogUtil.info('NavidromePlay', `- 封面: ${song.pixelMapPath ? '有' : '无'}`);
  1941. void ServerLogUtil.info('NavidromePlay', `- 播放路径: ${song.filePath}`);
  1942. const playlistSource = this.getVisibleSongs().length > 0 ? this.getVisibleSongs() : this.allVideos;
  1943. const targetIndex = playlistSource.findIndex(item => item.id === song.id);
  1944. const startIndex = targetIndex >= 0 ? targetIndex : Math.min(index, Math.max(playlistSource.length - 1, 0));
  1945. void ServerLogUtil.info('NavidromePlay', `播放列表设置: 起始索引 ${startIndex}, 总数 ${playlistSource.length}`);
  1946. setNavidromePlaylist(playlistSource, startIndex);
  1947. const playlistData: PlaylistEventData = {
  1948. playlistId: NAVIDROME_PLAYLIST_ID,
  1949. playlistName: `${getRemoteDriveDisplayLabel(account.webType)} - ${account.name ?? '未知账户'}`,
  1950. songCount: playlistSource.length,
  1951. startIndex,
  1952. isJump: isJump,//设置true会弹出播放页
  1953. songFilePaths: playlistSource.map(item => item.filePath)
  1954. };
  1955. const eventPlaylistPlay: emitter.InnerEvent = { eventId: EventConstants.EVENT_PLAYLIST_PLAY };
  1956. emitter.emit(eventPlaylistPlay, { data: playlistData });
  1957. void ServerLogUtil.info('NavidromePlay', `播放事件已发送`);
  1958. void ServerLogUtil.debug('NavidromePlay', `播放事件详情: 列表ID=${playlistData.playlistId}, 列表名称=${playlistData.playlistName}, 歌曲数=${playlistData.songCount}, 起始索引=${playlistData.startIndex}, 是否跳转=${playlistData.isJump}`);
  1959. if(!this.isNoJumpToHome){
  1960. void ServerLogUtil.debug('NavidromePlay', '跳转到首页播放器');
  1961. // 跳转到首页播放器
  1962. this.getUIContext()?.animateTo({ duration: 555 }, () => {
  1963. this.mType = 0
  1964. })
  1965. }
  1966. } catch (error) {
  1967. const err = error as Error;
  1968. void ServerLogUtil.error('NavidromePlay', `播放失败: ${err.message}`);
  1969. void ServerLogUtil.error('NavidromePlay', `失败歌曲信息: ${song.name} (${song.id})`);
  1970. ToastUtil.showToast('播放失败');
  1971. }
  1972. }
  1973. @Builder
  1974. buildContentView(){
  1975. // 主内容区域
  1976. if (this.loading) {
  1977. Column() {
  1978. LoadingProgress()
  1979. .width(50)
  1980. .height(50)
  1981. .color($r('app.color.title_bar_bg'))
  1982. Text('加载中...')
  1983. .margin({ top: 10 })
  1984. .fontSize(14)
  1985. .fontColor($r('app.color.index_tab_unselected_font_color'))
  1986. }
  1987. .width('100%')
  1988. .layoutWeight(1)
  1989. .padding({top:this.topSafeHeight+98})
  1990. .justifyContent(FlexAlign.Center)
  1991. } else {
  1992. if (this.isSearchMode && this.selectedTab === 0 && this.searchText.length > 0 && this.isSearchLoading) {
  1993. Column() {
  1994. LoadingProgress()
  1995. .width(40)
  1996. .height(40)
  1997. .color(this.themeColor)
  1998. Text('正在通过 API 搜索歌曲...')
  1999. .margin({ top: 12 })
  2000. .fontSize(14)
  2001. .fontColor($r('app.color.index_tab_unselected_font_color'))
  2002. }
  2003. .width('100%')
  2004. .layoutWeight(1)
  2005. } else if (this.selectedTab === 0 && this.filterType !== NavFilterType.None && this.isFilterLoading) {
  2006. Column() {
  2007. LoadingProgress()
  2008. .width(40)
  2009. .height(40)
  2010. .color(this.themeColor)
  2011. Text('正在加载筛选歌曲...')
  2012. .margin({ top: 12 })
  2013. .fontSize(14)
  2014. .fontColor($r('app.color.index_tab_unselected_font_color'))
  2015. }
  2016. .width('100%')
  2017. .layoutWeight(1)
  2018. } else {
  2019. List({scroller:this.scroller, space: 8 }) {
  2020. // 详情视图模式下显示筛选后的歌曲,否则根据标签页显示对应内容
  2021. if (this.isDetailView) {
  2022. ForEach(this.getVisibleSongs(), (item: VideoItem, index: number) => {
  2023. ListItem() {
  2024. this.buildSongItem(item, index)
  2025. }
  2026. }, (item: VideoItem) => item.id)
  2027. } else if (this.selectedTab === 0) {
  2028. ForEach(this.getVisibleSongs(), (item: VideoItem, index: number) => {
  2029. ListItem() {
  2030. this.buildSongItem(item, index)
  2031. }
  2032. }, (item: VideoItem) => item.id)
  2033. } else if (this.selectedTab === 1) {
  2034. ForEach(this.artists, (artist: NavidromeRestArtist) => {
  2035. ListItem() {
  2036. this.buildArtistItem(artist)
  2037. }
  2038. }, (artist: NavidromeRestArtist) => artist.id)
  2039. } else if (this.selectedTab === 2) {
  2040. ForEach(this.albums, (album: NavidromeRestAlbum) => {
  2041. ListItem() {
  2042. this.buildAlbumItem(album)
  2043. }
  2044. }, (album: NavidromeRestAlbum) => album.id)
  2045. } else if (this.selectedTab === 3) {
  2046. ForEach(this.playlists, (playlist: NavidromeRestPlaylist) => {
  2047. ListItem() {
  2048. this.buildPlaylistItem(playlist)
  2049. }
  2050. }, (playlist: NavidromeRestPlaylist) => playlist.id)
  2051. }
  2052. }
  2053. .onScrollFrameBegin((offset: number) => {
  2054. // 获取当前滚动偏移量
  2055. if(this.autoHideTitle){
  2056. const currentOffsetY = this.scroller.currentOffset().yOffset;
  2057. // 判断滚动方向
  2058. if (currentOffsetY > this.prevOffsetY) {
  2059. this.isShowTitleBar = false
  2060. } else if (currentOffsetY < this.prevOffsetY) {
  2061. this.isShowTitleBar = true
  2062. }
  2063. // 更新前一次偏移量
  2064. this.prevOffsetY = currentOffsetY;
  2065. }
  2066. return { offsetRemain: offset };
  2067. })
  2068. .width('100%')
  2069. .height('100%')
  2070. .layoutWeight(1)
  2071. .cachedCount(3)
  2072. .padding({ top: 5, bottom: 5 })
  2073. .listDirection(Axis.Vertical)
  2074. .contentEndOffset(this.bottomSafeHeight+70)
  2075. .contentStartOffset(this.topSafeHeight + 98)
  2076. .scrollBar(BarState.Auto)
  2077. .edgeEffect(EdgeEffect.Spring)
  2078. .onReachEnd(() => {
  2079. void this.handleReachEnd();
  2080. })
  2081. }
  2082. // 空状态
  2083. if (this.getCurrentCount() === 0 && !(this.selectedTab === 0 && this.filterType !== NavFilterType.None && this.isFilterLoading) && !(this.isSearchMode && this.searchText.length > 0 && this.isSearchLoading)) {
  2084. Column() {
  2085. SymbolGlyph($r('sys.symbol.music_fill'))
  2086. .fontSize(50)
  2087. .opacity(0.3)
  2088. Text(this.getEmptyTitle())
  2089. .margin({ top: 16 })
  2090. .fontSize(16)
  2091. .fontColor($r('app.color.index_tab_unselected_font_color'))
  2092. Text(this.getEmptySubtitle())
  2093. .margin({ top: 8 })
  2094. .fontSize(14)
  2095. .fontColor($r('app.color.index_tab_unselected_font_color'))
  2096. }
  2097. .width('100%')
  2098. .layoutWeight(1)
  2099. .margin({ bottom: 180 })
  2100. .justifyContent(FlexAlign.Center)
  2101. }
  2102. }
  2103. }
  2104. build() {
  2105. Stack() {
  2106. Column() {
  2107. this.buildContentView()
  2108. }
  2109. .height('100%')
  2110. Column() {
  2111. this.topTitleBar()
  2112. }
  2113. .visibility(this.isShowTitleBar?Visibility.Visible:
  2114. this.autoHideTitle?Visibility.None:Visibility.Visible)
  2115. .animation({
  2116. duration: 500,
  2117. curve: Curve.Friction // 可选动画曲线
  2118. })
  2119. }
  2120. .alignContent(Alignment.Top)
  2121. .width('100%')
  2122. .height('100%')
  2123. .backgroundImage(this.isCustomizeBg?this.customizeBgPath:$r('app.color.start_window_background'))
  2124. .backgroundImageSize(this.isLandscape?{width:'100%'}:{ height: '100%'})
  2125. .backgroundImagePosition(Alignment.Center)
  2126. .backdropBlur(this.blurValue)
  2127. .backgroundBrightness({rate:this.isCustomizeBg?0.1:0,lightUpDegree:this.bgBrightness})
  2128. .expandSafeArea([SafeAreaType.SYSTEM], [SafeAreaEdge.BOTTOM])
  2129. }
  2130. }