NavidromePage.ets 94 KB

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