RemoteMusicPage.ets 144 KB

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