NavidromePage.ets 140 KB

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