NavidromePage.ets 129 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400
  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 { audioStationApi, AudioStationAlbum, AudioStationArtist, AudioStationPlaylist, AudioStationSong } from '../common/network/AudioStationApi';
  29. import { plexApi, PlexAlbum, PlexArtist, PlexPlaylist, PlexSong } from '../common/network/PlexApi';
  30. import { getRemoteDriveDisplayLabel } from '../common/util/RemoteDriveLabel';
  31. import NavidromeListCache, { AllCacheData } from '../common/util/NavidromeListCache';
  32. import { taskpool } from '@kit.ArkTS';
  33. const NAVIDROME_PLAYLIST_ID = 'navidrome-playlist';
  34. const NAVIDROME_SEARCH_LIMIT = 500;
  35. interface PlaylistEventData {
  36. playlistId: string;
  37. playlistName: string;
  38. songCount: number;
  39. startIndex: number;
  40. isJump: boolean;
  41. songFilePaths: string[];
  42. }
  43. enum NavFilterType {
  44. None = 0,
  45. Artist = 1,
  46. Album = 2,
  47. Playlist = 3
  48. }
  49. interface CachePreviewInfo {
  50. cacheRoot: string;
  51. examplePath: string;
  52. }
  53. interface LibraryInfo {
  54. type: number;
  55. scheme: string;
  56. }
  57. class AudioStationAlbumKey {
  58. name: string;
  59. artist: string;
  60. constructor(name: string, artist: string) {
  61. this.name = name;
  62. this.artist = artist;
  63. }
  64. }
  65. /**
  66. * taskpool 任务结果接口
  67. * 返回带封面的完整数据
  68. */
  69. interface TaskResult {
  70. songs: VideoItem[];
  71. artists: NavidromeRestArtist[];
  72. albums: NavidromeRestAlbum[];
  73. playlists: NavidromeRestPlaylist[];
  74. }
  75. /**
  76. * Navidrome API 分页响应接口
  77. */
  78. interface PagedResponse<T> {
  79. data: T[];
  80. nextStart: number | null;
  81. }
  82. /**
  83. * Account 序列化数据接口 (用于 taskpool 传递)
  84. */
  85. interface AccountData {
  86. id: number;
  87. webType: number;
  88. host: string;
  89. port: number;
  90. account: string;
  91. password: string;
  92. enableHttps: boolean;
  93. navidromeBasePath: string;
  94. jellyfinBasePath: string;
  95. embyBasePath: string;
  96. name: string;
  97. }
  98. @Component
  99. export struct NavidromePage {
  100. @State isShowTitleBar: boolean = true //是否显示分类导航条
  101. private scroller: Scroller = new Scroller()
  102. private prevOffsetY: number = 0; // 记录上一次的Y轴偏移量
  103. @State autoHideTitle: boolean = true //滚动自动隐藏标题栏
  104. @State isCustomizeBg: boolean = false //自定义背景界面
  105. @StorageProp('isLandscape') isLandscape: boolean = false;
  106. @State blurValue: number = 0 //背景模糊
  107. @State bgBrightness: number = 0 //背景亮度
  108. @State customizeBgPath: string | undefined = '';
  109. @Link mType: number;
  110. @Link offsetX: number;
  111. @Link isShowDrawer: boolean;
  112. @State isNoJumpToHome: boolean = false //网盘播放不跳转首页
  113. @StorageProp('bottomSafeHeight') bottomSafeHeight: number = 0;
  114. @Prop @Watch('onSwitchAccount') selectedAccount: WebDavAccount;
  115. @StorageProp('currentTheme') currentTheme: number = 0;
  116. @State selectedTab: number = 0; // 0: 全部, 1: 艺术家, 2: 专辑
  117. @State allVideos: VideoItem[] = [];
  118. @State artists: NavidromeRestArtist[] = [];
  119. @State albums: NavidromeRestAlbum[] = [];
  120. @State playlists: NavidromeRestPlaylist[] = [];
  121. @State loading: boolean = false;
  122. @State songNextStart: number | null = 0;
  123. @State artistNextStart: number | null = 0;
  124. @State albumNextStart: number | null = 0;
  125. @State playlistNextStart: number | null = 0;
  126. @State isSongPageLoading: boolean = false;
  127. @State isArtistPageLoading: boolean = false;
  128. @State isAlbumPageLoading: boolean = false;
  129. @State isPlaylistPageLoading: boolean = false;
  130. // 新增:详情视图状态
  131. @Link isDetailView: boolean; // 是否在艺术家/专辑详情视图
  132. @State previousTab: number = 0; // 进入详情视图前的标签页索引
  133. @StorageProp('isDarkMode') isDarkMode: boolean = false;
  134. @StorageLink('currentSong') currentSong: VideoItem | undefined = undefined;
  135. @StorageProp('topSafeHeight') topSafeHeight: number = 0;
  136. @State @Watch('onTabSelectedIndexesChanged') tabSelectedIndexes: number[] = [0];
  137. @StorageProp('themeColor') themeColor: string =
  138. PreferencesUtil.getStringSync('THEME_COLOR', CommonConstants.DEFAULT_THEME_COLOR);
  139. private tabs: string[] = ['全部', '艺术家', '专辑', '歌单'];
  140. private loadTicket: number = 0;
  141. @State filterType: NavFilterType = NavFilterType.None;
  142. @State filterLabel: string = '';
  143. @State filterId: string = '';
  144. @State filterSongs: VideoItem[] = [];
  145. @State isFilterLoading: boolean = false;
  146. private coverUrlCache: Map<string, string> = new Map();
  147. private albumCoverLookup: Map<string, string> = new Map();
  148. private searchTicket: number = 0;
  149. private readonly REMOTE_PAGE_SIZE: number = 200;
  150. private jellyfinSongIdSeen: Set<string> = new Set();
  151. private embySongIdSeen: Set<string> = new Set();
  152. private jellyfinSongKeySeen: Set<string> = new Set();
  153. private embySongKeySeen: Set<string> = new Set();
  154. private listCache = NavidromeListCache.getInstance();
  155. private isNavidromeAccount(account: WebDavAccount): boolean {
  156. return account.webType === RemoteDriveType.Navidrome;
  157. }
  158. private isJellyfinAccount(account: WebDavAccount): boolean {
  159. return account.webType === RemoteDriveType.Jellyfin;
  160. }
  161. private isEmbyAccount(account: WebDavAccount): boolean {
  162. return account.webType === RemoteDriveType.Emby;
  163. }
  164. private isAudioStationAccount(account: WebDavAccount): boolean {
  165. return account.webType === RemoteDriveType.AudioStation;
  166. }
  167. private isPlexAccount(account: WebDavAccount): boolean {
  168. return account.webType === RemoteDriveType.Plex;
  169. }
  170. private createTabOptions(): SegmentButtonOptions {
  171. const buttons = [
  172. { text: '全部' },
  173. { text: '艺术家' },
  174. { text: '专辑' },
  175. { text: '歌单' }
  176. ] as SegmentButtonItemTuple;
  177. return SegmentButtonOptions.capsule({
  178. buttons,
  179. direction: Direction.Ltr,
  180. buttonPadding: { top: 10, bottom: 10 },
  181. backgroundColor: $r('app.color.index_background'),
  182. selectedBackgroundColor: $r('app.color.start_window_background'),
  183. selectedFontColor: $r('app.color.text_color'),
  184. fontSize: 14,
  185. selectedFontSize: 15,
  186. localizedTextPadding: {
  187. end: LengthMetrics.vp(20),
  188. start: LengthMetrics.vp(20)
  189. }
  190. });
  191. }
  192. private getCachePreviewInfo(account: WebDavAccount): CachePreviewInfo | null {
  193. try {
  194. const manager = RemoteDriveManager.getInstance();
  195. const context = manager.context;
  196. if (!context) {
  197. return null;
  198. }
  199. const baseDir = context.filesDir ?? context.cacheDir;
  200. if (!baseDir) {
  201. return null;
  202. }
  203. const accountId = account.id?.toString() || 'default';
  204. const cacheRoot = `${baseDir}/remote_cache/webdav/${accountId}`;
  205. const examplePath = `${cacheRoot}/navidrome_preview.cache`;
  206. return { cacheRoot, examplePath };
  207. } catch (error) {
  208. Logger.error('NavidromePage', `获取缓存预览路径失败: ${(error as Error).message}`);
  209. return null;
  210. }
  211. }
  212. // 搜索和排序相关状态
  213. @State isSearchMode: boolean = false;
  214. @State searchText: string = ''; // 用户输入内容
  215. @State filteredList: Array<VideoItem> = []; // 过滤后的歌曲结果
  216. @State sortType: number = 0; // 排序类型 0:名称升序 1:名称降序 2:时间升序 3:时间降序 4:大小升序 5:大小降序
  217. @State isSearchLoading: boolean = false;
  218. private readonly REMOTE_SEARCH_LIMIT: number = 500;
  219. // SegmentButton选项
  220. @State tabOptions: SegmentButtonOptions = this.createTabOptions();
  221. //当胶囊按钮的选择发生变化时调用此函数
  222. onTabSelectedIndexesChanged() {
  223. this.selectedTab = this.tabSelectedIndexes[0];
  224. console.info('heanup', `Selected tab: ${this.tabs[this.selectedTab]}`);
  225. // 如果在详情视图模式下切换标签页,退出详情视图并清除筛选
  226. if (this.isDetailView) {
  227. this.isDetailView = false;
  228. this.clearFilter();
  229. }
  230. // 从艺术家或专辑切换回全部时,清除筛选状态
  231. if (this.selectedTab === 0 && this.filterType !== NavFilterType.None) {
  232. // 不清除筛选,保持筛选状态
  233. } else if (this.selectedTab !== 0) {
  234. // 切换到艺术家或专辑标签页时,清除筛选和搜索状态
  235. this.clearFilter();
  236. this.isSearchMode = false;
  237. this.searchText = '';
  238. this.filteredList = [];
  239. this.isSearchLoading = false;
  240. this.searchTicket++;
  241. }
  242. }
  243. //切换不同的NavidromePage
  244. async onSwitchAccount() {
  245. await this.refreshNavidromeData(true);
  246. }
  247. initSetting(){
  248. this.isCustomizeBg = PreferencesUtil.getBooleanSync(SettingPage.IS_CUSTOMIZE_BG, false)
  249. this.customizeBgPath = PreferencesUtil.getStringSync(SettingPage.IS_CUSTOMIZE_BG_PATH, '')
  250. this.blurValue = PreferencesUtil.getNumberSync(SettingPage.CUSTOMIZE_BG_BLUR, 0)
  251. this.bgBrightness = PreferencesUtil.getNumberSync(SettingPage.BG_BRIGHTNESS, 0)
  252. this.isNoJumpToHome = PreferencesUtil.getBooleanSync('isNoJumpToHome', true)
  253. this.sortType = PreferencesUtil.getNumberSync('navidromeSortType', 0);
  254. this.isShowTitleBar = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_TITLTBAR, true)
  255. this.autoHideTitle = PreferencesUtil.getBooleanSync('autoHideTitle', true)
  256. }
  257. aboutToAppear() {
  258. this.initSetting()
  259. let eventSetting: emitter.InnerEvent = { eventId: 333 }
  260. // 监听广播事件(通用设置配置更新)
  261. emitter.on(eventSetting, (eventData: emitter.EventData) => {
  262. this.initSetting()
  263. });
  264. // 监听手势返回事件
  265. let eventBackSwipeBack: emitter.InnerEvent = { eventId: EventConstants.EVENT_SWIPE_BACK_NAVID }
  266. emitter.on(eventBackSwipeBack, (eventData: emitter.EventData) => {
  267. console.info('heanup', 'NavidromePage 收到 EVENT_SWIPE_BACK_NAVID 事件');
  268. // 如果在详情视图模式,退出详情视图
  269. if (this.isDetailView) {
  270. this.getUIContext().animateTo({ duration: 555 }, () => {
  271. this.isDetailView = false;
  272. this.clearFilter();
  273. })
  274. }
  275. });
  276. this.refreshNavidromeData();
  277. }
  278. private async refreshNavidromeData(showToastWhenMissing: boolean = false): Promise<void> {
  279. const account = this.resolveActiveAccount();
  280. if (!account) {
  281. this.resetData();
  282. if (showToastWhenMissing) {
  283. ToastUtil.showToast('请先选择媒体库账号');
  284. }
  285. return;
  286. }
  287. // 记录日志开关状态
  288. void ServerLogUtil.info('NavidromeLoad', `日志状态: ${ServerLogUtil.getLogUploadStatus()}`);
  289. // 记录账号信息和缓存路径
  290. await this.logAccountCacheInfo(account);
  291. await this.loadMediaLibrary(account);
  292. this.doSortType(this.sortType)
  293. }
  294. private resolveActiveAccount(): WebDavAccount | undefined {
  295. if (!this.selectedAccount) {
  296. return undefined;
  297. }
  298. if (!this.isNavidromeAccount(this.selectedAccount)
  299. && !this.isJellyfinAccount(this.selectedAccount)
  300. && !this.isEmbyAccount(this.selectedAccount)
  301. && !this.isAudioStationAccount(this.selectedAccount)
  302. && !this.isPlexAccount(this.selectedAccount)) {
  303. return undefined;
  304. }
  305. if (!this.selectedAccount.host || this.selectedAccount.host.length === 0) {
  306. return undefined;
  307. }
  308. return this.selectedAccount;
  309. }
  310. private resetData(): void {
  311. this.allVideos = [];
  312. this.artists = [];
  313. this.albums = [];
  314. this.playlists = [];
  315. this.jellyfinSongIdSeen.clear();
  316. this.embySongIdSeen.clear();
  317. this.jellyfinSongKeySeen.clear();
  318. this.embySongKeySeen.clear();
  319. this.clearFilter();
  320. this.coverUrlCache.clear();
  321. this.albumCoverLookup.clear();
  322. this.songNextStart = 0;
  323. this.artistNextStart = 0;
  324. this.albumNextStart = 0;
  325. this.playlistNextStart = 0;
  326. this.isSongPageLoading = false;
  327. this.isArtistPageLoading = false;
  328. this.isAlbumPageLoading = false;
  329. this.isPlaylistPageLoading = false;
  330. }
  331. private async loadMediaLibrary(account: WebDavAccount): Promise<void> {
  332. if (this.isNavidromeAccount(account)) {
  333. await this.loadNavidromeLibrary(account);
  334. return;
  335. }
  336. if (this.isJellyfinAccount(account)) {
  337. await this.loadJellyfinLibrary(account);
  338. return;
  339. }
  340. if (this.isEmbyAccount(account)) {
  341. await this.loadEmbyLibrary(account);
  342. return;
  343. }
  344. if (this.isAudioStationAccount(account)) {
  345. await this.loadAudioStationLibrary(account);
  346. return;
  347. }
  348. if (this.isPlexAccount(account)) {
  349. await this.loadPlexLibrary(account);
  350. }
  351. }
  352. private async loadNavidromeLibrary(account: WebDavAccount): Promise<void> {
  353. const ticket = ++this.loadTicket;
  354. this.loading = true;
  355. this.resetData();
  356. void ServerLogUtil.info('NavidromeLoad', '开始加载 Navidrome 数据库');
  357. void ServerLogUtil.info('NavidromeLoad', `服务器: ${ServerLogUtil.sanitizeAccount(account)}`);
  358. void ServerLogUtil.info('NavidromeLoad', `封面URL缓存已清空,当前缓存数量: ${this.coverUrlCache.size}`);
  359. try {
  360. await this.logAccountCacheInfo(account);
  361. // 尝试从缓存读取(前50条)
  362. const accountId = account.id?.toString() ?? 'default';
  363. const cachedData: AllCacheData = this.listCache.getAllCache(accountId);
  364. let loadedFromCache = false;
  365. if (cachedData.songs && cachedData.songs.length > 0) {
  366. this.allVideos = cachedData.songs;
  367. loadedFromCache = true;
  368. void ServerLogUtil.info('NavidromeLoad', `从缓存加载歌曲: ${cachedData.songs.length} 首`);
  369. }
  370. if (cachedData.artists && cachedData.artists.length > 0) {
  371. this.artists = cachedData.artists;
  372. void ServerLogUtil.info('NavidromeLoad', `从缓存加载艺术家: ${cachedData.artists.length} 位`);
  373. }
  374. if (cachedData.albums && cachedData.albums.length > 0) {
  375. this.albums = cachedData.albums;
  376. void ServerLogUtil.info('NavidromeLoad', `从缓存加载专辑: ${cachedData.albums.length} 张`);
  377. }
  378. if (cachedData.playlists && cachedData.playlists.length > 0) {
  379. this.playlists = cachedData.playlists;
  380. void ServerLogUtil.info('NavidromeLoad', `从缓存加载歌单: ${cachedData.playlists.length} 个`);
  381. }
  382. // 如果有缓存数据,先显示缓存,然后后台加载完整数据
  383. if (loadedFromCache || cachedData.artists || cachedData.albums || cachedData.playlists) {
  384. this.loading = false;
  385. void ServerLogUtil.info('NavidromeLoad', '缓存数据加载完成,开始后台加载完整数据');
  386. // 使用 taskpool 后台加载完整数据,避免 UI 卡顿
  387. // 提取 account 的序列化数据 (taskpool 不支持 Proxy 对象)
  388. const accountData: AccountData = {
  389. id: account.id ?? 0,
  390. webType: account.webType,
  391. host: account.host ?? '',
  392. port: account.port ?? 80,
  393. account: account.account ?? '',
  394. password: account.password ?? '',
  395. enableHttps: account.enableHttps ?? false,
  396. navidromeBasePath: account.navidromeBasePath ?? '/rest',
  397. jellyfinBasePath: account.jellyfinBasePath ?? '',
  398. embyBasePath: account.embyBasePath ?? '',
  399. name: account.name ?? ''
  400. };
  401. const task = new taskpool.Task(loadNavidromeDataTask, accountData, ticket);
  402. taskpool.execute(task, taskpool.Priority.MEDIUM).then((result: Object) => {
  403. if (ticket !== this.loadTicket) {
  404. return;
  405. }
  406. // 类型断言
  407. const taskResult = result as TaskResult;
  408. void ServerLogUtil.info('NavidromeLoad', `后台加载完成: 歌曲 ${taskResult.songs.length} / 艺术家 ${taskResult.artists.length} / 专辑 ${taskResult.albums.length} / 歌单 ${taskResult.playlists.length}`);
  409. // 直接更新数据(封面已在后台处理)
  410. if (taskResult.songs && taskResult.songs.length > 0) {
  411. this.allVideos = taskResult.songs;
  412. }
  413. if (taskResult.artists && taskResult.artists.length > 0) {
  414. this.artists = taskResult.artists;
  415. }
  416. if (taskResult.albums && taskResult.albums.length > 0) {
  417. this.albums = taskResult.albums;
  418. }
  419. if (taskResult.playlists && taskResult.playlists.length > 0) {
  420. this.playlists = taskResult.playlists;
  421. }
  422. // 保存新的缓存(前50条)
  423. this.listCache.saveSongsCache(accountId, this.allVideos);
  424. this.listCache.saveArtistsCache(accountId, this.artists);
  425. this.listCache.saveAlbumsCache(accountId, this.albums);
  426. this.listCache.savePlaylistsCache(accountId, this.playlists);
  427. void ServerLogUtil.info('NavidromeLoad', `后台加载完成并更新缓存: 歌曲 ${this.allVideos.length} / 艺术家 ${this.artists.length} / 专辑 ${this.albums.length} / 歌单 ${this.playlists.length}`);
  428. void this.logCacheStatistics(account);
  429. }).catch((error: Error) => {
  430. void ServerLogUtil.error('NavidromeLoad', `后台数据加载失败: ${error.message}`);
  431. });
  432. return;
  433. }
  434. // 没有缓存,正常加载
  435. await Promise.all([
  436. this.loadNextSongPage(account, ticket),
  437. this.loadNextArtistPage(account, ticket),
  438. this.loadNextAlbumPage(account, ticket),
  439. this.loadNextPlaylistPage(account, ticket)
  440. ]);
  441. if (ticket !== this.loadTicket) {
  442. return;
  443. }
  444. // 保存缓存(前50条)
  445. this.listCache.saveSongsCache(accountId, this.allVideos);
  446. this.listCache.saveArtistsCache(accountId, this.artists);
  447. this.listCache.saveAlbumsCache(accountId, this.albums);
  448. this.listCache.savePlaylistsCache(accountId, this.playlists);
  449. void ServerLogUtil.info('NavidromeLoad', `首次加载完成并已缓存: 歌曲 ${this.allVideos.length} / 艺术家 ${this.artists.length} / 专辑 ${this.albums.length} / 歌单 ${this.playlists.length}`);
  450. await this.logCacheStatistics(account);
  451. } catch (error) {
  452. if (ticket === this.loadTicket) {
  453. void ServerLogUtil.error('NavidromeLoad', `数据加载失败: ${(error as Error).message}`);
  454. void ServerLogUtil.error('NavidromeLoad', `失败时服务器信息: ${ServerLogUtil.sanitizeAccount(account)}`);
  455. ToastUtil.showToast((error as Error).message ?? 'Navidrome 数据加载失败');
  456. }
  457. } finally {
  458. if (ticket === this.loadTicket) {
  459. this.loading = false;
  460. void ServerLogUtil.info('NavidromeLoad', '加载流程结束');
  461. }
  462. }
  463. }
  464. private async loadJellyfinLibrary(account: WebDavAccount): Promise<void> {
  465. const ticket = ++this.loadTicket;
  466. this.loading = true;
  467. this.resetData();
  468. void ServerLogUtil.info('NavidromeLoad', '开始加载 Jellyfin 媒体库');
  469. void ServerLogUtil.info('NavidromeLoad', `服务器: ${ServerLogUtil.sanitizeAccount(account)}`);
  470. try {
  471. this.songNextStart = 0;
  472. this.artistNextStart = 0;
  473. this.albumNextStart = 0;
  474. this.playlistNextStart = null;
  475. await Promise.all([
  476. this.loadNextJellyfinSongPage(account, ticket),
  477. this.loadNextJellyfinArtistPage(account, ticket),
  478. this.loadNextJellyfinAlbumPage(account, ticket)
  479. ]);
  480. if (ticket === this.loadTicket) {
  481. void ServerLogUtil.info('NavidromeLoad', `Jellyfin 首屏完成: 歌曲 ${this.allVideos.length} / 艺术家 ${this.artists.length} / 专辑 ${this.albums.length}`);
  482. }
  483. } catch (error) {
  484. if (ticket === this.loadTicket) {
  485. void ServerLogUtil.error('NavidromeLoad', `Jellyfin 数据加载失败: ${(error as Error).message}`);
  486. ToastUtil.showToast((error as Error).message ?? 'Jellyfin 数据加载失败');
  487. }
  488. } finally {
  489. if (ticket === this.loadTicket) {
  490. this.loading = false;
  491. }
  492. }
  493. }
  494. private async loadEmbyLibrary(account: WebDavAccount): Promise<void> {
  495. const ticket = ++this.loadTicket;
  496. this.loading = true;
  497. this.resetData();
  498. void ServerLogUtil.info('NavidromeLoad', '开始加载 Emby 媒体库');
  499. void ServerLogUtil.info('NavidromeLoad', `服务器: ${ServerLogUtil.sanitizeAccount(account)}`);
  500. try {
  501. this.songNextStart = 0;
  502. this.artistNextStart = 0;
  503. this.albumNextStart = 0;
  504. this.playlistNextStart = null;
  505. await Promise.all([
  506. this.loadNextEmbySongPage(account, ticket),
  507. this.loadNextEmbyArtistPage(account, ticket),
  508. this.loadNextEmbyAlbumPage(account, ticket)
  509. ]);
  510. if (ticket === this.loadTicket) {
  511. void ServerLogUtil.info('NavidromeLoad', `Emby 首屏完成: 歌曲 ${this.allVideos.length} / 艺术家 ${this.artists.length} / 专辑 ${this.albums.length}`);
  512. }
  513. } catch (error) {
  514. if (ticket === this.loadTicket) {
  515. void ServerLogUtil.error('NavidromeLoad', `Emby 数据加载失败: ${(error as Error).message}`);
  516. ToastUtil.showToast((error as Error).message ?? 'Emby 数据加载失败');
  517. }
  518. } finally {
  519. if (ticket === this.loadTicket) {
  520. this.loading = false;
  521. }
  522. }
  523. }
  524. private async loadAudioStationLibrary(account: WebDavAccount): Promise<void> {
  525. const ticket = ++this.loadTicket;
  526. this.loading = true;
  527. this.resetData();
  528. void ServerLogUtil.info('NavidromeLoad', '开始加载 AudioStation 媒体库');
  529. void ServerLogUtil.info('NavidromeLoad', `服务器: ${ServerLogUtil.sanitizeAccount(account)}`);
  530. try {
  531. this.songNextStart = 0;
  532. this.artistNextStart = 0;
  533. this.albumNextStart = 0;
  534. this.playlistNextStart = 0;
  535. await Promise.all([
  536. this.loadNextAudioStationSongPage(account, ticket),
  537. this.loadNextAudioStationArtistPage(account, ticket),
  538. this.loadNextAudioStationAlbumPage(account, ticket),
  539. this.loadNextAudioStationPlaylistPage(account, ticket)
  540. ]);
  541. if (ticket === this.loadTicket) {
  542. void ServerLogUtil.info('NavidromeLoad', `AudioStation 首屏完成: 歌曲 ${this.allVideos.length} / 艺术家 ${this.artists.length} / 专辑 ${this.albums.length} / 歌单 ${this.playlists.length}`);
  543. }
  544. } catch (error) {
  545. if (ticket === this.loadTicket) {
  546. void ServerLogUtil.error('NavidromeLoad', `AudioStation 数据加载失败: ${(error as Error).message}`);
  547. ToastUtil.showToast((error as Error).message ?? 'AudioStation 数据加载失败');
  548. }
  549. } finally {
  550. if (ticket === this.loadTicket) {
  551. this.loading = false;
  552. }
  553. }
  554. }
  555. private async loadPlexLibrary(account: WebDavAccount): Promise<void> {
  556. const ticket = ++this.loadTicket;
  557. this.loading = true;
  558. this.resetData();
  559. void ServerLogUtil.info('NavidromeLoad', '开始加载 Plex 媒体库');
  560. void ServerLogUtil.info('NavidromeLoad', `服务器: ${ServerLogUtil.sanitizeAccount(account)}`);
  561. try {
  562. this.songNextStart = 0;
  563. this.artistNextStart = 0;
  564. this.albumNextStart = 0;
  565. this.playlistNextStart = 0;
  566. await Promise.all([
  567. this.loadNextPlexSongPage(account, ticket),
  568. this.loadNextPlexArtistPage(account, ticket),
  569. this.loadNextPlexAlbumPage(account, ticket),
  570. this.loadNextPlexPlaylistPage(account, ticket)
  571. ]);
  572. if (ticket === this.loadTicket) {
  573. void ServerLogUtil.info('NavidromeLoad', `Plex 首屏完成: 歌曲 ${this.allVideos.length} / 艺术家 ${this.artists.length} / 专辑 ${this.albums.length} / 歌单 ${this.playlists.length}`);
  574. }
  575. } catch (error) {
  576. if (ticket === this.loadTicket) {
  577. void ServerLogUtil.error('NavidromeLoad', `Plex 数据加载失败: ${(error as Error).message}`);
  578. ToastUtil.showToast((error as Error).message ?? 'Plex 数据加载失败');
  579. }
  580. } finally {
  581. if (ticket === this.loadTicket) {
  582. this.loading = false;
  583. }
  584. }
  585. }
  586. private async loadNextSongPage(account: WebDavAccount, ticket?: number): Promise<void> {
  587. if (this.songNextStart === null || this.isSongPageLoading) {
  588. return;
  589. }
  590. const currentTicket = ticket ?? this.loadTicket;
  591. this.isSongPageLoading = true;
  592. try {
  593. const response = await navidromeRestApi.fetchSongPage(account, this.songNextStart);
  594. if (currentTicket !== this.loadTicket) {
  595. return;
  596. }
  597. const chunk = response.data ?? [];
  598. if (chunk.length === 0) {
  599. this.songNextStart = null;
  600. return;
  601. }
  602. const videos = await this.convertSongsToVideoItems(chunk, account);
  603. if (currentTicket !== this.loadTicket) {
  604. return;
  605. }
  606. this.allVideos = [...this.allVideos, ...videos];
  607. // 打印前20条数据
  608. // const previewCount = Math.min(20, this.allVideos.length);
  609. // console.info(`onecold allVideos: ${this.allVideos.length}, 打印前${previewCount}条:`);
  610. // for (let i = 0; i < previewCount; i++) {
  611. // const all = this.allVideos[i];
  612. // console.info(`onecold allVideos[${i}]:`, JSON.stringify({
  613. // id: all.id,
  614. // name: all.name,
  615. // pixelMapPath: all.pixelMapPath
  616. // }));
  617. // }
  618. this.songNextStart = response.nextStart;
  619. void ServerLogUtil.info('NavidromeLoad', `歌曲列表追加: 本次 ${videos.length} 首, 总数 ${this.allVideos.length}`);
  620. } finally {
  621. this.isSongPageLoading = false;
  622. }
  623. }
  624. private async loadNextArtistPage(account: WebDavAccount, ticket?: number): Promise<void> {
  625. if (this.artistNextStart === null || this.isArtistPageLoading) {
  626. return;
  627. }
  628. const currentTicket = ticket ?? this.loadTicket;
  629. this.isArtistPageLoading = true;
  630. try {
  631. const response = await navidromeRestApi.fetchArtistPage(account, this.artistNextStart);
  632. if (currentTicket !== this.loadTicket) {
  633. return;
  634. }
  635. const chunk = response.data ?? [];
  636. if (chunk.length === 0) {
  637. this.artistNextStart = null;
  638. return;
  639. }
  640. const coverMap = await this.buildArtistCoverMap(chunk, account);
  641. if (currentTicket !== this.loadTicket) {
  642. return;
  643. }
  644. const processed = chunk.map(artist => {
  645. artist.coverUrl = coverMap.get(artist.id);
  646. return artist;
  647. });
  648. this.artists = [...this.artists, ...processed];
  649. // console.info('onecold 帮我打印这个artists的前20条数据');
  650. // 打印前20条艺术家数据
  651. // const previewCount = Math.min(20, this.artists.length);
  652. // console.info(`onecold artists总数: ${this.artists.length}, 打印前${previewCount}条:`);
  653. // for (let i = 0; i < previewCount; i++) {
  654. // const artist = this.artists[i];
  655. // console.info(`onecold artist[${i}]:`, JSON.stringify({
  656. // id: artist.id,
  657. // name: artist.name,
  658. // albumCount: artist.albumCount,
  659. // songCount: artist.songCount,
  660. // coverUrl: artist.coverUrl
  661. // }));
  662. // }
  663. this.artistNextStart = response.nextStart;
  664. void ServerLogUtil.info('ArtistCover', `艺术家列表追加: 本次 ${processed.length} 位, 总数 ${this.artists.length}`);
  665. } finally {
  666. this.isArtistPageLoading = false;
  667. }
  668. }
  669. private async loadNextAlbumPage(account: WebDavAccount, ticket?: number): Promise<void> {
  670. if (this.albumNextStart === null || this.isAlbumPageLoading) {
  671. return;
  672. }
  673. const currentTicket = ticket ?? this.loadTicket;
  674. this.isAlbumPageLoading = true;
  675. try {
  676. const response = await navidromeRestApi.fetchAlbumPage(account, this.albumNextStart);
  677. if (currentTicket !== this.loadTicket) {
  678. return;
  679. }
  680. const chunk = response.data ?? [];
  681. if (chunk.length === 0) {
  682. this.albumNextStart = null;
  683. return;
  684. }
  685. const coverMap = await this.buildAlbumCoverMap(chunk, account);
  686. if (currentTicket !== this.loadTicket) {
  687. return;
  688. }
  689. coverMap.forEach((value, key) => {
  690. if (value) {
  691. this.albumCoverLookup.set(key, value);
  692. }
  693. });
  694. const processed = chunk.map(album => {
  695. album.coverUrl = coverMap.get(album.id);
  696. return album;
  697. });
  698. this.albums = [...this.albums, ...processed];
  699. this.albumNextStart = response.nextStart;
  700. void ServerLogUtil.info('AlbumCover', `专辑列表追加: 本次 ${processed.length} 张, 总数 ${this.albums.length}`);
  701. } finally {
  702. this.isAlbumPageLoading = false;
  703. }
  704. }
  705. private async loadNextJellyfinSongPage(account: WebDavAccount, ticket?: number): Promise<void> {
  706. if (this.songNextStart === null || this.isSongPageLoading) {
  707. return;
  708. }
  709. const currentTicket = ticket ?? this.loadTicket;
  710. this.isSongPageLoading = true;
  711. try {
  712. const response = await jellyfinApi.getSongsPage(account, this.songNextStart, this.REMOTE_PAGE_SIZE);
  713. if (currentTicket !== this.loadTicket) {
  714. return;
  715. }
  716. const uniqueItems: JellyfinSong[] = [];
  717. for (let i = 0; i < response.items.length; i++) {
  718. const item = response.items[i];
  719. if (!item.id) {
  720. continue;
  721. }
  722. const key = this.buildSongDedupKey(item.title, item.artist, item.album, item.durationSeconds);
  723. if (this.jellyfinSongIdSeen.has(item.id) || this.jellyfinSongKeySeen.has(key)) {
  724. continue;
  725. }
  726. this.jellyfinSongIdSeen.add(item.id);
  727. this.jellyfinSongKeySeen.add(key);
  728. uniqueItems.push(item);
  729. }
  730. const restSongs = this.convertJellyfinSongsToRestSongs(uniqueItems);
  731. const videoItems = await this.convertSongsToVideoItems(restSongs, account);
  732. if (currentTicket !== this.loadTicket) {
  733. return;
  734. }
  735. this.allVideos = this.dedupRemoteSongsByKey([...this.allVideos, ...videoItems]);
  736. this.songNextStart = response.nextStart;
  737. void ServerLogUtil.info('NavidromeLoad', `Jellyfin 歌曲追加: 本次 ${videoItems.length} 首, 总数 ${this.allVideos.length}`);
  738. } finally {
  739. this.isSongPageLoading = false;
  740. }
  741. }
  742. private async loadNextJellyfinArtistPage(account: WebDavAccount, ticket?: number): Promise<void> {
  743. if (this.artistNextStart === null || this.isArtistPageLoading) {
  744. return;
  745. }
  746. const currentTicket = ticket ?? this.loadTicket;
  747. this.isArtistPageLoading = true;
  748. try {
  749. const response = await jellyfinApi.getArtistsPage(account, this.artistNextStart, this.REMOTE_PAGE_SIZE);
  750. if (currentTicket !== this.loadTicket) {
  751. return;
  752. }
  753. const processed = await this.convertJellyfinArtistsToRest(response.items, account);
  754. if (currentTicket !== this.loadTicket) {
  755. return;
  756. }
  757. this.artists = [...this.artists, ...processed];
  758. this.artistNextStart = response.nextStart;
  759. void ServerLogUtil.info('NavidromeLoad', `Jellyfin 艺术家追加: 本次 ${processed.length} 位, 总数 ${this.artists.length}`);
  760. } finally {
  761. this.isArtistPageLoading = false;
  762. }
  763. }
  764. private async loadNextJellyfinAlbumPage(account: WebDavAccount, ticket?: number): Promise<void> {
  765. if (this.albumNextStart === null || this.isAlbumPageLoading) {
  766. return;
  767. }
  768. const currentTicket = ticket ?? this.loadTicket;
  769. this.isAlbumPageLoading = true;
  770. try {
  771. const response = await jellyfinApi.getAlbumsPage(account, this.albumNextStart, this.REMOTE_PAGE_SIZE);
  772. if (currentTicket !== this.loadTicket) {
  773. return;
  774. }
  775. const processed = await this.convertJellyfinAlbumsToRest(response.items, account);
  776. if (currentTicket !== this.loadTicket) {
  777. return;
  778. }
  779. this.albums = [...this.albums, ...processed];
  780. this.albumNextStart = response.nextStart;
  781. void ServerLogUtil.info('NavidromeLoad', `Jellyfin 专辑追加: 本次 ${processed.length} 张, 总数 ${this.albums.length}`);
  782. } finally {
  783. this.isAlbumPageLoading = false;
  784. }
  785. }
  786. private async loadNextEmbySongPage(account: WebDavAccount, ticket?: number): Promise<void> {
  787. if (this.songNextStart === null || this.isSongPageLoading) {
  788. return;
  789. }
  790. const currentTicket = ticket ?? this.loadTicket;
  791. this.isSongPageLoading = true;
  792. try {
  793. const response = await embyApi.getSongsPage(account, this.songNextStart, this.REMOTE_PAGE_SIZE);
  794. if (currentTicket !== this.loadTicket) {
  795. return;
  796. }
  797. const uniqueItems: EmbySong[] = [];
  798. for (let i = 0; i < response.items.length; i++) {
  799. const item = response.items[i];
  800. if (!item.id) {
  801. continue;
  802. }
  803. const key = this.buildSongDedupKey(item.title, item.artist, item.album, item.durationSeconds);
  804. if (this.embySongIdSeen.has(item.id) || this.embySongKeySeen.has(key)) {
  805. continue;
  806. }
  807. this.embySongIdSeen.add(item.id);
  808. this.embySongKeySeen.add(key);
  809. uniqueItems.push(item);
  810. }
  811. const restSongs = this.convertEmbySongsToRestSongs(uniqueItems);
  812. const videoItems = await this.convertSongsToVideoItems(restSongs, account);
  813. if (currentTicket !== this.loadTicket) {
  814. return;
  815. }
  816. this.allVideos = this.dedupRemoteSongsByKey([...this.allVideos, ...videoItems]);
  817. this.songNextStart = response.nextStart;
  818. void ServerLogUtil.info('NavidromeLoad', `Emby 歌曲追加: 本次 ${videoItems.length} 首, 总数 ${this.allVideos.length}`);
  819. } finally {
  820. this.isSongPageLoading = false;
  821. }
  822. }
  823. private async loadNextEmbyArtistPage(account: WebDavAccount, ticket?: number): Promise<void> {
  824. if (this.artistNextStart === null || this.isArtistPageLoading) {
  825. return;
  826. }
  827. const currentTicket = ticket ?? this.loadTicket;
  828. this.isArtistPageLoading = true;
  829. try {
  830. const response = await embyApi.getArtistsPage(account, this.artistNextStart, this.REMOTE_PAGE_SIZE);
  831. if (currentTicket !== this.loadTicket) {
  832. return;
  833. }
  834. const processed = await this.convertEmbyArtistsToRest(response.items, account);
  835. if (currentTicket !== this.loadTicket) {
  836. return;
  837. }
  838. this.artists = [...this.artists, ...processed];
  839. this.artistNextStart = response.nextStart;
  840. void ServerLogUtil.info('NavidromeLoad', `Emby 艺术家追加: 本次 ${processed.length} 位, 总数 ${this.artists.length}`);
  841. } finally {
  842. this.isArtistPageLoading = false;
  843. }
  844. }
  845. private async loadNextEmbyAlbumPage(account: WebDavAccount, ticket?: number): Promise<void> {
  846. if (this.albumNextStart === null || this.isAlbumPageLoading) {
  847. return;
  848. }
  849. const currentTicket = ticket ?? this.loadTicket;
  850. this.isAlbumPageLoading = true;
  851. try {
  852. const response = await embyApi.getAlbumsPage(account, this.albumNextStart, this.REMOTE_PAGE_SIZE);
  853. if (currentTicket !== this.loadTicket) {
  854. return;
  855. }
  856. const processed = await this.convertEmbyAlbumsToRest(response.items, account);
  857. if (currentTicket !== this.loadTicket) {
  858. return;
  859. }
  860. this.albums = [...this.albums, ...processed];
  861. this.albumNextStart = response.nextStart;
  862. void ServerLogUtil.info('NavidromeLoad', `Emby 专辑追加: 本次 ${processed.length} 张, 总数 ${this.albums.length}`);
  863. } finally {
  864. this.isAlbumPageLoading = false;
  865. }
  866. }
  867. private async loadNextAudioStationSongPage(account: WebDavAccount, ticket?: number): Promise<void> {
  868. if (this.songNextStart === null || this.isSongPageLoading) {
  869. return;
  870. }
  871. const currentTicket = ticket ?? this.loadTicket;
  872. this.isSongPageLoading = true;
  873. try {
  874. const response = await audioStationApi.getSongsPage(account, this.songNextStart, this.REMOTE_PAGE_SIZE);
  875. if (currentTicket !== this.loadTicket) {
  876. return;
  877. }
  878. const restSongs = this.convertAudioStationSongsToRestSongs(response.items);
  879. const videoItems = await this.convertSongsToVideoItems(restSongs, account);
  880. if (currentTicket !== this.loadTicket) {
  881. return;
  882. }
  883. this.allVideos = this.dedupRemoteSongsByKey([...this.allVideos, ...videoItems]);
  884. this.songNextStart = response.nextStart;
  885. void ServerLogUtil.info('NavidromeLoad', `AudioStation 歌曲追加: 本次 ${videoItems.length} 首, 总数 ${this.allVideos.length}`);
  886. } finally {
  887. this.isSongPageLoading = false;
  888. }
  889. }
  890. private async loadNextAudioStationArtistPage(account: WebDavAccount, ticket?: number): Promise<void> {
  891. if (this.artistNextStart === null || this.isArtistPageLoading) {
  892. return;
  893. }
  894. const currentTicket = ticket ?? this.loadTicket;
  895. this.isArtistPageLoading = true;
  896. try {
  897. const response = await audioStationApi.getArtistsPage(account, this.artistNextStart, this.REMOTE_PAGE_SIZE);
  898. if (currentTicket !== this.loadTicket) {
  899. return;
  900. }
  901. const processed = this.convertAudioStationArtistsToRest(response.items);
  902. if (currentTicket !== this.loadTicket) {
  903. return;
  904. }
  905. this.artists = [...this.artists, ...processed];
  906. this.artistNextStart = response.nextStart;
  907. void ServerLogUtil.info('NavidromeLoad', `AudioStation 艺术家追加: 本次 ${processed.length} 位, 总数 ${this.artists.length}`);
  908. } finally {
  909. this.isArtistPageLoading = false;
  910. }
  911. }
  912. private async loadNextAudioStationAlbumPage(account: WebDavAccount, ticket?: number): Promise<void> {
  913. if (this.albumNextStart === null || this.isAlbumPageLoading) {
  914. return;
  915. }
  916. const currentTicket = ticket ?? this.loadTicket;
  917. this.isAlbumPageLoading = true;
  918. try {
  919. const response = await audioStationApi.getAlbumsPage(account, undefined, this.albumNextStart, this.REMOTE_PAGE_SIZE);
  920. if (currentTicket !== this.loadTicket) {
  921. return;
  922. }
  923. const processed = await this.convertAudioStationAlbumsToRest(response.items, account);
  924. if (currentTicket !== this.loadTicket) {
  925. return;
  926. }
  927. this.albums = [...this.albums, ...processed];
  928. this.albumNextStart = response.nextStart;
  929. void ServerLogUtil.info('NavidromeLoad', `AudioStation 专辑追加: 本次 ${processed.length} 张, 总数 ${this.albums.length}`);
  930. } finally {
  931. this.isAlbumPageLoading = false;
  932. }
  933. }
  934. private async loadNextAudioStationPlaylistPage(account: WebDavAccount, ticket?: number): Promise<void> {
  935. if (this.playlistNextStart === null || this.isPlaylistPageLoading) {
  936. return;
  937. }
  938. const currentTicket = ticket ?? this.loadTicket;
  939. this.isPlaylistPageLoading = true;
  940. try {
  941. const response = await audioStationApi.getPlaylistsPage(account, this.playlistNextStart, this.REMOTE_PAGE_SIZE);
  942. if (currentTicket !== this.loadTicket) {
  943. return;
  944. }
  945. const processed = this.convertAudioStationPlaylistsToRest(response.items);
  946. if (currentTicket !== this.loadTicket) {
  947. return;
  948. }
  949. this.playlists = [...this.playlists, ...processed];
  950. this.playlistNextStart = response.nextStart;
  951. void ServerLogUtil.info('NavidromeLoad', `AudioStation 歌单追加: 本次 ${processed.length} 个, 总数 ${this.playlists.length}`);
  952. } finally {
  953. this.isPlaylistPageLoading = false;
  954. }
  955. }
  956. private async loadNextPlexSongPage(account: WebDavAccount, ticket?: number): Promise<void> {
  957. if (this.songNextStart === null || this.isSongPageLoading) {
  958. return;
  959. }
  960. const currentTicket = ticket ?? this.loadTicket;
  961. this.isSongPageLoading = true;
  962. try {
  963. const response = await plexApi.getSongsPage(account, this.songNextStart, this.REMOTE_PAGE_SIZE);
  964. if (currentTicket !== this.loadTicket) {
  965. return;
  966. }
  967. const restSongs = this.convertPlexSongsToRestSongs(response.items);
  968. const videoItems = await this.convertSongsToVideoItems(restSongs, account);
  969. if (currentTicket !== this.loadTicket) {
  970. return;
  971. }
  972. this.allVideos = this.dedupRemoteSongsByKey([...this.allVideos, ...videoItems]);
  973. this.songNextStart = response.nextStart;
  974. void ServerLogUtil.info('NavidromeLoad', `Plex 歌曲追加: 本次 ${videoItems.length} 首, 总数 ${this.allVideos.length}`);
  975. } finally {
  976. this.isSongPageLoading = false;
  977. }
  978. }
  979. private async loadNextPlexArtistPage(account: WebDavAccount, ticket?: number): Promise<void> {
  980. if (this.artistNextStart === null || this.isArtistPageLoading) {
  981. return;
  982. }
  983. const currentTicket = ticket ?? this.loadTicket;
  984. this.isArtistPageLoading = true;
  985. try {
  986. const response = await plexApi.getArtistsPage(account, this.artistNextStart, this.REMOTE_PAGE_SIZE);
  987. if (currentTicket !== this.loadTicket) {
  988. return;
  989. }
  990. const processed = await this.convertPlexArtistsToRest(response.items, account);
  991. if (currentTicket !== this.loadTicket) {
  992. return;
  993. }
  994. this.artists = [...this.artists, ...processed];
  995. this.artistNextStart = response.nextStart;
  996. void ServerLogUtil.info('NavidromeLoad', `Plex 艺术家追加: 本次 ${processed.length} 位, 总数 ${this.artists.length}`);
  997. } finally {
  998. this.isArtistPageLoading = false;
  999. }
  1000. }
  1001. private async loadNextPlexAlbumPage(account: WebDavAccount, ticket?: number): Promise<void> {
  1002. if (this.albumNextStart === null || this.isAlbumPageLoading) {
  1003. return;
  1004. }
  1005. const currentTicket = ticket ?? this.loadTicket;
  1006. this.isAlbumPageLoading = true;
  1007. try {
  1008. const response = await plexApi.getAlbumsPage(account, this.albumNextStart, this.REMOTE_PAGE_SIZE);
  1009. if (currentTicket !== this.loadTicket) {
  1010. return;
  1011. }
  1012. const processed = await this.convertPlexAlbumsToRest(response.items, account);
  1013. if (currentTicket !== this.loadTicket) {
  1014. return;
  1015. }
  1016. this.albums = [...this.albums, ...processed];
  1017. this.albumNextStart = response.nextStart;
  1018. void ServerLogUtil.info('NavidromeLoad', `Plex 专辑追加: 本次 ${processed.length} 张, 总数 ${this.albums.length}`);
  1019. } finally {
  1020. this.isAlbumPageLoading = false;
  1021. }
  1022. }
  1023. private async loadNextPlexPlaylistPage(account: WebDavAccount, ticket?: number): Promise<void> {
  1024. if (this.playlistNextStart === null || this.isPlaylistPageLoading) {
  1025. return;
  1026. }
  1027. const currentTicket = ticket ?? this.loadTicket;
  1028. this.isPlaylistPageLoading = true;
  1029. try {
  1030. const response = await plexApi.getPlaylistsPage(account, this.playlistNextStart, this.REMOTE_PAGE_SIZE);
  1031. if (currentTicket !== this.loadTicket) {
  1032. return;
  1033. }
  1034. const processed = this.convertPlexPlaylistsToRest(response.items);
  1035. if (currentTicket !== this.loadTicket) {
  1036. return;
  1037. }
  1038. this.playlists = [...this.playlists, ...processed];
  1039. this.playlistNextStart = response.nextStart;
  1040. void ServerLogUtil.info('NavidromeLoad', `Plex 歌单追加: 本次 ${processed.length} 个, 总数 ${this.playlists.length}`);
  1041. } finally {
  1042. this.isPlaylistPageLoading = false;
  1043. }
  1044. }
  1045. private async loadNextPlaylistPage(account: WebDavAccount, ticket?: number): Promise<void> {
  1046. if (this.playlistNextStart === null || this.isPlaylistPageLoading) {
  1047. return;
  1048. }
  1049. const currentTicket = ticket ?? this.loadTicket;
  1050. this.isPlaylistPageLoading = true;
  1051. try {
  1052. const response = await navidromeRestApi.fetchPlaylistPage(account, this.playlistNextStart);
  1053. if (currentTicket !== this.loadTicket) {
  1054. return;
  1055. }
  1056. const chunk = response.data ?? [];
  1057. if (chunk.length === 0) {
  1058. this.playlistNextStart = null;
  1059. return;
  1060. }
  1061. this.playlists = [...this.playlists, ...chunk];
  1062. this.playlistNextStart = response.nextStart;
  1063. void ServerLogUtil.info('NavidromeLoad', `歌单列表追加: 本次 ${chunk.length} 个, 总数 ${this.playlists.length}`);
  1064. } finally {
  1065. this.isPlaylistPageLoading = false;
  1066. }
  1067. }
  1068. private async handleReachEnd(): Promise<void> {
  1069. if (this.loading) {
  1070. return;
  1071. }
  1072. if (this.selectedTab === 0 && this.filterType !== NavFilterType.None) {
  1073. return;
  1074. }
  1075. const account = this.selectedAccount;
  1076. if (!account) {
  1077. return;
  1078. }
  1079. if (this.isNavidromeAccount(account)) {
  1080. switch (this.selectedTab) {
  1081. case 0:
  1082. await this.loadNextSongPage(account);
  1083. break;
  1084. case 1:
  1085. await this.loadNextArtistPage(account);
  1086. break;
  1087. case 2:
  1088. await this.loadNextAlbumPage(account);
  1089. break;
  1090. case 3:
  1091. await this.loadNextPlaylistPage(account);
  1092. break;
  1093. default:
  1094. break;
  1095. }
  1096. return;
  1097. }
  1098. if (this.isJellyfinAccount(account)) {
  1099. switch (this.selectedTab) {
  1100. case 0:
  1101. await this.loadNextJellyfinSongPage(account);
  1102. break;
  1103. case 1:
  1104. await this.loadNextJellyfinArtistPage(account);
  1105. break;
  1106. case 2:
  1107. await this.loadNextJellyfinAlbumPage(account);
  1108. break;
  1109. default:
  1110. break;
  1111. }
  1112. return;
  1113. }
  1114. if (this.isEmbyAccount(account)) {
  1115. switch (this.selectedTab) {
  1116. case 0:
  1117. await this.loadNextEmbySongPage(account);
  1118. break;
  1119. case 1:
  1120. await this.loadNextEmbyArtistPage(account);
  1121. break;
  1122. case 2:
  1123. await this.loadNextEmbyAlbumPage(account);
  1124. break;
  1125. default:
  1126. break;
  1127. }
  1128. return;
  1129. }
  1130. if (this.isAudioStationAccount(account)) {
  1131. switch (this.selectedTab) {
  1132. case 0:
  1133. await this.loadNextAudioStationSongPage(account);
  1134. break;
  1135. case 1:
  1136. await this.loadNextAudioStationArtistPage(account);
  1137. break;
  1138. case 2:
  1139. await this.loadNextAudioStationAlbumPage(account);
  1140. break;
  1141. case 3:
  1142. await this.loadNextAudioStationPlaylistPage(account);
  1143. break;
  1144. default:
  1145. break;
  1146. }
  1147. return;
  1148. }
  1149. if (this.isPlexAccount(account)) {
  1150. switch (this.selectedTab) {
  1151. case 0:
  1152. await this.loadNextPlexSongPage(account);
  1153. break;
  1154. case 1:
  1155. await this.loadNextPlexArtistPage(account);
  1156. break;
  1157. case 2:
  1158. await this.loadNextPlexAlbumPage(account);
  1159. break;
  1160. case 3:
  1161. await this.loadNextPlexPlaylistPage(account);
  1162. break;
  1163. default:
  1164. break;
  1165. }
  1166. }
  1167. }
  1168. private async buildAlbumCoverMap(albums: NavidromeRestAlbum[], account: WebDavAccount): Promise<Map<string, string>> {
  1169. const map = new Map<string, string>();
  1170. const tasks: Promise<void>[] = [];
  1171. let directCoverCount = 0;
  1172. let generatedCoverCount = 0;
  1173. let failedCoverCount = 0;
  1174. void ServerLogUtil.info('NavidromePageCover', `📀 开始处理 ${albums.length} 张专辑的封面 - 账号: ${ServerLogUtil.sanitizeAccount(account)}`);
  1175. for (let i = 0; i < albums.length; i++) {
  1176. const album = albums[i];
  1177. void ServerLogUtil.debug('NavidromePageCover', `处理专辑 [${i + 1}/${albums.length}] - id: ${album.id}, name: ${album.name}`);
  1178. tasks.push((async () => {
  1179. try {
  1180. // 注意: embedArtPath 和 coverArtPath 可能指向音频文件而非封面图片
  1181. // 所以这里不能直接使用,需要通过 buildCoverUrl 生成正确的封面URL
  1182. // const directUrl = this.resolveEmbedCover(account, album.embedArtPath ?? album.coverArtPath);
  1183. // if (directUrl) {
  1184. // map.set(album.id, directUrl);
  1185. // directCoverCount++;
  1186. // void ServerLogUtil.info('NavidromePageCover', `✅ 专辑使用直接封面 - name: ${album.name}, url: ${directUrl}`);
  1187. // return;
  1188. // }
  1189. // 生成封面URL
  1190. const coverId = album.coverArt ?? album.coverArtId ?? (album.id ? `al-${album.id}` : undefined);
  1191. void ServerLogUtil.debug('NavidromePageCover', `专辑封面ID - name: ${album.name}, coverArt: ${album.coverArt}, coverArtId: ${album.coverArtId}, 最终coverId: ${coverId}`);
  1192. const url = await this.buildCoverUrl(account, coverId);
  1193. if (url) {
  1194. map.set(album.id, url);
  1195. generatedCoverCount++;
  1196. void ServerLogUtil.info('NavidromePageCover', `✅ 专辑生成封面成功 - name: ${album.name}, coverId: ${coverId}, url: ${url}`);
  1197. } else {
  1198. failedCoverCount++;
  1199. void ServerLogUtil.error('NavidromePageCover', `❌ 专辑封面失败 - name: ${album.name}, coverId: ${coverId}, 原始数据: ${JSON.stringify({coverArt: album.coverArt, coverArtId: album.coverArtId, id: album.id})}`);
  1200. }
  1201. } catch (error) {
  1202. failedCoverCount++;
  1203. void ServerLogUtil.error('NavidromePageCover', `❌ 专辑封面解析异常 - name: ${album.name}, error: ${(error as Error).message}`);
  1204. }
  1205. })());
  1206. }
  1207. await Promise.all(tasks);
  1208. void ServerLogUtil.info('NavidromePageCover', `📊 专辑封面处理完成 - 总数: ${albums.length}, 直接嵌入: ${directCoverCount}, 生成URL: ${generatedCoverCount}, 失败: ${failedCoverCount}`);
  1209. return map;
  1210. }
  1211. private async buildArtistCoverMap(artists: NavidromeRestArtist[], account: WebDavAccount): Promise<Map<string, string>> {
  1212. const map = new Map<string, string>();
  1213. const tasks: Promise<void>[] = [];
  1214. let directCoverCount = 0;
  1215. let generatedCoverCount = 0;
  1216. let failedCoverCount = 0;
  1217. void ServerLogUtil.info('NavidromePageCover', `🎤 开始处理 ${artists.length} 位艺术家的封面 - 账号: ${ServerLogUtil.sanitizeAccount(account)}`);
  1218. for (let i = 0; i < artists.length; i++) {
  1219. const artist = artists[i];
  1220. void ServerLogUtil.debug('NavidromePageCover', `处理艺术家 [${i + 1}/${artists.length}] - id: ${artist.id}, name: ${artist.name}`);
  1221. tasks.push((async () => {
  1222. try {
  1223. // 尝试获取已有图片URL
  1224. const directUrl = artist.mediumImageUrl ?? artist.largeImageUrl ?? this.resolveEmbedCover(account, artist.coverArtPath);
  1225. if (directUrl) {
  1226. map.set(artist.id, directUrl);
  1227. directCoverCount++;
  1228. void ServerLogUtil.info('NavidromePageCover', `✅ 艺术家使用已有图片 - name: ${artist.name}, url: ${directUrl}`);
  1229. return;
  1230. }
  1231. // 生成封面URL
  1232. const coverId = artist.coverArt ?? artist.coverArtId ?? (artist.id ? `ar-${artist.id}` : undefined);
  1233. void ServerLogUtil.debug('NavidromePageCover', `艺术家封面ID - name: ${artist.name}, coverArt: ${artist.coverArt}, coverArtId: ${artist.coverArtId}, 最终coverId: ${coverId}`);
  1234. const url = await this.buildCoverUrl(account, coverId, 256);
  1235. if (url) {
  1236. map.set(artist.id, url);
  1237. generatedCoverCount++;
  1238. void ServerLogUtil.info('NavidromePageCover', `✅ 艺术家生成封面成功 - name: ${artist.name}, coverId: ${coverId}, url: ${url}`);
  1239. } else {
  1240. failedCoverCount++;
  1241. void ServerLogUtil.error('NavidromePageCover', `❌ 艺术家封面失败 - name: ${artist.name}, coverId: ${coverId}, 原始数据: ${JSON.stringify({coverArt: artist.coverArt, coverArtId: artist.coverArtId, id: artist.id})}`);
  1242. }
  1243. } catch (error) {
  1244. failedCoverCount++;
  1245. void ServerLogUtil.error('NavidromePageCover', `❌ 艺术家封面解析异常 - name: ${artist.name}, error: ${(error as Error).message}`);
  1246. }
  1247. })());
  1248. }
  1249. await Promise.all(tasks);
  1250. void ServerLogUtil.info('NavidromePageCover', `📊 艺术家封面处理完成 - 总数: ${artists.length}, 直接链接: ${directCoverCount}, 生成URL: ${generatedCoverCount}, 失败: ${failedCoverCount}`);
  1251. return map;
  1252. }
  1253. private async buildRemoteCoverMap(ids: string[], account: WebDavAccount): Promise<Map<string, string>> {
  1254. const map = new Map<string, string>();
  1255. const tasks = ids.map(async (id) => {
  1256. if (!id) {
  1257. return;
  1258. }
  1259. try {
  1260. const url = await this.buildCoverUrl(account, id, 300);
  1261. if (url) {
  1262. map.set(id, url);
  1263. }
  1264. } catch (error) {
  1265. void ServerLogUtil.warn('CoverCache', `远程封面生成失败: ${id} ${(error as Error).message}`);
  1266. }
  1267. });
  1268. await Promise.all(tasks);
  1269. return map;
  1270. }
  1271. private buildAudioStationAlbumKey(name?: string, artist?: string): string {
  1272. const safeName = name ?? '';
  1273. const safeArtist = artist ?? '';
  1274. return `as:${safeName}|||${safeArtist}`;
  1275. }
  1276. private parseAudioStationAlbumKey(value: string): AudioStationAlbumKey {
  1277. let raw = value ?? '';
  1278. if (raw.startsWith('as:')) {
  1279. raw = raw.slice(3);
  1280. }
  1281. const parts = raw.split('|||');
  1282. const name = parts.length > 0 ? parts[0] : '';
  1283. const artist = parts.length > 1 ? parts.slice(1).join('|||') : '';
  1284. return new AudioStationAlbumKey(name, artist);
  1285. }
  1286. private async convertJellyfinArtistsToRest(artists: JellyfinArtist[], account: WebDavAccount): Promise<NavidromeRestArtist[]> {
  1287. const results: NavidromeRestArtist[] = [];
  1288. for (let i = 0; i < artists.length; i++) {
  1289. const artist = artists[i];
  1290. const coverUrl = await this.buildCoverUrl(account, artist.id, 300);
  1291. const restArtist: NavidromeRestArtist = {
  1292. id: artist.id,
  1293. name: artist.name,
  1294. albumCount: artist.albumCount,
  1295. songCount: artist.songCount,
  1296. coverUrl: coverUrl
  1297. };
  1298. results.push(restArtist);
  1299. }
  1300. return results;
  1301. }
  1302. private async convertEmbyArtistsToRest(artists: EmbyArtist[], account: WebDavAccount): Promise<NavidromeRestArtist[]> {
  1303. const results: NavidromeRestArtist[] = [];
  1304. for (let i = 0; i < artists.length; i++) {
  1305. const artist = artists[i];
  1306. const coverUrl = await this.buildCoverUrl(account, artist.id, 300);
  1307. const restArtist: NavidromeRestArtist = {
  1308. id: artist.id,
  1309. name: artist.name,
  1310. albumCount: artist.albumCount,
  1311. songCount: artist.songCount,
  1312. coverUrl: coverUrl
  1313. };
  1314. results.push(restArtist);
  1315. }
  1316. return results;
  1317. }
  1318. private async convertJellyfinAlbumsToRest(albums: JellyfinAlbum[], account: WebDavAccount): Promise<NavidromeRestAlbum[]> {
  1319. const results: NavidromeRestAlbum[] = [];
  1320. for (let i = 0; i < albums.length; i++) {
  1321. const album = albums[i];
  1322. const coverUrl = await this.buildCoverUrl(account, album.id, 300);
  1323. const restAlbum: NavidromeRestAlbum = {
  1324. id: album.id,
  1325. name: album.name,
  1326. artist: album.artist,
  1327. minYear: album.year,
  1328. coverUrl: coverUrl
  1329. };
  1330. results.push(restAlbum);
  1331. }
  1332. return results;
  1333. }
  1334. private async convertEmbyAlbumsToRest(albums: EmbyAlbum[], account: WebDavAccount): Promise<NavidromeRestAlbum[]> {
  1335. const results: NavidromeRestAlbum[] = [];
  1336. for (let i = 0; i < albums.length; i++) {
  1337. const album = albums[i];
  1338. const coverUrl = await this.buildCoverUrl(account, album.id, 300);
  1339. const restAlbum: NavidromeRestAlbum = {
  1340. id: album.id,
  1341. name: album.name,
  1342. artist: album.artist,
  1343. minYear: album.year,
  1344. coverUrl: coverUrl
  1345. };
  1346. results.push(restAlbum);
  1347. }
  1348. return results;
  1349. }
  1350. private convertAudioStationArtistsToRest(artists: AudioStationArtist[]): NavidromeRestArtist[] {
  1351. return artists.map(artist => {
  1352. const name = artist.name ?? '';
  1353. return {
  1354. id: name,
  1355. name: name
  1356. } as NavidromeRestArtist;
  1357. });
  1358. }
  1359. private async convertAudioStationAlbumsToRest(albums: AudioStationAlbum[], account: WebDavAccount): Promise<NavidromeRestAlbum[]> {
  1360. const results: NavidromeRestAlbum[] = [];
  1361. for (let i = 0; i < albums.length; i++) {
  1362. const album = albums[i];
  1363. const artistName = album.albumArtist ?? album.displayArtist ?? '';
  1364. const albumKey = this.buildAudioStationAlbumKey(album.name, artistName);
  1365. const coverUrl = await this.buildCoverUrl(account, albumKey, 300);
  1366. const restAlbum: NavidromeRestAlbum = {
  1367. id: albumKey,
  1368. name: album.name,
  1369. artist: artistName,
  1370. minYear: album.year,
  1371. coverArtId: albumKey,
  1372. coverUrl: coverUrl
  1373. };
  1374. results.push(restAlbum);
  1375. }
  1376. return results;
  1377. }
  1378. private async convertPlexArtistsToRest(artists: PlexArtist[], account: WebDavAccount): Promise<NavidromeRestArtist[]> {
  1379. const results: NavidromeRestArtist[] = [];
  1380. for (let i = 0; i < artists.length; i++) {
  1381. const artist = artists[i];
  1382. const coverId = artist.thumb ?? (artist.id ? `ar-${artist.id}` : '');
  1383. const coverUrl = coverId ? await this.buildCoverUrl(account, coverId, 300) : undefined;
  1384. const restArtist: NavidromeRestArtist = {
  1385. id: artist.id,
  1386. name: artist.name,
  1387. coverArtId: coverId,
  1388. coverUrl: coverUrl
  1389. };
  1390. results.push(restArtist);
  1391. }
  1392. return results;
  1393. }
  1394. private async convertPlexAlbumsToRest(albums: PlexAlbum[], account: WebDavAccount): Promise<NavidromeRestAlbum[]> {
  1395. const results: NavidromeRestAlbum[] = [];
  1396. for (let i = 0; i < albums.length; i++) {
  1397. const album = albums[i];
  1398. const coverId = album.thumb ?? (album.id ? `al-${album.id}` : '');
  1399. const coverUrl = coverId ? await this.buildCoverUrl(account, coverId, 300) : undefined;
  1400. const restAlbum: NavidromeRestAlbum = {
  1401. id: album.id,
  1402. name: album.name,
  1403. artist: album.artist,
  1404. minYear: album.year,
  1405. coverArtId: coverId,
  1406. coverUrl: coverUrl
  1407. };
  1408. results.push(restAlbum);
  1409. }
  1410. return results;
  1411. }
  1412. private convertJellyfinSongsToRestSongs(songs: JellyfinSong[]): NavidromeRestSong[] {
  1413. return songs.map(song => {
  1414. const restSong: NavidromeRestSong = {
  1415. id: song.id,
  1416. title: song.title,
  1417. album: song.album,
  1418. albumId: song.albumId,
  1419. artist: song.artist,
  1420. artistId: song.artistId,
  1421. duration: song.durationSeconds,
  1422. bitRate: song.bitRate,
  1423. suffix: song.suffix,
  1424. size: song.size,
  1425. track: song.track,
  1426. year: song.year,
  1427. coverArt: song.albumId ?? song.id
  1428. };
  1429. return restSong;
  1430. });
  1431. }
  1432. private convertEmbySongsToRestSongs(songs: EmbySong[]): NavidromeRestSong[] {
  1433. return songs.map(song => {
  1434. const restSong: NavidromeRestSong = {
  1435. id: song.id,
  1436. title: song.title,
  1437. album: song.album,
  1438. albumId: song.albumId,
  1439. artist: song.artist,
  1440. artistId: song.artistId,
  1441. duration: song.durationSeconds,
  1442. bitRate: song.bitRate,
  1443. suffix: song.suffix,
  1444. size: song.size,
  1445. track: song.track,
  1446. year: song.year,
  1447. coverArt: song.albumId ?? song.id
  1448. };
  1449. return restSong;
  1450. });
  1451. }
  1452. private convertAudioStationSongsToRestSongs(songs: AudioStationSong[]): NavidromeRestSong[] {
  1453. return songs.map(song => {
  1454. const artistName = song.artist ?? song.albumArtist ?? '';
  1455. const albumKey = this.buildAudioStationAlbumKey(song.album, song.albumArtist ?? song.artist);
  1456. const restSong: NavidromeRestSong = {
  1457. id: song.id,
  1458. title: song.title,
  1459. album: song.album,
  1460. albumId: albumKey,
  1461. artist: artistName,
  1462. artistId: artistName,
  1463. duration: song.durationSeconds,
  1464. bitRate: song.bitRate,
  1465. suffix: song.container,
  1466. size: song.size,
  1467. track: song.track,
  1468. year: song.year,
  1469. contentType: song.container ? `audio/${song.container}` : undefined,
  1470. coverArtId: albumKey
  1471. };
  1472. return restSong;
  1473. });
  1474. }
  1475. private convertPlexSongsToRestSongs(songs: PlexSong[]): NavidromeRestSong[] {
  1476. return songs.map(song => {
  1477. const coverId = song.albumThumb ?? song.thumb ?? song.albumId ?? song.id;
  1478. const restSong: NavidromeRestSong = {
  1479. id: song.id,
  1480. title: song.title,
  1481. album: song.album,
  1482. albumId: song.albumId,
  1483. artist: song.artist,
  1484. artistId: song.artistId,
  1485. duration: song.durationSeconds,
  1486. bitRate: song.bitRate,
  1487. suffix: song.suffix,
  1488. size: song.size,
  1489. track: song.track,
  1490. year: song.year,
  1491. contentType: song.mimeType,
  1492. coverArtId: coverId
  1493. };
  1494. return restSong;
  1495. });
  1496. }
  1497. private convertAudioStationPlaylistsToRest(playlists: AudioStationPlaylist[]): NavidromeRestPlaylist[] {
  1498. return playlists.map(playlist => {
  1499. const restPlaylist: NavidromeRestPlaylist = {
  1500. id: playlist.id,
  1501. name: playlist.name,
  1502. path: playlist.path
  1503. };
  1504. return restPlaylist;
  1505. });
  1506. }
  1507. private convertPlexPlaylistsToRest(playlists: PlexPlaylist[]): NavidromeRestPlaylist[] {
  1508. return playlists.map(playlist => {
  1509. const restPlaylist: NavidromeRestPlaylist = {
  1510. id: playlist.id,
  1511. name: playlist.title,
  1512. comment: playlist.summary,
  1513. duration: playlist.duration,
  1514. songCount: playlist.leafCount
  1515. };
  1516. return restPlaylist;
  1517. });
  1518. }
  1519. private async fetchAllJellyfinArtistSongs(account: WebDavAccount, artistId: string): Promise<JellyfinSong[]> {
  1520. const results: JellyfinSong[] = [];
  1521. let startIndex = 0;
  1522. while (true) {
  1523. const response = await jellyfinApi.getArtistSongs(account, artistId, startIndex, this.REMOTE_PAGE_SIZE);
  1524. results.push(...response.items);
  1525. if (response.nextStart === null) {
  1526. break;
  1527. }
  1528. startIndex = response.nextStart;
  1529. }
  1530. return results;
  1531. }
  1532. private async fetchAllEmbyArtistSongs(account: WebDavAccount, artistId: string): Promise<EmbySong[]> {
  1533. const results: EmbySong[] = [];
  1534. let startIndex = 0;
  1535. while (true) {
  1536. const response = await embyApi.getArtistSongs(account, artistId, startIndex, this.REMOTE_PAGE_SIZE);
  1537. results.push(...response.items);
  1538. if (response.nextStart === null) {
  1539. break;
  1540. }
  1541. startIndex = response.nextStart;
  1542. }
  1543. return results;
  1544. }
  1545. private async fetchAllAudioStationArtistSongs(account: WebDavAccount, artistName: string): Promise<AudioStationSong[]> {
  1546. if (!artistName || artistName.trim().length === 0) {
  1547. return [];
  1548. }
  1549. const keyword = artistName.trim();
  1550. const songs = await audioStationApi.searchSongs(account, keyword, 0, this.REMOTE_SEARCH_LIMIT);
  1551. return songs.filter(song => {
  1552. const artist = song.artist ?? song.albumArtist ?? '';
  1553. return artist.trim() === keyword;
  1554. });
  1555. }
  1556. private async fetchAllAudioStationPlaylistSongs(account: WebDavAccount, playlistId: string): Promise<AudioStationSong[]> {
  1557. const results: AudioStationSong[] = [];
  1558. let startIndex = 0;
  1559. while (true) {
  1560. const response = await audioStationApi.getPlaylistSongsPage(account, playlistId, startIndex, this.REMOTE_PAGE_SIZE);
  1561. results.push(...response.items);
  1562. if (response.nextStart === null) {
  1563. break;
  1564. }
  1565. startIndex = response.nextStart;
  1566. }
  1567. return results;
  1568. }
  1569. private async fetchAllPlexArtistSongs(account: WebDavAccount, artistId: string): Promise<PlexSong[]> {
  1570. const results: PlexSong[] = [];
  1571. const albums = await plexApi.getArtistAlbums(account, artistId);
  1572. for (let i = 0; i < albums.length; i++) {
  1573. const album = albums[i];
  1574. if (!album.id) {
  1575. continue;
  1576. }
  1577. const songs = await plexApi.getAlbumSongs(account, album.id);
  1578. results.push(...songs);
  1579. }
  1580. return results;
  1581. }
  1582. private async fetchAllPlexPlaylistSongs(account: WebDavAccount, playlistId: string): Promise<PlexSong[]> {
  1583. const results: PlexSong[] = [];
  1584. let startIndex = 0;
  1585. while (true) {
  1586. const response = await plexApi.getPlaylistSongsPage(account, playlistId, startIndex, this.REMOTE_PAGE_SIZE);
  1587. results.push(...response.items);
  1588. if (response.nextStart === null) {
  1589. break;
  1590. }
  1591. startIndex = response.nextStart;
  1592. }
  1593. return results;
  1594. }
  1595. private buildSongDedupKey(title?: string, artist?: string, album?: string, durationSeconds?: number): string {
  1596. const safeTitle = title ?? '';
  1597. const safeArtist = artist ?? '';
  1598. const safeAlbum = album ?? '';
  1599. const safeDuration = durationSeconds !== undefined && durationSeconds !== null ? durationSeconds.toString() : '';
  1600. return `${safeTitle}__${safeArtist}__${safeAlbum}__${safeDuration}`.toLowerCase();
  1601. }
  1602. private buildSongKeyFromItem(item: VideoItem): string {
  1603. const safeTitle = item.name ?? '';
  1604. const safeArtist = item.artist ?? '';
  1605. const safeAlbum = item.album ?? '';
  1606. const safeDuration = item.duration ?? '';
  1607. return `${safeTitle}__${safeArtist}__${safeAlbum}__${safeDuration}`.toLowerCase();
  1608. }
  1609. private dedupRemoteSongsByKey(items: VideoItem[]): VideoItem[] {
  1610. const map = new Map<string, VideoItem>();
  1611. for (let i = 0; i < items.length; i++) {
  1612. const item = items[i];
  1613. const key = this.buildSongKeyFromItem(item);
  1614. const existing = map.get(key);
  1615. if (!existing) {
  1616. map.set(key, item);
  1617. continue;
  1618. }
  1619. const existingHasAlbumId = StrUtil.isNotEmpty(existing.navAlbumId);
  1620. const currentHasAlbumId = StrUtil.isNotEmpty(item.navAlbumId);
  1621. if (!existingHasAlbumId && currentHasAlbumId) {
  1622. map.set(key, item);
  1623. }
  1624. }
  1625. return Array.from(map.values());
  1626. }
  1627. private convertApiSongsToRestSongs(songs: NavidromeSong[]): NavidromeRestSong[] {
  1628. return songs.map((song: NavidromeSong): NavidromeRestSong => ({
  1629. id: song.id,
  1630. title: song.title,
  1631. artist: song.artist,
  1632. artistId: song.artistId,
  1633. album: song.album,
  1634. albumId: song.albumId,
  1635. duration: song.duration,
  1636. bitRate: song.bitRate,
  1637. suffix: song.suffix,
  1638. size: song.size,
  1639. createdAt: song.created,
  1640. genre: song.genre,
  1641. track: song.track,
  1642. year: song.year,
  1643. contentType: song.contentType,
  1644. coverArt: song.coverArt,
  1645. coverArtId: song.coverArt,
  1646. lyrics: song.lyrics,
  1647. }));
  1648. }
  1649. private async convertSongsToVideoItems(songs: NavidromeRestSong[], account: WebDavAccount): Promise<VideoItem[]> {
  1650. const tasks: Promise<VideoItem>[] = [];
  1651. let successCount = 0;
  1652. let failedCount = 0;
  1653. void ServerLogUtil.info('SongConvert', `开始转换 ${songs.length} 首歌曲为 VideoItem`);
  1654. for (let i = 0; i < songs.length; i++) {
  1655. const song = songs[i];
  1656. tasks.push((async () => {
  1657. try {
  1658. let coverUrl: string | undefined;
  1659. try {
  1660. coverUrl = await this.resolveSongCover(song, account);
  1661. } catch (error) {
  1662. void ServerLogUtil.warn('SongConvert', `歌曲 ${song.title} 封面解析失败: ${(error as Error).message}`);
  1663. }
  1664. const videoItem = this.convertSongToVideoItem(song, account, coverUrl);
  1665. successCount++;
  1666. // 记录前几首歌的详细信息用于调试
  1667. if (i < 3) {
  1668. void ServerLogUtil.debug('SongConvert', `歌曲 ${i + 1}: ${videoItem.name}, 封面: ${coverUrl ? '有' : '无'}, 路径: ${videoItem.filePath}`);
  1669. }
  1670. return videoItem;
  1671. } catch (error) {
  1672. failedCount++;
  1673. void ServerLogUtil.error('SongConvert', `歌曲 ${song.title} 转换失败: ${(error as Error).message}`);
  1674. throw new Error(`歌曲 ${song.title} 转换失败: ${(error as Error).message}`);
  1675. }
  1676. })());
  1677. }
  1678. const results = await Promise.all(tasks);
  1679. void ServerLogUtil.info('SongConvert', `歌曲转换完成: 成功 ${successCount}, 失败 ${failedCount}`);
  1680. return results;
  1681. }
  1682. private async resolveSongCover(song: NavidromeRestSong, account: WebDavAccount): Promise<string | undefined> {
  1683. void ServerLogUtil.debug('NavidromePageCover', `🎵 解析歌曲封面 - title: ${song.title}, albumId: ${song.albumId}, id: ${song.id}`);
  1684. // 注释掉这个代码可以解决NavidRome部分账号没有封面问题
  1685. // if (this.isNavidromeAccount(account) && song.albumId) {
  1686. // const albumCover = song.albumId ? this.albumCoverLookup.get(song.albumId) : undefined;
  1687. // if (albumCover) {
  1688. // void ServerLogUtil.debug('NavidromePageCover', `✅ 歌曲使用专辑封面缓存 - title: ${song.title}, albumCover: ${albumCover}`);
  1689. // return albumCover;
  1690. // }
  1691. // }
  1692. if (!this.isNavidromeAccount(account)) {
  1693. const fallbackId = song.albumId ?? song.id;
  1694. void ServerLogUtil.debug('NavidromePageCover', `歌曲使用非Navidrome账号封面 - title: ${song.title}, fallbackId: ${fallbackId}`);
  1695. return this.buildCoverUrl(account, fallbackId);
  1696. }
  1697. const directUrl = this.resolveEmbedCover(account, song.embedArtPath ?? song.coverArtPath);
  1698. if (directUrl) {
  1699. void ServerLogUtil.info('NavidromePageCover', `✅ 歌曲使用直接封面 - title: ${song.title}, url: ${directUrl}`);
  1700. return directUrl;
  1701. }
  1702. const coverId = song.coverArt ?? song.coverArtId ?? song.id;
  1703. void ServerLogUtil.debug('NavidromePageCover', `歌曲生成封面URL - title: ${song.title}, coverArt: ${song.coverArt}, coverArtId: ${song.coverArtId}, 最终coverId: ${coverId}`);
  1704. return this.buildCoverUrl(account, coverId);
  1705. }
  1706. private async buildCoverUrl(account: WebDavAccount, coverId?: string, size: number = 300): Promise<string | undefined> {
  1707. void ServerLogUtil.info('NavidromePageCover', `开始构建封面URL - coverId: ${coverId}, size: ${size}, 账号: ${ServerLogUtil.sanitizeAccount(account)}`);
  1708. if (!coverId || coverId.trim().length === 0) {
  1709. void ServerLogUtil.warn('NavidromePageCover', `封面ID为空,跳过构建 - coverId: "${coverId}"`);
  1710. return undefined;
  1711. }
  1712. const normalizedId = coverId.trim();
  1713. const cacheKey = `${normalizedId}_${size}`;
  1714. if (this.isNavidromeAccount(account)) {
  1715. const cached = this.coverUrlCache.get(cacheKey);
  1716. if (cached) {
  1717. void ServerLogUtil.info('NavidromePageCover', `✅ 缓存命中 - coverId: ${coverId}, size: ${size}, url: ${cached}`);
  1718. return cached;
  1719. }
  1720. }
  1721. void ServerLogUtil.info('NavidromePageCover', `⚡ 调用API生成封面URL - coverId: ${coverId}, size: ${size}`);
  1722. let url: string | undefined = undefined;
  1723. try {
  1724. if (this.isNavidromeAccount(account)) {
  1725. void ServerLogUtil.debug('NavidromePageCover', `[开始] 调用 navidromeApi.buildCoverArtUrl - coverId: ${normalizedId}, size: ${size}`);
  1726. void ServerLogUtil.debug('NavidromePageCover', `[账号信息] host=${account.host}, port=${account.port}, enableHttps=${account.enableHttps}`);
  1727. void ServerLogUtil.debug('NavidromePageCover', `[账号信息] basePath=${account.navidromeBasePath}`);
  1728. url = await navidromeApi.buildCoverArtUrl(account, normalizedId, size);
  1729. void ServerLogUtil.debug('NavidromePageCover', `[完成] navidromeApi.buildCoverArtUrl 返回 - coverId: ${normalizedId}, 返回值: "${url}"`);
  1730. if (url) {
  1731. void ServerLogUtil.info('NavidromePageCover', `✅ API返回URL成功 - coverId: ${coverId}, url: ${url}`);
  1732. } else {
  1733. void ServerLogUtil.warn('NavidromePageCover', `⚠️ API返回空值 - coverId: ${coverId}`);
  1734. }
  1735. } else if (this.isJellyfinAccount(account)) {
  1736. void ServerLogUtil.debug('NavidromePageCover', `调用 jellyfinApi.buildPrimaryImageUrl - coverId: ${normalizedId}, size: ${size}`);
  1737. url = await jellyfinApi.buildPrimaryImageUrl(account, normalizedId, size, size);
  1738. } else if (this.isEmbyAccount(account)) {
  1739. void ServerLogUtil.debug('NavidromePageCover', `调用 embyApi.buildPrimaryImageUrl - coverId: ${normalizedId}, size: ${size}`);
  1740. url = await embyApi.buildPrimaryImageUrl(account, normalizedId, size, size);
  1741. } else if (this.isAudioStationAccount(account)) {
  1742. const key = this.parseAudioStationAlbumKey(normalizedId);
  1743. void ServerLogUtil.debug('NavidromePageCover', `调用 audioStationApi.buildAlbumCoverUrl - album=${key.name}, artist=${key.artist}`);
  1744. url = await audioStationApi.buildAlbumCoverUrl(account, key.name, key.artist);
  1745. } else if (this.isPlexAccount(account)) {
  1746. void ServerLogUtil.debug('NavidromePageCover', `调用 plexApi.buildImageUrl - coverId: ${normalizedId}`);
  1747. url = plexApi.buildImageUrl(account, normalizedId);
  1748. }
  1749. if (url && this.isNavidromeAccount(account)) {
  1750. this.coverUrlCache.set(cacheKey, url);
  1751. void ServerLogUtil.info('NavidromePageCover', `✅ 封面URL生成成功并已缓存 - coverId: ${coverId}, url: ${url}`);
  1752. void ServerLogUtil.debug('NavidromePageCover', `缓存键值 - cacheKey: ${cacheKey}`);
  1753. } else if (!url) {
  1754. void ServerLogUtil.error('NavidromePageCover', `❌ 封面URL生成失败(返回空) - coverId: ${coverId}, size: ${size}`);
  1755. } else {
  1756. void ServerLogUtil.info('NavidromePageCover', `✅ 封面URL生成成功(非Navidrome账号) - coverId: ${coverId}, url: ${url}`);
  1757. }
  1758. } catch (error) {
  1759. const err = error as Error;
  1760. void ServerLogUtil.error('NavidromePageCover', `❌ 封面URL生成异常 - coverId: ${coverId}, error: ${err.message}`);
  1761. void ServerLogUtil.error('NavidromePageCover', `错误类型: ${err.name || 'Unknown'}`);
  1762. void ServerLogUtil.error('NavidromePageCover', `错误堆栈: ${err.stack || '无'}`);
  1763. }
  1764. return url;
  1765. }
  1766. /**
  1767. * 记录账号缓存信息
  1768. */
  1769. private async logAccountCacheInfo(account: WebDavAccount): Promise<void> {
  1770. try {
  1771. void ServerLogUtil.info('AccountInfo', `账号信息: ${ServerLogUtil.sanitizeAccount(account)}`);
  1772. // 记录缓存路径信息
  1773. const cachePreview = this.getCachePreviewInfo(account);
  1774. if (cachePreview) {
  1775. void ServerLogUtil.info('AccountInfo', `Navidrome缓存目录结构:`);
  1776. void ServerLogUtil.info('AccountInfo', `- 缓存根目录: ${cachePreview.cacheRoot}`);
  1777. void ServerLogUtil.info('AccountInfo', `- 示例缓存路径: ${cachePreview.examplePath}`);
  1778. } else {
  1779. void ServerLogUtil.warn('AccountInfo', '无法预览缓存目录:上下文或根目录不可用');
  1780. }
  1781. // 记录封面缓存状态
  1782. void ServerLogUtil.info('AccountInfo', `当前封面URL缓存数量: ${this.coverUrlCache.size}`);
  1783. if (this.coverUrlCache.size > 0) {
  1784. const cacheKeys = Array.from(this.coverUrlCache.keys()).slice(0, 10);
  1785. void ServerLogUtil.debug('AccountInfo', `封面缓存示例: ${cacheKeys.join(', ')}`);
  1786. }
  1787. } catch (error) {
  1788. void ServerLogUtil.error('AccountInfo', `记录账号信息失败: ${(error as Error).message}`);
  1789. }
  1790. }
  1791. /**
  1792. * 记录缓存统计信息
  1793. */
  1794. private async logCacheStatistics(account: WebDavAccount): Promise<void> {
  1795. try {
  1796. void ServerLogUtil.info('CacheStats', '=== Navidrome 缓存统计 ===');
  1797. void ServerLogUtil.info('CacheStats', `封面URL缓存: ${this.coverUrlCache.size} 个条目`);
  1798. void ServerLogUtil.info('CacheStats', `已加载歌曲: ${this.allVideos.length} 首`);
  1799. void ServerLogUtil.info('CacheStats', `已处理艺术家: ${this.artists.length} 位`);
  1800. void ServerLogUtil.info('CacheStats', `已处理专辑: ${this.albums.length} 张`);
  1801. // 计算封面统计
  1802. const songsWithCover = this.allVideos.filter(song => song.pixelMapPath && song.pixelMapPath.length > 0).length;
  1803. const albumsWithCover = this.albums.filter(album => album.coverUrl && album.coverUrl.length > 0).length;
  1804. const artistsWithCover = this.artists.filter(artist => artist.coverUrl && artist.coverUrl.length > 0).length;
  1805. void ServerLogUtil.info('CacheStats', `封面统计:`);
  1806. void ServerLogUtil.info('CacheStats', `- 歌曲有封面: ${songsWithCover}/${this.allVideos.length} (${Math.round(songsWithCover / this.allVideos.length * 100)}%)`);
  1807. void ServerLogUtil.info('CacheStats', `- 专辑有封面: ${albumsWithCover}/${this.albums.length} (${Math.round(albumsWithCover / this.albums.length * 100)}%)`);
  1808. void ServerLogUtil.info('CacheStats', `- 艺术家有封面: ${artistsWithCover}/${this.artists.length} (${Math.round(artistsWithCover / this.artists.length * 100)}%)`);
  1809. } catch (error) {
  1810. void ServerLogUtil.error('CacheStats', `记录缓存统计失败: ${(error as Error).message}`);
  1811. }
  1812. }
  1813. private resolveEmbedCover(account: WebDavAccount, path?: string): string | undefined {
  1814. if (!this.isNavidromeAccount(account)) {
  1815. return undefined;
  1816. }
  1817. return navidromeRestApi.resolveResourceUrl(account, path);
  1818. }
  1819. private resolveLibraryInfo(account: WebDavAccount): LibraryInfo {
  1820. if (this.isJellyfinAccount(account)) {
  1821. return { type: CommonConstants.TYPE_JELLYFIN, scheme: 'jellyfin' } as LibraryInfo;
  1822. }
  1823. if (this.isEmbyAccount(account)) {
  1824. return { type: CommonConstants.TYPE_EMBY, scheme: 'emby' } as LibraryInfo;
  1825. }
  1826. if (this.isAudioStationAccount(account)) {
  1827. return { type: CommonConstants.TYPE_AUDIOSTATION, scheme: 'audiostation' } as LibraryInfo;
  1828. }
  1829. if (this.isPlexAccount(account)) {
  1830. return { type: CommonConstants.TYPE_PLEX, scheme: 'plex' } as LibraryInfo;
  1831. }
  1832. return { type: CommonConstants.TYPE_NAVIDROME, scheme: 'navidrome' } as LibraryInfo;
  1833. }
  1834. private convertSongToVideoItem(song: NavidromeRestSong, account: WebDavAccount, coverUrl?: string): VideoItem {
  1835. const title = song.title ?? Constants.UNKNOWN_TITLE;
  1836. const libraryInfo = this.resolveLibraryInfo(account);
  1837. // 调试日志:记录从playlist或其他API获取的歌曲的id字段
  1838. void ServerLogUtil.debug('SongConvert', `转换歌曲: ${title}`);
  1839. void ServerLogUtil.debug('SongConvert', `- song.id: ${song.id}`);
  1840. void ServerLogUtil.debug('SongConvert', `- song.artistId: ${song.artistId}`);
  1841. void ServerLogUtil.debug('SongConvert', `- song.albumId: ${song.albumId}`);
  1842. void ServerLogUtil.debug('SongConvert', `- song.lyrics: ${song.lyrics}`);
  1843. const videoItem = new VideoItem(
  1844. title,
  1845. song.id,
  1846. `${libraryInfo.scheme}://${account.id ?? 0}/${song.id}`,
  1847. libraryInfo.type,
  1848. song.size ?? 0,
  1849. song.createdAt ?? '',
  1850. Utility.formatFSize(song.size ?? 0),
  1851. undefined,
  1852. song.artist ?? Constants.UNKNOWN_ARTIST,
  1853. song.album ?? '',
  1854. `${title}${song.suffix ? '.' + song.suffix : ''}`
  1855. );
  1856. const durationStr = this.formatSongDuration(song.duration);
  1857. if (durationStr) {
  1858. videoItem.duration = durationStr;
  1859. }
  1860. videoItem.size = Utility.formatFSize(song.size ?? 0);
  1861. videoItem.bit_rate = song.bitRate ? song.bitRate.toString() : undefined;
  1862. videoItem.genre = song.genre;
  1863. videoItem.webdav_account_id = account.id?.toString();
  1864. videoItem.remote_rel_path = song.id;
  1865. videoItem.navArtistId = song.artistId;
  1866. videoItem.navAlbumId = song.albumId;
  1867. videoItem.pixelMapPath = coverUrl;
  1868. videoItem.lyricContent = song.lyrics;
  1869. // 调试日志:检查歌曲的 albumId 和 artistId
  1870. // if (this.allVideos.length < 3) {
  1871. // Logger.info('heanup', `歌曲 ${title}: artistId=${song.artistId}, albumId=${song.albumId}, artist=${song.artist}, album=${song.album}`);
  1872. // }
  1873. if (song.track !== undefined && song.track !== null) {
  1874. videoItem.track = song.track.toString();
  1875. }
  1876. if (song.year !== undefined && song.year !== null) {
  1877. videoItem.year = song.year.toString();
  1878. }
  1879. if (song.contentType) {
  1880. videoItem.mimeType = song.contentType;
  1881. }
  1882. // 记录最终生成的VideoItem路径
  1883. void ServerLogUtil.debug('SongConvert', `- VideoItem.filePath: ${videoItem.filePath}`);
  1884. void ServerLogUtil.debug('SongConvert', `- VideoItem.remote_rel_path: ${videoItem.remote_rel_path}`);
  1885. return videoItem;
  1886. }
  1887. private formatSongDuration(durationSeconds?: number): string | undefined {
  1888. if (durationSeconds === undefined || durationSeconds === null || durationSeconds < 0) {
  1889. return undefined;
  1890. }
  1891. const totalSeconds = Math.floor(durationSeconds);
  1892. const minutes = Math.floor(totalSeconds / 60);
  1893. const seconds = totalSeconds % 60;
  1894. const pad = (value: number) => value.toString().padStart(2, '0');
  1895. return `${pad(minutes)}:${pad(seconds)}`;
  1896. }
  1897. @Builder
  1898. topTitleBar() {
  1899. Column() {
  1900. Row({ space: 6 }) {
  1901. // 标题或搜索框
  1902. if (!this.isSearchMode) {
  1903. // 详情视图模式下显示返回按钮
  1904. if (this.isDetailView) {
  1905. Button({ type: ButtonType.Circle, stateEffect: true }) {
  1906. SymbolGlyph($r('sys.symbol.chevron_left'))
  1907. .attributeModifier(new SymbolGlyphFancyModifier(24, '', ''))
  1908. }
  1909. .attributeModifier(new ButtonFancyModifier(40, 40))
  1910. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.6 })
  1911. .animation({ duration: 300, curve: Curve.Ease })
  1912. .onClick(() => {
  1913. // 返回到之前的标签页
  1914. this.isDetailView = false;
  1915. this.clearFilter();
  1916. })
  1917. .attributeModifier(new ShadowModifier())
  1918. .zIndex(0)
  1919. Text(this.filterLabel)
  1920. .margin({ left: 3, right: 10 })
  1921. .fontColor($r('app.color.text_color'))
  1922. .fontSize(18)
  1923. .maxLines(1)
  1924. .textOverflow({ overflow: TextOverflow.MARQUEE })
  1925. .layoutWeight(1)
  1926. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.6 })
  1927. .animation({ duration: 300, curve: Curve.Ease })
  1928. } else {
  1929. // 正常模式:侧边栏按钮和账号名
  1930. Button({ type: ButtonType.Circle, stateEffect: true }) {
  1931. SymbolGlyph($r('sys.symbol.sort'))
  1932. .attributeModifier(new SymbolGlyphFancyModifier(25, '', ''))
  1933. }
  1934. .attributeModifier(new ButtonFancyModifier(40, 40))
  1935. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.6 })
  1936. .animation({ duration: 300, curve: Curve.Ease })
  1937. .onClick(() => {
  1938. this.getUIContext().animateTo({ duration: 555 }, () => {
  1939. // 动画闭包内控制Image组件的出现和消失
  1940. this.isShowDrawer = !this.isShowDrawer
  1941. this.offsetX = 0
  1942. })
  1943. })
  1944. .attributeModifier(new ShadowModifier())
  1945. .zIndex(0)
  1946. Text(this.selectedAccount.name)
  1947. .margin({ left: 3, right: 10 })
  1948. .fontColor($r('app.color.text_color'))
  1949. .fontSize(18)
  1950. .maxLines(1)
  1951. .textOverflow({ overflow: TextOverflow.MARQUEE })
  1952. .layoutWeight(1)
  1953. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.6 })
  1954. .onClick(() => {
  1955. // 可以添加标题点击事件
  1956. })
  1957. .animation({ duration: 300, curve: Curve.Ease })
  1958. }
  1959. } else {
  1960. Button({ type: ButtonType.Circle, stateEffect: true }) {
  1961. SymbolGlyph($r('sys.symbol.chevron_left'))
  1962. .attributeModifier(new SymbolGlyphFancyModifier(24, '', ''))
  1963. }
  1964. .attributeModifier(new ButtonFancyModifier(40, 40))
  1965. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.6 })
  1966. .animation({ duration: 300, curve: Curve.Ease })
  1967. .onClick(() => {
  1968. this.isSearchMode = false;
  1969. void this.onSearchInput('');
  1970. })
  1971. .attributeModifier(new ShadowModifier())
  1972. .zIndex(0)
  1973. }
  1974. // 搜索框
  1975. Search({ value: this.searchText, placeholder: '搜索标题、艺术家...' })
  1976. .searchButton('搜索', { fontColor: this.themeColor })
  1977. .searchIcon({
  1978. src: $r('sys.media.ohos_ic_public_search_filled')
  1979. })
  1980. .cancelButton({
  1981. style: CancelButtonStyle.CONSTANT,
  1982. icon: {
  1983. src: $r('sys.media.ohos_ic_public_cancel_filled')
  1984. }
  1985. })
  1986. .layoutWeight(1)
  1987. .height(35)
  1988. .maxLength(20)
  1989. .backgroundColor(this.isDarkMode?Color.Black:'#F5F5F5')
  1990. .placeholderColor(Color.Grey)
  1991. .placeholderFont({ size: 14, weight: 400 })
  1992. .textFont({ size: 14, weight: 400 })
  1993. .onSubmit((value: string) => {
  1994. void this.onSearchInput(value);
  1995. })
  1996. .onChange((value: string) => {
  1997. void this.onSearchInput(value);
  1998. })
  1999. .visibility(this.isSearchMode?Visibility.Visible:Visibility.None)
  2000. .animation({ duration: 300, curve: Curve.Ease })
  2001. // 搜索/排序按钮
  2002. if (!this.isSearchMode) {
  2003. // 搜索按钮
  2004. Button({ type: ButtonType.Circle, stateEffect: true }) {
  2005. SymbolGlyph($r('sys.symbol.magnifyingglass'))
  2006. .attributeModifier(new SymbolGlyphFancyModifier(25, '', ''))
  2007. }
  2008. .attributeModifier(new ButtonFancyModifier(40, 40))
  2009. .animation({ duration: 300, curve: Curve.Ease })
  2010. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.6 })
  2011. .attributeModifier(new ShadowModifier())
  2012. .zIndex(0)
  2013. .visibility(this.selectedTab==0?Visibility.Visible:Visibility.None)
  2014. .onClick(() => {
  2015. this.isSearchMode = true;
  2016. if (!this.isSearchLoading && this.searchText.length === 0) {
  2017. this.filteredList = [];
  2018. }
  2019. })
  2020. // 排序按钮
  2021. Button({ type: ButtonType.Circle, stateEffect: true }) {
  2022. SymbolGlyph($r('sys.symbol.list_number'))
  2023. .attributeModifier(new SymbolGlyphFancyModifier(25, '', ''))
  2024. }
  2025. .attributeModifier(new ButtonFancyModifier(40, 40))
  2026. .animation({ duration: 300, curve: Curve.Ease })
  2027. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.6 })
  2028. .bindMenu(this.SortMenuBuilder)
  2029. .attributeModifier(new ShadowModifier())
  2030. .zIndex(0)
  2031. }
  2032. }
  2033. .width('100%')
  2034. .height(55)
  2035. .padding({ left: 15, right: 15 })
  2036. .justifyContent(FlexAlign.SpaceBetween)
  2037. .alignItems(VerticalAlign.Center)
  2038. // 分段按钮
  2039. SegmentButton({
  2040. options: this.tabOptions,
  2041. selectedIndexes: $tabSelectedIndexes
  2042. })
  2043. .width('100%')
  2044. .padding({ left: 25, right: 25, top: 5, bottom: 5 })
  2045. }
  2046. .width('100%')
  2047. .padding({ top: this.topSafeHeight + 5 })
  2048. // .backgroundColor($r('app.color.start_window_background'))
  2049. }
  2050. @Builder
  2051. SortMenuBuilder() {
  2052. Menu() {
  2053. MenuItem({
  2054. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.text_and_arrow_up')),
  2055. content: $r('app.string.sort_by_name')
  2056. })
  2057. .onClick(async () => {
  2058. this.doSortType(0);
  2059. PreferencesUtil.put("navidromeSortType", 0);
  2060. })
  2061. MenuItem({
  2062. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.text_and_arrow_down')),
  2063. content: '按名称降序'
  2064. })
  2065. .onClick(async () => {
  2066. this.doSortType(1);
  2067. PreferencesUtil.put("navidromeSortType", 1);
  2068. })
  2069. MenuItem({
  2070. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.clock')),
  2071. content: '按艺术家升序'
  2072. })
  2073. .onClick(async () => {
  2074. this.doSortType(2);
  2075. PreferencesUtil.put("navidromeSortType", 2);
  2076. })
  2077. MenuItem({
  2078. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.timer')),
  2079. content: '按艺术家降序'
  2080. })
  2081. .onClick(async () => {
  2082. this.doSortType(3);
  2083. PreferencesUtil.put("navidromeSortType", 3);
  2084. })
  2085. MenuItem({
  2086. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.text_and_arrow_up')),
  2087. content: '按专辑升序'
  2088. })
  2089. .onClick(async () => {
  2090. this.doSortType(4);
  2091. PreferencesUtil.put("navidromeSortType", 4);
  2092. })
  2093. MenuItem({
  2094. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.text_and_arrow_down')),
  2095. content: '按专辑降序'
  2096. })
  2097. .onClick(async () => {
  2098. this.doSortType(5);
  2099. PreferencesUtil.put("navidromeSortType", 5);
  2100. })
  2101. }
  2102. }
  2103. doSortType(index: number) {
  2104. this.sortType = index;
  2105. const songs = this.isSearchMode && this.searchText.length > 0 ? this.filteredList : this.allVideos;
  2106. const sortTypeNames = ['名称升序', '名称降序', '艺术家升序', '艺术家降序', '专辑升序', '专辑降序'];
  2107. const sortTypeName = sortTypeNames[index] || '未知排序';
  2108. // 记录排序操作
  2109. void ServerLogUtil.info('NavidromeSort', `应用排序: ${sortTypeName} (${index})`);
  2110. void ServerLogUtil.info('NavidromeSort', `排序范围: ${songs.length} 首歌曲 (${this.isSearchMode ? '搜索结果' : '全部歌曲'})`);
  2111. const startTime = Date.now();
  2112. // 对歌曲列表进行排序
  2113. switch (index) {
  2114. case 0: // 名称升序
  2115. Utility.doSortListAscending(songs,false)
  2116. break;
  2117. case 1: // 名称降序
  2118. Utility.doSortListDescending(songs,true)
  2119. break;
  2120. case 2: // 艺术家升序
  2121. songs.sort((a, b) => {
  2122. // 处理艺术家可能为undefined的字符串比较
  2123. const artistA = a.artist?.trim() || ''; // 可选添加 trim() 处理空格
  2124. const artistB = b.artist?.trim() || '';
  2125. return artistA.localeCompare(artistB);
  2126. });
  2127. break;
  2128. case 3: // 艺术家降序
  2129. songs.sort((a, b) => {
  2130. // 处理艺术家可能为undefined的字符串比较
  2131. const artistA = a.artist?.trim() || ''; // 可选添加 trim() 处理空格
  2132. const artistB = b.artist?.trim() || '';
  2133. return artistB.localeCompare(artistA);
  2134. });
  2135. break;
  2136. case 4: // 专辑升序
  2137. songs.sort((a, b) => {
  2138. const albumA = a.album?.trim() || ''; // 可选添加 trim() 处理空格
  2139. const albumB = b.album?.trim() || '';
  2140. return albumA.localeCompare(albumB);
  2141. });
  2142. break;
  2143. case 5: // 专辑降序
  2144. songs.sort((a, b) => {
  2145. const albumA = a.album?.trim() || ''; // 可选添加 trim() 处理空格
  2146. const albumB = b.album?.trim() || '';
  2147. return albumB.localeCompare(albumA);
  2148. });
  2149. break;
  2150. }
  2151. const sortTime = Date.now() - startTime;
  2152. // 更新显示列表
  2153. if (this.isSearchMode) {
  2154. this.filteredList = [...songs];
  2155. }
  2156. // 记录排序结果
  2157. void ServerLogUtil.info('NavidromeSort', `排序完成: ${sortTypeName}`);
  2158. void ServerLogUtil.info('NavidromeSort', `- 排序耗时: ${sortTime}ms`);
  2159. void ServerLogUtil.debug('NavidromeSort', `排序结果示例: ${songs.slice(0, 3).map(s => `${s.name} (${s.artist})`).join(', ')}`);
  2160. }
  2161. // 实时搜索逻辑(改为远程API搜索)
  2162. private async onSearchInput(value: string): Promise<void> {
  2163. const keyword = value.trim();
  2164. this.searchText = keyword;
  2165. const ticket = ++this.searchTicket;
  2166. void ServerLogUtil.debug('NavidromeSearch', `搜索输入: "${value}" -> "${keyword}"`);
  2167. if (keyword.length === 0) {
  2168. this.filteredList = [];
  2169. this.isSearchLoading = false;
  2170. void ServerLogUtil.info('NavidromeSearch', '搜索已清空,显示所有歌曲');
  2171. return;
  2172. }
  2173. if (!this.isSearchMode) {
  2174. this.isSearchMode = true;
  2175. }
  2176. const account = this.resolveActiveAccount();
  2177. if (!account) {
  2178. this.filteredList = [];
  2179. this.isSearchLoading = false;
  2180. ToastUtil.showToast('媒体库账号不可用');
  2181. return;
  2182. }
  2183. this.isSearchLoading = true;
  2184. this.filteredList = [];
  2185. const startTime = Date.now();
  2186. void ServerLogUtil.info('NavidromeSearch', `开始远程搜索: "${keyword}"`);
  2187. try {
  2188. let restSongs: NavidromeRestSong[] = [];
  2189. if (this.isNavidromeAccount(account)) {
  2190. const songs = await navidromeApi.searchSongs(account, keyword, NAVIDROME_SEARCH_LIMIT);
  2191. restSongs = this.convertApiSongsToRestSongs(songs);
  2192. } else if (this.isJellyfinAccount(account)) {
  2193. const response = await jellyfinApi.searchSongs(account, keyword, 0, this.REMOTE_SEARCH_LIMIT);
  2194. restSongs = this.convertJellyfinSongsToRestSongs(response.items);
  2195. } else if (this.isEmbyAccount(account)) {
  2196. const response = await embyApi.searchSongs(account, keyword, 0, this.REMOTE_SEARCH_LIMIT);
  2197. restSongs = this.convertEmbySongsToRestSongs(response.items);
  2198. } else if (this.isAudioStationAccount(account)) {
  2199. const songs = await audioStationApi.searchSongs(account, keyword, 0, this.REMOTE_SEARCH_LIMIT);
  2200. restSongs = this.convertAudioStationSongsToRestSongs(songs);
  2201. } else if (this.isPlexAccount(account)) {
  2202. const response = await plexApi.searchSongs(account, keyword, 0, this.REMOTE_SEARCH_LIMIT);
  2203. restSongs = this.convertPlexSongsToRestSongs(response.items);
  2204. }
  2205. if (ticket !== this.searchTicket) {
  2206. return;
  2207. }
  2208. const searchTime = Date.now() - startTime;
  2209. if (!restSongs || restSongs.length === 0) {
  2210. this.filteredList = [];
  2211. void ServerLogUtil.warn('NavidromeSearch', `搜索无结果: "${keyword}"`);
  2212. void ServerLogUtil.info('NavidromeSearch', `- 搜索耗时: ${searchTime}ms`);
  2213. return;
  2214. }
  2215. const videoItems = await this.convertSongsToVideoItems(restSongs, account);
  2216. if (ticket !== this.searchTicket) {
  2217. return;
  2218. }
  2219. this.filteredList = videoItems;
  2220. this.doSortType(this.sortType);
  2221. void ServerLogUtil.info('NavidromeSearch', `搜索完成: "${keyword}"`);
  2222. void ServerLogUtil.info('NavidromeSearch', `- 搜索耗时: ${searchTime}ms`);
  2223. void ServerLogUtil.info('NavidromeSearch', `- 匹配结果: ${videoItems.length}`);
  2224. void ServerLogUtil.debug('NavidromeSearch', `搜索结果示例: ${videoItems.slice(0, 3).map(s => `${s.name} (${s.artist})`).join(', ')}`);
  2225. } catch (error) {
  2226. if (ticket !== this.searchTicket) {
  2227. return;
  2228. }
  2229. this.filteredList = [];
  2230. const message = (error as Error).message ?? 'Navidrome 搜索失败';
  2231. ToastUtil.showToast(message);
  2232. void ServerLogUtil.error('NavidromeSearch', `搜索失败: ${message}`);
  2233. void ServerLogUtil.info('NavidromeSearch', `- 搜索耗时: ${Date.now() - startTime}ms`);
  2234. } finally {
  2235. if (ticket === this.searchTicket) {
  2236. this.isSearchLoading = false;
  2237. }
  2238. }
  2239. }
  2240. private getCurrentCount(): number {
  2241. switch (this.selectedTab) {
  2242. case 1:
  2243. return this.artists.length;
  2244. case 2:
  2245. return this.albums.length;
  2246. case 3:
  2247. return this.playlists.length;
  2248. default:
  2249. return this.getVisibleSongs().length;
  2250. }
  2251. }
  2252. private getEmptyTitle(): string {
  2253. switch (this.selectedTab) {
  2254. case 1:
  2255. return '暂无艺术家';
  2256. case 2:
  2257. return '暂无专辑';
  2258. case 3:
  2259. return '暂无歌单';
  2260. default:
  2261. if (this.isSearchMode && this.searchText.length > 0) {
  2262. return this.isSearchLoading ? '正在搜索远程歌曲' : '没有匹配的远程歌曲';
  2263. }
  2264. if (this.filterType !== NavFilterType.None && this.isFilterLoading) {
  2265. return '正在加载筛选结果';
  2266. }
  2267. return this.filterType === NavFilterType.None ? '暂无音乐' : '该筛选下暂无歌曲';
  2268. }
  2269. }
  2270. private getEmptySubtitle(): string {
  2271. switch (this.selectedTab) {
  2272. case 1:
  2273. return '当前筛选没有找到艺术家';
  2274. case 2:
  2275. return '当前筛选没有找到专辑';
  2276. case 3:
  2277. return '当前筛选没有找到歌单';
  2278. default:
  2279. if (this.isSearchMode && this.searchText.length > 0) {
  2280. return this.isSearchLoading ? '请稍候,正在通过 API 搜索' : '换个关键词再试试吧';
  2281. }
  2282. if (this.filterType !== NavFilterType.None && this.isFilterLoading) {
  2283. return '请稍候...';
  2284. }
  2285. return this.filterType === NavFilterType.None ? '当前分类下没有找到音乐文件' : '请尝试调整筛选条件';
  2286. }
  2287. }
  2288. @Builder
  2289. buildSongItem(song: VideoItem, index: number) {
  2290. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  2291. Row({ space: 12 }) {
  2292. // 歌曲封面
  2293. Image(song.pixelMapPath ? song.pixelMapPath : $r('app.media.nocover'))
  2294. .width(52)
  2295. .height(52)
  2296. .borderRadius(9)
  2297. .sourceSize({ width: 38, height: 38 })
  2298. .draggable(false)
  2299. .interpolation(ImageInterpolation.High)// 用于重采样后的抗锯齿
  2300. .autoResize(true) // 重采样,可减少内存占用
  2301. .alt($r('app.media.nocover'))
  2302. .fillColor(song.pixelMapPath ? undefined : this.themeColor)
  2303. .objectFit(ImageFit.Cover)
  2304. .margin({ left: 20 })
  2305. .animation({
  2306. duration: 500,
  2307. curve: Curve.Friction // 可选动画曲线
  2308. })
  2309. .shadow({
  2310. radius: StrUtil.isEmpty(song.pixelMapPath) ?6:14,
  2311. type: ShadowType.BLUR,
  2312. color: 'on_primary'
  2313. })
  2314. .onClick(() => {
  2315. this.playSong(song, index, true);
  2316. })
  2317. // 歌曲信息
  2318. Column({ space: 4 }) {
  2319. Text(song.name)
  2320. .fontSize(15)
  2321. .fontColor(this.currentSong?.filePath == song.filePath ? this.themeColor : $r('app.color.index_tab_font_color'))
  2322. .maxLines(1)
  2323. .textOverflow({ overflow: TextOverflow.Ellipsis })
  2324. Row() {
  2325. Text((song.artist ?? '') + " ")
  2326. .fontSize(13)
  2327. .fontColor(this.currentSong?.filePath == song.filePath ? this.themeColor : $r('app.color.index_tab_font_color'))
  2328. .opacity(0.6)
  2329. .maxLines(1)
  2330. .visibility(song.artist ? Visibility.Visible : Visibility.None)
  2331. .textOverflow({ overflow: TextOverflow.Ellipsis })
  2332. Text(this.buildSongMetaLine(song))
  2333. .fontSize(13)
  2334. .fontColor(this.currentSong?.filePath == song.filePath ? this.themeColor : $r('app.color.index_tab_font_color'))
  2335. .opacity(0.6)
  2336. .maxLines(1)
  2337. .textOverflow({ overflow: TextOverflow.Ellipsis })
  2338. }
  2339. .width('90%')
  2340. }
  2341. .alignItems(HorizontalAlign.Start)
  2342. .layoutWeight(1)
  2343. .padding({ right: 20 })
  2344. Column() {
  2345. ImageAnimator()
  2346. .images(CommonConstants.IMAGE_FRAME_INFO)// 动画数组
  2347. .duration(1000)// 持续
  2348. .state(AnimationStatus.Running)// 动画状态
  2349. .fillMode(FillMode.Forwards)
  2350. .visibility(this.currentSong?.filePath == song.filePath ? Visibility.Visible :
  2351. Visibility.None)
  2352. .width(18)
  2353. .margin({ right: 12, top: 8, bottom: 8 })
  2354. .height(18)
  2355. .iterations(-1) // 播放次数
  2356. }
  2357. }
  2358. }
  2359. .width('100%')
  2360. .padding(12)
  2361. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.8 })
  2362. .backgroundColor(Color.Transparent)
  2363. .onClick(() => {
  2364. this.playSong(song, index);
  2365. })
  2366. }
  2367. @Builder
  2368. buildArtistItem(artist: NavidromeRestArtist) {
  2369. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  2370. Row({ space: 12 }) {
  2371. Image(artist.coverUrl ?? $r('app.media.nocover'))
  2372. .width(48)
  2373. .height(48)
  2374. .borderRadius(10)
  2375. .draggable(false)
  2376. .alt($r('app.media.nocover'))
  2377. // .interpolation(ImageInterpolation.High)// 用于重采样后的抗锯齿
  2378. // .autoResize(true) // 重采样,可减少内存占用
  2379. .sourceSize({ width: 38, height: 38 })
  2380. .fillColor(artist.coverUrl ? undefined : this.themeColor)
  2381. .objectFit(ImageFit.Cover)
  2382. .margin({ left: 20 })
  2383. Column({ space: 4 }) {
  2384. Text(artist.name ?? Constants.UNKNOWN_ARTIST)
  2385. .fontSize(15)
  2386. .fontColor($r('app.color.index_tab_font_color'))
  2387. .maxLines(1)
  2388. .textAlign(TextAlign.Start)
  2389. .textOverflow({ overflow: TextOverflow.Ellipsis })
  2390. Text(this.buildArtistMetaLine(artist))
  2391. .fontSize(13)
  2392. .fontColor($r('app.color.index_tab_font_color'))
  2393. .opacity(0.6)
  2394. .maxLines(1)
  2395. .textOverflow({ overflow: TextOverflow.Ellipsis })
  2396. .visibility((artist.albumCount ?? 0) === 0 && (artist.songCount ?? 0) === 0 ? Visibility.None : Visibility.Visible)
  2397. }
  2398. .alignItems(HorizontalAlign.Start)
  2399. .padding({ right: 20 })
  2400. }
  2401. .width('100%')
  2402. }
  2403. .width('100%')
  2404. .padding(12)
  2405. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.85 })
  2406. .backgroundColor(Color.Transparent)
  2407. .onClick(() => {
  2408. this.onArtistSelected(artist);
  2409. })
  2410. }
  2411. @Builder
  2412. buildAlbumItem(album: NavidromeRestAlbum) {
  2413. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  2414. Row({ space: 12 }) {
  2415. Image(album.coverUrl ?? $r('app.media.nocover'))
  2416. .width(48)
  2417. .height(48)
  2418. .borderRadius(10)
  2419. .clip(true)
  2420. .alt($r('app.media.nocover'))
  2421. .draggable(false)
  2422. // .interpolation(ImageInterpolation.High)// 用于重采样后的抗锯齿
  2423. // .autoResize(true) // 重采样,可减少内存占用
  2424. .sourceSize({ width: 38, height: 38 })
  2425. .fillColor(album.coverUrl ? undefined : this.themeColor)
  2426. .objectFit(ImageFit.Cover)
  2427. .margin({ left: 20 })
  2428. Column({ space: 4 }) {
  2429. Text(album.name ?? '未知专辑')
  2430. .fontSize(15)
  2431. .fontColor($r('app.color.index_tab_font_color'))
  2432. .maxLines(1)
  2433. .textAlign(TextAlign.Start)
  2434. .textOverflow({ overflow: TextOverflow.Ellipsis })
  2435. Row() {
  2436. Text(album.artist ?? Constants.UNKNOWN_ARTIST)
  2437. .fontSize(13)
  2438. .fontColor($r('app.color.index_tab_font_color'))
  2439. .opacity(0.6)
  2440. .maxLines(1)
  2441. .textOverflow({ overflow: TextOverflow.Ellipsis })
  2442. Text(this.buildAlbumMetaLine(album))
  2443. .fontSize(13)
  2444. .fontColor($r('app.color.index_tab_font_color'))
  2445. .opacity(0.6)
  2446. .maxLines(1)
  2447. .textOverflow({ overflow: TextOverflow.Ellipsis })
  2448. }
  2449. }
  2450. .alignItems(HorizontalAlign.Start)
  2451. .padding({ right: 20 })
  2452. }
  2453. .width('100%')
  2454. }
  2455. .width('100%')
  2456. .padding(12)
  2457. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.85 })
  2458. .backgroundColor(Color.Transparent)
  2459. .onClick(() => {
  2460. this.onAlbumSelected(album);
  2461. })
  2462. }
  2463. @Builder
  2464. buildPlaylistItem(playlist: NavidromeRestPlaylist) {
  2465. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  2466. Row({ space: 12 }) {
  2467. Image($r('app.media.nocover'))
  2468. .width(48)
  2469. .height(48)
  2470. .borderRadius(10)
  2471. .alt($r('app.media.nocover'))
  2472. .draggable(false)
  2473. .sourceSize({ width: 38, height: 38 })
  2474. .fillColor(this.themeColor)
  2475. .objectFit(ImageFit.Cover)
  2476. .margin({ left: 20 })
  2477. Column({ space: 4 }) {
  2478. Text(playlist.name ?? '未知歌单')
  2479. .fontSize(15)
  2480. .fontColor($r('app.color.index_tab_font_color'))
  2481. .maxLines(1)
  2482. .textAlign(TextAlign.Start)
  2483. .textOverflow({ overflow: TextOverflow.Ellipsis })
  2484. Text(this.buildPlaylistMetaLine(playlist))
  2485. .fontSize(13)
  2486. .fontColor($r('app.color.index_tab_font_color'))
  2487. .opacity(0.6)
  2488. .maxLines(1)
  2489. .textOverflow({ overflow: TextOverflow.Ellipsis })
  2490. // if (playlist.ownerName) {
  2491. // Text(playlist.ownerName)
  2492. // .fontSize(12)
  2493. // .fontColor($r('app.color.index_tab_font_color'))
  2494. // .opacity(0.5)
  2495. // .maxLines(1)
  2496. // .textOverflow({ overflow: TextOverflow.Ellipsis })
  2497. // }
  2498. }
  2499. .alignItems(HorizontalAlign.Start)
  2500. .padding({ right: 20 })
  2501. }
  2502. .width('100%')
  2503. }
  2504. .width('100%')
  2505. .padding(12)
  2506. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.85 })
  2507. .backgroundColor(Color.Transparent)
  2508. .onClick(() => {
  2509. this.onPlaylistSelected(playlist);
  2510. })
  2511. }
  2512. private buildSongMetaLine(song: VideoItem): string {
  2513. const parts: string[] = [];
  2514. if (song.duration) {
  2515. parts.push(song.duration as string);
  2516. }
  2517. // if (song.size) {
  2518. // parts.push(song.size as string);
  2519. // }
  2520. // if (parts.length === 0 && song.cTime) {
  2521. // parts.push(song.cTime as string);
  2522. // }
  2523. return parts.join(' · ');
  2524. }
  2525. private buildArtistMetaLine(artist: NavidromeRestArtist): string {
  2526. const albumCount = artist.albumCount ?? 0;
  2527. const songCount = artist.songCount ?? 0;
  2528. const playCount = artist.playCount ?? 0;
  2529. // 如果专辑和歌曲数都为0,不显示元数据信息
  2530. if (albumCount === 0 && songCount === 0) {
  2531. return '';
  2532. }
  2533. return `专辑 ${albumCount} · 歌曲 ${songCount} `;
  2534. }
  2535. private buildAlbumMetaLine(album: NavidromeRestAlbum): string {
  2536. const parts: string[] = [];
  2537. if (album.duration !== undefined) {
  2538. const duration = this.formatSongDuration(album.duration);
  2539. if (duration) {
  2540. parts.push(' '+duration);
  2541. }
  2542. }
  2543. if (album.minYear) {
  2544. parts.push(`发行 ${album.minYear}`);
  2545. }
  2546. return parts.join(' · ');
  2547. }
  2548. private buildPlaylistMetaLine(playlist: NavidromeRestPlaylist): string {
  2549. const parts: string[] = [];
  2550. if (playlist.songCount !== undefined) {
  2551. parts.push(`${playlist.songCount} 首歌`);
  2552. }
  2553. if (playlist.duration !== undefined) {
  2554. const duration = this.formatSongDuration(playlist.duration);
  2555. if (duration) {
  2556. parts.push(duration);
  2557. }
  2558. }
  2559. return parts.join(' · ');
  2560. }
  2561. private getVisibleSongs(): VideoItem[] {
  2562. if (this.isSearchMode) {
  2563. return this.searchText.length > 0 ? this.filteredList : this.allVideos;
  2564. }
  2565. if (this.filterType !== NavFilterType.None) {
  2566. return this.filterSongs;
  2567. }
  2568. return this.allVideos;
  2569. }
  2570. private onArtistSelected(artist: NavidromeRestArtist): void {
  2571. if (!artist || !artist.id) {
  2572. return;
  2573. }
  2574. this.isShowTitleBar = true;
  2575. // 保存当前标签页,进入详情视图
  2576. this.previousTab = this.selectedTab;
  2577. this.isDetailView = true;
  2578. // 应用筛选但不切换标签页
  2579. void this.applyFilter(NavFilterType.Artist, artist.id, artist.name ?? Constants.UNKNOWN_ARTIST);
  2580. }
  2581. private onAlbumSelected(album: NavidromeRestAlbum): void {
  2582. if (!album || !album.id) {
  2583. return;
  2584. }
  2585. this.isShowTitleBar = true;
  2586. // 保存当前标签页,进入详情视图
  2587. this.previousTab = this.selectedTab;
  2588. this.isDetailView = true;
  2589. // 应用筛选但不切换标签页
  2590. void this.applyFilter(NavFilterType.Album, album.id, album.name ?? '未知专辑');
  2591. }
  2592. private onPlaylistSelected(playlist: NavidromeRestPlaylist): void {
  2593. if (!playlist || !playlist.id) {
  2594. return;
  2595. }
  2596. this.isShowTitleBar = true;
  2597. // 保存当前标签页,进入详情视图
  2598. this.previousTab = this.selectedTab;
  2599. this.isDetailView = true;
  2600. // 应用筛选但不切换标签页
  2601. void this.applyFilter(NavFilterType.Playlist, playlist.id, playlist.name ?? '未知歌单');
  2602. }
  2603. private async applyFilter(type: NavFilterType, id: string, label: string): Promise<void> {
  2604. // 记录筛选操作
  2605. void ServerLogUtil.info('NavidromeFilter', `应用筛选:`);
  2606. const typeText = type === NavFilterType.Artist ? '艺术家' : type === NavFilterType.Album ? '专辑' : type === NavFilterType.Playlist ? '歌单' : '无';
  2607. void ServerLogUtil.info('NavidromeFilter', `- 类型: ${type} (${typeText})`);
  2608. void ServerLogUtil.info('NavidromeFilter', `- ID: ${id}`);
  2609. void ServerLogUtil.info('NavidromeFilter', `- 标签: ${label}`);
  2610. void ServerLogUtil.info('NavidromeFilter', `- 筛选前总歌曲数: ${this.allVideos.length}`);
  2611. // 先更新状态
  2612. this.filterType = type;
  2613. this.filterId = id;
  2614. this.filterLabel = label;
  2615. // 退出搜索模式,确保显示筛选结果
  2616. this.isSearchMode = false;
  2617. this.searchText = '';
  2618. this.filteredList = [];
  2619. this.isSearchLoading = false;
  2620. this.searchTicket++;
  2621. this.filterSongs = [];
  2622. this.isFilterLoading = true;
  2623. // 调试日志:检查筛选结果
  2624. void this.loadSongsForFilter(label).catch((error: Error) => {
  2625. void ServerLogUtil.error('NavidromeFilter', `筛选歌曲加载失败: ${error.message}`);
  2626. ToastUtil.showToast(error.message || '筛选数据加载失败');
  2627. });
  2628. // 不再自动切换标签页,保持在详情视图模式
  2629. }
  2630. private async loadSongsForFilter(label:string): Promise<void> {
  2631. if (this.filterType === NavFilterType.None || !this.filterId) {
  2632. this.filterSongs = [];
  2633. this.isFilterLoading = false;
  2634. return;
  2635. }
  2636. const account = this.resolveActiveAccount();
  2637. if (!account) {
  2638. this.filterSongs = [];
  2639. this.isFilterLoading = false;
  2640. throw new Error('媒体库账号不可用');
  2641. }
  2642. if (!this.isNavidromeAccount(account)) {
  2643. let restSongs: NavidromeRestSong[] = [];
  2644. if (this.filterType === NavFilterType.Artist) {
  2645. if (this.isJellyfinAccount(account)) {
  2646. const songs = await this.fetchAllJellyfinArtistSongs(account, this.filterId);
  2647. restSongs = this.convertJellyfinSongsToRestSongs(songs);
  2648. } else if (this.isEmbyAccount(account)) {
  2649. const songs = await this.fetchAllEmbyArtistSongs(account, this.filterId);
  2650. restSongs = this.convertEmbySongsToRestSongs(songs);
  2651. } else if (this.isAudioStationAccount(account)) {
  2652. const songs = await this.fetchAllAudioStationArtistSongs(account, this.filterId);
  2653. restSongs = this.convertAudioStationSongsToRestSongs(songs);
  2654. } else if (this.isPlexAccount(account)) {
  2655. const songs = await this.fetchAllPlexArtistSongs(account, this.filterId);
  2656. restSongs = this.convertPlexSongsToRestSongs(songs);
  2657. }
  2658. } else if (this.filterType === NavFilterType.Album) {
  2659. if (this.isJellyfinAccount(account)) {
  2660. const songs = await jellyfinApi.getAlbumSongs(account, this.filterId);
  2661. restSongs = this.convertJellyfinSongsToRestSongs(songs);
  2662. } else if (this.isEmbyAccount(account)) {
  2663. const songs = await embyApi.getAlbumSongs(account, this.filterId);
  2664. restSongs = this.convertEmbySongsToRestSongs(songs);
  2665. } else if (this.isAudioStationAccount(account)) {
  2666. const albumKey = this.parseAudioStationAlbumKey(this.filterId);
  2667. const songs = await audioStationApi.getAlbumSongs(account, albumKey.name, albumKey.artist);
  2668. restSongs = this.convertAudioStationSongsToRestSongs(songs);
  2669. } else if (this.isPlexAccount(account)) {
  2670. const songs = await plexApi.getAlbumSongs(account, this.filterId);
  2671. restSongs = this.convertPlexSongsToRestSongs(songs);
  2672. }
  2673. } else if (this.filterType === NavFilterType.Playlist) {
  2674. if (this.isAudioStationAccount(account)) {
  2675. const songs = await this.fetchAllAudioStationPlaylistSongs(account, this.filterId);
  2676. restSongs = this.convertAudioStationSongsToRestSongs(songs);
  2677. } else if (this.isPlexAccount(account)) {
  2678. const songs = await this.fetchAllPlexPlaylistSongs(account, this.filterId);
  2679. restSongs = this.convertPlexSongsToRestSongs(songs);
  2680. } else {
  2681. this.filterSongs = [];
  2682. this.isFilterLoading = false;
  2683. ToastUtil.showToast('当前媒体库不支持歌单');
  2684. return;
  2685. }
  2686. }
  2687. const videoItems = await this.convertSongsToVideoItems(restSongs, account);
  2688. this.filterSongs = videoItems;
  2689. this.isFilterLoading = false;
  2690. return;
  2691. }
  2692. const expectedFilterId = this.filterId;
  2693. const expectedFilterType = this.filterType;
  2694. try {
  2695. let songs: NavidromeRestSong[] = [];
  2696. if (this.filterType === NavFilterType.Artist) {
  2697. songs = await navidromeRestApi.fetchSongsByArtist(account, this.filterId,label);
  2698. } else if (this.filterType === NavFilterType.Album) {
  2699. songs = await navidromeRestApi.fetchSongsByAlbum(account, this.filterId,label);
  2700. } else if (this.filterType === NavFilterType.Playlist) {
  2701. songs = await navidromeRestApi.fetchSongsByPlaylist(account, this.filterId);
  2702. }
  2703. const videoItems = await this.convertSongsToVideoItems(songs, account);
  2704. if (expectedFilterId !== this.filterId || expectedFilterType !== this.filterType) {
  2705. return;
  2706. }
  2707. this.filterSongs = videoItems;
  2708. if (videoItems.length === 0) {
  2709. void ServerLogUtil.warn('NavidromeFilter', '筛选下暂无歌曲');
  2710. } else {
  2711. void ServerLogUtil.info('NavidromeFilter', `筛选歌曲加载完成: ${videoItems.length} 首`);
  2712. }
  2713. } finally {
  2714. this.isFilterLoading = false;
  2715. }
  2716. }
  2717. private clearFilter(): void {
  2718. this.filterType = NavFilterType.None;
  2719. this.filterId = '';
  2720. this.filterLabel = '';
  2721. this.filterSongs = [];
  2722. this.isFilterLoading = false;
  2723. // 退出详情视图
  2724. this.isDetailView = false;
  2725. }
  2726. private playSong(song: VideoItem, index: number, isJump: boolean = false): void {
  2727. try {
  2728. if (!this.allVideos || this.allVideos.length === 0) {
  2729. ToastUtil.showToast('暂无可播放的歌曲');
  2730. return;
  2731. }
  2732. const account = this.resolveActiveAccount();
  2733. if (!account || !account.id) {
  2734. ToastUtil.showToast('媒体库账号信息不完整,无法播放');
  2735. return;
  2736. }
  2737. // 记录播放详细信息
  2738. void ServerLogUtil.info('NavidromePlay', `开始播放歌曲: ${song.name} (#${index})`);
  2739. void ServerLogUtil.info('NavidromePlay', `歌曲信息:`);
  2740. void ServerLogUtil.info('NavidromePlay', `- ID: ${song.id}`);
  2741. void ServerLogUtil.info('NavidromePlay', `- 艺术家: ${song.artist || '未知'}`);
  2742. void ServerLogUtil.info('NavidromePlay', `- 专辑: ${song.album || '未知'}`);
  2743. void ServerLogUtil.info('NavidromePlay', `- 文件大小: ${song.size || '未知'}`);
  2744. void ServerLogUtil.info('NavidromePlay', `- 时长: ${song.duration || '未知'}`);
  2745. void ServerLogUtil.info('NavidromePlay', `- 封面: ${song.pixelMapPath ? '有' : '无'}`);
  2746. void ServerLogUtil.info('NavidromePlay', `- 播放路径: ${song.filePath}`);
  2747. const playlistSource = this.getVisibleSongs().length > 0 ? this.getVisibleSongs() : this.allVideos;
  2748. const targetIndex = playlistSource.findIndex(item => item.id === song.id);
  2749. const startIndex = targetIndex >= 0 ? targetIndex : Math.min(index, Math.max(playlistSource.length - 1, 0));
  2750. void ServerLogUtil.info('NavidromePlay', `播放列表设置: 起始索引 ${startIndex}, 总数 ${playlistSource.length}`);
  2751. setNavidromePlaylist(playlistSource, startIndex);
  2752. const playlistData: PlaylistEventData = {
  2753. playlistId: NAVIDROME_PLAYLIST_ID,
  2754. playlistName: `${getRemoteDriveDisplayLabel(account.webType)} - ${account.name ?? '未知账户'}`,
  2755. songCount: playlistSource.length,
  2756. startIndex,
  2757. isJump: isJump,//设置true会弹出播放页
  2758. songFilePaths: playlistSource.map(item => item.filePath)
  2759. };
  2760. const eventPlaylistPlay: emitter.InnerEvent = { eventId: EventConstants.EVENT_PLAYLIST_PLAY };
  2761. emitter.emit(eventPlaylistPlay, { data: playlistData });
  2762. void ServerLogUtil.info('NavidromePlay', `播放事件已发送`);
  2763. void ServerLogUtil.debug('NavidromePlay', `播放事件详情: 列表ID=${playlistData.playlistId}, 列表名称=${playlistData.playlistName}, 歌曲数=${playlistData.songCount}, 起始索引=${playlistData.startIndex}, 是否跳转=${playlistData.isJump}`);
  2764. if(!this.isNoJumpToHome){
  2765. void ServerLogUtil.debug('NavidromePlay', '跳转到首页播放器');
  2766. // 跳转到首页播放器
  2767. this.getUIContext()?.animateTo({ duration: 555 }, () => {
  2768. this.mType = 0
  2769. })
  2770. }
  2771. } catch (error) {
  2772. const err = error as Error;
  2773. void ServerLogUtil.error('NavidromePlay', `播放失败: ${err.message}`);
  2774. void ServerLogUtil.error('NavidromePlay', `失败歌曲信息: ${song.name} (${song.id})`);
  2775. ToastUtil.showToast('播放失败');
  2776. }
  2777. }
  2778. @Builder
  2779. buildContentView(){
  2780. // 主内容区域
  2781. if (this.loading) {
  2782. Column() {
  2783. LoadingProgress()
  2784. .width(50)
  2785. .height(50)
  2786. .color($r('app.color.title_bar_bg'))
  2787. Text('加载中...')
  2788. .margin({ top: 10 })
  2789. .fontSize(14)
  2790. .fontColor($r('app.color.index_tab_unselected_font_color'))
  2791. }
  2792. .width('100%')
  2793. .layoutWeight(1)
  2794. .padding({top:this.topSafeHeight+98})
  2795. .justifyContent(FlexAlign.Center)
  2796. } else {
  2797. if (this.isSearchMode && this.selectedTab === 0 && this.searchText.length > 0 && this.isSearchLoading) {
  2798. Column() {
  2799. LoadingProgress()
  2800. .width(40)
  2801. .height(40)
  2802. .color(this.themeColor)
  2803. Text('正在通过 API 搜索歌曲...')
  2804. .margin({ top: 12 })
  2805. .fontSize(14)
  2806. .fontColor($r('app.color.index_tab_unselected_font_color'))
  2807. }
  2808. .width('100%')
  2809. .layoutWeight(1)
  2810. } else if (this.selectedTab === 0 && this.filterType !== NavFilterType.None && this.isFilterLoading) {
  2811. Column() {
  2812. LoadingProgress()
  2813. .width(40)
  2814. .height(40)
  2815. .color(this.themeColor)
  2816. Text('正在加载筛选歌曲...')
  2817. .margin({ top: 12 })
  2818. .fontSize(14)
  2819. .fontColor($r('app.color.index_tab_unselected_font_color'))
  2820. }
  2821. .width('100%')
  2822. .layoutWeight(1)
  2823. } else {
  2824. List({scroller:this.scroller, space: 8 }) {
  2825. // 详情视图模式下显示筛选后的歌曲,否则根据标签页显示对应内容
  2826. if (this.selectedTab === 0||this.isDetailView) {
  2827. ForEach(this.getVisibleSongs(), (item: VideoItem, index: number) => {
  2828. ListItem() {
  2829. this.buildSongItem(item, index)
  2830. }
  2831. }, (item: VideoItem) => item.id)
  2832. } else if (this.selectedTab === 1) {
  2833. ForEach(this.artists, (artist: NavidromeRestArtist) => {
  2834. ListItem() {
  2835. this.buildArtistItem(artist)
  2836. }
  2837. }, (artist: NavidromeRestArtist) => artist.id)
  2838. } else if (this.selectedTab === 2) {
  2839. ForEach(this.albums, (album: NavidromeRestAlbum) => {
  2840. ListItem() {
  2841. this.buildAlbumItem(album)
  2842. }
  2843. }, (album: NavidromeRestAlbum) => album.id)
  2844. } else if (this.selectedTab === 3) {
  2845. ForEach(this.playlists, (playlist: NavidromeRestPlaylist) => {
  2846. ListItem() {
  2847. this.buildPlaylistItem(playlist)
  2848. }
  2849. }, (playlist: NavidromeRestPlaylist) => playlist.id)
  2850. }
  2851. }
  2852. .onScrollFrameBegin((offset: number) => {
  2853. // 获取当前滚动偏移量
  2854. if(this.autoHideTitle){
  2855. const currentOffsetY = this.scroller.currentOffset().yOffset;
  2856. // 判断滚动方向
  2857. if (currentOffsetY > this.prevOffsetY) {
  2858. this.isShowTitleBar = false
  2859. } else if (currentOffsetY < this.prevOffsetY) {
  2860. this.isShowTitleBar = true
  2861. }
  2862. // 更新前一次偏移量
  2863. this.prevOffsetY = currentOffsetY;
  2864. }
  2865. return { offsetRemain: offset };
  2866. })
  2867. .width('100%')
  2868. .height('100%')
  2869. .layoutWeight(1)
  2870. .cachedCount(3)
  2871. .padding({ top: 5, bottom: 5 })
  2872. .listDirection(Axis.Vertical)
  2873. .contentEndOffset(this.bottomSafeHeight+70)
  2874. .contentStartOffset(this.topSafeHeight + 98)
  2875. .scrollBar(BarState.Auto)
  2876. .edgeEffect(EdgeEffect.Spring)
  2877. .onReachEnd(() => {
  2878. void this.handleReachEnd();
  2879. })
  2880. }
  2881. // 空状态
  2882. if (this.getCurrentCount() === 0 && !(this.selectedTab === 0 && this.filterType !== NavFilterType.None && this.isFilterLoading) && !(this.isSearchMode && this.searchText.length > 0 && this.isSearchLoading)) {
  2883. Column() {
  2884. SymbolGlyph($r('sys.symbol.music_fill'))
  2885. .fontSize(50)
  2886. .opacity(0.3)
  2887. Text(this.getEmptyTitle())
  2888. .margin({ top: 16 })
  2889. .fontSize(16)
  2890. .fontColor($r('app.color.index_tab_unselected_font_color'))
  2891. Text(this.getEmptySubtitle())
  2892. .margin({ top: 8 })
  2893. .fontSize(14)
  2894. .fontColor($r('app.color.index_tab_unselected_font_color'))
  2895. }
  2896. .width('100%')
  2897. .height('100%')
  2898. .justifyContent(FlexAlign.Center)
  2899. }
  2900. }
  2901. }
  2902. build() {
  2903. Stack() {
  2904. Column() {
  2905. this.buildContentView()
  2906. }
  2907. .height('100%')
  2908. Column() {
  2909. this.topTitleBar()
  2910. }
  2911. .visibility(this.isShowTitleBar?Visibility.Visible:
  2912. this.autoHideTitle?Visibility.None:Visibility.Visible)
  2913. .animation({
  2914. duration: 500,
  2915. curve: Curve.Friction // 可选动画曲线
  2916. })
  2917. }
  2918. .alignContent(Alignment.Top)
  2919. .width('100%')
  2920. .height('100%')
  2921. .backgroundImage(this.isCustomizeBg?this.customizeBgPath:$r('app.color.start_window_background'))
  2922. .backgroundImageSize(this.isLandscape?{width:'100%'}:{ height: '100%'})
  2923. .backgroundImagePosition(Alignment.Center)
  2924. .backdropBlur(this.blurValue)
  2925. .backgroundBrightness({rate:this.isCustomizeBg?0.1:0,lightUpDegree:this.bgBrightness})
  2926. .expandSafeArea([SafeAreaType.SYSTEM], [SafeAreaEdge.BOTTOM])
  2927. }
  2928. }
  2929. /**
  2930. * Navidrome 数据加载任务 (使用 taskpool 后台执行)
  2931. * 该函数在 worker 线程中运行,避免阻塞 UI 线程
  2932. */
  2933. @Concurrent
  2934. async function loadNavidromeDataTask(accountData: AccountData, ticket: number): Promise<TaskResult> {
  2935. const result: TaskResult = {
  2936. songs: [],
  2937. artists: [],
  2938. albums: [],
  2939. playlists: []
  2940. };
  2941. try {
  2942. // 从 AccountData 重建 WebDavAccount 对象 (用于 API 调用)
  2943. const account: WebDavAccount = new WebDavAccount();
  2944. account.id = accountData.id;
  2945. account.webType = accountData.webType;
  2946. account.host = accountData.host;
  2947. account.port = accountData.port;
  2948. account.account = accountData.account;
  2949. account.password = accountData.password;
  2950. account.enableHttps = accountData.enableHttps;
  2951. account.navidromeBasePath = accountData.navidromeBasePath;
  2952. account.jellyfinBasePath = accountData.jellyfinBasePath;
  2953. account.embyBasePath = accountData.embyBasePath;
  2954. account.name = accountData.name;
  2955. // 加载歌曲并转换成 VideoItem(包含封面)
  2956. let songNextStart: number | null = 0;
  2957. while (songNextStart !== null) {
  2958. const response: PagedResponse<NavidromeRestSong> = await navidromeRestApi.fetchSongPage(account, songNextStart);
  2959. const chunk: NavidromeRestSong[] = response.data ?? [];
  2960. if (chunk.length === 0) {
  2961. break;
  2962. }
  2963. // 转换歌曲为 VideoItem 并处理封面
  2964. for (let i = 0; i < chunk.length; i++) {
  2965. const song: NavidromeRestSong = chunk[i];
  2966. const title: string = song.title ?? Constants.UNKNOWN_TITLE;
  2967. // 获取库类型
  2968. let libraryType = CommonConstants.TYPE_NAVIDROME;
  2969. let libraryScheme = 'navidrome';
  2970. if (account.webType === RemoteDriveType.Jellyfin) {
  2971. libraryType = CommonConstants.TYPE_JELLYFIN;
  2972. libraryScheme = 'jellyfin';
  2973. } else if (account.webType === RemoteDriveType.Emby) {
  2974. libraryType = CommonConstants.TYPE_EMBY;
  2975. libraryScheme = 'emby';
  2976. }
  2977. const videoItem = new VideoItem(
  2978. title,
  2979. song.id,
  2980. `${libraryScheme}://${account.id ?? 0}/${song.id}`,
  2981. libraryType,
  2982. song.size ?? 0,
  2983. song.createdAt ?? '',
  2984. Utility.formatFSize(song.size ?? 0),
  2985. undefined,
  2986. song.artist ?? Constants.UNKNOWN_ARTIST,
  2987. song.album ?? '',
  2988. `${title}${song.suffix ? '.' + song.suffix : ''}`
  2989. );
  2990. // 设置时长
  2991. if (song.duration !== undefined && song.duration !== null && song.duration >= 0) {
  2992. const totalSeconds = Math.floor(song.duration);
  2993. const minutes = Math.floor(totalSeconds / 60);
  2994. const seconds = totalSeconds % 60;
  2995. const pad = (value: number) => value.toString().padStart(2, '0');
  2996. videoItem.duration = `${pad(minutes)}:${pad(seconds)}`;
  2997. }
  2998. videoItem.size = Utility.formatFSize(song.size ?? 0);
  2999. videoItem.bit_rate = song.bitRate ? song.bitRate.toString() : undefined;
  3000. videoItem.genre = song.genre;
  3001. videoItem.webdav_account_id = account.id?.toString();
  3002. videoItem.remote_rel_path = song.id;
  3003. videoItem.navArtistId = song.artistId;
  3004. videoItem.navAlbumId = song.albumId;
  3005. videoItem.lyricContent = song.lyrics;
  3006. if (song.track !== undefined && song.track !== null) {
  3007. videoItem.track = song.track.toString();
  3008. }
  3009. if (song.year !== undefined && song.year !== null) {
  3010. videoItem.year = song.year.toString();
  3011. }
  3012. if (song.contentType) {
  3013. videoItem.mimeType = song.contentType;
  3014. }
  3015. // 处理封面(在 worker 线程中调用 API)
  3016. let coverUrl: string | undefined = undefined;
  3017. try {
  3018. // 获取封面ID
  3019. const coverId = song.coverArt ?? song.coverArtId ?? song.id;
  3020. // 判断是否是 Navidrome 账号
  3021. const isNavidrome = account.webType === RemoteDriveType.Navidrome;
  3022. if (!isNavidrome) {
  3023. // Jellyfin/Emby 直接使用 albumId 或 id
  3024. const fallbackId = song.albumId ?? song.id;
  3025. coverUrl = await navidromeApi.buildCoverArtUrl(account, fallbackId, 300);
  3026. } else {
  3027. // Navidrome 优先使用直接封面路径
  3028. const embedArtPath = song.embedArtPath ?? song.coverArtPath;
  3029. if (embedArtPath) {
  3030. // 构建直接封面URL
  3031. const protocol = account.enableHttps ? 'https' : 'http';
  3032. const host = account.isUseLocalHost && account.localHost ? account.localHost : account.host;
  3033. const portPart = account.port && account.port !== 80 && account.port !== 443 ? `:${account.port}` : '';
  3034. const basePath = account.navidromeBasePath ?? '/rest';
  3035. // 移除 /rest 后缀
  3036. const apiBase = basePath.endsWith('/rest') ? basePath.slice(0, -5) : basePath;
  3037. coverUrl = `${protocol}://${host}${portPart}${apiBase}/embed/${embedArtPath}?${account.account}:${account.password}`;
  3038. } else {
  3039. // 使用封面API
  3040. coverUrl = await navidromeApi.buildCoverArtUrl(account, coverId, 300);
  3041. }
  3042. }
  3043. } catch (error) {
  3044. // 封面获取失败,忽略
  3045. }
  3046. videoItem.pixelMapPath = coverUrl;
  3047. result.songs.push(videoItem);
  3048. }
  3049. songNextStart = response.nextStart;
  3050. }
  3051. // 加载艺术家并处理封面
  3052. let artistNextStart: number | null = 0;
  3053. while (artistNextStart !== null) {
  3054. const response: PagedResponse<NavidromeRestArtist> = await navidromeRestApi.fetchArtistPage(account, artistNextStart);
  3055. const chunk: NavidromeRestArtist[] = response.data ?? [];
  3056. if (chunk.length === 0) {
  3057. break;
  3058. }
  3059. // 处理艺术家封面
  3060. for (let i = 0; i < chunk.length; i++) {
  3061. const artist = chunk[i];
  3062. // 尝试获取已有图片URL
  3063. let coverUrl: string | undefined = artist.mediumImageUrl ?? artist.largeImageUrl;
  3064. // 如果没有直接URL,生成封面URL
  3065. if (!coverUrl) {
  3066. const coverId = artist.coverArt ?? artist.coverArtId ?? (artist.id ? `ar-${artist.id}` : undefined);
  3067. try {
  3068. coverUrl = await navidromeApi.buildCoverArtUrl(account, coverId, 256);
  3069. } catch (error) {
  3070. // 封面生成失败,忽略
  3071. }
  3072. }
  3073. artist.coverUrl = coverUrl;
  3074. result.artists.push(artist);
  3075. }
  3076. artistNextStart = response.nextStart;
  3077. }
  3078. // 加载专辑并处理封面
  3079. let albumNextStart: number | null = 0;
  3080. while (albumNextStart !== null) {
  3081. const response: PagedResponse<NavidromeRestAlbum> = await navidromeRestApi.fetchAlbumPage(account, albumNextStart);
  3082. const chunk: NavidromeRestAlbum[] = response.data ?? [];
  3083. if (chunk.length === 0) {
  3084. break;
  3085. }
  3086. // 处理专辑封面
  3087. for (let i = 0; i < chunk.length; i++) {
  3088. const album = chunk[i];
  3089. // 专辑没有直接的 imageUrl 属性,需要生成封面URL
  3090. let coverUrl: string | undefined = undefined;
  3091. // 优先使用 embed 路径
  3092. if (album.embedArtPath) {
  3093. const protocol = account.enableHttps ? 'https' : 'http';
  3094. const host = account.isUseLocalHost && account.localHost ? account.localHost : account.host;
  3095. const portPart = account.port && account.port !== 80 && account.port !== 443 ? `:${account.port}` : '';
  3096. const basePath = account.navidromeBasePath ?? '/rest';
  3097. const apiBase = basePath.endsWith('/rest') ? basePath.slice(0, -5) : basePath;
  3098. coverUrl = `${protocol}://${host}${portPart}${apiBase}/embed/${album.embedArtPath}?${account.account}:${account.password}`;
  3099. }
  3100. // 如果没有 embed 路径,使用封面API
  3101. if (!coverUrl) {
  3102. const coverId = album.coverArt ?? album.coverArtId ?? album.id;
  3103. try {
  3104. coverUrl = await navidromeApi.buildCoverArtUrl(account, coverId, 300);
  3105. } catch (error) {
  3106. // 封面生成失败,忽略
  3107. }
  3108. }
  3109. album.coverUrl = coverUrl;
  3110. result.albums.push(album);
  3111. }
  3112. albumNextStart = response.nextStart;
  3113. }
  3114. // 加载歌单
  3115. let playlistNextStart: number | null = 0;
  3116. while (playlistNextStart !== null) {
  3117. const response: PagedResponse<NavidromeRestPlaylist> = await navidromeRestApi.fetchPlaylistPage(account, playlistNextStart);
  3118. const chunk: NavidromeRestPlaylist[] = response.data ?? [];
  3119. if (chunk.length === 0) {
  3120. break;
  3121. }
  3122. // 使用循环代替展开运算符
  3123. for (let i = 0; i < chunk.length; i++) {
  3124. result.playlists.push(chunk[i]);
  3125. }
  3126. playlistNextStart = response.nextStart;
  3127. }
  3128. } catch (error) {
  3129. Logger.error('NavidromeTask', `后台加载数据失败: ${(error as Error).message}`);
  3130. }
  3131. return result;
  3132. }