RemoteMusicPage.ets 183 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911
  1. import { VideoItem } from '../viewmodel/VideoItem';
  2. import { LengthMetrics, SegmentButton, SegmentButtonItemTuple, SegmentButtonOptions,
  3. SymbolGlyphModifier } from '@kit.ArkUI';
  4. import {
  5. PreferencesUtil, ToastUtil, StrUtil
  6. } from '@pura/harmony-utils';
  7. import {
  8. ButtonFancyModifier,
  9. SymbolGlyphFancyModifier,
  10. ShadowModifier
  11. } from '../common/util/AttributeModifierUtil';
  12. import { CommonConstants } from '../common/constants/CommonConstants';
  13. import { WebDavAccount } from '../viewmodel/WebDavAccount';
  14. import Logger from '../common/util/Logger';
  15. import { RemoteDriveType } from '../common/enums/RemoteDriveType';
  16. import { navidromeRestApi, NavidromeRestAlbum, NavidromeRestArtist, NavidromeRestSong, NavidromeRestPlaylist } from '../common/network/NavidromeRestApi';
  17. import { Utility } from '../common/util/Utility';
  18. import { Constants } from '../Constants';
  19. import { EventConstants } from '../common/constants/EventConstants';
  20. import { emitter } from '@kit.BasicServicesKit';
  21. import { setNavidromePlaylist, appendToNavidromePlaylist, setNavidromeTotalCount } from '../common/util/NavidromePlaylistStore';
  22. import { registerLoadMoreCallback, unregisterLoadMoreCallback } from '../common/util/NavidromeRandomLoader';
  23. import { navidromeApi, NavidromeSong } from '../common/network/NavidromeApi';
  24. import { ServerLogUtil } from '../common/util/ServerLogUtil';
  25. import { RemoteDriveManager } from '../common/util/RemoteDriveManager';
  26. import { SettingPage } from '../pages/SettingPage';
  27. import { jellyfinApi, JellyfinAlbum, JellyfinArtist, JellyfinSong } from '../common/network/JellyfinApi';
  28. import { embyApi, EmbyAlbum, EmbyArtist, EmbySong } from '../common/network/EmbyApi';
  29. import { audioStationApi, AudioStationAlbum, AudioStationArtist, AudioStationPlaylist, AudioStationSong } from '../common/network/AudioStationApi';
  30. import { plexApi, PlexAlbum, PlexArtist, PlexPlaylist, PlexSong } from '../common/network/PlexApi';
  31. import { daoLiYuApi, DaoLiYuAlbum, DaoLiYuArtist, DaoLiYuTrack, DaoLiYuPlaylist } from '../common/network/DaoLiYuApi';
  32. import { getRemoteDriveDisplayLabel } from '../common/util/RemoteDriveLabel';
  33. import NavidromeListCache, { AllCacheData } from '../common/util/NavidromeListCache';
  34. import { LazyDataSource } from '../common/util/LazyDataSource';
  35. import { taskpool } from '@kit.ArkTS';
  36. const NAVIDROME_PLAYLIST_ID = 'navidrome-playlist';
  37. const NAVIDROME_SEARCH_LIMIT = 500;
  38. const ITEM_HEIGHT_SMALL: number = 48; // 列表项小高度
  39. const ITEM_HEIGHT: number = 65; // 列表项中高度
  40. const ITEM_HEIGHT_BIG: number = 78; // 列表项大高度
  41. interface PlaylistEventData {
  42. playlistId: string;
  43. playlistName: string;
  44. songCount: number;
  45. startIndex: number;
  46. isJump: boolean;
  47. songFilePaths: string[];
  48. }
  49. enum NavFilterType {
  50. None = 0,
  51. Artist = 1,
  52. Album = 2,
  53. Playlist = 3
  54. }
  55. interface CachePreviewInfo {
  56. cacheRoot: string;
  57. examplePath: string;
  58. }
  59. interface LibraryInfo {
  60. type: number;
  61. scheme: string;
  62. }
  63. class AudioStationAlbumKey {
  64. name: string;
  65. artist: string;
  66. constructor(name: string, artist: string) {
  67. this.name = name;
  68. this.artist = artist;
  69. }
  70. }
  71. /**
  72. * taskpool 任务结果接口
  73. * 返回带封面的完整数据
  74. */
  75. interface TaskResult {
  76. songs: VideoItem[];
  77. artists: NavidromeRestArtist[];
  78. albums: NavidromeRestAlbum[];
  79. playlists: NavidromeRestPlaylist[];
  80. }
  81. /**
  82. * Navidrome API 分页响应接口
  83. */
  84. interface PagedResponse<T> {
  85. data: T[];
  86. nextStart: number | null;
  87. }
  88. /**
  89. * Account 序列化数据接口 (用于 taskpool 传递)
  90. */
  91. interface AccountData {
  92. id: number;
  93. webType: number;
  94. host: string;
  95. port: number;
  96. account: string;
  97. password: string;
  98. enableHttps: boolean;
  99. navidromeBasePath: string;
  100. jellyfinBasePath: string;
  101. embyBasePath: string;
  102. name: string;
  103. }
  104. @Component
  105. export struct RemoteMusicPage {
  106. private gridScroller: Scroller = new Scroller()
  107. private waterScroller: Scroller = new Scroller()
  108. @State isGridMusic: boolean = false //是否网格布局
  109. @State twoFingerType: number = 3 //双指放大缩小的类型 (1=List小, 2=List中, 3=Grid大, 4=WaterFlow)
  110. @State scaleValue: number = 1 //缩放值
  111. @State columns: number = 4 //瀑布流列数
  112. @State isWaterFlowScrolling: boolean = false //WaterFlow是否正在滚动
  113. @State isShowTitleBar: boolean = true //是否显示分类导航条
  114. private scroller: Scroller = new Scroller()
  115. private prevOffsetY: number = 0; // 记录上一次的Y轴偏移量
  116. @State autoHideTitle: boolean = true //滚动自动隐藏标题栏
  117. @State isCustomizeBg: boolean = false //自定义背景界面
  118. @StorageProp('isLandscape') isLandscape: boolean = false;
  119. @State blurValue: number = 0 //背景模糊
  120. @State bgBrightness: number = 0 //背景亮度
  121. @State customizeBgPath: string | undefined = '';
  122. @Link mType: number;
  123. @Link offsetX: number;
  124. @Link isShowDrawer: boolean;
  125. @State isNoJumpToHome: boolean = false //网盘播放不跳转首页
  126. @StorageProp('bottomSafeHeight') bottomSafeHeight: number = 0;
  127. @Prop @Watch('onSwitchAccount') selectedAccount: WebDavAccount;
  128. @StorageProp('currentTheme') currentTheme: number = 0;
  129. @State selectedTab: number = 0; // 0: 全部, 1: 艺术家, 2: 专辑
  130. @State allVideos: VideoItem[] = [];
  131. @State artists: NavidromeRestArtist[] = [];
  132. @State albums: NavidromeRestAlbum[] = [];
  133. @State playlists: NavidromeRestPlaylist[] = [];
  134. // LazyForEach 数据源实例
  135. private songDataSource: LazyDataSource<VideoItem> = new LazyDataSource<VideoItem>([]);
  136. private artistDataSource: LazyDataSource<NavidromeRestArtist> = new LazyDataSource<NavidromeRestArtist>([]);
  137. private albumDataSource: LazyDataSource<NavidromeRestAlbum> = new LazyDataSource<NavidromeRestAlbum>([]);
  138. private playlistDataSource: LazyDataSource<NavidromeRestPlaylist> = new LazyDataSource<NavidromeRestPlaylist>([]);
  139. @State loading: boolean = false;
  140. @State songNextStart: number | null = 0;
  141. @State artistNextStart: number | null = 0;
  142. @State albumNextStart: number | null = 0;
  143. @State playlistNextStart: number | null = 0;
  144. @State isSongPageLoading: boolean = false;
  145. @State isArtistPageLoading: boolean = false;
  146. @State isAlbumPageLoading: boolean = false;
  147. @State isPlaylistPageLoading: boolean = false;
  148. @State serverTotalSongCount: number = 0; // 服务端返回的歌曲总数
  149. // 新增:详情视图状态
  150. @Link isDetailView: boolean; // 是否在艺术家/专辑详情视图
  151. @State previousTab: number = 0; // 进入详情视图前的标签页索引
  152. @StorageProp('isDarkMode') isDarkMode: boolean = false;
  153. @StorageLink('currentSong') currentSong: VideoItem | undefined = undefined;
  154. @StorageProp('topSafeHeight') topSafeHeight: number = 0;
  155. @State @Watch('onTabSelectedIndexesChanged') tabSelectedIndexes: number[] = [0];
  156. @StorageProp('themeColor') themeColor: string =
  157. PreferencesUtil.getStringSync('THEME_COLOR', CommonConstants.DEFAULT_THEME_COLOR);
  158. private tabs: string[] = ['全部', '艺术家', '专辑', '歌单'];
  159. private loadTicket: number = 0;
  160. @State filterType: NavFilterType = NavFilterType.None;
  161. @State filterLabel: string = '';
  162. @State filterId: string = '';
  163. @State filterSongs: VideoItem[] = [];
  164. @State isFilterLoading: boolean = false;
  165. private coverUrlCache: Map<string, string> = new Map();
  166. private albumCoverLookup: Map<string, string> = new Map();
  167. private searchTicket: number = 0;
  168. private readonly REMOTE_PAGE_SIZE: number = 200;
  169. private jellyfinSongIdSeen: Set<string> = new Set();
  170. private embySongIdSeen: Set<string> = new Set();
  171. private jellyfinSongKeySeen: Set<string> = new Set();
  172. private embySongKeySeen: Set<string> = new Set();
  173. private listCache = NavidromeListCache.getInstance();
  174. private isNavidromeAccount(account: WebDavAccount): boolean {
  175. return account.webType === RemoteDriveType.Navidrome;
  176. }
  177. private isJellyfinAccount(account: WebDavAccount): boolean {
  178. return account.webType === RemoteDriveType.Jellyfin;
  179. }
  180. private isEmbyAccount(account: WebDavAccount): boolean {
  181. return account.webType === RemoteDriveType.Emby;
  182. }
  183. private isAudioStationAccount(account: WebDavAccount): boolean {
  184. return account.webType === RemoteDriveType.AudioStation;
  185. }
  186. private isPlexAccount(account: WebDavAccount): boolean {
  187. return account.webType === RemoteDriveType.Plex;
  188. }
  189. private isDaoLiYuAccount(account: WebDavAccount): boolean {
  190. return account.webType === RemoteDriveType.DaoLiYu;
  191. }
  192. private createTabOptions(): SegmentButtonOptions {
  193. const buttons = [
  194. { text: '全部' },
  195. { text: '艺术家' },
  196. { text: '专辑' },
  197. { text: '歌单' }
  198. ] as SegmentButtonItemTuple;
  199. return SegmentButtonOptions.capsule({
  200. buttons,
  201. direction: Direction.Ltr,
  202. buttonPadding: { top: 10, bottom: 10 },
  203. backgroundColor: $r('app.color.index_background'),
  204. selectedBackgroundColor: $r('app.color.start_window_background'),
  205. selectedFontColor: $r('app.color.text_color'),
  206. fontSize: 14,
  207. selectedFontSize: 15
  208. });
  209. }
  210. private getCachePreviewInfo(account: WebDavAccount): CachePreviewInfo | null {
  211. try {
  212. const manager = RemoteDriveManager.getInstance();
  213. const context = manager.context;
  214. if (!context) {
  215. return null;
  216. }
  217. const baseDir = context.filesDir ?? context.cacheDir;
  218. if (!baseDir) {
  219. return null;
  220. }
  221. const accountId = account.id?.toString() || 'default';
  222. const cacheRoot = `${baseDir}/remote_cache/webdav/${accountId}`;
  223. const examplePath = `${cacheRoot}/navidrome_preview.cache`;
  224. return { cacheRoot, examplePath };
  225. } catch (error) {
  226. Logger.error('RemoteMusicPage', `获取缓存预览路径失败: ${(error as Error).message}`);
  227. return null;
  228. }
  229. }
  230. // 搜索和排序相关状态
  231. @State isSearchMode: boolean = false;
  232. @State searchText: string = ''; // 用户输入内容
  233. @State filteredList: Array<VideoItem> = []; // 过滤后的歌曲结果
  234. @State sortType: number = 0; // 排序类型 0:名称升序 1:名称降序 2:时间升序 3:时间降序 4:大小升序 5:大小降序
  235. @State isSearchLoading: boolean = false;
  236. private readonly REMOTE_SEARCH_LIMIT: number = 500;
  237. // SegmentButton选项
  238. @State tabOptions: SegmentButtonOptions = this.createTabOptions();
  239. //当胶囊按钮的选择发生变化时调用此函数
  240. onTabSelectedIndexesChanged() {
  241. this.selectedTab = this.tabSelectedIndexes[0];
  242. console.info('heanup', `Selected tab: ${this.tabs[this.selectedTab]}`);
  243. // 如果在详情视图模式下切换标签页,退出详情视图并清除筛选
  244. if (this.isDetailView) {
  245. this.isDetailView = false;
  246. this.clearFilter();
  247. }
  248. // 从艺术家或专辑切换回全部时,清除筛选状态
  249. if (this.selectedTab === 0 && this.filterType !== NavFilterType.None) {
  250. // 不清除筛选,保持筛选状态
  251. } else if (this.selectedTab !== 0) {
  252. // 切换到艺术家或专辑标签页时,清除筛选和搜索状态
  253. this.clearFilter();
  254. this.isSearchMode = false;
  255. this.searchText = '';
  256. this.filteredList = [];
  257. this.isSearchLoading = false;
  258. this.searchTicket++;
  259. }
  260. }
  261. //切换不同的RemoteMusicPage
  262. async onSwitchAccount() {
  263. await this.refreshNavidromeData(true);
  264. }
  265. initSetting(){
  266. this.isCustomizeBg = PreferencesUtil.getBooleanSync(SettingPage.IS_CUSTOMIZE_BG, false)
  267. this.customizeBgPath = PreferencesUtil.getStringSync(SettingPage.IS_CUSTOMIZE_BG_PATH, '')
  268. this.blurValue = PreferencesUtil.getNumberSync(SettingPage.CUSTOMIZE_BG_BLUR, 0)
  269. this.bgBrightness = PreferencesUtil.getNumberSync(SettingPage.BG_BRIGHTNESS, 0)
  270. this.isNoJumpToHome = PreferencesUtil.getBooleanSync('isNoJumpToHome', true)
  271. this.sortType = PreferencesUtil.getNumberSync('navidromeSortType', 0);
  272. this.isShowTitleBar = PreferencesUtil.getBooleanSync(SettingPage.IS_SHOW_TITLTBAR, true)
  273. this.autoHideTitle = PreferencesUtil.getBooleanSync('autoHideTitle', true)
  274. this.twoFingerType = PreferencesUtil.getNumberSync(SettingPage.TWO_FINGER_TYPE, 3)
  275. this.isGridMusic = PreferencesUtil.getBooleanSync(SettingPage.IS_GRID_MUSIC, false)
  276. }
  277. aboutToAppear() {
  278. this.initSetting()
  279. let eventSetting: emitter.InnerEvent = { eventId: 333 }
  280. // 监听广播事件(通用设置配置更新)
  281. emitter.on(eventSetting, (eventData: emitter.EventData) => {
  282. this.initSetting()
  283. });
  284. // 监听手势返回事件
  285. let eventBackSwipeBack: emitter.InnerEvent = { eventId: EventConstants.EVENT_SWIPE_BACK_NAVID }
  286. emitter.on(eventBackSwipeBack, (eventData: emitter.EventData) => {
  287. console.info('heanup', 'RemoteMusicPage 收到 EVENT_SWIPE_BACK_NAVID 事件');
  288. // 如果在详情视图模式,退出详情视图
  289. if (this.isDetailView) {
  290. this.getUIContext().animateTo({ duration: 555 }, () => {
  291. this.isDetailView = false;
  292. this.clearFilter();
  293. })
  294. }
  295. });
  296. // 注册加载更多页回调(用于渐进式随机播放)
  297. this.registerRandomLoadCallback();
  298. this.refreshNavidromeData();
  299. }
  300. /**
  301. * 注册加载更多页回调函数(供LocalMusic的randomPlay调用)
  302. */
  303. private registerRandomLoadCallback(): void {
  304. registerLoadMoreCallback(
  305. // 加载一页数据并返回新增歌曲
  306. async (): Promise<VideoItem[]> => {
  307. const account = this.resolveActiveAccount();
  308. if (!account) {
  309. return [];
  310. }
  311. // 记录加载前的数量
  312. const beforeCount = this.allVideos.length;
  313. // 根据账户类型调用对应的加载方法
  314. await this.loadNextSongPageByAccountType(account);
  315. // 获取新增的歌曲
  316. const newItems = this.allVideos.slice(beforeCount);
  317. // 同步到播放列表存储
  318. if (newItems.length > 0) {
  319. appendToNavidromePlaylist(newItems);
  320. void ServerLogUtil.info('NavidromeRandom', `加载更多: 新增${newItems.length}首,总数${this.allVideos.length}`);
  321. }
  322. return newItems;
  323. },
  324. // 检查是否还有更多数据
  325. (): boolean => {
  326. return this.songNextStart !== null && !this.isSongPageLoading;
  327. }
  328. );
  329. }
  330. /**
  331. * 根据账户类型调用对应的歌曲加载方法
  332. */
  333. private async loadNextSongPageByAccountType(account: WebDavAccount): Promise<void> {
  334. if (this.isJellyfinAccount(account)) {
  335. await this.loadNextJellyfinSongPage(account);
  336. } else if (this.isEmbyAccount(account)) {
  337. await this.loadNextEmbySongPage(account);
  338. } else if (this.isAudioStationAccount(account)) {
  339. await this.loadNextAudioStationSongPage(account);
  340. } else if (this.isPlexAccount(account)) {
  341. await this.loadNextPlexSongPage(account);
  342. } else if (this.isDaoLiYuAccount(account)) {
  343. await this.loadNextDaoLiYuSongPage(account);
  344. } else {
  345. // 默认使用 Navidrome
  346. await this.loadNextSongPage(account);
  347. }
  348. }
  349. private async refreshNavidromeData(showToastWhenMissing: boolean = false): Promise<void> {
  350. const account = this.resolveActiveAccount();
  351. if (!account) {
  352. this.resetData();
  353. if (showToastWhenMissing) {
  354. ToastUtil.showToast('请先选择媒体库账号');
  355. }
  356. return;
  357. }
  358. // 记录日志开关状态
  359. void ServerLogUtil.info('NavidromeLoad', `日志状态: ${ServerLogUtil.getLogUploadStatus()}`);
  360. // 记录账号信息和缓存路径
  361. await this.logAccountCacheInfo(account);
  362. await this.loadMediaLibrary(account);
  363. this.doSortType(this.sortType)
  364. }
  365. private resolveActiveAccount(): WebDavAccount | undefined {
  366. if (!this.selectedAccount) {
  367. return undefined;
  368. }
  369. if (!this.isNavidromeAccount(this.selectedAccount)
  370. && !this.isJellyfinAccount(this.selectedAccount)
  371. && !this.isEmbyAccount(this.selectedAccount)
  372. && !this.isAudioStationAccount(this.selectedAccount)
  373. && !this.isPlexAccount(this.selectedAccount)
  374. && !this.isDaoLiYuAccount(this.selectedAccount)) {
  375. return undefined;
  376. }
  377. if (!this.selectedAccount.host || this.selectedAccount.host.length === 0) {
  378. return undefined;
  379. }
  380. return this.selectedAccount;
  381. }
  382. private resetData(): void {
  383. this.allVideos = [];
  384. this.artists = [];
  385. this.albums = [];
  386. this.playlists = [];
  387. // 更新 LazyForEach 数据源
  388. this.songDataSource.pushArrayData([]);
  389. this.artistDataSource.pushArrayData([]);
  390. this.albumDataSource.pushArrayData([]);
  391. this.playlistDataSource.pushArrayData([]);
  392. this.jellyfinSongIdSeen.clear();
  393. this.embySongIdSeen.clear();
  394. this.jellyfinSongKeySeen.clear();
  395. this.embySongKeySeen.clear();
  396. this.clearFilter();
  397. this.coverUrlCache.clear();
  398. this.albumCoverLookup.clear();
  399. this.songNextStart = 0;
  400. this.artistNextStart = 0;
  401. this.albumNextStart = 0;
  402. this.playlistNextStart = 0;
  403. this.isSongPageLoading = false;
  404. this.isArtistPageLoading = false;
  405. this.isAlbumPageLoading = false;
  406. this.isPlaylistPageLoading = false;
  407. this.serverTotalSongCount = 0;
  408. }
  409. // 更新所有 LazyForEach 数据源
  410. private updateAllDataSources(): void {
  411. this.songDataSource.pushArrayData(this.getVisibleSongs());
  412. this.artistDataSource.pushArrayData(this.artists);
  413. this.albumDataSource.pushArrayData(this.albums);
  414. this.playlistDataSource.pushArrayData(this.playlists);
  415. }
  416. private async loadMediaLibrary(account: WebDavAccount): Promise<void> {
  417. if (this.isNavidromeAccount(account)) {
  418. await this.loadNavidromeLibrary(account);
  419. return;
  420. }
  421. if (this.isJellyfinAccount(account)) {
  422. await this.loadJellyfinLibrary(account);
  423. return;
  424. }
  425. if (this.isEmbyAccount(account)) {
  426. await this.loadEmbyLibrary(account);
  427. return;
  428. }
  429. if (this.isAudioStationAccount(account)) {
  430. await this.loadAudioStationLibrary(account);
  431. return;
  432. }
  433. if (this.isPlexAccount(account)) {
  434. await this.loadPlexLibrary(account);
  435. return;
  436. }
  437. if (this.isDaoLiYuAccount(account)) {
  438. await this.loadDaoLiYuLibrary(account);
  439. }
  440. }
  441. private async loadNavidromeLibrary(account: WebDavAccount): Promise<void> {
  442. const ticket = ++this.loadTicket;
  443. this.loading = true;
  444. this.resetData();
  445. void ServerLogUtil.info('NavidromeLoad', '开始加载 Navidrome 数据库');
  446. void ServerLogUtil.info('NavidromeLoad', `服务器: ${ServerLogUtil.sanitizeAccount(account)}`);
  447. void ServerLogUtil.info('NavidromeLoad', `封面URL缓存已清空,当前缓存数量: ${this.coverUrlCache.size}`);
  448. try {
  449. await this.logAccountCacheInfo(account);
  450. // 尝试从缓存读取(前50条)
  451. const accountId = account.id?.toString() ?? 'default';
  452. const cachedData: AllCacheData = this.listCache.getAllCache(accountId);
  453. let loadedFromCache = false;
  454. if (cachedData.songs && cachedData.songs.length > 0) {
  455. this.allVideos = cachedData.songs;
  456. this.songDataSource.pushArrayData(cachedData.songs);
  457. loadedFromCache = true;
  458. void ServerLogUtil.info('NavidromeLoad', `从缓存加载歌曲: ${cachedData.songs.length} 首`);
  459. }
  460. if (cachedData.artists && cachedData.artists.length > 0) {
  461. this.artists = cachedData.artists;
  462. this.artistDataSource.pushArrayData(cachedData.artists);
  463. void ServerLogUtil.info('NavidromeLoad', `从缓存加载艺术家: ${cachedData.artists.length} 位`);
  464. }
  465. if (cachedData.albums && cachedData.albums.length > 0) {
  466. this.albums = cachedData.albums;
  467. this.albumDataSource.pushArrayData(cachedData.albums);
  468. void ServerLogUtil.info('NavidromeLoad', `从缓存加载专辑: ${cachedData.albums.length} 张`);
  469. }
  470. if (cachedData.playlists && cachedData.playlists.length > 0) {
  471. this.playlists = cachedData.playlists;
  472. this.playlistDataSource.pushArrayData(cachedData.playlists);
  473. void ServerLogUtil.info('NavidromeLoad', `从缓存加载歌单: ${cachedData.playlists.length} 个`);
  474. }
  475. // 如果有缓存数据,先显示缓存,然后后台加载完整数据
  476. if (loadedFromCache || cachedData.artists || cachedData.albums || cachedData.playlists) {
  477. this.loading = false;
  478. void ServerLogUtil.info('NavidromeLoad', '缓存数据加载完成,开始后台加载完整数据');
  479. // 使用 taskpool 后台加载完整数据,避免 UI 卡顿
  480. // 提取 account 的序列化数据 (taskpool 不支持 Proxy 对象)
  481. const accountData: AccountData = {
  482. id: account.id ?? 0,
  483. webType: account.webType,
  484. host: account.host ?? '',
  485. port: account.port ?? 80,
  486. account: account.account ?? '',
  487. password: account.password ?? '',
  488. enableHttps: account.enableHttps ?? false,
  489. navidromeBasePath: account.navidromeBasePath ?? '/rest',
  490. jellyfinBasePath: account.jellyfinBasePath ?? '',
  491. embyBasePath: account.embyBasePath ?? '',
  492. name: account.name ?? ''
  493. };
  494. const task = new taskpool.Task(loadNavidromeDataTask, accountData, ticket);
  495. taskpool.execute(task, taskpool.Priority.MEDIUM).then((result: Object) => {
  496. if (ticket !== this.loadTicket) {
  497. return;
  498. }
  499. // 类型断言
  500. const taskResult = result as TaskResult;
  501. void ServerLogUtil.info('NavidromeLoad', `后台加载完成: 歌曲 ${taskResult.songs.length} / 艺术家 ${taskResult.artists.length} / 专辑 ${taskResult.albums.length} / 歌单 ${taskResult.playlists.length}`);
  502. // 直接更新数据(封面已在后台处理)
  503. if (taskResult.songs && taskResult.songs.length > 0) {
  504. this.allVideos = taskResult.songs;
  505. this.songDataSource.pushArrayData(taskResult.songs);
  506. }
  507. if (taskResult.artists && taskResult.artists.length > 0) {
  508. this.artists = taskResult.artists;
  509. this.artistDataSource.pushArrayData(taskResult.artists);
  510. }
  511. if (taskResult.albums && taskResult.albums.length > 0) {
  512. this.albums = taskResult.albums;
  513. this.albumDataSource.pushArrayData(taskResult.albums);
  514. }
  515. if (taskResult.playlists && taskResult.playlists.length > 0) {
  516. this.playlists = taskResult.playlists;
  517. this.playlistDataSource.pushArrayData(taskResult.playlists);
  518. }
  519. // 保存新的缓存(前50条)
  520. this.listCache.saveSongsCache(accountId, this.allVideos);
  521. this.listCache.saveArtistsCache(accountId, this.artists);
  522. this.listCache.saveAlbumsCache(accountId, this.albums);
  523. this.listCache.savePlaylistsCache(accountId, this.playlists);
  524. void ServerLogUtil.info('NavidromeLoad', `后台加载完成并更新缓存: 歌曲 ${this.allVideos.length} / 艺术家 ${this.artists.length} / 专辑 ${this.albums.length} / 歌单 ${this.playlists.length}`);
  525. void this.logCacheStatistics(account);
  526. }).catch((error: Error) => {
  527. void ServerLogUtil.error('NavidromeLoad', `后台数据加载失败: ${error.message}`);
  528. });
  529. return;
  530. }
  531. // 没有缓存,正常加载
  532. await Promise.all([
  533. this.loadNextSongPage(account, ticket),
  534. this.loadNextArtistPage(account, ticket),
  535. this.loadNextAlbumPage(account, ticket),
  536. this.loadNextPlaylistPage(account, ticket)
  537. ]);
  538. if (ticket !== this.loadTicket) {
  539. return;
  540. }
  541. // 保存缓存(前50条)
  542. this.listCache.saveSongsCache(accountId, this.allVideos);
  543. this.listCache.saveArtistsCache(accountId, this.artists);
  544. this.listCache.saveAlbumsCache(accountId, this.albums);
  545. this.listCache.savePlaylistsCache(accountId, this.playlists);
  546. void ServerLogUtil.info('NavidromeLoad', `首次加载完成并已缓存: 歌曲 ${this.allVideos.length} / 艺术家 ${this.artists.length} / 专辑 ${this.albums.length} / 歌单 ${this.playlists.length}`);
  547. await this.logCacheStatistics(account);
  548. } catch (error) {
  549. if (ticket === this.loadTicket) {
  550. void ServerLogUtil.error('NavidromeLoad', `数据加载失败: ${(error as Error).message}`);
  551. void ServerLogUtil.error('NavidromeLoad', `失败时服务器信息: ${ServerLogUtil.sanitizeAccount(account)}`);
  552. ToastUtil.showToast((error as Error).message ?? 'Navidrome 数据加载失败');
  553. }
  554. } finally {
  555. if (ticket === this.loadTicket) {
  556. this.loading = false;
  557. void ServerLogUtil.info('NavidromeLoad', '加载流程结束');
  558. }
  559. }
  560. }
  561. private async loadJellyfinLibrary(account: WebDavAccount): Promise<void> {
  562. const ticket = ++this.loadTicket;
  563. this.loading = true;
  564. this.resetData();
  565. void ServerLogUtil.info('NavidromeLoad', '开始加载 Jellyfin 媒体库');
  566. void ServerLogUtil.info('NavidromeLoad', `服务器: ${ServerLogUtil.sanitizeAccount(account)}`);
  567. try {
  568. this.songNextStart = 0;
  569. this.artistNextStart = 0;
  570. this.albumNextStart = 0;
  571. this.playlistNextStart = null;
  572. await Promise.all([
  573. this.loadNextJellyfinSongPage(account, ticket),
  574. this.loadNextJellyfinArtistPage(account, ticket),
  575. this.loadNextJellyfinAlbumPage(account, ticket)
  576. ]);
  577. if (ticket === this.loadTicket) {
  578. void ServerLogUtil.info('NavidromeLoad', `Jellyfin 首屏完成: 歌曲 ${this.allVideos.length} / 艺术家 ${this.artists.length} / 专辑 ${this.albums.length}`);
  579. }
  580. } catch (error) {
  581. if (ticket === this.loadTicket) {
  582. void ServerLogUtil.error('NavidromeLoad', `Jellyfin 数据加载失败: ${(error as Error).message}`);
  583. ToastUtil.showToast((error as Error).message ?? 'Jellyfin 数据加载失败');
  584. }
  585. } finally {
  586. if (ticket === this.loadTicket) {
  587. this.loading = false;
  588. }
  589. }
  590. }
  591. private async loadEmbyLibrary(account: WebDavAccount): Promise<void> {
  592. const ticket = ++this.loadTicket;
  593. this.loading = true;
  594. this.resetData();
  595. void ServerLogUtil.info('NavidromeLoad', '开始加载 Emby 媒体库');
  596. void ServerLogUtil.info('NavidromeLoad', `服务器: ${ServerLogUtil.sanitizeAccount(account)}`);
  597. try {
  598. this.songNextStart = 0;
  599. this.artistNextStart = 0;
  600. this.albumNextStart = 0;
  601. this.playlistNextStart = null;
  602. await Promise.all([
  603. this.loadNextEmbySongPage(account, ticket),
  604. this.loadNextEmbyArtistPage(account, ticket),
  605. this.loadNextEmbyAlbumPage(account, ticket)
  606. ]);
  607. if (ticket === this.loadTicket) {
  608. void ServerLogUtil.info('NavidromeLoad', `Emby 首屏完成: 歌曲 ${this.allVideos.length} / 艺术家 ${this.artists.length} / 专辑 ${this.albums.length}`);
  609. }
  610. } catch (error) {
  611. if (ticket === this.loadTicket) {
  612. void ServerLogUtil.error('NavidromeLoad', `Emby 数据加载失败: ${(error as Error).message}`);
  613. ToastUtil.showToast((error as Error).message ?? 'Emby 数据加载失败');
  614. }
  615. } finally {
  616. if (ticket === this.loadTicket) {
  617. this.loading = false;
  618. }
  619. }
  620. }
  621. private async loadAudioStationLibrary(account: WebDavAccount): Promise<void> {
  622. const ticket = ++this.loadTicket;
  623. this.loading = true;
  624. this.resetData();
  625. void ServerLogUtil.info('NavidromeLoad', '开始加载 AudioStation 媒体库');
  626. void ServerLogUtil.info('NavidromeLoad', `服务器: ${ServerLogUtil.sanitizeAccount(account)}`);
  627. try {
  628. this.songNextStart = 0;
  629. this.artistNextStart = 0;
  630. this.albumNextStart = 0;
  631. this.playlistNextStart = 0;
  632. await Promise.all([
  633. this.loadNextAudioStationSongPage(account, ticket),
  634. this.loadNextAudioStationArtistPage(account, ticket),
  635. this.loadNextAudioStationAlbumPage(account, ticket),
  636. this.loadNextAudioStationPlaylistPage(account, ticket)
  637. ]);
  638. if (ticket === this.loadTicket) {
  639. void ServerLogUtil.info('NavidromeLoad', `AudioStation 首屏完成: 歌曲 ${this.allVideos.length} / 艺术家 ${this.artists.length} / 专辑 ${this.albums.length} / 歌单 ${this.playlists.length}`);
  640. }
  641. } catch (error) {
  642. if (ticket === this.loadTicket) {
  643. void ServerLogUtil.error('NavidromeLoad', `AudioStation 数据加载失败: ${(error as Error).message}`);
  644. ToastUtil.showToast((error as Error).message ?? 'AudioStation 数据加载失败');
  645. }
  646. } finally {
  647. if (ticket === this.loadTicket) {
  648. this.loading = false;
  649. }
  650. }
  651. }
  652. private async loadPlexLibrary(account: WebDavAccount): Promise<void> {
  653. const ticket = ++this.loadTicket;
  654. this.loading = true;
  655. this.resetData();
  656. void ServerLogUtil.info('NavidromeLoad', '开始加载 Plex 媒体库');
  657. void ServerLogUtil.info('NavidromeLoad', `服务器: ${ServerLogUtil.sanitizeAccount(account)}`);
  658. try {
  659. this.songNextStart = 0;
  660. this.artistNextStart = 0;
  661. this.albumNextStart = 0;
  662. this.playlistNextStart = 0;
  663. await Promise.all([
  664. this.loadNextPlexSongPage(account, ticket),
  665. this.loadNextPlexArtistPage(account, ticket),
  666. this.loadNextPlexAlbumPage(account, ticket),
  667. this.loadNextPlexPlaylistPage(account, ticket)
  668. ]);
  669. if (ticket === this.loadTicket) {
  670. void ServerLogUtil.info('NavidromeLoad', `Plex 首屏完成: 歌曲 ${this.allVideos.length} / 艺术家 ${this.artists.length} / 专辑 ${this.albums.length} / 歌单 ${this.playlists.length}`);
  671. }
  672. } catch (error) {
  673. if (ticket === this.loadTicket) {
  674. void ServerLogUtil.error('NavidromeLoad', `Plex 数据加载失败: ${(error as Error).message}`);
  675. ToastUtil.showToast((error as Error).message ?? 'Plex 数据加载失败');
  676. }
  677. } finally {
  678. if (ticket === this.loadTicket) {
  679. this.loading = false;
  680. }
  681. }
  682. }
  683. private async loadDaoLiYuLibrary(account: WebDavAccount): Promise<void> {
  684. const ticket = ++this.loadTicket;
  685. this.loading = true;
  686. this.resetData();
  687. void ServerLogUtil.info('NavidromeLoad', '开始加载 道理鱼 媒体库');
  688. void ServerLogUtil.info('NavidromeLoad', `服务器: ${ServerLogUtil.sanitizeAccount(account)}`);
  689. try {
  690. this.songNextStart = 0;
  691. this.artistNextStart = 0;
  692. this.albumNextStart = 0;
  693. this.playlistNextStart = 0;
  694. await Promise.all([
  695. this.loadNextDaoLiYuSongPage(account, ticket),
  696. this.loadNextDaoLiYuArtistPage(account, ticket),
  697. this.loadNextDaoLiYuAlbumPage(account, ticket),
  698. this.loadNextDaoLiYuPlaylistPage(account, ticket)
  699. ]);
  700. if (ticket === this.loadTicket) {
  701. void ServerLogUtil.info('NavidromeLoad', `道理鱼 首屏完成: 歌曲 ${this.allVideos.length} / 艺术家 ${this.artists.length} / 专辑 ${this.albums.length}`);
  702. }
  703. } catch (error) {
  704. if (ticket === this.loadTicket) {
  705. void ServerLogUtil.error('NavidromeLoad', `道理鱼 数据加载失败: ${(error as Error).message}`);
  706. ToastUtil.showToast((error as Error).message ?? '道理鱼 数据加载失败');
  707. }
  708. } finally {
  709. if (ticket === this.loadTicket) {
  710. this.loading = false;
  711. }
  712. }
  713. }
  714. private async loadNextSongPage(account: WebDavAccount, ticket?: number): Promise<void> {
  715. if (this.songNextStart === null || this.isSongPageLoading) {
  716. return;
  717. }
  718. const currentTicket = ticket ?? this.loadTicket;
  719. this.isSongPageLoading = true;
  720. try {
  721. const response = await navidromeRestApi.fetchSongPage(account, this.songNextStart);
  722. if (currentTicket !== this.loadTicket) {
  723. return;
  724. }
  725. const chunk = response.data ?? [];
  726. if (chunk.length === 0) {
  727. this.songNextStart = null;
  728. return;
  729. }
  730. const videos = await this.convertSongsToVideoItems(chunk, account);
  731. if (currentTicket !== this.loadTicket) {
  732. return;
  733. }
  734. this.allVideos = [...this.allVideos, ...videos];
  735. this.updateAllDataSources();
  736. // 打印前20条数据
  737. // const previewCount = Math.min(20, this.allVideos.length);
  738. // console.info(`onecold allVideos: ${this.allVideos.length}, 打印前${previewCount}条:`);
  739. // for (let i = 0; i < previewCount; i++) {
  740. // const all = this.allVideos[i];
  741. // console.info(`onecold allVideos[${i}]:`, JSON.stringify({
  742. // id: all.id,
  743. // name: all.name,
  744. // pixelMapPath: all.pixelMapPath
  745. // }));
  746. // }
  747. this.songNextStart = response.nextStart;
  748. void ServerLogUtil.info('NavidromeLoad', `歌曲列表追加: 本次 ${videos.length} 首, 总数 ${this.allVideos.length}`);
  749. } finally {
  750. this.isSongPageLoading = false;
  751. }
  752. }
  753. private async loadNextArtistPage(account: WebDavAccount, ticket?: number): Promise<void> {
  754. if (this.artistNextStart === null || this.isArtistPageLoading) {
  755. return;
  756. }
  757. const currentTicket = ticket ?? this.loadTicket;
  758. this.isArtistPageLoading = true;
  759. try {
  760. const response = await navidromeRestApi.fetchArtistPage(account, this.artistNextStart);
  761. if (currentTicket !== this.loadTicket) {
  762. return;
  763. }
  764. const chunk = response.data ?? [];
  765. if (chunk.length === 0) {
  766. this.artistNextStart = null;
  767. return;
  768. }
  769. const coverMap = await this.buildArtistCoverMap(chunk, account);
  770. if (currentTicket !== this.loadTicket) {
  771. return;
  772. }
  773. const processed = chunk.map(artist => {
  774. artist.coverUrl = coverMap.get(artist.id);
  775. return artist;
  776. });
  777. this.artists = [...this.artists, ...processed];
  778. // console.info('onecold 帮我打印这个artists的前20条数据');
  779. // 打印前20条艺术家数据
  780. // const previewCount = Math.min(20, this.artists.length);
  781. // console.info(`onecold artists总数: ${this.artists.length}, 打印前${previewCount}条:`);
  782. // for (let i = 0; i < previewCount; i++) {
  783. // const artist = this.artists[i];
  784. // console.info(`onecold artist[${i}]:`, JSON.stringify({
  785. // id: artist.id,
  786. // name: artist.name,
  787. // albumCount: artist.albumCount,
  788. // songCount: artist.songCount,
  789. // coverUrl: artist.coverUrl
  790. // }));
  791. // }
  792. this.artistNextStart = response.nextStart;
  793. void ServerLogUtil.info('ArtistCover', `艺术家列表追加: 本次 ${processed.length} 位, 总数 ${this.artists.length}`);
  794. } finally {
  795. this.isArtistPageLoading = false;
  796. }
  797. }
  798. private async loadNextAlbumPage(account: WebDavAccount, ticket?: number): Promise<void> {
  799. if (this.albumNextStart === null || this.isAlbumPageLoading) {
  800. return;
  801. }
  802. const currentTicket = ticket ?? this.loadTicket;
  803. this.isAlbumPageLoading = true;
  804. try {
  805. const response = await navidromeRestApi.fetchAlbumPage(account, this.albumNextStart);
  806. if (currentTicket !== this.loadTicket) {
  807. return;
  808. }
  809. const chunk = response.data ?? [];
  810. if (chunk.length === 0) {
  811. this.albumNextStart = null;
  812. return;
  813. }
  814. const coverMap = await this.buildAlbumCoverMap(chunk, account);
  815. if (currentTicket !== this.loadTicket) {
  816. return;
  817. }
  818. coverMap.forEach((value, key) => {
  819. if (value) {
  820. this.albumCoverLookup.set(key, value);
  821. }
  822. });
  823. const processed = chunk.map(album => {
  824. album.coverUrl = coverMap.get(album.id);
  825. return album;
  826. });
  827. this.albums = [...this.albums, ...processed];
  828. this.updateAllDataSources();
  829. this.albumNextStart = response.nextStart;
  830. void ServerLogUtil.info('AlbumCover', `专辑列表追加: 本次 ${processed.length} 张, 总数 ${this.albums.length}`);
  831. } finally {
  832. this.isAlbumPageLoading = false;
  833. }
  834. }
  835. private async loadNextJellyfinSongPage(account: WebDavAccount, ticket?: number): Promise<void> {
  836. if (this.songNextStart === null || this.isSongPageLoading) {
  837. return;
  838. }
  839. const currentTicket = ticket ?? this.loadTicket;
  840. const isFirstPage = this.songNextStart === 0;
  841. this.isSongPageLoading = true;
  842. try {
  843. const response = await jellyfinApi.getSongsPage(account, this.songNextStart, this.REMOTE_PAGE_SIZE);
  844. if (currentTicket !== this.loadTicket) {
  845. return;
  846. }
  847. // 首次加载时保存服务端总数
  848. if (isFirstPage && response.total !== undefined && response.total > 0) {
  849. this.serverTotalSongCount = response.total;
  850. void ServerLogUtil.info('NavidromeLoad', `Jellyfin 服务端歌曲总数: ${this.serverTotalSongCount}`);
  851. }
  852. const uniqueItems: JellyfinSong[] = [];
  853. for (let i = 0; i < response.items.length; i++) {
  854. const item = response.items[i];
  855. if (!item.id) {
  856. continue;
  857. }
  858. const key = this.buildSongDedupKey(item.title, item.artist, item.album, item.durationSeconds);
  859. if (this.jellyfinSongIdSeen.has(item.id) || this.jellyfinSongKeySeen.has(key)) {
  860. continue;
  861. }
  862. this.jellyfinSongIdSeen.add(item.id);
  863. this.jellyfinSongKeySeen.add(key);
  864. uniqueItems.push(item);
  865. }
  866. const restSongs = this.convertJellyfinSongsToRestSongs(uniqueItems);
  867. const videoItems = await this.convertSongsToVideoItems(restSongs, account);
  868. if (currentTicket !== this.loadTicket) {
  869. return;
  870. }
  871. this.allVideos = this.dedupRemoteSongsByKey([...this.allVideos, ...videoItems]);
  872. this.updateAllDataSources();
  873. this.songNextStart = response.nextStart;
  874. void ServerLogUtil.info('NavidromeLoad', `Jellyfin 歌曲追加: 本次 ${videoItems.length} 首, 已加载 ${this.allVideos.length}, 服务端总数 ${this.serverTotalSongCount}`);
  875. } finally {
  876. this.isSongPageLoading = false;
  877. }
  878. }
  879. private async loadNextJellyfinArtistPage(account: WebDavAccount, ticket?: number): Promise<void> {
  880. if (this.artistNextStart === null || this.isArtistPageLoading) {
  881. return;
  882. }
  883. const currentTicket = ticket ?? this.loadTicket;
  884. this.isArtistPageLoading = true;
  885. try {
  886. const response = await jellyfinApi.getArtistsPage(account, this.artistNextStart, this.REMOTE_PAGE_SIZE);
  887. if (currentTicket !== this.loadTicket) {
  888. return;
  889. }
  890. const processed = await this.convertJellyfinArtistsToRest(response.items, account);
  891. if (currentTicket !== this.loadTicket) {
  892. return;
  893. }
  894. this.artists = [...this.artists, ...processed];
  895. this.updateAllDataSources();
  896. this.artistNextStart = response.nextStart;
  897. void ServerLogUtil.info('NavidromeLoad', `Jellyfin 艺术家追加: 本次 ${processed.length} 位, 总数 ${this.artists.length}`);
  898. } finally {
  899. this.isArtistPageLoading = false;
  900. }
  901. }
  902. private async loadNextJellyfinAlbumPage(account: WebDavAccount, ticket?: number): Promise<void> {
  903. if (this.albumNextStart === null || this.isAlbumPageLoading) {
  904. return;
  905. }
  906. const currentTicket = ticket ?? this.loadTicket;
  907. this.isAlbumPageLoading = true;
  908. try {
  909. const response = await jellyfinApi.getAlbumsPage(account, this.albumNextStart, this.REMOTE_PAGE_SIZE);
  910. if (currentTicket !== this.loadTicket) {
  911. return;
  912. }
  913. const processed = await this.convertJellyfinAlbumsToRest(response.items, account);
  914. if (currentTicket !== this.loadTicket) {
  915. return;
  916. }
  917. this.albums = [...this.albums, ...processed];
  918. this.updateAllDataSources();
  919. this.albumNextStart = response.nextStart;
  920. void ServerLogUtil.info('NavidromeLoad', `Jellyfin 专辑追加: 本次 ${processed.length} 张, 总数 ${this.albums.length}`);
  921. } finally {
  922. this.isAlbumPageLoading = false;
  923. }
  924. }
  925. private async loadNextEmbySongPage(account: WebDavAccount, ticket?: number): Promise<void> {
  926. if (this.songNextStart === null || this.isSongPageLoading) {
  927. return;
  928. }
  929. const currentTicket = ticket ?? this.loadTicket;
  930. const isFirstPage = this.songNextStart === 0;
  931. this.isSongPageLoading = true;
  932. try {
  933. const response = await embyApi.getSongsPage(account, this.songNextStart, this.REMOTE_PAGE_SIZE);
  934. if (currentTicket !== this.loadTicket) {
  935. return;
  936. }
  937. // 首次加载时保存服务端总数
  938. if (isFirstPage && response.total !== undefined && response.total > 0) {
  939. this.serverTotalSongCount = response.total;
  940. void ServerLogUtil.info('NavidromeLoad', `Emby 服务端歌曲总数: ${this.serverTotalSongCount}`);
  941. }
  942. const uniqueItems: EmbySong[] = [];
  943. for (let i = 0; i < response.items.length; i++) {
  944. const item = response.items[i];
  945. if (!item.id) {
  946. continue;
  947. }
  948. const key = this.buildSongDedupKey(item.title, item.artist, item.album, item.durationSeconds);
  949. if (this.embySongIdSeen.has(item.id) || this.embySongKeySeen.has(key)) {
  950. continue;
  951. }
  952. this.embySongIdSeen.add(item.id);
  953. this.embySongKeySeen.add(key);
  954. uniqueItems.push(item);
  955. }
  956. const restSongs = this.convertEmbySongsToRestSongs(uniqueItems);
  957. const videoItems = await this.convertSongsToVideoItems(restSongs, account);
  958. if (currentTicket !== this.loadTicket) {
  959. return;
  960. }
  961. this.allVideos = this.dedupRemoteSongsByKey([...this.allVideos, ...videoItems]);
  962. this.updateAllDataSources();
  963. this.songNextStart = response.nextStart;
  964. void ServerLogUtil.info('NavidromeLoad', `Emby 歌曲追加: 本次 ${videoItems.length} 首, 已加载 ${this.allVideos.length}, 服务端总数 ${this.serverTotalSongCount}`);
  965. } finally {
  966. this.isSongPageLoading = false;
  967. }
  968. }
  969. private async loadNextEmbyArtistPage(account: WebDavAccount, ticket?: number): Promise<void> {
  970. if (this.artistNextStart === null || this.isArtistPageLoading) {
  971. return;
  972. }
  973. const currentTicket = ticket ?? this.loadTicket;
  974. this.isArtistPageLoading = true;
  975. try {
  976. const response = await embyApi.getArtistsPage(account, this.artistNextStart, this.REMOTE_PAGE_SIZE);
  977. if (currentTicket !== this.loadTicket) {
  978. return;
  979. }
  980. const processed = await this.convertEmbyArtistsToRest(response.items, account);
  981. if (currentTicket !== this.loadTicket) {
  982. return;
  983. }
  984. this.artists = [...this.artists, ...processed];
  985. this.updateAllDataSources();
  986. this.artistNextStart = response.nextStart;
  987. void ServerLogUtil.info('NavidromeLoad', `Emby 艺术家追加: 本次 ${processed.length} 位, 总数 ${this.artists.length}`);
  988. } finally {
  989. this.isArtistPageLoading = false;
  990. }
  991. }
  992. private async loadNextEmbyAlbumPage(account: WebDavAccount, ticket?: number): Promise<void> {
  993. if (this.albumNextStart === null || this.isAlbumPageLoading) {
  994. return;
  995. }
  996. const currentTicket = ticket ?? this.loadTicket;
  997. this.isAlbumPageLoading = true;
  998. try {
  999. const response = await embyApi.getAlbumsPage(account, this.albumNextStart, this.REMOTE_PAGE_SIZE);
  1000. if (currentTicket !== this.loadTicket) {
  1001. return;
  1002. }
  1003. const processed = await this.convertEmbyAlbumsToRest(response.items, account);
  1004. if (currentTicket !== this.loadTicket) {
  1005. return;
  1006. }
  1007. this.albums = [...this.albums, ...processed];
  1008. this.updateAllDataSources();
  1009. this.albumNextStart = response.nextStart;
  1010. void ServerLogUtil.info('NavidromeLoad', `Emby 专辑追加: 本次 ${processed.length} 张, 总数 ${this.albums.length}`);
  1011. } finally {
  1012. this.isAlbumPageLoading = false;
  1013. }
  1014. }
  1015. private async loadNextAudioStationSongPage(account: WebDavAccount, ticket?: number): Promise<void> {
  1016. if (this.songNextStart === null || this.isSongPageLoading) {
  1017. return;
  1018. }
  1019. const currentTicket = ticket ?? this.loadTicket;
  1020. const isFirstPage = this.songNextStart === 0; // 在调用前保存是否为首页
  1021. this.isSongPageLoading = true;
  1022. try {
  1023. const response = await audioStationApi.getSongsPage(account, this.songNextStart, this.REMOTE_PAGE_SIZE);
  1024. if (currentTicket !== this.loadTicket) {
  1025. return;
  1026. }
  1027. // 首次加载时保存服务端总数
  1028. if (isFirstPage && response.total !== undefined && response.total > 0) {
  1029. this.serverTotalSongCount = response.total;
  1030. void ServerLogUtil.info('NavidromeLoad', `AudioStation 服务端歌曲总数: ${this.serverTotalSongCount}`);
  1031. }
  1032. const restSongs = this.convertAudioStationSongsToRestSongs(response.items);
  1033. const videoItems = await this.convertSongsToVideoItems(restSongs, account);
  1034. if (currentTicket !== this.loadTicket) {
  1035. return;
  1036. }
  1037. this.allVideos = this.dedupRemoteSongsByKey([...this.allVideos, ...videoItems]);
  1038. this.updateAllDataSources();
  1039. this.songNextStart = response.nextStart;
  1040. void ServerLogUtil.info('NavidromeLoad', `AudioStation 歌曲追加: 本次 ${videoItems.length} 首, 已加载 ${this.allVideos.length}, 服务端总数 ${this.serverTotalSongCount}`);
  1041. } finally {
  1042. this.isSongPageLoading = false;
  1043. }
  1044. }
  1045. private async loadNextAudioStationArtistPage(account: WebDavAccount, ticket?: number): Promise<void> {
  1046. if (this.artistNextStart === null || this.isArtistPageLoading) {
  1047. return;
  1048. }
  1049. const currentTicket = ticket ?? this.loadTicket;
  1050. this.isArtistPageLoading = true;
  1051. try {
  1052. const response = await audioStationApi.getArtistsPage(account, this.artistNextStart, this.REMOTE_PAGE_SIZE);
  1053. if (currentTicket !== this.loadTicket) {
  1054. return;
  1055. }
  1056. const processed = this.convertAudioStationArtistsToRest(response.items);
  1057. if (currentTicket !== this.loadTicket) {
  1058. return;
  1059. }
  1060. this.artists = [...this.artists, ...processed];
  1061. this.updateAllDataSources();
  1062. this.artistNextStart = response.nextStart;
  1063. void ServerLogUtil.info('NavidromeLoad', `AudioStation 艺术家追加: 本次 ${processed.length} 位, 总数 ${this.artists.length}`);
  1064. } finally {
  1065. this.isArtistPageLoading = false;
  1066. }
  1067. }
  1068. private async loadNextAudioStationAlbumPage(account: WebDavAccount, ticket?: number): Promise<void> {
  1069. if (this.albumNextStart === null || this.isAlbumPageLoading) {
  1070. return;
  1071. }
  1072. const currentTicket = ticket ?? this.loadTicket;
  1073. this.isAlbumPageLoading = true;
  1074. try {
  1075. const response = await audioStationApi.getAlbumsPage(account, undefined, this.albumNextStart, this.REMOTE_PAGE_SIZE);
  1076. if (currentTicket !== this.loadTicket) {
  1077. return;
  1078. }
  1079. const processed = await this.convertAudioStationAlbumsToRest(response.items, account);
  1080. if (currentTicket !== this.loadTicket) {
  1081. return;
  1082. }
  1083. this.albums = [...this.albums, ...processed];
  1084. this.updateAllDataSources();
  1085. this.albumNextStart = response.nextStart;
  1086. void ServerLogUtil.info('NavidromeLoad', `AudioStation 专辑追加: 本次 ${processed.length} 张, 总数 ${this.albums.length}`);
  1087. } finally {
  1088. this.isAlbumPageLoading = false;
  1089. }
  1090. }
  1091. private async loadNextAudioStationPlaylistPage(account: WebDavAccount, ticket?: number): Promise<void> {
  1092. if (this.playlistNextStart === null || this.isPlaylistPageLoading) {
  1093. return;
  1094. }
  1095. const currentTicket = ticket ?? this.loadTicket;
  1096. this.isPlaylistPageLoading = true;
  1097. try {
  1098. const response = await audioStationApi.getPlaylistsPage(account, this.playlistNextStart, this.REMOTE_PAGE_SIZE);
  1099. if (currentTicket !== this.loadTicket) {
  1100. return;
  1101. }
  1102. const processed = this.convertAudioStationPlaylistsToRest(response.items);
  1103. if (currentTicket !== this.loadTicket) {
  1104. return;
  1105. }
  1106. this.playlists = [...this.playlists, ...processed];
  1107. this.updateAllDataSources();
  1108. this.playlistNextStart = response.nextStart;
  1109. void ServerLogUtil.info('NavidromeLoad', `AudioStation 歌单追加: 本次 ${processed.length} 个, 总数 ${this.playlists.length}`);
  1110. } finally {
  1111. this.isPlaylistPageLoading = false;
  1112. }
  1113. }
  1114. private async loadNextPlexSongPage(account: WebDavAccount, ticket?: number): Promise<void> {
  1115. if (this.songNextStart === null || this.isSongPageLoading) {
  1116. return;
  1117. }
  1118. const currentTicket = ticket ?? this.loadTicket;
  1119. const isFirstPage = this.songNextStart === 0;
  1120. this.isSongPageLoading = true;
  1121. try {
  1122. const response = await plexApi.getSongsPage(account, this.songNextStart, this.REMOTE_PAGE_SIZE);
  1123. if (currentTicket !== this.loadTicket) {
  1124. return;
  1125. }
  1126. // 首次加载时保存服务端总数
  1127. if (isFirstPage && response.total !== undefined && response.total > 0) {
  1128. this.serverTotalSongCount = response.total;
  1129. void ServerLogUtil.info('NavidromeLoad', `Plex 服务端歌曲总数: ${this.serverTotalSongCount}`);
  1130. }
  1131. const restSongs = this.convertPlexSongsToRestSongs(response.items);
  1132. const videoItems = await this.convertSongsToVideoItems(restSongs, account);
  1133. if (currentTicket !== this.loadTicket) {
  1134. return;
  1135. }
  1136. this.allVideos = this.dedupRemoteSongsByKey([...this.allVideos, ...videoItems]);
  1137. this.updateAllDataSources();
  1138. this.songNextStart = response.nextStart;
  1139. void ServerLogUtil.info('NavidromeLoad', `Plex 歌曲追加: 本次 ${videoItems.length} 首, 已加载 ${this.allVideos.length}, 服务端总数 ${this.serverTotalSongCount}`);
  1140. } finally {
  1141. this.isSongPageLoading = false;
  1142. }
  1143. }
  1144. private async loadNextPlexArtistPage(account: WebDavAccount, ticket?: number): Promise<void> {
  1145. if (this.artistNextStart === null || this.isArtistPageLoading) {
  1146. return;
  1147. }
  1148. const currentTicket = ticket ?? this.loadTicket;
  1149. this.isArtistPageLoading = true;
  1150. try {
  1151. const response = await plexApi.getArtistsPage(account, this.artistNextStart, this.REMOTE_PAGE_SIZE);
  1152. if (currentTicket !== this.loadTicket) {
  1153. return;
  1154. }
  1155. const processed = await this.convertPlexArtistsToRest(response.items, account);
  1156. if (currentTicket !== this.loadTicket) {
  1157. return;
  1158. }
  1159. this.artists = [...this.artists, ...processed];
  1160. this.updateAllDataSources();
  1161. this.artistNextStart = response.nextStart;
  1162. void ServerLogUtil.info('NavidromeLoad', `Plex 艺术家追加: 本次 ${processed.length} 位, 总数 ${this.artists.length}`);
  1163. } finally {
  1164. this.isArtistPageLoading = false;
  1165. }
  1166. }
  1167. private async loadNextPlexAlbumPage(account: WebDavAccount, ticket?: number): Promise<void> {
  1168. if (this.albumNextStart === null || this.isAlbumPageLoading) {
  1169. return;
  1170. }
  1171. const currentTicket = ticket ?? this.loadTicket;
  1172. this.isAlbumPageLoading = true;
  1173. try {
  1174. const response = await plexApi.getAlbumsPage(account, this.albumNextStart, this.REMOTE_PAGE_SIZE);
  1175. if (currentTicket !== this.loadTicket) {
  1176. return;
  1177. }
  1178. const processed = await this.convertPlexAlbumsToRest(response.items, account);
  1179. if (currentTicket !== this.loadTicket) {
  1180. return;
  1181. }
  1182. this.albums = [...this.albums, ...processed];
  1183. this.updateAllDataSources();
  1184. this.albumNextStart = response.nextStart;
  1185. void ServerLogUtil.info('NavidromeLoad', `Plex 专辑追加: 本次 ${processed.length} 张, 总数 ${this.albums.length}`);
  1186. } finally {
  1187. this.isAlbumPageLoading = false;
  1188. }
  1189. }
  1190. private async loadNextPlexPlaylistPage(account: WebDavAccount, ticket?: number): Promise<void> {
  1191. if (this.playlistNextStart === null || this.isPlaylistPageLoading) {
  1192. return;
  1193. }
  1194. const currentTicket = ticket ?? this.loadTicket;
  1195. this.isPlaylistPageLoading = true;
  1196. try {
  1197. const response = await plexApi.getPlaylistsPage(account, this.playlistNextStart, this.REMOTE_PAGE_SIZE);
  1198. if (currentTicket !== this.loadTicket) {
  1199. return;
  1200. }
  1201. const processed = this.convertPlexPlaylistsToRest(response.items);
  1202. if (currentTicket !== this.loadTicket) {
  1203. return;
  1204. }
  1205. this.playlists = [...this.playlists, ...processed];
  1206. this.updateAllDataSources();
  1207. this.playlistNextStart = response.nextStart;
  1208. void ServerLogUtil.info('NavidromeLoad', `Plex 歌单追加: 本次 ${processed.length} 个, 总数 ${this.playlists.length}`);
  1209. } finally {
  1210. this.isPlaylistPageLoading = false;
  1211. }
  1212. }
  1213. private async loadNextDaoLiYuSongPage(account: WebDavAccount, ticket?: number): Promise<void> {
  1214. if (this.songNextStart === null || this.isSongPageLoading) {
  1215. return;
  1216. }
  1217. const currentTicket = ticket ?? this.loadTicket;
  1218. const isFirstPage = this.songNextStart === 0;
  1219. this.isSongPageLoading = true;
  1220. try {
  1221. const response = await daoLiYuApi.getTracksPage(account, this.songNextStart, this.REMOTE_PAGE_SIZE);
  1222. if (currentTicket !== this.loadTicket) {
  1223. return;
  1224. }
  1225. // 首次加载时保存服务端总数
  1226. if (isFirstPage && response.total !== undefined && response.total > 0) {
  1227. this.serverTotalSongCount = response.total;
  1228. void ServerLogUtil.info('NavidromeLoad', `道理鱼 服务端歌曲总数: ${this.serverTotalSongCount}`);
  1229. }
  1230. const restSongs = this.convertDaoLiYuSongsToRestSongs(response.items);
  1231. const videoItems = await this.convertSongsToVideoItems(restSongs, account);
  1232. if (currentTicket !== this.loadTicket) {
  1233. return;
  1234. }
  1235. this.allVideos = [...this.allVideos, ...videoItems];
  1236. this.updateAllDataSources();
  1237. this.songNextStart = response.nextStart;
  1238. void ServerLogUtil.info('NavidromeLoad', `道理鱼 歌曲追加: 本次 ${videoItems.length} 首, 已加载 ${this.allVideos.length}, 服务端总数 ${this.serverTotalSongCount}`);
  1239. } finally {
  1240. this.isSongPageLoading = false;
  1241. }
  1242. }
  1243. private async loadNextDaoLiYuArtistPage(account: WebDavAccount, ticket?: number): Promise<void> {
  1244. if (this.artistNextStart === null || this.isArtistPageLoading) {
  1245. return;
  1246. }
  1247. const currentTicket = ticket ?? this.loadTicket;
  1248. this.isArtistPageLoading = true;
  1249. try {
  1250. const response = await daoLiYuApi.getArtistsPage(account, this.artistNextStart, this.REMOTE_PAGE_SIZE);
  1251. if (currentTicket !== this.loadTicket) {
  1252. return;
  1253. }
  1254. const processed = await this.convertDaoLiYuArtistsToRest(response.items, account);
  1255. if (currentTicket !== this.loadTicket) {
  1256. return;
  1257. }
  1258. this.artists = [...this.artists, ...processed];
  1259. this.updateAllDataSources();
  1260. this.artistNextStart = response.nextStart;
  1261. void ServerLogUtil.info('NavidromeLoad', `道理鱼 艺术家追加: 本次 ${processed.length} 位, 总数 ${this.artists.length}`);
  1262. } finally {
  1263. this.isArtistPageLoading = false;
  1264. }
  1265. }
  1266. private async loadNextDaoLiYuAlbumPage(account: WebDavAccount, ticket?: number): Promise<void> {
  1267. if (this.albumNextStart === null || this.isAlbumPageLoading) {
  1268. return;
  1269. }
  1270. const currentTicket = ticket ?? this.loadTicket;
  1271. this.isAlbumPageLoading = true;
  1272. try {
  1273. const response = await daoLiYuApi.getAlbumsPage(account, this.albumNextStart, this.REMOTE_PAGE_SIZE);
  1274. if (currentTicket !== this.loadTicket) {
  1275. return;
  1276. }
  1277. const processed = await this.convertDaoLiYuAlbumsToRest(response.items, account);
  1278. if (currentTicket !== this.loadTicket) {
  1279. return;
  1280. }
  1281. this.albums = [...this.albums, ...processed];
  1282. this.updateAllDataSources();
  1283. this.albumNextStart = response.nextStart;
  1284. void ServerLogUtil.info('NavidromeLoad', `道理鱼 专辑追加: 本次 ${processed.length} 张, 总数 ${this.albums.length}`);
  1285. } finally {
  1286. this.isAlbumPageLoading = false;
  1287. }
  1288. }
  1289. private async loadNextDaoLiYuPlaylistPage(account: WebDavAccount, ticket?: number): Promise<void> {
  1290. if (this.playlistNextStart === null || this.isPlaylistPageLoading) {
  1291. return;
  1292. }
  1293. const currentTicket = ticket ?? this.loadTicket;
  1294. this.isPlaylistPageLoading = true;
  1295. try {
  1296. const response = await daoLiYuApi.getPlaylistsPage(account, this.playlistNextStart, this.REMOTE_PAGE_SIZE);
  1297. if (currentTicket !== this.loadTicket) {
  1298. return;
  1299. }
  1300. const processed = await this.convertDaoLiYuPlaylistsToRest(response.items, account);
  1301. if (currentTicket !== this.loadTicket) {
  1302. return;
  1303. }
  1304. this.playlists = [...this.playlists, ...processed];
  1305. this.updateAllDataSources();
  1306. this.playlistNextStart = response.nextStart;
  1307. void ServerLogUtil.info('NavidromeLoad', `道理鱼 歌单追加: 本次 ${processed.length} 个, 总数 ${this.playlists.length}`);
  1308. } finally {
  1309. this.isPlaylistPageLoading = false;
  1310. }
  1311. }
  1312. private async loadNextPlaylistPage(account: WebDavAccount, ticket?: number): Promise<void> {
  1313. if (this.playlistNextStart === null || this.isPlaylistPageLoading) {
  1314. return;
  1315. }
  1316. const currentTicket = ticket ?? this.loadTicket;
  1317. this.isPlaylistPageLoading = true;
  1318. try {
  1319. const response = await navidromeRestApi.fetchPlaylistPage(account, this.playlistNextStart);
  1320. if (currentTicket !== this.loadTicket) {
  1321. return;
  1322. }
  1323. const chunk = response.data ?? [];
  1324. if (chunk.length === 0) {
  1325. this.playlistNextStart = null;
  1326. return;
  1327. }
  1328. this.playlists = [...this.playlists, ...chunk];
  1329. this.playlistNextStart = response.nextStart;
  1330. void ServerLogUtil.info('NavidromeLoad', `歌单列表追加: 本次 ${chunk.length} 个, 总数 ${this.playlists.length}`);
  1331. } finally {
  1332. this.isPlaylistPageLoading = false;
  1333. }
  1334. }
  1335. private async handleReachEnd(): Promise<void> {
  1336. if (this.loading) {
  1337. return;
  1338. }
  1339. // 搜索结果列表不参与分页,避免滚动时被全量列表覆盖
  1340. if (this.selectedTab === 0 && this.isSearchMode && this.searchText.length > 0) {
  1341. return;
  1342. }
  1343. // 详情视图模式下不支持加载更多(筛选数据是一次性加载的)
  1344. if (this.isDetailView || this.filterType !== NavFilterType.None) {
  1345. return;
  1346. }
  1347. const account = this.selectedAccount;
  1348. if (!account) {
  1349. return;
  1350. }
  1351. if (this.isNavidromeAccount(account)) {
  1352. switch (this.selectedTab) {
  1353. case 0:
  1354. await this.loadNextSongPage(account);
  1355. break;
  1356. case 1:
  1357. await this.loadNextArtistPage(account);
  1358. break;
  1359. case 2:
  1360. await this.loadNextAlbumPage(account);
  1361. break;
  1362. case 3:
  1363. await this.loadNextPlaylistPage(account);
  1364. break;
  1365. default:
  1366. break;
  1367. }
  1368. return;
  1369. }
  1370. if (this.isJellyfinAccount(account)) {
  1371. switch (this.selectedTab) {
  1372. case 0:
  1373. await this.loadNextJellyfinSongPage(account);
  1374. break;
  1375. case 1:
  1376. await this.loadNextJellyfinArtistPage(account);
  1377. break;
  1378. case 2:
  1379. await this.loadNextJellyfinAlbumPage(account);
  1380. break;
  1381. default:
  1382. break;
  1383. }
  1384. return;
  1385. }
  1386. if (this.isEmbyAccount(account)) {
  1387. switch (this.selectedTab) {
  1388. case 0:
  1389. await this.loadNextEmbySongPage(account);
  1390. break;
  1391. case 1:
  1392. await this.loadNextEmbyArtistPage(account);
  1393. break;
  1394. case 2:
  1395. await this.loadNextEmbyAlbumPage(account);
  1396. break;
  1397. default:
  1398. break;
  1399. }
  1400. return;
  1401. }
  1402. if (this.isAudioStationAccount(account)) {
  1403. switch (this.selectedTab) {
  1404. case 0:
  1405. await this.loadNextAudioStationSongPage(account);
  1406. break;
  1407. case 1:
  1408. await this.loadNextAudioStationArtistPage(account);
  1409. break;
  1410. case 2:
  1411. await this.loadNextAudioStationAlbumPage(account);
  1412. break;
  1413. case 3:
  1414. await this.loadNextAudioStationPlaylistPage(account);
  1415. break;
  1416. default:
  1417. break;
  1418. }
  1419. return;
  1420. }
  1421. if (this.isPlexAccount(account)) {
  1422. switch (this.selectedTab) {
  1423. case 0:
  1424. await this.loadNextPlexSongPage(account);
  1425. break;
  1426. case 1:
  1427. await this.loadNextPlexArtistPage(account);
  1428. break;
  1429. case 2:
  1430. await this.loadNextPlexAlbumPage(account);
  1431. break;
  1432. case 3:
  1433. await this.loadNextPlexPlaylistPage(account);
  1434. break;
  1435. default:
  1436. break;
  1437. }
  1438. return;
  1439. }
  1440. if (this.isDaoLiYuAccount(account)) {
  1441. switch (this.selectedTab) {
  1442. case 0:
  1443. await this.loadNextDaoLiYuSongPage(account);
  1444. break;
  1445. case 1:
  1446. await this.loadNextDaoLiYuArtistPage(account);
  1447. break;
  1448. case 2:
  1449. await this.loadNextDaoLiYuAlbumPage(account);
  1450. break;
  1451. case 3:
  1452. await this.loadNextDaoLiYuPlaylistPage(account);
  1453. break;
  1454. default:
  1455. break;
  1456. }
  1457. }
  1458. }
  1459. private async buildAlbumCoverMap(albums: NavidromeRestAlbum[], account: WebDavAccount): Promise<Map<string, string>> {
  1460. const map = new Map<string, string>();
  1461. const tasks: Promise<void>[] = [];
  1462. let directCoverCount = 0;
  1463. let generatedCoverCount = 0;
  1464. let failedCoverCount = 0;
  1465. void ServerLogUtil.info('RemoteMusicPageCover', `📀 开始处理 ${albums.length} 张专辑的封面 - 账号: ${ServerLogUtil.sanitizeAccount(account)}`);
  1466. for (let i = 0; i < albums.length; i++) {
  1467. const album = albums[i];
  1468. void ServerLogUtil.debug('RemoteMusicPageCover', `处理专辑 [${i + 1}/${albums.length}] - id: ${album.id}, name: ${album.name}`);
  1469. tasks.push((async () => {
  1470. try {
  1471. // 注意: embedArtPath 和 coverArtPath 可能指向音频文件而非封面图片
  1472. // 所以这里不能直接使用,需要通过 buildCoverUrl 生成正确的封面URL
  1473. // const directUrl = this.resolveEmbedCover(account, album.embedArtPath ?? album.coverArtPath);
  1474. // if (directUrl) {
  1475. // map.set(album.id, directUrl);
  1476. // directCoverCount++;
  1477. // void ServerLogUtil.info('RemoteMusicPageCover', `✅ 专辑使用直接封面 - name: ${album.name}, url: ${directUrl}`);
  1478. // return;
  1479. // }
  1480. // 生成封面URL
  1481. const coverId = album.coverArt ?? album.coverArtId ?? (album.id ? `al-${album.id}` : undefined);
  1482. void ServerLogUtil.debug('RemoteMusicPageCover', `专辑封面ID - name: ${album.name}, coverArt: ${album.coverArt}, coverArtId: ${album.coverArtId}, 最终coverId: ${coverId}`);
  1483. const url = await this.buildCoverUrl(account, coverId);
  1484. if (url) {
  1485. map.set(album.id, url);
  1486. generatedCoverCount++;
  1487. void ServerLogUtil.info('RemoteMusicPageCover', `✅ 专辑生成封面成功 - name: ${album.name}, coverId: ${coverId}, url: ${url}`);
  1488. } else {
  1489. failedCoverCount++;
  1490. void ServerLogUtil.error('RemoteMusicPageCover', `❌ 专辑封面失败 - name: ${album.name}, coverId: ${coverId}, 原始数据: ${JSON.stringify({coverArt: album.coverArt, coverArtId: album.coverArtId, id: album.id})}`);
  1491. }
  1492. } catch (error) {
  1493. failedCoverCount++;
  1494. void ServerLogUtil.error('RemoteMusicPageCover', `❌ 专辑封面解析异常 - name: ${album.name}, error: ${(error as Error).message}`);
  1495. }
  1496. })());
  1497. }
  1498. await Promise.all(tasks);
  1499. void ServerLogUtil.info('RemoteMusicPageCover', `📊 专辑封面处理完成 - 总数: ${albums.length}, 直接嵌入: ${directCoverCount}, 生成URL: ${generatedCoverCount}, 失败: ${failedCoverCount}`);
  1500. return map;
  1501. }
  1502. private async buildArtistCoverMap(artists: NavidromeRestArtist[], account: WebDavAccount): Promise<Map<string, string>> {
  1503. const map = new Map<string, string>();
  1504. const tasks: Promise<void>[] = [];
  1505. let directCoverCount = 0;
  1506. let generatedCoverCount = 0;
  1507. let failedCoverCount = 0;
  1508. void ServerLogUtil.info('RemoteMusicPageCover', `🎤 开始处理 ${artists.length} 位艺术家的封面 - 账号: ${ServerLogUtil.sanitizeAccount(account)}`);
  1509. for (let i = 0; i < artists.length; i++) {
  1510. const artist = artists[i];
  1511. void ServerLogUtil.debug('RemoteMusicPageCover', `处理艺术家 [${i + 1}/${artists.length}] - id: ${artist.id}, name: ${artist.name}`);
  1512. tasks.push((async () => {
  1513. try {
  1514. // 尝试获取已有图片URL
  1515. const directUrl = artist.mediumImageUrl ?? artist.largeImageUrl ?? this.resolveEmbedCover(account, artist.coverArtPath);
  1516. if (directUrl) {
  1517. map.set(artist.id, directUrl);
  1518. directCoverCount++;
  1519. void ServerLogUtil.info('RemoteMusicPageCover', `✅ 艺术家使用已有图片 - name: ${artist.name}, url: ${directUrl}`);
  1520. return;
  1521. }
  1522. // 生成封面URL
  1523. const coverId = artist.coverArt ?? artist.coverArtId ?? (artist.id ? `ar-${artist.id}` : undefined);
  1524. void ServerLogUtil.debug('RemoteMusicPageCover', `艺术家封面ID - name: ${artist.name}, coverArt: ${artist.coverArt}, coverArtId: ${artist.coverArtId}, 最终coverId: ${coverId}`);
  1525. const url = await this.buildCoverUrl(account, coverId, 256);
  1526. if (url) {
  1527. map.set(artist.id, url);
  1528. generatedCoverCount++;
  1529. void ServerLogUtil.info('RemoteMusicPageCover', `✅ 艺术家生成封面成功 - name: ${artist.name}, coverId: ${coverId}, url: ${url}`);
  1530. } else {
  1531. failedCoverCount++;
  1532. void ServerLogUtil.error('RemoteMusicPageCover', `❌ 艺术家封面失败 - name: ${artist.name}, coverId: ${coverId}, 原始数据: ${JSON.stringify({coverArt: artist.coverArt, coverArtId: artist.coverArtId, id: artist.id})}`);
  1533. }
  1534. } catch (error) {
  1535. failedCoverCount++;
  1536. void ServerLogUtil.error('RemoteMusicPageCover', `❌ 艺术家封面解析异常 - name: ${artist.name}, error: ${(error as Error).message}`);
  1537. }
  1538. })());
  1539. }
  1540. await Promise.all(tasks);
  1541. void ServerLogUtil.info('RemoteMusicPageCover', `📊 艺术家封面处理完成 - 总数: ${artists.length}, 直接链接: ${directCoverCount}, 生成URL: ${generatedCoverCount}, 失败: ${failedCoverCount}`);
  1542. return map;
  1543. }
  1544. private async buildRemoteCoverMap(ids: string[], account: WebDavAccount): Promise<Map<string, string>> {
  1545. const map = new Map<string, string>();
  1546. const tasks = ids.map(async (id) => {
  1547. if (!id) {
  1548. return;
  1549. }
  1550. try {
  1551. const url = await this.buildCoverUrl(account, id, 300);
  1552. if (url) {
  1553. map.set(id, url);
  1554. }
  1555. } catch (error) {
  1556. void ServerLogUtil.warn('CoverCache', `远程封面生成失败: ${id} ${(error as Error).message}`);
  1557. }
  1558. });
  1559. await Promise.all(tasks);
  1560. return map;
  1561. }
  1562. private buildAudioStationAlbumKey(name?: string, artist?: string): string {
  1563. const safeName = name ?? '';
  1564. const safeArtist = artist ?? '';
  1565. return `as:${safeName}|||${safeArtist}`;
  1566. }
  1567. private parseAudioStationAlbumKey(value: string): AudioStationAlbumKey {
  1568. let raw = value ?? '';
  1569. if (raw.startsWith('as:')) {
  1570. raw = raw.slice(3);
  1571. }
  1572. const parts = raw.split('|||');
  1573. const name = parts.length > 0 ? parts[0] : '';
  1574. const artist = parts.length > 1 ? parts.slice(1).join('|||') : '';
  1575. return new AudioStationAlbumKey(name, artist);
  1576. }
  1577. private async convertJellyfinArtistsToRest(artists: JellyfinArtist[], account: WebDavAccount): Promise<NavidromeRestArtist[]> {
  1578. const results: NavidromeRestArtist[] = [];
  1579. for (let i = 0; i < artists.length; i++) {
  1580. const artist = artists[i];
  1581. const coverUrl = await this.buildCoverUrl(account, artist.id, 300);
  1582. const restArtist: NavidromeRestArtist = {
  1583. id: artist.id,
  1584. name: artist.name,
  1585. albumCount: artist.albumCount,
  1586. songCount: artist.songCount,
  1587. coverUrl: coverUrl
  1588. };
  1589. results.push(restArtist);
  1590. }
  1591. return results;
  1592. }
  1593. private async convertEmbyArtistsToRest(artists: EmbyArtist[], account: WebDavAccount): Promise<NavidromeRestArtist[]> {
  1594. const results: NavidromeRestArtist[] = [];
  1595. for (let i = 0; i < artists.length; i++) {
  1596. const artist = artists[i];
  1597. const coverUrl = await this.buildCoverUrl(account, artist.id, 300);
  1598. const restArtist: NavidromeRestArtist = {
  1599. id: artist.id,
  1600. name: artist.name,
  1601. albumCount: artist.albumCount,
  1602. songCount: artist.songCount,
  1603. coverUrl: coverUrl
  1604. };
  1605. results.push(restArtist);
  1606. }
  1607. return results;
  1608. }
  1609. private async convertJellyfinAlbumsToRest(albums: JellyfinAlbum[], account: WebDavAccount): Promise<NavidromeRestAlbum[]> {
  1610. const results: NavidromeRestAlbum[] = [];
  1611. for (let i = 0; i < albums.length; i++) {
  1612. const album = albums[i];
  1613. const coverUrl = await this.buildCoverUrl(account, album.id, 300);
  1614. const restAlbum: NavidromeRestAlbum = {
  1615. id: album.id,
  1616. name: album.name,
  1617. artist: album.artist,
  1618. minYear: album.year,
  1619. coverUrl: coverUrl
  1620. };
  1621. results.push(restAlbum);
  1622. }
  1623. return results;
  1624. }
  1625. private async convertEmbyAlbumsToRest(albums: EmbyAlbum[], account: WebDavAccount): Promise<NavidromeRestAlbum[]> {
  1626. const results: NavidromeRestAlbum[] = [];
  1627. for (let i = 0; i < albums.length; i++) {
  1628. const album = albums[i];
  1629. const coverUrl = await this.buildCoverUrl(account, album.id, 300);
  1630. const restAlbum: NavidromeRestAlbum = {
  1631. id: album.id,
  1632. name: album.name,
  1633. artist: album.artist,
  1634. minYear: album.year,
  1635. coverUrl: coverUrl
  1636. };
  1637. results.push(restAlbum);
  1638. }
  1639. return results;
  1640. }
  1641. private convertAudioStationArtistsToRest(artists: AudioStationArtist[]): NavidromeRestArtist[] {
  1642. return artists.map(artist => {
  1643. const name = artist.name ?? '';
  1644. return {
  1645. id: name,
  1646. name: name
  1647. } as NavidromeRestArtist;
  1648. });
  1649. }
  1650. private async convertAudioStationAlbumsToRest(albums: AudioStationAlbum[], account: WebDavAccount): Promise<NavidromeRestAlbum[]> {
  1651. const results: NavidromeRestAlbum[] = [];
  1652. for (let i = 0; i < albums.length; i++) {
  1653. const album = albums[i];
  1654. const artistName = album.albumArtist ?? album.displayArtist ?? '';
  1655. const albumKey = this.buildAudioStationAlbumKey(album.name, artistName);
  1656. const coverUrl = await this.buildCoverUrl(account, albumKey, 300);
  1657. const restAlbum: NavidromeRestAlbum = {
  1658. id: albumKey,
  1659. name: album.name,
  1660. artist: artistName,
  1661. minYear: album.year,
  1662. coverArtId: albumKey,
  1663. coverUrl: coverUrl
  1664. };
  1665. results.push(restAlbum);
  1666. }
  1667. return results;
  1668. }
  1669. private async convertPlexArtistsToRest(artists: PlexArtist[], account: WebDavAccount): Promise<NavidromeRestArtist[]> {
  1670. const results: NavidromeRestArtist[] = [];
  1671. for (let i = 0; i < artists.length; i++) {
  1672. const artist = artists[i];
  1673. const coverId = artist.thumb ?? (artist.id ? `ar-${artist.id}` : '');
  1674. const coverUrl = coverId ? await this.buildCoverUrl(account, coverId, 300) : undefined;
  1675. const restArtist: NavidromeRestArtist = {
  1676. id: artist.id,
  1677. name: artist.name,
  1678. coverArtId: coverId,
  1679. coverUrl: coverUrl
  1680. };
  1681. results.push(restArtist);
  1682. }
  1683. return results;
  1684. }
  1685. private async convertPlexAlbumsToRest(albums: PlexAlbum[], account: WebDavAccount): Promise<NavidromeRestAlbum[]> {
  1686. const results: NavidromeRestAlbum[] = [];
  1687. for (let i = 0; i < albums.length; i++) {
  1688. const album = albums[i];
  1689. const coverId = album.thumb ?? (album.id ? `al-${album.id}` : '');
  1690. const coverUrl = coverId ? await this.buildCoverUrl(account, coverId, 300) : undefined;
  1691. const restAlbum: NavidromeRestAlbum = {
  1692. id: album.id,
  1693. name: album.name,
  1694. artist: album.artist,
  1695. minYear: album.year,
  1696. coverArtId: coverId,
  1697. coverUrl: coverUrl
  1698. };
  1699. results.push(restAlbum);
  1700. }
  1701. return results;
  1702. }
  1703. private async convertDaoLiYuArtistsToRest(artists: DaoLiYuArtist[], account: WebDavAccount): Promise<NavidromeRestArtist[]> {
  1704. const results: NavidromeRestArtist[] = [];
  1705. for (let i = 0; i < artists.length; i++) {
  1706. const artist = artists[i];
  1707. const coverId = artist.coverArtUrl ?? '';
  1708. const coverUrl = coverId ? await this.buildCoverUrl(account, coverId, 300) : undefined;
  1709. const restArtist: NavidromeRestArtist = {
  1710. id: artist.id,
  1711. name: artist.name,
  1712. albumCount: artist.albumCount,
  1713. songCount: artist.trackCount,
  1714. coverArtId: coverId,
  1715. coverUrl: coverUrl
  1716. };
  1717. results.push(restArtist);
  1718. }
  1719. return results;
  1720. }
  1721. private async convertDaoLiYuAlbumsToRest(albums: DaoLiYuAlbum[], account: WebDavAccount): Promise<NavidromeRestAlbum[]> {
  1722. const results: NavidromeRestAlbum[] = [];
  1723. for (let i = 0; i < albums.length; i++) {
  1724. const album = albums[i];
  1725. const coverId = album.coverArtUrl ?? '';
  1726. const coverUrl = coverId ? await this.buildCoverUrl(account, coverId, 300) : undefined;
  1727. const restAlbum: NavidromeRestAlbum = {
  1728. id: album.id,
  1729. name: album.title,
  1730. artist: album.artist,
  1731. minYear: album.year,
  1732. coverArtId: coverId,
  1733. coverUrl: coverUrl
  1734. };
  1735. results.push(restAlbum);
  1736. }
  1737. return results;
  1738. }
  1739. private async convertDaoLiYuPlaylistsToRest(playlists: DaoLiYuPlaylist[], account: WebDavAccount): Promise<NavidromeRestPlaylist[]> {
  1740. const results: NavidromeRestPlaylist[] = [];
  1741. for (let i = 0; i < playlists.length; i++) {
  1742. const playlist = playlists[i];
  1743. const coverId = playlist.coverArtUrl ?? '';
  1744. const coverUrl = coverId ? await this.buildCoverUrl(account, coverId, 300) : undefined;
  1745. const restPlaylist: NavidromeRestPlaylist = {
  1746. id: playlist.id,
  1747. name: playlist.name,
  1748. comment: playlist.description ?? undefined,
  1749. songCount: playlist.songCount,
  1750. coverArtId: coverId,
  1751. coverUrl: coverUrl
  1752. };
  1753. results.push(restPlaylist);
  1754. }
  1755. return results;
  1756. }
  1757. private convertJellyfinSongsToRestSongs(songs: JellyfinSong[]): NavidromeRestSong[] {
  1758. return songs.map(song => {
  1759. const restSong: NavidromeRestSong = {
  1760. id: song.id,
  1761. title: song.title,
  1762. album: song.album,
  1763. albumId: song.albumId,
  1764. artist: song.artist,
  1765. artistId: song.artistId,
  1766. duration: song.durationSeconds,
  1767. bitRate: song.bitRate,
  1768. suffix: song.suffix,
  1769. size: song.size,
  1770. track: song.track,
  1771. year: song.year,
  1772. coverArt: song.albumId ?? song.id
  1773. };
  1774. return restSong;
  1775. });
  1776. }
  1777. private convertEmbySongsToRestSongs(songs: EmbySong[]): NavidromeRestSong[] {
  1778. return songs.map(song => {
  1779. const restSong: NavidromeRestSong = {
  1780. id: song.id,
  1781. title: song.title,
  1782. album: song.album,
  1783. albumId: song.albumId,
  1784. artist: song.artist,
  1785. artistId: song.artistId,
  1786. duration: song.durationSeconds,
  1787. bitRate: song.bitRate,
  1788. suffix: song.suffix,
  1789. size: song.size,
  1790. track: song.track,
  1791. year: song.year,
  1792. coverArt: song.albumId ?? song.id
  1793. };
  1794. return restSong;
  1795. });
  1796. }
  1797. private convertAudioStationSongsToRestSongs(songs: AudioStationSong[]): NavidromeRestSong[] {
  1798. return songs.map(song => {
  1799. const artistName = song.artist ?? song.albumArtist ?? '';
  1800. const albumKey = this.buildAudioStationAlbumKey(song.album, song.albumArtist ?? song.artist);
  1801. const songCoverId = song.id ? `as-song:${song.id}` : albumKey;
  1802. const restSong: NavidromeRestSong = {
  1803. id: song.id,
  1804. title: song.title,
  1805. album: song.album,
  1806. albumId: albumKey,
  1807. artist: artistName,
  1808. artistId: artistName,
  1809. duration: song.durationSeconds,
  1810. bitRate: song.bitRate,
  1811. suffix: song.container,
  1812. size: song.size,
  1813. track: song.track,
  1814. year: song.year,
  1815. contentType: song.container ? `audio/${song.container}` : undefined,
  1816. coverArtId: songCoverId
  1817. };
  1818. return restSong;
  1819. });
  1820. }
  1821. private convertPlexSongsToRestSongs(songs: PlexSong[]): NavidromeRestSong[] {
  1822. return songs.map(song => {
  1823. const coverId = song.albumThumb ?? song.thumb ?? song.albumId ?? song.id;
  1824. const restSong: NavidromeRestSong = {
  1825. id: song.id,
  1826. title: song.title,
  1827. album: song.album,
  1828. albumId: song.albumId,
  1829. artist: song.artist,
  1830. artistId: song.artistId,
  1831. duration: song.durationSeconds,
  1832. bitRate: song.bitRate,
  1833. suffix: song.suffix,
  1834. size: song.size,
  1835. track: song.track,
  1836. year: song.year,
  1837. contentType: song.mimeType,
  1838. coverArtId: coverId
  1839. };
  1840. return restSong;
  1841. });
  1842. }
  1843. private convertDaoLiYuSongsToRestSongs(songs: DaoLiYuTrack[]): NavidromeRestSong[] {
  1844. return songs.map(song => {
  1845. const coverId = song.coverArtUrl ?? song.albumId ?? song.id;
  1846. const restSong: NavidromeRestSong = {
  1847. id: song.id,
  1848. title: song.title,
  1849. album: song.album,
  1850. albumId: song.albumId,
  1851. artist: song.artist,
  1852. artistId: song.artistId,
  1853. duration: song.durationSeconds,
  1854. bitRate: song.bitRate,
  1855. suffix: song.suffix,
  1856. size: song.size,
  1857. track: song.track,
  1858. year: song.year,
  1859. contentType: song.mimeType,
  1860. coverArtId: coverId,
  1861. lyrics: song.lyrics,
  1862. createdAt: song.createdAt
  1863. };
  1864. return restSong;
  1865. });
  1866. }
  1867. private convertAudioStationPlaylistsToRest(playlists: AudioStationPlaylist[]): NavidromeRestPlaylist[] {
  1868. return playlists.map(playlist => {
  1869. const restPlaylist: NavidromeRestPlaylist = {
  1870. id: playlist.id,
  1871. name: playlist.name,
  1872. path: playlist.path
  1873. };
  1874. return restPlaylist;
  1875. });
  1876. }
  1877. private convertPlexPlaylistsToRest(playlists: PlexPlaylist[]): NavidromeRestPlaylist[] {
  1878. return playlists.map(playlist => {
  1879. const restPlaylist: NavidromeRestPlaylist = {
  1880. id: playlist.id,
  1881. name: playlist.title,
  1882. comment: playlist.summary,
  1883. duration: playlist.duration,
  1884. songCount: playlist.leafCount
  1885. };
  1886. return restPlaylist;
  1887. });
  1888. }
  1889. private async fetchAllJellyfinArtistSongs(account: WebDavAccount, artistId: string): Promise<JellyfinSong[]> {
  1890. const results: JellyfinSong[] = [];
  1891. let startIndex = 0;
  1892. while (true) {
  1893. const response = await jellyfinApi.getArtistSongs(account, artistId, startIndex, this.REMOTE_PAGE_SIZE);
  1894. results.push(...response.items);
  1895. if (response.nextStart === null) {
  1896. break;
  1897. }
  1898. startIndex = response.nextStart;
  1899. }
  1900. return results;
  1901. }
  1902. private async fetchAllEmbyArtistSongs(account: WebDavAccount, artistId: string): Promise<EmbySong[]> {
  1903. const results: EmbySong[] = [];
  1904. let startIndex = 0;
  1905. while (true) {
  1906. const response = await embyApi.getArtistSongs(account, artistId, startIndex, this.REMOTE_PAGE_SIZE);
  1907. results.push(...response.items);
  1908. if (response.nextStart === null) {
  1909. break;
  1910. }
  1911. startIndex = response.nextStart;
  1912. }
  1913. return results;
  1914. }
  1915. private async fetchAllAudioStationArtistSongs(account: WebDavAccount, artistName: string): Promise<AudioStationSong[]> {
  1916. if (!artistName || artistName.trim().length === 0) {
  1917. return [];
  1918. }
  1919. const keyword = artistName.trim();
  1920. const songs = await audioStationApi.searchSongs(account, keyword, 0, this.REMOTE_SEARCH_LIMIT);
  1921. return songs.filter(song => {
  1922. const artist = song.artist ?? song.albumArtist ?? '';
  1923. return artist.trim() === keyword;
  1924. });
  1925. }
  1926. private async fetchAllAudioStationPlaylistSongs(account: WebDavAccount, playlistId: string): Promise<AudioStationSong[]> {
  1927. const results: AudioStationSong[] = [];
  1928. let startIndex = 0;
  1929. while (true) {
  1930. const response = await audioStationApi.getPlaylistSongsPage(account, playlistId, startIndex, this.REMOTE_PAGE_SIZE);
  1931. results.push(...response.items);
  1932. if (response.nextStart === null) {
  1933. break;
  1934. }
  1935. startIndex = response.nextStart;
  1936. }
  1937. return results;
  1938. }
  1939. private async fetchAllPlexArtistSongs(account: WebDavAccount, artistId: string): Promise<PlexSong[]> {
  1940. const results: PlexSong[] = [];
  1941. const albums = await plexApi.getArtistAlbums(account, artistId);
  1942. for (let i = 0; i < albums.length; i++) {
  1943. const album = albums[i];
  1944. if (!album.id) {
  1945. continue;
  1946. }
  1947. const songs = await plexApi.getAlbumSongs(account, album.id);
  1948. results.push(...songs);
  1949. }
  1950. return results;
  1951. }
  1952. private async fetchAllPlexPlaylistSongs(account: WebDavAccount, playlistId: string): Promise<PlexSong[]> {
  1953. const results: PlexSong[] = [];
  1954. let startIndex = 0;
  1955. while (true) {
  1956. const response = await plexApi.getPlaylistSongsPage(account, playlistId, startIndex, this.REMOTE_PAGE_SIZE);
  1957. results.push(...response.items);
  1958. if (response.nextStart === null) {
  1959. break;
  1960. }
  1961. startIndex = response.nextStart;
  1962. }
  1963. return results;
  1964. }
  1965. private buildSongDedupKey(title?: string, artist?: string, album?: string, durationSeconds?: number): string {
  1966. const safeTitle = title ?? '';
  1967. const safeArtist = artist ?? '';
  1968. const safeAlbum = album ?? '';
  1969. const safeDuration = durationSeconds !== undefined && durationSeconds !== null ? durationSeconds.toString() : '';
  1970. return `${safeTitle}__${safeArtist}__${safeAlbum}__${safeDuration}`.toLowerCase();
  1971. }
  1972. private buildSongKeyFromItem(item: VideoItem): string {
  1973. const safeTitle = item.name ?? '';
  1974. const safeArtist = item.artist ?? '';
  1975. const safeAlbum = item.album ?? '';
  1976. const safeDuration = item.duration ?? '';
  1977. return `${safeTitle}__${safeArtist}__${safeAlbum}__${safeDuration}`.toLowerCase();
  1978. }
  1979. private dedupRemoteSongsByKey(items: VideoItem[]): VideoItem[] {
  1980. const map = new Map<string, VideoItem>();
  1981. for (let i = 0; i < items.length; i++) {
  1982. const item = items[i];
  1983. const key = this.buildSongKeyFromItem(item);
  1984. const existing = map.get(key);
  1985. if (!existing) {
  1986. map.set(key, item);
  1987. continue;
  1988. }
  1989. const existingHasAlbumId = StrUtil.isNotEmpty(existing.navAlbumId);
  1990. const currentHasAlbumId = StrUtil.isNotEmpty(item.navAlbumId);
  1991. if (!existingHasAlbumId && currentHasAlbumId) {
  1992. map.set(key, item);
  1993. }
  1994. }
  1995. return Array.from(map.values());
  1996. }
  1997. private convertApiSongsToRestSongs(songs: NavidromeSong[]): NavidromeRestSong[] {
  1998. return songs.map((song: NavidromeSong): NavidromeRestSong => ({
  1999. id: song.id,
  2000. title: song.title,
  2001. artist: song.artist,
  2002. artistId: song.artistId,
  2003. album: song.album,
  2004. albumId: song.albumId,
  2005. duration: song.duration,
  2006. bitRate: song.bitRate,
  2007. suffix: song.suffix,
  2008. size: song.size,
  2009. createdAt: song.created,
  2010. genre: song.genre,
  2011. track: song.track,
  2012. year: song.year,
  2013. contentType: song.contentType,
  2014. coverArt: song.coverArt,
  2015. coverArtId: song.coverArt,
  2016. lyrics: song.lyrics,
  2017. }));
  2018. }
  2019. private async convertSongsToVideoItems(songs: NavidromeRestSong[], account: WebDavAccount): Promise<VideoItem[]> {
  2020. const tasks: Promise<VideoItem>[] = [];
  2021. let successCount = 0;
  2022. let failedCount = 0;
  2023. void ServerLogUtil.info('SongConvert', `开始转换 ${songs.length} 首歌曲为 VideoItem`);
  2024. for (let i = 0; i < songs.length; i++) {
  2025. const song = songs[i];
  2026. tasks.push((async () => {
  2027. try {
  2028. let coverUrl: string | undefined;
  2029. try {
  2030. coverUrl = await this.resolveSongCover(song, account);
  2031. } catch (error) {
  2032. void ServerLogUtil.warn('SongConvert', `歌曲 ${song.title} 封面解析失败: ${(error as Error).message}`);
  2033. }
  2034. const videoItem = this.convertSongToVideoItem(song, account, coverUrl);
  2035. successCount++;
  2036. // 记录前几首歌的详细信息用于调试
  2037. if (i < 3) {
  2038. void ServerLogUtil.debug('SongConvert', `歌曲 ${i + 1}: ${videoItem.name}, 封面: ${coverUrl ? '有' : '无'}, 路径: ${videoItem.filePath}`);
  2039. }
  2040. return videoItem;
  2041. } catch (error) {
  2042. failedCount++;
  2043. void ServerLogUtil.error('SongConvert', `歌曲 ${song.title} 转换失败: ${(error as Error).message}`);
  2044. throw new Error(`歌曲 ${song.title} 转换失败: ${(error as Error).message}`);
  2045. }
  2046. })());
  2047. }
  2048. const results = await Promise.all(tasks);
  2049. void ServerLogUtil.info('SongConvert', `歌曲转换完成: 成功 ${successCount}, 失败 ${failedCount}`);
  2050. return results;
  2051. }
  2052. private async resolveSongCover(song: NavidromeRestSong, account: WebDavAccount): Promise<string | undefined> {
  2053. void ServerLogUtil.debug('RemoteMusicPageCover', `🎵 解析歌曲封面 - title: ${song.title}, albumId: ${song.albumId}, id: ${song.id}`);
  2054. // 注释掉这个代码可以解决NavidRome部分账号没有封面问题
  2055. // if (this.isNavidromeAccount(account) && song.albumId) {
  2056. // const albumCover = song.albumId ? this.albumCoverLookup.get(song.albumId) : undefined;
  2057. // if (albumCover) {
  2058. // void ServerLogUtil.debug('RemoteMusicPageCover', `✅ 歌曲使用专辑封面缓存 - title: ${song.title}, albumCover: ${albumCover}`);
  2059. // return albumCover;
  2060. // }
  2061. // }
  2062. if (!this.isNavidromeAccount(account)) {
  2063. const fallbackId = song.coverArtId ?? song.albumId ?? song.id;
  2064. void ServerLogUtil.debug('RemoteMusicPageCover', `歌曲使用非Navidrome账号封面 - title: ${song.title}, fallbackId: ${fallbackId}`);
  2065. return this.buildCoverUrl(account, fallbackId);
  2066. }
  2067. const directUrl = this.resolveEmbedCover(account, song.embedArtPath ?? song.coverArtPath);
  2068. if (directUrl) {
  2069. void ServerLogUtil.info('RemoteMusicPageCover', `✅ 歌曲使用直接封面 - title: ${song.title}, url: ${directUrl}`);
  2070. return directUrl;
  2071. }
  2072. const coverId = song.coverArt ?? song.coverArtId ?? song.id;
  2073. void ServerLogUtil.debug('RemoteMusicPageCover', `歌曲生成封面URL - title: ${song.title}, coverArt: ${song.coverArt}, coverArtId: ${song.coverArtId}, 最终coverId: ${coverId}`);
  2074. return this.buildCoverUrl(account, coverId);
  2075. }
  2076. private async buildCoverUrl(account: WebDavAccount, coverId?: string, size: number = 300): Promise<string | undefined> {
  2077. void ServerLogUtil.info('RemoteMusicPageCover', `开始构建封面URL - coverId: ${coverId}, size: ${size}, 账号: ${ServerLogUtil.sanitizeAccount(account)}`);
  2078. if (!coverId || coverId.trim().length === 0) {
  2079. void ServerLogUtil.warn('RemoteMusicPageCover', `封面ID为空,跳过构建 - coverId: "${coverId}"`);
  2080. return undefined;
  2081. }
  2082. const normalizedId = coverId.trim();
  2083. const cacheKey = `${normalizedId}_${size}`;
  2084. if (this.isNavidromeAccount(account)) {
  2085. const cached = this.coverUrlCache.get(cacheKey);
  2086. if (cached) {
  2087. void ServerLogUtil.info('RemoteMusicPageCover', `✅ 缓存命中 - coverId: ${coverId}, size: ${size}, url: ${cached}`);
  2088. return cached;
  2089. }
  2090. }
  2091. void ServerLogUtil.info('RemoteMusicPageCover', `⚡ 调用API生成封面URL - coverId: ${coverId}, size: ${size}`);
  2092. let url: string | undefined = undefined;
  2093. try {
  2094. if (this.isNavidromeAccount(account)) {
  2095. void ServerLogUtil.debug('RemoteMusicPageCover', `[开始] 调用 navidromeApi.buildCoverArtUrl - coverId: ${normalizedId}, size: ${size}`);
  2096. void ServerLogUtil.debug('RemoteMusicPageCover', `[账号信息] host=${account.host}, port=${account.port}, enableHttps=${account.enableHttps}`);
  2097. void ServerLogUtil.debug('RemoteMusicPageCover', `[账号信息] basePath=${account.navidromeBasePath}`);
  2098. url = await navidromeApi.buildCoverArtUrl(account, normalizedId, size);
  2099. void ServerLogUtil.debug('RemoteMusicPageCover', `[完成] navidromeApi.buildCoverArtUrl 返回 - coverId: ${normalizedId}, 返回值: "${url}"`);
  2100. if (url) {
  2101. void ServerLogUtil.info('RemoteMusicPageCover', `✅ API返回URL成功 - coverId: ${coverId}, url: ${url}`);
  2102. } else {
  2103. void ServerLogUtil.warn('RemoteMusicPageCover', `⚠️ API返回空值 - coverId: ${coverId}`);
  2104. }
  2105. } else if (this.isJellyfinAccount(account)) {
  2106. void ServerLogUtil.debug('RemoteMusicPageCover', `调用 jellyfinApi.buildPrimaryImageUrl - coverId: ${normalizedId}, size: ${size}`);
  2107. url = await jellyfinApi.buildPrimaryImageUrl(account, normalizedId, size, size);
  2108. } else if (this.isEmbyAccount(account)) {
  2109. void ServerLogUtil.debug('RemoteMusicPageCover', `调用 embyApi.buildPrimaryImageUrl - coverId: ${normalizedId}, size: ${size}`);
  2110. url = await embyApi.buildPrimaryImageUrl(account, normalizedId, size, size);
  2111. } else if (this.isAudioStationAccount(account)) {
  2112. if (this.isAudioStationSongCoverId(normalizedId)) {
  2113. const songId = this.stripAudioStationSongCoverId(normalizedId);
  2114. void ServerLogUtil.debug('RemoteMusicPageCover', `调用 audioStationApi.buildSongCoverUrl - songId=${songId}`);
  2115. url = await audioStationApi.buildSongCoverUrl(account, songId);
  2116. } else {
  2117. const key = this.parseAudioStationAlbumKey(normalizedId);
  2118. void ServerLogUtil.debug('RemoteMusicPageCover', `调用 audioStationApi.buildAlbumCoverUrl - album=${key.name}, artist=${key.artist}`);
  2119. url = await audioStationApi.buildAlbumCoverUrl(account, key.name, key.artist);
  2120. }
  2121. } else if (this.isPlexAccount(account)) {
  2122. void ServerLogUtil.debug('RemoteMusicPageCover', `调用 plexApi.buildImageUrl - coverId: ${normalizedId}`);
  2123. url = plexApi.buildImageUrl(account, normalizedId);
  2124. } else if (this.isDaoLiYuAccount(account)) {
  2125. void ServerLogUtil.debug('RemoteMusicPageCover', `调用 daoLiYuApi.buildImageUrl - coverId: ${normalizedId}`);
  2126. url = daoLiYuApi.buildImageUrl(account, normalizedId);
  2127. }
  2128. if (url && this.isNavidromeAccount(account)) {
  2129. this.coverUrlCache.set(cacheKey, url);
  2130. void ServerLogUtil.info('RemoteMusicPageCover', `✅ 封面URL生成成功并已缓存 - coverId: ${coverId}, url: ${url}`);
  2131. void ServerLogUtil.debug('RemoteMusicPageCover', `缓存键值 - cacheKey: ${cacheKey}`);
  2132. } else if (!url) {
  2133. void ServerLogUtil.error('RemoteMusicPageCover', `❌ 封面URL生成失败(返回空) - coverId: ${coverId}, size: ${size}`);
  2134. } else {
  2135. void ServerLogUtil.info('RemoteMusicPageCover', `✅ 封面URL生成成功(非Navidrome账号) - coverId: ${coverId}, url: ${url}`);
  2136. }
  2137. } catch (error) {
  2138. const err = error as Error;
  2139. void ServerLogUtil.error('RemoteMusicPageCover', `❌ 封面URL生成异常 - coverId: ${coverId}, error: ${err.message}`);
  2140. void ServerLogUtil.error('RemoteMusicPageCover', `错误类型: ${err.name || 'Unknown'}`);
  2141. void ServerLogUtil.error('RemoteMusicPageCover', `错误堆栈: ${err.stack || '无'}`);
  2142. }
  2143. return url;
  2144. }
  2145. private isAudioStationSongCoverId(value: string): boolean {
  2146. return value.startsWith('as-song:');
  2147. }
  2148. private stripAudioStationSongCoverId(value: string): string {
  2149. return value.replace(/^as-song:/, '');
  2150. }
  2151. /**
  2152. * 记录账号缓存信息
  2153. */
  2154. private async logAccountCacheInfo(account: WebDavAccount): Promise<void> {
  2155. try {
  2156. void ServerLogUtil.info('AccountInfo', `账号信息: ${ServerLogUtil.sanitizeAccount(account)}`);
  2157. // 记录缓存路径信息
  2158. const cachePreview = this.getCachePreviewInfo(account);
  2159. if (cachePreview) {
  2160. void ServerLogUtil.info('AccountInfo', `Navidrome缓存目录结构:`);
  2161. void ServerLogUtil.info('AccountInfo', `- 缓存根目录: ${cachePreview.cacheRoot}`);
  2162. void ServerLogUtil.info('AccountInfo', `- 示例缓存路径: ${cachePreview.examplePath}`);
  2163. } else {
  2164. void ServerLogUtil.warn('AccountInfo', '无法预览缓存目录:上下文或根目录不可用');
  2165. }
  2166. // 记录封面缓存状态
  2167. void ServerLogUtil.info('AccountInfo', `当前封面URL缓存数量: ${this.coverUrlCache.size}`);
  2168. if (this.coverUrlCache.size > 0) {
  2169. const cacheKeys = Array.from(this.coverUrlCache.keys()).slice(0, 10);
  2170. void ServerLogUtil.debug('AccountInfo', `封面缓存示例: ${cacheKeys.join(', ')}`);
  2171. }
  2172. } catch (error) {
  2173. void ServerLogUtil.error('AccountInfo', `记录账号信息失败: ${(error as Error).message}`);
  2174. }
  2175. }
  2176. /**
  2177. * 记录缓存统计信息
  2178. */
  2179. private async logCacheStatistics(account: WebDavAccount): Promise<void> {
  2180. try {
  2181. void ServerLogUtil.info('CacheStats', '=== Navidrome 缓存统计 ===');
  2182. void ServerLogUtil.info('CacheStats', `封面URL缓存: ${this.coverUrlCache.size} 个条目`);
  2183. void ServerLogUtil.info('CacheStats', `已加载歌曲: ${this.allVideos.length} 首`);
  2184. void ServerLogUtil.info('CacheStats', `已处理艺术家: ${this.artists.length} 位`);
  2185. void ServerLogUtil.info('CacheStats', `已处理专辑: ${this.albums.length} 张`);
  2186. // 计算封面统计
  2187. const songsWithCover = this.allVideos.filter(song => song.pixelMapPath && song.pixelMapPath.length > 0).length;
  2188. const albumsWithCover = this.albums.filter(album => album.coverUrl && album.coverUrl.length > 0).length;
  2189. const artistsWithCover = this.artists.filter(artist => artist.coverUrl && artist.coverUrl.length > 0).length;
  2190. void ServerLogUtil.info('CacheStats', `封面统计:`);
  2191. void ServerLogUtil.info('CacheStats', `- 歌曲有封面: ${songsWithCover}/${this.allVideos.length} (${Math.round(songsWithCover / this.allVideos.length * 100)}%)`);
  2192. void ServerLogUtil.info('CacheStats', `- 专辑有封面: ${albumsWithCover}/${this.albums.length} (${Math.round(albumsWithCover / this.albums.length * 100)}%)`);
  2193. void ServerLogUtil.info('CacheStats', `- 艺术家有封面: ${artistsWithCover}/${this.artists.length} (${Math.round(artistsWithCover / this.artists.length * 100)}%)`);
  2194. } catch (error) {
  2195. void ServerLogUtil.error('CacheStats', `记录缓存统计失败: ${(error as Error).message}`);
  2196. }
  2197. }
  2198. private resolveEmbedCover(account: WebDavAccount, path?: string): string | undefined {
  2199. if (!this.isNavidromeAccount(account)) {
  2200. return undefined;
  2201. }
  2202. return navidromeRestApi.resolveResourceUrl(account, path);
  2203. }
  2204. private resolveLibraryInfo(account: WebDavAccount): LibraryInfo {
  2205. if (this.isJellyfinAccount(account)) {
  2206. return { type: CommonConstants.TYPE_JELLYFIN, scheme: 'jellyfin' } as LibraryInfo;
  2207. }
  2208. if (this.isEmbyAccount(account)) {
  2209. return { type: CommonConstants.TYPE_EMBY, scheme: 'emby' } as LibraryInfo;
  2210. }
  2211. if (this.isAudioStationAccount(account)) {
  2212. return { type: CommonConstants.TYPE_AUDIOSTATION, scheme: 'audiostation' } as LibraryInfo;
  2213. }
  2214. if (this.isPlexAccount(account)) {
  2215. return { type: CommonConstants.TYPE_PLEX, scheme: 'plex' } as LibraryInfo;
  2216. }
  2217. if (this.isDaoLiYuAccount(account)) {
  2218. return { type: CommonConstants.TYPE_DAOLIYU, scheme: 'daoliyu' } as LibraryInfo;
  2219. }
  2220. return { type: CommonConstants.TYPE_NAVIDROME, scheme: 'navidrome' } as LibraryInfo;
  2221. }
  2222. private convertSongToVideoItem(song: NavidromeRestSong, account: WebDavAccount, coverUrl?: string): VideoItem {
  2223. const title = song.title ?? Constants.UNKNOWN_TITLE;
  2224. const libraryInfo = this.resolveLibraryInfo(account);
  2225. // 调试日志:记录从playlist或其他API获取的歌曲的id字段
  2226. void ServerLogUtil.debug('SongConvert', `转换歌曲: ${title}`);
  2227. void ServerLogUtil.debug('SongConvert', `- song.id: ${song.id}`);
  2228. void ServerLogUtil.debug('SongConvert', `- song.artistId: ${song.artistId}`);
  2229. void ServerLogUtil.debug('SongConvert', `- song.albumId: ${song.albumId}`);
  2230. void ServerLogUtil.debug('SongConvert', `- song.lyrics: ${song.lyrics}`);
  2231. const videoItem = new VideoItem(
  2232. title,
  2233. song.id,
  2234. `${libraryInfo.scheme}://${account.id ?? 0}/${song.id}`,
  2235. libraryInfo.type,
  2236. song.size ?? 0,
  2237. song.createdAt ?? '',
  2238. Utility.formatFSize(song.size ?? 0),
  2239. undefined,
  2240. song.artist ?? Constants.UNKNOWN_ARTIST,
  2241. song.album ?? '',
  2242. `${title}${song.suffix ? '.' + song.suffix : ''}`
  2243. );
  2244. const durationStr = this.formatSongDuration(song.duration);
  2245. if (durationStr) {
  2246. videoItem.duration = durationStr;
  2247. }
  2248. videoItem.size = Utility.formatFSize(song.size ?? 0);
  2249. videoItem.bit_rate = song.bitRate ? song.bitRate.toString() : undefined;
  2250. videoItem.genre = song.genre;
  2251. videoItem.webdav_account_id = account.id?.toString();
  2252. videoItem.remote_rel_path = song.id;
  2253. videoItem.navArtistId = song.artistId;
  2254. videoItem.navAlbumId = song.albumId;
  2255. videoItem.pixelMapPath = coverUrl;
  2256. videoItem.lyricContent = song.lyrics;
  2257. // 调试日志:检查歌曲的 albumId 和 artistId
  2258. // if (this.allVideos.length < 3) {
  2259. // Logger.info('heanup', `歌曲 ${title}: artistId=${song.artistId}, albumId=${song.albumId}, artist=${song.artist}, album=${song.album}`);
  2260. // }
  2261. if (song.track !== undefined && song.track !== null) {
  2262. videoItem.track = song.track.toString();
  2263. }
  2264. if (song.year !== undefined && song.year !== null) {
  2265. videoItem.year = song.year.toString();
  2266. }
  2267. if (song.contentType) {
  2268. videoItem.mimeType = song.contentType;
  2269. }
  2270. // 记录最终生成的VideoItem路径
  2271. void ServerLogUtil.debug('SongConvert', `- VideoItem.filePath: ${videoItem.filePath}`);
  2272. void ServerLogUtil.debug('SongConvert', `- VideoItem.remote_rel_path: ${videoItem.remote_rel_path}`);
  2273. return videoItem;
  2274. }
  2275. private formatSongDuration(durationSeconds?: number): string | undefined {
  2276. if (durationSeconds === undefined || durationSeconds === null || durationSeconds < 0) {
  2277. return undefined;
  2278. }
  2279. const totalSeconds = Math.floor(durationSeconds);
  2280. const minutes = Math.floor(totalSeconds / 60);
  2281. const seconds = totalSeconds % 60;
  2282. const pad = (value: number) => value.toString().padStart(2, '0');
  2283. return `${pad(minutes)}:${pad(seconds)}`;
  2284. }
  2285. @Builder
  2286. topTitleBar() {
  2287. Column() {
  2288. Row({ space: 6 }) {
  2289. // 标题或搜索框
  2290. if (!this.isSearchMode) {
  2291. // 详情视图模式下显示返回按钮
  2292. if (this.isDetailView) {
  2293. Button({ type: ButtonType.Circle, stateEffect: true }) {
  2294. SymbolGlyph($r('sys.symbol.chevron_left'))
  2295. .attributeModifier(new SymbolGlyphFancyModifier(24, '', ''))
  2296. }
  2297. .attributeModifier(new ButtonFancyModifier(40, 40))
  2298. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.6 })
  2299. .animation({ duration: 300, curve: Curve.Ease })
  2300. .onClick(() => {
  2301. // 返回到之前的标签页
  2302. this.isDetailView = false;
  2303. this.clearFilter();
  2304. })
  2305. .attributeModifier(new ShadowModifier())
  2306. .zIndex(0)
  2307. Text(this.filterLabel)
  2308. .margin({ left: 3, right: 10 })
  2309. .fontColor($r('app.color.text_color'))
  2310. .fontSize(18)
  2311. .maxLines(1)
  2312. .textOverflow({ overflow: TextOverflow.MARQUEE })
  2313. .layoutWeight(1)
  2314. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.6 })
  2315. .animation({ duration: 300, curve: Curve.Ease })
  2316. } else {
  2317. // 正常模式:侧边栏按钮和账号名
  2318. Button({ type: ButtonType.Circle, stateEffect: true }) {
  2319. SymbolGlyph($r('sys.symbol.sort'))
  2320. .attributeModifier(new SymbolGlyphFancyModifier(25, '', ''))
  2321. }
  2322. .attributeModifier(new ButtonFancyModifier(40, 40))
  2323. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.6 })
  2324. .animation({ duration: 300, curve: Curve.Ease })
  2325. .onClick(() => {
  2326. this.getUIContext().animateTo({ duration: 555 }, () => {
  2327. // 动画闭包内控制Image组件的出现和消失
  2328. this.isShowDrawer = !this.isShowDrawer
  2329. this.offsetX = 0
  2330. })
  2331. })
  2332. .attributeModifier(new ShadowModifier())
  2333. .zIndex(0)
  2334. Text(this.selectedAccount.name)
  2335. .margin({ left: 3, right: 10 })
  2336. .fontColor($r('app.color.text_color'))
  2337. .fontSize(18)
  2338. .maxLines(1)
  2339. .textOverflow({ overflow: TextOverflow.MARQUEE })
  2340. .layoutWeight(1)
  2341. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.6 })
  2342. .onClick(() => {
  2343. // 可以添加标题点击事件
  2344. })
  2345. .animation({ duration: 300, curve: Curve.Ease })
  2346. }
  2347. } else {
  2348. Button({ type: ButtonType.Circle, stateEffect: true }) {
  2349. SymbolGlyph($r('sys.symbol.chevron_left'))
  2350. .attributeModifier(new SymbolGlyphFancyModifier(24, '', ''))
  2351. }
  2352. .attributeModifier(new ButtonFancyModifier(40, 40))
  2353. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.6 })
  2354. .animation({ duration: 300, curve: Curve.Ease })
  2355. .onClick(() => {
  2356. this.isSearchMode = false;
  2357. void this.onSearchInput('');
  2358. })
  2359. .attributeModifier(new ShadowModifier())
  2360. .zIndex(0)
  2361. }
  2362. // 搜索框
  2363. Search({ value: this.searchText, placeholder: '搜索标题、艺术家...' })
  2364. .searchButton('搜索', { fontColor: this.themeColor })
  2365. .searchIcon({
  2366. src: $r('sys.media.ohos_ic_public_search_filled')
  2367. })
  2368. .cancelButton({
  2369. style: CancelButtonStyle.CONSTANT,
  2370. icon: {
  2371. src: $r('sys.media.ohos_ic_public_cancel_filled')
  2372. }
  2373. })
  2374. .layoutWeight(1)
  2375. .height(35)
  2376. .maxLength(20)
  2377. .backgroundColor(this.isDarkMode?Color.Black:'#F5F5F5')
  2378. .placeholderColor(Color.Grey)
  2379. .placeholderFont({ size: 14, weight: 400 })
  2380. .textFont({ size: 14, weight: 400 })
  2381. .onSubmit((value: string) => {
  2382. void this.onSearchInput(value);
  2383. })
  2384. .onChange((value: string) => {
  2385. void this.onSearchInput(value);
  2386. })
  2387. .visibility(this.isSearchMode?Visibility.Visible:Visibility.None)
  2388. .animation({ duration: 300, curve: Curve.Ease })
  2389. // 搜索/排序按钮
  2390. if (!this.isSearchMode) {
  2391. // 搜索按钮
  2392. Button({ type: ButtonType.Circle, stateEffect: true }) {
  2393. SymbolGlyph($r('sys.symbol.magnifyingglass'))
  2394. .attributeModifier(new SymbolGlyphFancyModifier(25, '', ''))
  2395. }
  2396. .attributeModifier(new ButtonFancyModifier(40, 40))
  2397. .animation({ duration: 300, curve: Curve.Ease })
  2398. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.6 })
  2399. .attributeModifier(new ShadowModifier())
  2400. .zIndex(0)
  2401. .visibility(this.selectedTab==0?Visibility.Visible:Visibility.None)
  2402. .onClick(() => {
  2403. this.isSearchMode = true;
  2404. if (!this.isSearchLoading && this.searchText.length === 0) {
  2405. this.filteredList = [];
  2406. }
  2407. })
  2408. // 排序按钮
  2409. Button({ type: ButtonType.Circle, stateEffect: true }) {
  2410. SymbolGlyph($r('sys.symbol.list_number'))
  2411. .attributeModifier(new SymbolGlyphFancyModifier(25, '', ''))
  2412. }
  2413. .attributeModifier(new ButtonFancyModifier(40, 40))
  2414. .animation({ duration: 300, curve: Curve.Ease })
  2415. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.6 })
  2416. .bindMenu(this.SortMenuBuilder)
  2417. .attributeModifier(new ShadowModifier())
  2418. .zIndex(0)
  2419. }
  2420. }
  2421. .width('100%')
  2422. .height(55)
  2423. .padding({ left: 15, right: 15 })
  2424. .justifyContent(FlexAlign.SpaceBetween)
  2425. .alignItems(VerticalAlign.Center)
  2426. // 分段按钮
  2427. SegmentButton({
  2428. options: this.tabOptions,
  2429. selectedIndexes: $tabSelectedIndexes
  2430. })
  2431. .width('100%')
  2432. .padding({ left: 25, right: 25, top: 5, bottom: 5 })
  2433. }
  2434. .width('100%')
  2435. .padding({ top: this.topSafeHeight + 5 })
  2436. .translate({
  2437. x: 0,
  2438. y: (this.isShowTitleBar || !this.autoHideTitle) ? 0 : -80
  2439. })
  2440. .opacity((this.isShowTitleBar || !this.autoHideTitle) ? 1 : 0)
  2441. .animation({
  2442. duration: 240,
  2443. curve: Curve.EaseInOut
  2444. })
  2445. // .backgroundColor($r('app.color.start_window_background'))
  2446. }
  2447. @Builder
  2448. SortMenuBuilder() {
  2449. Menu() {
  2450. MenuItem({
  2451. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.text_and_arrow_up')),
  2452. content: $r('app.string.sort_by_name')
  2453. })
  2454. .onClick(async () => {
  2455. this.doSortType(0);
  2456. PreferencesUtil.put("navidromeSortType", 0);
  2457. })
  2458. MenuItem({
  2459. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.text_and_arrow_down')),
  2460. content: '按名称降序'
  2461. })
  2462. .onClick(async () => {
  2463. this.doSortType(1);
  2464. PreferencesUtil.put("navidromeSortType", 1);
  2465. })
  2466. MenuItem({
  2467. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.clock')),
  2468. content: '按艺术家升序'
  2469. })
  2470. .onClick(async () => {
  2471. this.doSortType(2);
  2472. PreferencesUtil.put("navidromeSortType", 2);
  2473. })
  2474. MenuItem({
  2475. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.timer')),
  2476. content: '按艺术家降序'
  2477. })
  2478. .onClick(async () => {
  2479. this.doSortType(3);
  2480. PreferencesUtil.put("navidromeSortType", 3);
  2481. })
  2482. MenuItem({
  2483. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.text_and_arrow_up')),
  2484. content: '按专辑升序'
  2485. })
  2486. .onClick(async () => {
  2487. this.doSortType(4);
  2488. PreferencesUtil.put("navidromeSortType", 4);
  2489. })
  2490. MenuItem({
  2491. symbolStartIcon: new SymbolGlyphModifier($r('sys.symbol.text_and_arrow_down')),
  2492. content: '按专辑降序'
  2493. })
  2494. .onClick(async () => {
  2495. this.doSortType(5);
  2496. PreferencesUtil.put("navidromeSortType", 5);
  2497. })
  2498. }
  2499. }
  2500. doSortType(index: number) {
  2501. this.sortType = index;
  2502. const songs = this.isSearchMode && this.searchText.length > 0 ? this.filteredList : this.allVideos;
  2503. const sortTypeNames = ['名称升序', '名称降序', '艺术家升序', '艺术家降序', '专辑升序', '专辑降序'];
  2504. const sortTypeName = sortTypeNames[index] || '未知排序';
  2505. // 记录排序操作
  2506. void ServerLogUtil.info('NavidromeSort', `应用排序: ${sortTypeName} (${index})`);
  2507. void ServerLogUtil.info('NavidromeSort', `排序范围: ${songs.length} 首歌曲 (${this.isSearchMode ? '搜索结果' : '全部歌曲'})`);
  2508. const startTime = Date.now();
  2509. // 对歌曲列表进行排序
  2510. switch (index) {
  2511. case 0: // 名称升序
  2512. Utility.doSortListAscending(songs,false)
  2513. break;
  2514. case 1: // 名称降序
  2515. Utility.doSortListDescending(songs,true)
  2516. break;
  2517. case 2: // 艺术家升序
  2518. songs.sort((a, b) => {
  2519. // 处理艺术家可能为undefined的字符串比较
  2520. const artistA = a.artist?.trim() || ''; // 可选添加 trim() 处理空格
  2521. const artistB = b.artist?.trim() || '';
  2522. return artistA.localeCompare(artistB);
  2523. });
  2524. break;
  2525. case 3: // 艺术家降序
  2526. songs.sort((a, b) => {
  2527. // 处理艺术家可能为undefined的字符串比较
  2528. const artistA = a.artist?.trim() || ''; // 可选添加 trim() 处理空格
  2529. const artistB = b.artist?.trim() || '';
  2530. return artistB.localeCompare(artistA);
  2531. });
  2532. break;
  2533. case 4: // 专辑升序
  2534. songs.sort((a, b) => {
  2535. const albumA = a.album?.trim() || ''; // 可选添加 trim() 处理空格
  2536. const albumB = b.album?.trim() || '';
  2537. return albumA.localeCompare(albumB);
  2538. });
  2539. break;
  2540. case 5: // 专辑降序
  2541. songs.sort((a, b) => {
  2542. const albumA = a.album?.trim() || ''; // 可选添加 trim() 处理空格
  2543. const albumB = b.album?.trim() || '';
  2544. return albumB.localeCompare(albumA);
  2545. });
  2546. break;
  2547. }
  2548. const sortTime = Date.now() - startTime;
  2549. // 更新显示列表
  2550. if (this.isSearchMode && this.searchText.length > 0) {
  2551. this.filteredList = [...songs];
  2552. } else {
  2553. this.allVideos = [...songs];
  2554. }
  2555. this.songDataSource.pushArrayData(this.getVisibleSongs());
  2556. // 记录排序结果
  2557. void ServerLogUtil.info('NavidromeSort', `排序完成: ${sortTypeName}`);
  2558. void ServerLogUtil.info('NavidromeSort', `- 排序耗时: ${sortTime}ms`);
  2559. void ServerLogUtil.debug('NavidromeSort', `排序结果示例: ${songs.slice(0, 3).map(s => `${s.name} (${s.artist})`).join(', ')}`);
  2560. }
  2561. // 实时搜索逻辑(改为远程API搜索)
  2562. private async onSearchInput(value: string): Promise<void> {
  2563. const keyword = value.trim();
  2564. this.searchText = keyword;
  2565. const ticket = ++this.searchTicket;
  2566. void ServerLogUtil.debug('NavidromeSearch', `搜索输入: "${value}" -> "${keyword}"`);
  2567. if (keyword.length === 0) {
  2568. this.filteredList = [];
  2569. this.isSearchLoading = false;
  2570. this.songDataSource.pushArrayData(this.getVisibleSongs());
  2571. void ServerLogUtil.info('NavidromeSearch', '搜索已清空,显示所有歌曲');
  2572. return;
  2573. }
  2574. if (!this.isSearchMode) {
  2575. this.isSearchMode = true;
  2576. }
  2577. const account = this.resolveActiveAccount();
  2578. if (!account) {
  2579. this.filteredList = [];
  2580. this.isSearchLoading = false;
  2581. ToastUtil.showToast('媒体库账号不可用');
  2582. return;
  2583. }
  2584. this.isSearchLoading = true;
  2585. this.filteredList = [];
  2586. const startTime = Date.now();
  2587. void ServerLogUtil.info('NavidromeSearch', `开始远程搜索: "${keyword}"`);
  2588. try {
  2589. let restSongs: NavidromeRestSong[] = [];
  2590. if (this.isNavidromeAccount(account)) {
  2591. const songs = await navidromeApi.searchSongs(account, keyword, NAVIDROME_SEARCH_LIMIT);
  2592. restSongs = this.convertApiSongsToRestSongs(songs);
  2593. } else if (this.isJellyfinAccount(account)) {
  2594. const response = await jellyfinApi.searchSongs(account, keyword, 0, this.REMOTE_SEARCH_LIMIT);
  2595. restSongs = this.convertJellyfinSongsToRestSongs(response.items);
  2596. } else if (this.isEmbyAccount(account)) {
  2597. const response = await embyApi.searchSongs(account, keyword, 0, this.REMOTE_SEARCH_LIMIT);
  2598. restSongs = this.convertEmbySongsToRestSongs(response.items);
  2599. } else if (this.isAudioStationAccount(account)) {
  2600. const songs = await audioStationApi.searchSongs(account, keyword, 0, this.REMOTE_SEARCH_LIMIT);
  2601. restSongs = this.convertAudioStationSongsToRestSongs(songs);
  2602. } else if (this.isPlexAccount(account)) {
  2603. const response = await plexApi.searchSongs(account, keyword, 0, this.REMOTE_SEARCH_LIMIT);
  2604. restSongs = this.convertPlexSongsToRestSongs(response.items);
  2605. } else if (this.isDaoLiYuAccount(account)) {
  2606. const tracks = await daoLiYuApi.searchTracks(account, keyword, this.REMOTE_SEARCH_LIMIT);
  2607. restSongs = this.convertDaoLiYuSongsToRestSongs(tracks);
  2608. }
  2609. if (ticket !== this.searchTicket) {
  2610. return;
  2611. }
  2612. const searchTime = Date.now() - startTime;
  2613. if (!restSongs || restSongs.length === 0) {
  2614. this.filteredList = [];
  2615. this.songDataSource.pushArrayData(this.getVisibleSongs());
  2616. void ServerLogUtil.warn('NavidromeSearch', `搜索无结果: "${keyword}"`);
  2617. void ServerLogUtil.info('NavidromeSearch', `- 搜索耗时: ${searchTime}ms`);
  2618. return;
  2619. }
  2620. const videoItems = await this.convertSongsToVideoItems(restSongs, account);
  2621. if (ticket !== this.searchTicket) {
  2622. return;
  2623. }
  2624. this.filteredList = videoItems;
  2625. this.doSortType(this.sortType);
  2626. void ServerLogUtil.info('NavidromeSearch', `搜索完成: "${keyword}"`);
  2627. void ServerLogUtil.info('NavidromeSearch', `- 搜索耗时: ${searchTime}ms`);
  2628. void ServerLogUtil.info('NavidromeSearch', `- 匹配结果: ${videoItems.length}`);
  2629. void ServerLogUtil.debug('NavidromeSearch', `搜索结果示例: ${videoItems.slice(0, 3).map(s => `${s.name} (${s.artist})`).join(', ')}`);
  2630. } catch (error) {
  2631. if (ticket !== this.searchTicket) {
  2632. return;
  2633. }
  2634. this.filteredList = [];
  2635. this.songDataSource.pushArrayData(this.getVisibleSongs());
  2636. const message = (error as Error).message ?? 'Navidrome 搜索失败';
  2637. ToastUtil.showToast(message);
  2638. void ServerLogUtil.error('NavidromeSearch', `搜索失败: ${message}`);
  2639. void ServerLogUtil.info('NavidromeSearch', `- 搜索耗时: ${Date.now() - startTime}ms`);
  2640. } finally {
  2641. if (ticket === this.searchTicket) {
  2642. this.isSearchLoading = false;
  2643. }
  2644. }
  2645. }
  2646. private getCurrentCount(): number {
  2647. switch (this.selectedTab) {
  2648. case 1:
  2649. return this.artists.length;
  2650. case 2:
  2651. return this.albums.length;
  2652. case 3:
  2653. return this.playlists.length;
  2654. default:
  2655. return this.getVisibleSongs().length;
  2656. }
  2657. }
  2658. private getEmptyTitle(): string {
  2659. switch (this.selectedTab) {
  2660. case 1:
  2661. return '暂无艺术家';
  2662. case 2:
  2663. return '暂无专辑';
  2664. case 3:
  2665. return '暂无歌单';
  2666. default:
  2667. if (this.isSearchMode && this.searchText.length > 0) {
  2668. return this.isSearchLoading ? '正在搜索远程歌曲' : '没有匹配的远程歌曲';
  2669. }
  2670. if (this.filterType !== NavFilterType.None && this.isFilterLoading) {
  2671. return '正在加载筛选结果';
  2672. }
  2673. return this.filterType === NavFilterType.None ? '暂无音乐' : '该筛选下暂无歌曲';
  2674. }
  2675. }
  2676. private getEmptySubtitle(): string {
  2677. switch (this.selectedTab) {
  2678. case 1:
  2679. return '当前筛选没有找到艺术家';
  2680. case 2:
  2681. return '当前筛选没有找到专辑';
  2682. case 3:
  2683. return '当前筛选没有找到歌单';
  2684. default:
  2685. if (this.isSearchMode && this.searchText.length > 0) {
  2686. return this.isSearchLoading ? '请稍候,正在通过 API 搜索' : '换个关键词再试试吧';
  2687. }
  2688. if (this.filterType !== NavFilterType.None && this.isFilterLoading) {
  2689. return '请稍候...';
  2690. }
  2691. return this.filterType === NavFilterType.None ? '当前分类下没有找到音乐文件' : '请尝试调整筛选条件';
  2692. }
  2693. }
  2694. @Builder
  2695. buildSongItem(song: VideoItem, index: number) {
  2696. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  2697. Row({ space: 12 }) {
  2698. // 歌曲封面
  2699. Image(song.pixelMapPath ? song.pixelMapPath : $r('app.media.nocover'))
  2700. .height(this.twoFingerType == 3 ? 55 : this.twoFingerType == 2 ? 50 : 40)
  2701. .width(this.twoFingerType == 3 ? 55 : this.twoFingerType == 2 ? 50 : 40)
  2702. .borderRadius(9)
  2703. .sourceSize({ width: 38, height: 38 })
  2704. .draggable(false)
  2705. .interpolation(ImageInterpolation.High)// 用于重采样后的抗锯齿
  2706. .autoResize(true) // 重采样,可减少内存占用
  2707. .alt($r('app.media.nocover'))
  2708. .fillColor(song.pixelMapPath ? undefined : this.themeColor)
  2709. .objectFit(ImageFit.Cover)
  2710. .margin({ left: 20 })
  2711. .animation({
  2712. duration: 500,
  2713. curve: Curve.Friction // 可选动画曲线
  2714. })
  2715. .shadow({
  2716. radius: StrUtil.isEmpty(song.pixelMapPath) ?6:14,
  2717. type: ShadowType.BLUR,
  2718. color: 'on_primary'
  2719. })
  2720. .onClick(() => {
  2721. this.playSong(song, index, true);
  2722. })
  2723. // 歌曲信息
  2724. Column({ space: 4 }) {
  2725. Text(song.name)
  2726. .fontSize(this.twoFingerType == 1 ? 12 : this.twoFingerType == 2 ? 15 : 18)
  2727. .fontColor(this.currentSong?.filePath == song.filePath ? this.themeColor : $r('app.color.index_tab_font_color'))
  2728. .maxLines(1)
  2729. .textOverflow({ overflow: TextOverflow.Ellipsis })
  2730. Row() {
  2731. Text((song.artist ?? '') + " ")
  2732. .fontSize(this.twoFingerType == 1 ? 11 : this.twoFingerType == 2 ? 12 : 14)
  2733. .fontColor(this.currentSong?.filePath == song.filePath ? this.themeColor : $r('app.color.index_tab_font_color'))
  2734. .opacity(0.6)
  2735. .maxLines(1)
  2736. .visibility(song.artist ? Visibility.Visible : Visibility.None)
  2737. .textOverflow({ overflow: TextOverflow.Ellipsis })
  2738. Text(this.buildSongMetaLine(song))
  2739. .fontSize(this.twoFingerType == 1 ? 11 : this.twoFingerType == 2 ? 12 : 14)
  2740. .fontColor(this.currentSong?.filePath == song.filePath ? this.themeColor : $r('app.color.index_tab_font_color'))
  2741. .opacity(0.6)
  2742. .maxLines(1)
  2743. .textOverflow({ overflow: TextOverflow.Ellipsis })
  2744. }
  2745. .width('90%')
  2746. }
  2747. .alignItems(HorizontalAlign.Start)
  2748. .layoutWeight(1)
  2749. .padding({ right: 20 })
  2750. Column() {
  2751. ImageAnimator()
  2752. .images(CommonConstants.IMAGE_FRAME_INFO)// 动画数组
  2753. .duration(1000)// 持续
  2754. .state(AnimationStatus.Running)// 动画状态
  2755. .fillMode(FillMode.Forwards)
  2756. .visibility(this.currentSong?.filePath == song.filePath ? Visibility.Visible :
  2757. Visibility.None)
  2758. .width(18)
  2759. .margin({ right: 12, top: 8, bottom: 8 })
  2760. .height(18)
  2761. .iterations(-1) // 播放次数
  2762. }
  2763. }
  2764. }
  2765. .width('100%')
  2766. .padding(12)
  2767. .height(this.twoFingerType == 3 ? ITEM_HEIGHT_BIG : this.twoFingerType == 2 ? ITEM_HEIGHT : ITEM_HEIGHT_SMALL)
  2768. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.8 })
  2769. .backgroundColor(Color.Transparent)
  2770. .onClick(() => {
  2771. this.playSong(song, index);
  2772. })
  2773. }
  2774. @Builder
  2775. buildArtistItem(artist: NavidromeRestArtist) {
  2776. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  2777. Row({ space: 12 }) {
  2778. Image(artist.coverUrl ?? $r('app.media.nocover'))
  2779. .width(48)
  2780. .height(48)
  2781. .borderRadius(10)
  2782. .draggable(false)
  2783. .alt($r('app.media.nocover'))
  2784. // .interpolation(ImageInterpolation.High)// 用于重采样后的抗锯齿
  2785. // .autoResize(true) // 重采样,可减少内存占用
  2786. .sourceSize({ width: 38, height: 38 })
  2787. .fillColor(artist.coverUrl ? undefined : this.themeColor)
  2788. .objectFit(ImageFit.Cover)
  2789. .margin({ left: 20 })
  2790. Column({ space: 4 }) {
  2791. Text(artist.name ?? Constants.UNKNOWN_ARTIST)
  2792. .fontSize(15)
  2793. .fontColor($r('app.color.index_tab_font_color'))
  2794. .maxLines(1)
  2795. .textAlign(TextAlign.Start)
  2796. .textOverflow({ overflow: TextOverflow.Ellipsis })
  2797. Text(this.buildArtistMetaLine(artist))
  2798. .fontSize(13)
  2799. .fontColor($r('app.color.index_tab_font_color'))
  2800. .opacity(0.6)
  2801. .maxLines(1)
  2802. .textOverflow({ overflow: TextOverflow.Ellipsis })
  2803. .visibility((artist.albumCount ?? 0) === 0 && (artist.songCount ?? 0) === 0 ? Visibility.None : Visibility.Visible)
  2804. }
  2805. .alignItems(HorizontalAlign.Start)
  2806. .padding({ right: 20 })
  2807. }
  2808. .width('100%')
  2809. }
  2810. .width('100%')
  2811. .padding(12)
  2812. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.85 })
  2813. .backgroundColor(Color.Transparent)
  2814. .onClick(() => {
  2815. this.onArtistSelected(artist);
  2816. })
  2817. }
  2818. @Builder
  2819. buildAlbumItem(album: NavidromeRestAlbum) {
  2820. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  2821. Row({ space: 12 }) {
  2822. Image(album.coverUrl ?? $r('app.media.nocover'))
  2823. .width(48)
  2824. .height(48)
  2825. .borderRadius(10)
  2826. .clip(true)
  2827. .alt($r('app.media.nocover'))
  2828. .draggable(false)
  2829. // .interpolation(ImageInterpolation.High)// 用于重采样后的抗锯齿
  2830. // .autoResize(true) // 重采样,可减少内存占用
  2831. .sourceSize({ width: 38, height: 38 })
  2832. .fillColor(album.coverUrl ? undefined : this.themeColor)
  2833. .objectFit(ImageFit.Cover)
  2834. .margin({ left: 20 })
  2835. Column({ space: 4 }) {
  2836. Text(album.name ?? '未知专辑')
  2837. .fontSize(15)
  2838. .fontColor($r('app.color.index_tab_font_color'))
  2839. .maxLines(1)
  2840. .textAlign(TextAlign.Start)
  2841. .textOverflow({ overflow: TextOverflow.Ellipsis })
  2842. Row() {
  2843. Text(album.artist ?? Constants.UNKNOWN_ARTIST)
  2844. .fontSize(13)
  2845. .fontColor($r('app.color.index_tab_font_color'))
  2846. .opacity(0.6)
  2847. .maxLines(1)
  2848. .textOverflow({ overflow: TextOverflow.Ellipsis })
  2849. Text(this.buildAlbumMetaLine(album))
  2850. .fontSize(13)
  2851. .fontColor($r('app.color.index_tab_font_color'))
  2852. .opacity(0.6)
  2853. .maxLines(1)
  2854. .textOverflow({ overflow: TextOverflow.Ellipsis })
  2855. }
  2856. }
  2857. .alignItems(HorizontalAlign.Start)
  2858. .padding({ right: 20 })
  2859. }
  2860. .width('100%')
  2861. }
  2862. .width('100%')
  2863. .padding(12)
  2864. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.85 })
  2865. .backgroundColor(Color.Transparent)
  2866. .onClick(() => {
  2867. this.onAlbumSelected(album);
  2868. })
  2869. }
  2870. @Builder
  2871. buildPlaylistItem(playlist: NavidromeRestPlaylist) {
  2872. Button({ type: ButtonType.Capsule, stateEffect: true }) {
  2873. Row({ space: 12 }) {
  2874. Image(playlist.coverUrl ?? $r('app.media.nocover'))
  2875. .width(48)
  2876. .height(48)
  2877. .borderRadius(10)
  2878. .alt($r('app.media.nocover'))
  2879. .draggable(false)
  2880. .sourceSize({ width: 38, height: 38 })
  2881. .fillColor(playlist.coverUrl ? undefined : this.themeColor)
  2882. .objectFit(ImageFit.Cover)
  2883. .margin({ left: 20 })
  2884. Column({ space: 4 }) {
  2885. Text(playlist.name ?? '未知歌单')
  2886. .fontSize(15)
  2887. .fontColor($r('app.color.index_tab_font_color'))
  2888. .maxLines(1)
  2889. .textAlign(TextAlign.Start)
  2890. .textOverflow({ overflow: TextOverflow.Ellipsis })
  2891. Text(this.buildPlaylistMetaLine(playlist))
  2892. .fontSize(13)
  2893. .fontColor($r('app.color.index_tab_font_color'))
  2894. .opacity(0.6)
  2895. .maxLines(1)
  2896. .textOverflow({ overflow: TextOverflow.Ellipsis })
  2897. // if (playlist.ownerName) {
  2898. // Text(playlist.ownerName)
  2899. // .fontSize(12)
  2900. // .fontColor($r('app.color.index_tab_font_color'))
  2901. // .opacity(0.5)
  2902. // .maxLines(1)
  2903. // .textOverflow({ overflow: TextOverflow.Ellipsis })
  2904. // }
  2905. }
  2906. .alignItems(HorizontalAlign.Start)
  2907. .padding({ right: 20 })
  2908. }
  2909. .width('100%')
  2910. }
  2911. .width('100%')
  2912. .padding(12)
  2913. .clickEffect({ level: ClickEffectLevel.MIDDLE, scale: 0.85 })
  2914. .backgroundColor(Color.Transparent)
  2915. .onClick(() => {
  2916. this.onPlaylistSelected(playlist);
  2917. })
  2918. }
  2919. private buildSongMetaLine(song: VideoItem): string {
  2920. const parts: string[] = [];
  2921. if (song.duration) {
  2922. parts.push(song.duration as string);
  2923. }
  2924. // if (song.size) {
  2925. // parts.push(song.size as string);
  2926. // }
  2927. // if (parts.length === 0 && song.cTime) {
  2928. // parts.push(song.cTime as string);
  2929. // }
  2930. return parts.join(' · ');
  2931. }
  2932. private buildArtistMetaLine(artist: NavidromeRestArtist): string {
  2933. const albumCount = artist.albumCount ?? 0;
  2934. const songCount = artist.songCount ?? 0;
  2935. const playCount = artist.playCount ?? 0;
  2936. // 如果专辑和歌曲数都为0,不显示元数据信息
  2937. if (albumCount === 0 && songCount === 0) {
  2938. return '';
  2939. }
  2940. return `专辑 ${albumCount} · 歌曲 ${songCount} `;
  2941. }
  2942. private buildAlbumMetaLine(album: NavidromeRestAlbum): string {
  2943. const parts: string[] = [];
  2944. if (album.duration !== undefined) {
  2945. const duration = this.formatSongDuration(album.duration);
  2946. if (duration) {
  2947. parts.push(' '+duration);
  2948. }
  2949. }
  2950. if (album.minYear) {
  2951. parts.push(`发行 ${album.minYear}`);
  2952. }
  2953. return parts.join(' · ');
  2954. }
  2955. private buildPlaylistMetaLine(playlist: NavidromeRestPlaylist): string {
  2956. const parts: string[] = [];
  2957. if (playlist.songCount !== undefined) {
  2958. parts.push(`${playlist.songCount} 首歌`);
  2959. }
  2960. if (playlist.duration !== undefined) {
  2961. const duration = this.formatSongDuration(playlist.duration);
  2962. if (duration) {
  2963. parts.push(duration);
  2964. }
  2965. }
  2966. return parts.join(' · ');
  2967. }
  2968. private getVisibleSongs(): VideoItem[] {
  2969. if (this.isSearchMode) {
  2970. return this.searchText.length > 0 ? this.filteredList : this.allVideos;
  2971. }
  2972. // 详情视图模式或有筛选时,返回筛选后的歌曲
  2973. if (this.isDetailView || this.filterType !== NavFilterType.None) {
  2974. return this.filterSongs;
  2975. }
  2976. return this.allVideos;
  2977. }
  2978. private onArtistSelected(artist: NavidromeRestArtist): void {
  2979. if (!artist || !artist.id) {
  2980. return;
  2981. }
  2982. this.isShowTitleBar = true;
  2983. // 保存当前标签页,进入详情视图
  2984. this.previousTab = this.selectedTab;
  2985. this.isDetailView = true;
  2986. // 应用筛选但不切换标签页
  2987. void this.applyFilter(NavFilterType.Artist, artist.id, artist.name ?? Constants.UNKNOWN_ARTIST);
  2988. }
  2989. private onAlbumSelected(album: NavidromeRestAlbum): void {
  2990. if (!album || !album.id) {
  2991. return;
  2992. }
  2993. this.isShowTitleBar = true;
  2994. // 保存当前标签页,进入详情视图
  2995. this.previousTab = this.selectedTab;
  2996. this.isDetailView = true;
  2997. // 应用筛选但不切换标签页
  2998. void this.applyFilter(NavFilterType.Album, album.id, album.name ?? '未知专辑');
  2999. }
  3000. private onPlaylistSelected(playlist: NavidromeRestPlaylist): void {
  3001. if (!playlist || !playlist.id) {
  3002. return;
  3003. }
  3004. this.isShowTitleBar = true;
  3005. // 保存当前标签页,进入详情视图
  3006. this.previousTab = this.selectedTab;
  3007. this.isDetailView = true;
  3008. // 应用筛选但不切换标签页
  3009. void this.applyFilter(NavFilterType.Playlist, playlist.id, playlist.name ?? '未知歌单');
  3010. }
  3011. private async applyFilter(type: NavFilterType, id: string, label: string): Promise<void> {
  3012. // 记录筛选操作
  3013. void ServerLogUtil.info('NavidromeFilter', `应用筛选:`);
  3014. const typeText = type === NavFilterType.Artist ? '艺术家' : type === NavFilterType.Album ? '专辑' : type === NavFilterType.Playlist ? '歌单' : '无';
  3015. void ServerLogUtil.info('NavidromeFilter', `- 类型: ${type} (${typeText})`);
  3016. void ServerLogUtil.info('NavidromeFilter', `- ID: ${id}`);
  3017. void ServerLogUtil.info('NavidromeFilter', `- 标签: ${label}`);
  3018. void ServerLogUtil.info('NavidromeFilter', `- 筛选前总歌曲数: ${this.allVideos.length}`);
  3019. // 先更新状态
  3020. this.filterType = type;
  3021. this.filterId = id;
  3022. this.filterLabel = label;
  3023. // 退出搜索模式,确保显示筛选结果
  3024. this.isSearchMode = false;
  3025. this.searchText = '';
  3026. this.filteredList = [];
  3027. this.isSearchLoading = false;
  3028. this.searchTicket++;
  3029. this.filterSongs = [];
  3030. this.songDataSource.pushArrayData([]); // 立即清空数据源,避免闪现旧数据
  3031. this.isFilterLoading = true;
  3032. // 调试日志:检查筛选结果
  3033. void this.loadSongsForFilter(label).catch((error: Error) => {
  3034. void ServerLogUtil.error('NavidromeFilter', `筛选歌曲加载失败: ${error.message}`);
  3035. ToastUtil.showToast(error.message || '筛选数据加载失败');
  3036. });
  3037. // 不再自动切换标签页,保持在详情视图模式
  3038. }
  3039. private async loadSongsForFilter(label:string): Promise<void> {
  3040. if (this.filterType === NavFilterType.None || !this.filterId) {
  3041. this.filterSongs = [];
  3042. this.isFilterLoading = false;
  3043. return;
  3044. }
  3045. const account = this.resolveActiveAccount();
  3046. if (!account) {
  3047. this.filterSongs = [];
  3048. this.isFilterLoading = false;
  3049. throw new Error('媒体库账号不可用');
  3050. }
  3051. if (!this.isNavidromeAccount(account)) {
  3052. let restSongs: NavidromeRestSong[] = [];
  3053. if (this.filterType === NavFilterType.Artist) {
  3054. if (this.isJellyfinAccount(account)) {
  3055. const songs = await this.fetchAllJellyfinArtistSongs(account, this.filterId);
  3056. restSongs = this.convertJellyfinSongsToRestSongs(songs);
  3057. } else if (this.isEmbyAccount(account)) {
  3058. const songs = await this.fetchAllEmbyArtistSongs(account, this.filterId);
  3059. restSongs = this.convertEmbySongsToRestSongs(songs);
  3060. } else if (this.isAudioStationAccount(account)) {
  3061. const songs = await this.fetchAllAudioStationArtistSongs(account, this.filterId);
  3062. restSongs = this.convertAudioStationSongsToRestSongs(songs);
  3063. } else if (this.isPlexAccount(account)) {
  3064. const songs = await this.fetchAllPlexArtistSongs(account, this.filterId);
  3065. restSongs = this.convertPlexSongsToRestSongs(songs);
  3066. } else if (this.isDaoLiYuAccount(account)) {
  3067. // 同时传递 artistId 和 artistName,支持按名称匹配作为后备
  3068. const songs = await daoLiYuApi.getTracksByArtistId(account, this.filterId, label);
  3069. restSongs = this.convertDaoLiYuSongsToRestSongs(songs);
  3070. }
  3071. } else if (this.filterType === NavFilterType.Album) {
  3072. if (this.isJellyfinAccount(account)) {
  3073. const songs = await jellyfinApi.getAlbumSongs(account, this.filterId);
  3074. restSongs = this.convertJellyfinSongsToRestSongs(songs);
  3075. } else if (this.isEmbyAccount(account)) {
  3076. const songs = await embyApi.getAlbumSongs(account, this.filterId);
  3077. restSongs = this.convertEmbySongsToRestSongs(songs);
  3078. } else if (this.isAudioStationAccount(account)) {
  3079. const albumKey = this.parseAudioStationAlbumKey(this.filterId);
  3080. const songs = await audioStationApi.getAlbumSongs(account, albumKey.name, albumKey.artist);
  3081. restSongs = this.convertAudioStationSongsToRestSongs(songs);
  3082. } else if (this.isPlexAccount(account)) {
  3083. const songs = await plexApi.getAlbumSongs(account, this.filterId);
  3084. restSongs = this.convertPlexSongsToRestSongs(songs);
  3085. } else if (this.isDaoLiYuAccount(account)) {
  3086. // 同时传递 albumId 和 albumName,支持按名称匹配作为后备
  3087. const songs = await daoLiYuApi.getTracksByAlbumId(account, this.filterId, label);
  3088. restSongs = this.convertDaoLiYuSongsToRestSongs(songs);
  3089. }
  3090. } else if (this.filterType === NavFilterType.Playlist) {
  3091. if (this.isAudioStationAccount(account)) {
  3092. const songs = await this.fetchAllAudioStationPlaylistSongs(account, this.filterId);
  3093. restSongs = this.convertAudioStationSongsToRestSongs(songs);
  3094. } else if (this.isPlexAccount(account)) {
  3095. const songs = await this.fetchAllPlexPlaylistSongs(account, this.filterId);
  3096. restSongs = this.convertPlexSongsToRestSongs(songs);
  3097. } else if (this.isDaoLiYuAccount(account)) {
  3098. const songs = await daoLiYuApi.getPlaylistTracks(account, this.filterId);
  3099. restSongs = this.convertDaoLiYuSongsToRestSongs(songs);
  3100. } else {
  3101. this.filterSongs = [];
  3102. this.isFilterLoading = false;
  3103. ToastUtil.showToast('当前媒体库不支持歌单');
  3104. return;
  3105. }
  3106. }
  3107. const videoItems = await this.convertSongsToVideoItems(restSongs, account);
  3108. this.filterSongs = videoItems;
  3109. this.songDataSource.pushArrayData(this.filterSongs);
  3110. this.isFilterLoading = false;
  3111. return;
  3112. }
  3113. const expectedFilterId = this.filterId;
  3114. const expectedFilterType = this.filterType;
  3115. try {
  3116. let songs: NavidromeRestSong[] = [];
  3117. if (this.filterType === NavFilterType.Artist) {
  3118. songs = await navidromeRestApi.fetchSongsByArtist(account, this.filterId,label);
  3119. } else if (this.filterType === NavFilterType.Album) {
  3120. songs = await navidromeRestApi.fetchSongsByAlbum(account, this.filterId,label);
  3121. } else if (this.filterType === NavFilterType.Playlist) {
  3122. songs = await navidromeRestApi.fetchSongsByPlaylist(account, this.filterId);
  3123. }
  3124. const videoItems = await this.convertSongsToVideoItems(songs, account);
  3125. if (expectedFilterId !== this.filterId || expectedFilterType !== this.filterType) {
  3126. return;
  3127. }
  3128. this.filterSongs = videoItems;
  3129. this.songDataSource.pushArrayData(this.filterSongs);
  3130. if (videoItems.length === 0) {
  3131. void ServerLogUtil.warn('NavidromeFilter', '筛选下暂无歌曲');
  3132. } else {
  3133. void ServerLogUtil.info('NavidromeFilter', `筛选歌曲加载完成: ${videoItems.length} 首`);
  3134. }
  3135. } finally {
  3136. this.isFilterLoading = false;
  3137. }
  3138. }
  3139. private clearFilter(): void {
  3140. this.filterType = NavFilterType.None;
  3141. this.filterId = '';
  3142. this.filterLabel = '';
  3143. this.filterSongs = [];
  3144. this.isFilterLoading = false;
  3145. // 恢复完整列表的数据源
  3146. this.songDataSource.pushArrayData(this.allVideos);
  3147. // 退出详情视图
  3148. this.isDetailView = false;
  3149. }
  3150. private playSong(song: VideoItem, index: number, isJump: boolean = false): void {
  3151. try {
  3152. if (!this.allVideos || this.allVideos.length === 0) {
  3153. ToastUtil.showToast('暂无可播放的歌曲');
  3154. return;
  3155. }
  3156. const account = this.resolveActiveAccount();
  3157. if (!account || !account.id) {
  3158. ToastUtil.showToast('媒体库账号信息不完整,无法播放');
  3159. return;
  3160. }
  3161. // 记录播放详细信息
  3162. void ServerLogUtil.info('StreamingPlay', `开始播放歌曲: ${song.name} (#${index})`);
  3163. void ServerLogUtil.info('StreamingPlay', `歌曲信息:`);
  3164. void ServerLogUtil.info('StreamingPlay', `- ID: ${song.id}`);
  3165. void ServerLogUtil.info('StreamingPlay', `- 艺术家: ${song.artist || '未知'}`);
  3166. void ServerLogUtil.info('StreamingPlay', `- 专辑: ${song.album || '未知'}`);
  3167. void ServerLogUtil.info('StreamingPlay', `- 文件大小: ${song.size || '未知'}`);
  3168. void ServerLogUtil.info('StreamingPlay', `- 时长: ${song.duration || '未知'}`);
  3169. void ServerLogUtil.info('StreamingPlay', `- 封面: ${song.pixelMapPath ? '有' : '无'}`);
  3170. void ServerLogUtil.info('StreamingPlay', `- 播放路径: ${song.filePath}`);
  3171. const playlistSource = this.getVisibleSongs().length > 0 ? this.getVisibleSongs() : this.allVideos;
  3172. const targetIndex = playlistSource.findIndex(item => item.id === song.id);
  3173. const startIndex = targetIndex >= 0 ? targetIndex : Math.min(index, Math.max(playlistSource.length - 1, 0));
  3174. void ServerLogUtil.info('StreamingPlay', `播放列表设置: 起始索引 ${startIndex}, 已加载 ${playlistSource.length}, 服务端总数 ${this.serverTotalSongCount}`);
  3175. setNavidromePlaylist(playlistSource, startIndex);
  3176. // 保存服务端总数到全局存储
  3177. if (this.serverTotalSongCount > 0) {
  3178. setNavidromeTotalCount(this.serverTotalSongCount);
  3179. }
  3180. const playlistData: PlaylistEventData = {
  3181. playlistId: NAVIDROME_PLAYLIST_ID,
  3182. playlistName: `${getRemoteDriveDisplayLabel(account.webType)} - ${account.name ?? '未知账户'}`,
  3183. songCount: this.serverTotalSongCount > 0 ? this.serverTotalSongCount : playlistSource.length,
  3184. startIndex,
  3185. isJump: isJump,//设置true会弹出播放页
  3186. songFilePaths: playlistSource.map(item => item.filePath)
  3187. };
  3188. const eventPlaylistPlay: emitter.InnerEvent = { eventId: EventConstants.EVENT_PLAYLIST_PLAY };
  3189. emitter.emit(eventPlaylistPlay, { data: playlistData });
  3190. void ServerLogUtil.info('StreamingPlay', `播放事件已发送`);
  3191. void ServerLogUtil.debug('StreamingPlay', `播放事件详情: 列表ID=${playlistData.playlistId}, 列表名称=${playlistData.playlistName}, 歌曲数=${playlistData.songCount}, 起始索引=${playlistData.startIndex}, 是否跳转=${playlistData.isJump}`);
  3192. if(!this.isNoJumpToHome){
  3193. void ServerLogUtil.debug('StreamingPlay', '跳转到首页播放器');
  3194. // 跳转到首页播放器
  3195. this.getUIContext()?.animateTo({ duration: 555 }, () => {
  3196. this.mType = 0
  3197. })
  3198. }
  3199. } catch (error) {
  3200. const err = error as Error;
  3201. void ServerLogUtil.error('StreamingPlay', `播放失败: ${err.message}`);
  3202. void ServerLogUtil.error('StreamingPlay', `失败歌曲信息: ${song.name} (${song.id})`);
  3203. ToastUtil.showToast('播放失败');
  3204. }
  3205. }
  3206. @Builder
  3207. buildContentView(){
  3208. // 主内容区域
  3209. if (this.loading) {
  3210. Column() {
  3211. LoadingProgress()
  3212. .width(50)
  3213. .height(50)
  3214. .color($r('app.color.title_bar_bg'))
  3215. Text('加载中...')
  3216. .margin({ top: 10 })
  3217. .fontSize(14)
  3218. .fontColor($r('app.color.index_tab_unselected_font_color'))
  3219. }
  3220. .width('100%')
  3221. .layoutWeight(1)
  3222. .padding({top:this.topSafeHeight+98})
  3223. .justifyContent(FlexAlign.Center)
  3224. } else {
  3225. if (this.isSearchMode && this.selectedTab === 0 && this.searchText.length > 0 && this.isSearchLoading) {
  3226. Column() {
  3227. LoadingProgress()
  3228. .width(40)
  3229. .height(40)
  3230. .color(this.themeColor)
  3231. Text('正在通过 API 搜索歌曲...')
  3232. .margin({ top: 12 })
  3233. .fontSize(14)
  3234. .fontColor($r('app.color.index_tab_unselected_font_color'))
  3235. }
  3236. .width('100%')
  3237. .layoutWeight(1)
  3238. } else if (this.isDetailView && this.filterType !== NavFilterType.None && this.isFilterLoading) {
  3239. Column() {
  3240. LoadingProgress()
  3241. .width(40)
  3242. .height(40)
  3243. .color(this.themeColor)
  3244. Text('正在加载')
  3245. .margin({ top: 12 })
  3246. .fontSize(14)
  3247. .fontColor($r('app.color.index_tab_unselected_font_color'))
  3248. }
  3249. .width('100%')
  3250. .layoutWeight(1)
  3251. .justifyContent(FlexAlign.Center)
  3252. } else {
  3253. if(this.twoFingerType==4){
  3254. this.getWaterView()
  3255. }else{
  3256. if(this.isGridMusic){
  3257. this.getGridView()
  3258. }else {
  3259. this.getListView()
  3260. }
  3261. }
  3262. }
  3263. // 空状态
  3264. if (this.getCurrentCount() === 0 && !(this.isDetailView && this.filterType !== NavFilterType.None && this.isFilterLoading) && !(this.isSearchMode && this.searchText.length > 0 && this.isSearchLoading)) {
  3265. Column() {
  3266. SymbolGlyph($r('sys.symbol.music_fill'))
  3267. .fontSize(50)
  3268. .opacity(0.3)
  3269. Text(this.getEmptyTitle())
  3270. .margin({ top: 16 })
  3271. .fontSize(16)
  3272. .fontColor($r('app.color.index_tab_unselected_font_color'))
  3273. Text(this.getEmptySubtitle())
  3274. .margin({ top: 8 })
  3275. .fontSize(14)
  3276. .fontColor($r('app.color.index_tab_unselected_font_color'))
  3277. }
  3278. .width('100%')
  3279. .height('100%')
  3280. .justifyContent(FlexAlign.Center)
  3281. }
  3282. }
  3283. }
  3284. @State startIndex: number = 0
  3285. @State endIndex: number = 0
  3286. @State pinchValue: number = 1
  3287. layoutOptionsForHeader: GridLayoutOptions = {
  3288. regularSize: [1, 1], // 只支持[1, 1]
  3289. irregularIndexes: [0], // 索引为0的GridItem占用一行
  3290. };
  3291. @Builder
  3292. getGridView() {
  3293. Grid(this.scroller, this.layoutOptionsForHeader) {
  3294. GridItem() {
  3295. Column(){
  3296. Blank().height(this.topSafeHeight + 98)
  3297. }
  3298. }
  3299. if (this.selectedTab === 0||this.isDetailView) {
  3300. LazyForEach(this.songDataSource, (item: VideoItem, index: number) => {
  3301. GridItem() {
  3302. this.buildSongItemGrid(item, index)
  3303. }
  3304. }, (item: VideoItem) => item.id)
  3305. } else if (this.selectedTab === 1) {
  3306. LazyForEach(this.artistDataSource, (artist: NavidromeRestArtist) => {
  3307. GridItem() {
  3308. this.buildArtistItemGrid(artist)
  3309. }
  3310. }, (artist: NavidromeRestArtist) => artist.id)
  3311. } else if (this.selectedTab === 2) {
  3312. LazyForEach(this.albumDataSource, (album: NavidromeRestAlbum) => {
  3313. GridItem() {
  3314. this.buildAlbumItemGrid(album)
  3315. }
  3316. }, (album: NavidromeRestAlbum) => album.id)
  3317. } else if (this.selectedTab === 3) {
  3318. LazyForEach(this.playlistDataSource, (playlist: NavidromeRestPlaylist) => {
  3319. GridItem() {
  3320. this.buildPlaylistItemGrid(playlist)
  3321. }
  3322. }, (playlist: NavidromeRestPlaylist) => playlist.id)
  3323. }
  3324. }
  3325. .width('94%')
  3326. .height('100%')
  3327. .editMode(true)
  3328. .padding({bottom:this.bottomSafeHeight+this.bottomSafeHeight+52})
  3329. .reuseId('grid_item')
  3330. .layoutWeight(1)
  3331. .cachedCount(this.twoFingerType==1?5:this.twoFingerType==2?4:3)
  3332. .scrollBar(BarState.Off)
  3333. .supportAnimation(true)
  3334. .onReachEnd(() => {
  3335. void this.handleReachEnd();
  3336. })
  3337. .columnsTemplate(
  3338. this.twoFingerType == 3 ? 'repeat(auto-fit, 160)' :
  3339. this.twoFingerType == 2 ? 'repeat(auto-fit, 110)' : 'repeat(auto-fit, 80)'
  3340. )
  3341. .rowsGap(this.isShowDrawer ? 25 : (this.twoFingerType == 3 ? 10 : this.twoFingerType == 2 ? 5 : 1))
  3342. .visibility(this.isGridMusic ? Visibility.Visible : Visibility.None)
  3343. .scale({ x: this.scaleValue, y: this.scaleValue, z: 1 })
  3344. .gesture(PinchGesture({ fingers: 2 })
  3345. .onActionEnd((event: GestureEvent) => {
  3346. this.setGridTwoFingers()
  3347. })
  3348. .onActionUpdate(e => {
  3349. this.scaleValue = this.pinchValue * e.scale
  3350. })
  3351. .onActionStart(e => {
  3352. }))
  3353. .enableScrollInteraction(true)
  3354. .onScrollIndex((start: number, end: number) => {
  3355. this.startIndex = start
  3356. this.endIndex = end
  3357. })
  3358. .onScrollFrameBegin((offset: number) => {
  3359. if(this.autoHideTitle){
  3360. const currentOffsetY = this.scroller.currentOffset().yOffset;
  3361. // 判断滚动方向
  3362. if (currentOffsetY > this.prevOffsetY) {
  3363. // console.log("onecold 向上滚动");
  3364. this.isShowTitleBar = false
  3365. } else if (currentOffsetY < this.prevOffsetY) {
  3366. // console.log("onecold 向下滚动");
  3367. this.isShowTitleBar = true
  3368. }
  3369. // 更新前一次偏移量
  3370. this.prevOffsetY = currentOffsetY;
  3371. }
  3372. return { offsetRemain: offset };
  3373. })
  3374. }
  3375. setGridTwoFingers() {
  3376. this.pinchValue = this.scaleValue;
  3377. Logger.info('this.pinchValue = ' + this.pinchValue);
  3378. if (this.pinchValue >= 1) {
  3379. this.twoFingerType++
  3380. Logger.info('this.twoFingerType1 = ' + this.twoFingerType);
  3381. if(this.twoFingerType >= 4){
  3382. this.twoFingerType = 4//切换成瀑布流
  3383. this.columns = 4
  3384. }
  3385. } else {
  3386. this.twoFingerType--
  3387. Logger.info('this.twoFingerType2 = ' + this.twoFingerType);
  3388. if (this.twoFingerType < 1) {
  3389. this.twoFingerType = 3
  3390. this.isGridMusic = false
  3391. PreferencesUtil.put(SettingPage.IS_GRID_MUSIC, this.isGridMusic)
  3392. }
  3393. }
  3394. PreferencesUtil.put(SettingPage.TWO_FINGER_TYPE, this.twoFingerType)
  3395. PreferencesUtil.put(SettingPage.IS_GRID_MUSIC, this.isGridMusic)
  3396. this.pinchValue = 1;
  3397. this.scaleValue = 1;
  3398. }
  3399. @Builder
  3400. buildSongItemGrid(item: VideoItem, index: number) {
  3401. Button({ type: ButtonType.Normal, stateEffect: false }) {
  3402. Stack() {
  3403. Column() {
  3404. Image(item.pixelMapPath ? item.pixelMapPath : $r('app.media.nocover'))
  3405. .height(this.getGridHeight())
  3406. .width(this.getGridWight())
  3407. .draggable(false)
  3408. .interpolation(ImageInterpolation.High)// 用于重采样后的抗锯齿
  3409. .autoResize(true) // 重采样,可减少内存占用
  3410. .alt(item.type==CommonConstants.TYPE_IS_DIR?$r('app.media.dir_alt'):$r('app.media.alt'))
  3411. .clip(true)
  3412. .borderRadius({
  3413. topLeft: 12,
  3414. topRight: 12,
  3415. bottomLeft: 0,
  3416. bottomRight: 0
  3417. })
  3418. .draggable(false)
  3419. .animation({
  3420. duration: 666,
  3421. curve: 'ease-in-out' // 可选动画曲线
  3422. })
  3423. .margin({
  3424. left: 25,
  3425. right:25
  3426. })
  3427. Column() {
  3428. Text(item.name)
  3429. .fontSize(this.twoFingerType == 1 ? 12 : this.twoFingerType == 2 ? 15 : 18)
  3430. .maxLines(1)
  3431. .fontWeight(FontWeight.Bold)
  3432. .animation({
  3433. duration: 555,
  3434. curve: 'Linear',
  3435. })
  3436. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  3437. $r('app.color.text_color'))
  3438. Column() {
  3439. // Text(`${this.getArtistSongCount(item.name)}首`)
  3440. // .fontSize(11)
  3441. // .fontSize(this.twoFingerType == 1 ? 10 : this.twoFingerType == 2 ? 12 : 14)
  3442. // .fontColor($r('app.color.text_color'))
  3443. // Text(`${this.getAlbumSongCount(item.name)}首`)
  3444. // .fontSize(11)
  3445. // .fontSize(this.twoFingerType == 1 ? 10 : this.twoFingerType == 2 ? 12 : 14)
  3446. // .fontColor($r('app.color.text_color'))
  3447. Row(){
  3448. Text((item.artist ?? '') + " ")
  3449. .fontSize(this.twoFingerType == 1 ? 10 : this.twoFingerType == 2 ? 12 : 13)
  3450. .maxLines(1)
  3451. .margin({ top: 2})
  3452. .visibility(item.type == CommonConstants.TYPE_IS_ARTIST
  3453. || item.type == CommonConstants.TYPE_IS_ALBUM
  3454. || item.type == CommonConstants.TYPE_IS_DIR ? Visibility.None : Visibility.Visible)
  3455. .fontWeight(FontWeight.Medium)
  3456. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor :
  3457. $r('app.color.text_color'))
  3458. }
  3459. }
  3460. .alignItems(HorizontalAlign.Center) // 关键:使内容水平居中
  3461. }
  3462. .height(this.twoFingerType == 3 ? 60 : this.twoFingerType == 2 ? 48 : 35)
  3463. .width(this.getGridWight())
  3464. .justifyContent(FlexAlign.Center)
  3465. .margin({
  3466. left: 25,
  3467. right: 25
  3468. })
  3469. }
  3470. .width(this.getGridWight())
  3471. .borderRadius(12)
  3472. .backgroundColor(this.isDarkMode ? '#141414' : '#F7F7F7')
  3473. .animation({ curve: Curve.Sharp, duration: 300 })
  3474. }
  3475. }
  3476. .backgroundColor(Color.Transparent)
  3477. .width('100%')
  3478. .padding({ top: 15 })
  3479. .height(this.getGridAllHeight())
  3480. .onClick(() => {
  3481. this.playSong(item, index);
  3482. })
  3483. }
  3484. getGridAllHeight() {
  3485. let heightG = 222
  3486. switch (this.twoFingerType) {
  3487. case 1:
  3488. heightG = 143
  3489. break;
  3490. case 2:
  3491. heightG = 178
  3492. break;
  3493. case 3:
  3494. heightG = 222
  3495. break;
  3496. }
  3497. return heightG
  3498. }
  3499. getGridHeight() {
  3500. let heightG = 150
  3501. switch (this.twoFingerType) {
  3502. case 1:
  3503. heightG = 80
  3504. break;
  3505. case 2:
  3506. heightG = 110
  3507. break;
  3508. case 3:
  3509. heightG = 150
  3510. break;
  3511. }
  3512. return heightG
  3513. }
  3514. getGridWight() {
  3515. let wightG = 158
  3516. switch (this.twoFingerType) {
  3517. case 1:
  3518. wightG = 80
  3519. break;
  3520. case 2:
  3521. wightG = 110
  3522. break;
  3523. case 3:
  3524. wightG = 158
  3525. break;
  3526. }
  3527. return wightG
  3528. }
  3529. @Builder
  3530. buildArtistItemGrid(artist: NavidromeRestArtist) {
  3531. Button({ type: ButtonType.Normal, stateEffect: false }) {
  3532. Stack() {
  3533. Column() {
  3534. Image(artist.coverUrl ?? $r('app.media.nocover'))
  3535. .height(this.getGridHeight())
  3536. .width(this.getGridWight())
  3537. .draggable(false)
  3538. .interpolation(ImageInterpolation.High)
  3539. .autoResize(true)
  3540. .alt($r('app.media.nocover'))
  3541. .clip(true)
  3542. .borderRadius({
  3543. topLeft: 12,
  3544. topRight: 12,
  3545. bottomLeft: 0,
  3546. bottomRight: 0
  3547. })
  3548. .draggable(false)
  3549. .animation({
  3550. duration: 666,
  3551. curve: 'ease-in-out'
  3552. })
  3553. .margin({
  3554. left: 25,
  3555. right: 25
  3556. })
  3557. .sourceSize({ width: 200, height: 200 })
  3558. .fillColor(artist.coverUrl ? undefined : this.themeColor)
  3559. .objectFit(ImageFit.Cover)
  3560. Column() {
  3561. Text(artist.name ?? Constants.UNKNOWN_ARTIST)
  3562. .fontSize(this.twoFingerType == 1 ? 12 : this.twoFingerType == 2 ? 15 : 18)
  3563. .maxLines(1)
  3564. .fontWeight(FontWeight.Bold)
  3565. .fontColor($r('app.color.text_color'))
  3566. .textOverflow({ overflow: TextOverflow.Ellipsis })
  3567. .animation({
  3568. duration: 555,
  3569. curve: 'Linear',
  3570. })
  3571. Column() {
  3572. Row() {
  3573. Text(this.buildArtistMetaLine(artist))
  3574. .fontSize(this.twoFingerType == 1 ? 10 : this.twoFingerType == 2 ? 12 : 13)
  3575. .maxLines(1)
  3576. .margin({ top: 2 })
  3577. .fontWeight(FontWeight.Medium)
  3578. .fontColor($r('app.color.text_color'))
  3579. .opacity(0.6)
  3580. .textOverflow({ overflow: TextOverflow.Ellipsis })
  3581. .visibility((artist.albumCount ?? 0) === 0 && (artist.songCount ?? 0) === 0 ? Visibility.None : Visibility.Visible)
  3582. }
  3583. }
  3584. .alignItems(HorizontalAlign.Center)
  3585. }
  3586. .height(this.twoFingerType == 3 ? 60 : this.twoFingerType == 2 ? 48 : 35)
  3587. .width(this.getGridWight())
  3588. .justifyContent(FlexAlign.Center)
  3589. .margin({
  3590. left: 25,
  3591. right: 25
  3592. })
  3593. }
  3594. .width(this.getGridWight())
  3595. .borderRadius(12)
  3596. .backgroundColor(this.isDarkMode ? '#141414' : '#F7F7F7')
  3597. .animation({ curve: Curve.Sharp, duration: 300 })
  3598. }
  3599. }
  3600. .backgroundColor(Color.Transparent)
  3601. .width('100%')
  3602. .padding({ top: 15 })
  3603. .height(this.getGridAllHeight())
  3604. .onClick(() => {
  3605. this.onArtistSelected(artist);
  3606. })
  3607. }
  3608. @Builder
  3609. buildAlbumItemGrid(album: NavidromeRestAlbum) {
  3610. Button({ type: ButtonType.Normal, stateEffect: false }) {
  3611. Stack() {
  3612. Column() {
  3613. Image(album.coverUrl ?? $r('app.media.nocover'))
  3614. .height(this.getGridHeight())
  3615. .width(this.getGridWight())
  3616. .draggable(false)
  3617. .interpolation(ImageInterpolation.High)
  3618. .autoResize(true)
  3619. .alt($r('app.media.nocover'))
  3620. .clip(true)
  3621. .borderRadius({
  3622. topLeft: 12,
  3623. topRight: 12,
  3624. bottomLeft: 0,
  3625. bottomRight: 0
  3626. })
  3627. .draggable(false)
  3628. .animation({
  3629. duration: 666,
  3630. curve: 'ease-in-out'
  3631. })
  3632. .margin({
  3633. left: 25,
  3634. right: 25
  3635. })
  3636. .sourceSize({ width: 200, height: 200 })
  3637. .fillColor(album.coverUrl ? undefined : this.themeColor)
  3638. .objectFit(ImageFit.Cover)
  3639. Column() {
  3640. Text(album.name ?? '未知专辑')
  3641. .fontSize(this.twoFingerType == 1 ? 12 : this.twoFingerType == 2 ? 15 : 18)
  3642. .maxLines(1)
  3643. .fontWeight(FontWeight.Bold)
  3644. .fontColor($r('app.color.text_color'))
  3645. .textOverflow({ overflow: TextOverflow.Ellipsis })
  3646. .animation({
  3647. duration: 555,
  3648. curve: 'Linear',
  3649. })
  3650. Column() {
  3651. Row() {
  3652. Text(album.artist ?? Constants.UNKNOWN_ARTIST)
  3653. .fontSize(this.twoFingerType == 1 ? 10 : this.twoFingerType == 2 ? 12 : 13)
  3654. .maxLines(1)
  3655. .margin({ top: 2 })
  3656. .fontWeight(FontWeight.Medium)
  3657. .fontColor($r('app.color.text_color'))
  3658. .opacity(0.6)
  3659. .textOverflow({ overflow: TextOverflow.Ellipsis })
  3660. }
  3661. }
  3662. .alignItems(HorizontalAlign.Center)
  3663. }
  3664. .height(this.twoFingerType == 3 ? 60 : this.twoFingerType == 2 ? 48 : 35)
  3665. .width(this.getGridWight())
  3666. .justifyContent(FlexAlign.Center)
  3667. .margin({
  3668. left: 25,
  3669. right: 25
  3670. })
  3671. }
  3672. .width(this.getGridWight())
  3673. .borderRadius(12)
  3674. .backgroundColor(this.isDarkMode ? '#141414' : '#F7F7F7')
  3675. .animation({ curve: Curve.Sharp, duration: 300 })
  3676. }
  3677. }
  3678. .backgroundColor(Color.Transparent)
  3679. .width('100%')
  3680. .padding({ top: 15 })
  3681. .height(this.getGridAllHeight())
  3682. .onClick(() => {
  3683. this.onAlbumSelected(album);
  3684. })
  3685. }
  3686. @Builder
  3687. buildPlaylistItemGrid(playlist: NavidromeRestPlaylist) {
  3688. Button({ type: ButtonType.Normal, stateEffect: false }) {
  3689. Stack() {
  3690. Column() {
  3691. Image(playlist.coverUrl ?? $r('app.media.nocover'))
  3692. .height(this.getGridHeight())
  3693. .width(this.getGridWight())
  3694. .draggable(false)
  3695. .interpolation(ImageInterpolation.High)
  3696. .autoResize(true)
  3697. .alt($r('app.media.nocover'))
  3698. .clip(true)
  3699. .borderRadius({
  3700. topLeft: 12,
  3701. topRight: 12,
  3702. bottomLeft: 0,
  3703. bottomRight: 0
  3704. })
  3705. .draggable(false)
  3706. .animation({
  3707. duration: 666,
  3708. curve: 'ease-in-out'
  3709. })
  3710. .margin({
  3711. left: 25,
  3712. right: 25
  3713. })
  3714. .sourceSize({ width: 200, height: 200 })
  3715. .fillColor(playlist.coverUrl ? undefined : this.themeColor)
  3716. .objectFit(ImageFit.Cover)
  3717. Column() {
  3718. Text(playlist.name ?? '未知歌单')
  3719. .fontSize(this.twoFingerType == 1 ? 12 : this.twoFingerType == 2 ? 15 : 18)
  3720. .maxLines(1)
  3721. .fontWeight(FontWeight.Bold)
  3722. .fontColor($r('app.color.text_color'))
  3723. .textOverflow({ overflow: TextOverflow.Ellipsis })
  3724. .animation({
  3725. duration: 555,
  3726. curve: 'Linear',
  3727. })
  3728. Column() {
  3729. Row() {
  3730. Text(this.buildPlaylistMetaLine(playlist))
  3731. .fontSize(this.twoFingerType == 1 ? 10 : this.twoFingerType == 2 ? 12 : 13)
  3732. .maxLines(1)
  3733. .margin({ top: 2 })
  3734. .fontWeight(FontWeight.Medium)
  3735. .fontColor($r('app.color.text_color'))
  3736. .opacity(0.6)
  3737. .textOverflow({ overflow: TextOverflow.Ellipsis })
  3738. }
  3739. }
  3740. .alignItems(HorizontalAlign.Center)
  3741. }
  3742. .height(this.twoFingerType == 3 ? 60 : this.twoFingerType == 2 ? 48 : 35)
  3743. .width(this.getGridWight())
  3744. .justifyContent(FlexAlign.Center)
  3745. .margin({
  3746. left: 25,
  3747. right: 25
  3748. })
  3749. }
  3750. .width(this.getGridWight())
  3751. .borderRadius(12)
  3752. .backgroundColor(this.isDarkMode ? '#141414' : '#F7F7F7')
  3753. .animation({ curve: Curve.Sharp, duration: 300 })
  3754. }
  3755. }
  3756. .backgroundColor(Color.Transparent)
  3757. .width('100%')
  3758. .padding({ top: 15 })
  3759. .height(this.getGridAllHeight())
  3760. .onClick(() => {
  3761. this.onPlaylistSelected(playlist);
  3762. })
  3763. }
  3764. @Builder
  3765. getListView() {
  3766. List({scroller:this.scroller, space: 8 }) {
  3767. // 详情视图模式下显示筛选后的歌曲,否则根据标签页显示对应内容
  3768. if (this.selectedTab === 0||this.isDetailView) {
  3769. LazyForEach(this.songDataSource, (item: VideoItem, index: number) => {
  3770. ListItem() {
  3771. this.buildSongItem(item, index)
  3772. }
  3773. }, (item: VideoItem) => item.id)
  3774. } else if (this.selectedTab === 1) {
  3775. LazyForEach(this.artistDataSource, (artist: NavidromeRestArtist) => {
  3776. ListItem() {
  3777. this.buildArtistItem(artist)
  3778. }
  3779. }, (artist: NavidromeRestArtist) => artist.id)
  3780. } else if (this.selectedTab === 2) {
  3781. LazyForEach(this.albumDataSource, (album: NavidromeRestAlbum) => {
  3782. ListItem() {
  3783. this.buildAlbumItem(album)
  3784. }
  3785. }, (album: NavidromeRestAlbum) => album.id)
  3786. } else if (this.selectedTab === 3) {
  3787. LazyForEach(this.playlistDataSource, (playlist: NavidromeRestPlaylist) => {
  3788. ListItem() {
  3789. this.buildPlaylistItem(playlist)
  3790. }
  3791. }, (playlist: NavidromeRestPlaylist) => playlist.id)
  3792. }
  3793. }
  3794. .onScrollFrameBegin((offset: number) => {
  3795. // 获取当前滚动偏移量
  3796. if(this.autoHideTitle){
  3797. const currentOffsetY = this.scroller.currentOffset().yOffset;
  3798. // 判断滚动方向
  3799. if (currentOffsetY > this.prevOffsetY) {
  3800. this.isShowTitleBar = false
  3801. } else if (currentOffsetY < this.prevOffsetY) {
  3802. this.isShowTitleBar = true
  3803. }
  3804. // 更新前一次偏移量
  3805. this.prevOffsetY = currentOffsetY;
  3806. }
  3807. return { offsetRemain: offset };
  3808. })
  3809. .width('100%')
  3810. .height('100%')
  3811. .layoutWeight(1)
  3812. .cachedCount(3)
  3813. .padding({ top: 5, bottom: 5 })
  3814. .listDirection(Axis.Vertical)
  3815. .contentEndOffset(this.bottomSafeHeight+70)
  3816. .contentStartOffset(this.topSafeHeight + 98)
  3817. .scrollBar(BarState.Auto)
  3818. .scale({ x: this.scaleValue, y: this.scaleValue, z: 1 })
  3819. .edgeEffect(EdgeEffect.Spring)
  3820. .gesture(PinchGesture({ fingers: 2 })
  3821. .onActionEnd((event: GestureEvent) => {
  3822. this.setlistTwoFingers()
  3823. })
  3824. .onActionUpdate(e => {
  3825. this.scaleValue = this.pinchValue * e.scale
  3826. })
  3827. )
  3828. .onReachEnd(() => {
  3829. void this.handleReachEnd();
  3830. })
  3831. }
  3832. // ==================== 双指缩放切换视图功能 ====================
  3833. // 双指缩放切换 List/Grid/WaterFlow
  3834. setlistTwoFingers() {
  3835. this.pinchValue = this.scaleValue;
  3836. Logger.info('this.pinchValue = ' + this.pinchValue);
  3837. if (this.pinchValue >= 1) {
  3838. this.twoFingerType++
  3839. Logger.info('this.twoFingerType1 = ' + this.twoFingerType);
  3840. if (this.twoFingerType > 3) {
  3841. this.twoFingerType = 1
  3842. this.isGridMusic = true
  3843. PreferencesUtil.put(SettingPage.IS_GRID_MUSIC, this.isGridMusic)
  3844. }
  3845. } else {
  3846. this.twoFingerType--
  3847. Logger.info('this.twoFingerType2 = ' + this.twoFingerType);
  3848. if (this.twoFingerType < 1) {
  3849. this.twoFingerType = 4
  3850. this.columns = 1
  3851. }
  3852. }
  3853. PreferencesUtil.put(SettingPage.TWO_FINGER_TYPE, this.twoFingerType)
  3854. PreferencesUtil.put(SettingPage.IS_GRID_MUSIC, this.isGridMusic)
  3855. this.pinchValue = 1;
  3856. this.scaleValue = 1;
  3857. }
  3858. // WaterFlow 列数切换
  3859. private columnChanged: boolean = false;
  3860. private oldColumn: number = 4;
  3861. changeColumns(scale: number): void {
  3862. if (scale > (this.columns / (this.columns - 0.5)) && this.columns > 1) {
  3863. this.columns--;
  3864. this.columnChanged = true;
  3865. } else if (scale < ((this.columns - 1) / this.columns) && this.columns < 6) {
  3866. this.columns++;
  3867. this.columnChanged = true;
  3868. }
  3869. }
  3870. build() {
  3871. Stack() {
  3872. Column() {
  3873. this.buildContentView()
  3874. }
  3875. .height('100%')
  3876. Column() {
  3877. this.topTitleBar()
  3878. }
  3879. }
  3880. .alignContent(Alignment.Top)
  3881. .width('100%')
  3882. .height('100%')
  3883. .backgroundImage(this.isCustomizeBg?this.customizeBgPath:$r('app.color.start_window_background'))
  3884. .backgroundImageSize(this.isLandscape?{width:'100%'}:{ height: '100%'})
  3885. .backgroundImagePosition(Alignment.Center)
  3886. .backdropBlur(this.blurValue)
  3887. .backgroundBrightness({rate:this.isCustomizeBg?0.1:0,lightUpDegree:this.bgBrightness})
  3888. .expandSafeArea([SafeAreaType.SYSTEM], [SafeAreaEdge.BOTTOM])
  3889. }
  3890. @Builder
  3891. getWaterView(){
  3892. Scroll(this.scroller) {
  3893. Column() {
  3894. if(!this.isWaterFlowScrolling&&(this.isShowTitleBar || !this.autoHideTitle)){
  3895. Blank().height(this.topSafeHeight + 115)
  3896. }
  3897. WaterFlow({
  3898. scroller:this.waterScroller,
  3899. layoutMode: WaterFlowLayoutMode.SLIDING_WINDOW
  3900. }) {
  3901. if (this.selectedTab === 0) {
  3902. // 歌曲瀑布流
  3903. LazyForEach(this.songDataSource, (item: VideoItem, index: number) => {
  3904. FlowItem() {
  3905. this.buildSongWaterCardItem(item, index)
  3906. }
  3907. .width('100%')
  3908. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.9 })
  3909. }, (item: VideoItem) => item.id)
  3910. } else if (this.selectedTab === 1) {
  3911. // 艺术家瀑布流
  3912. LazyForEach(this.artistDataSource, (artist: NavidromeRestArtist) => {
  3913. FlowItem() {
  3914. this.buildArtistWaterCardItem(artist)
  3915. }
  3916. .width('100%')
  3917. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.9 })
  3918. }, (artist: NavidromeRestArtist) => artist.id)
  3919. } else if (this.selectedTab === 2) {
  3920. // 专辑瀑布流
  3921. LazyForEach(this.albumDataSource, (album: NavidromeRestAlbum) => {
  3922. FlowItem() {
  3923. this.buildAlbumWaterCardItem(album)
  3924. }
  3925. .width('100%')
  3926. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.9 })
  3927. }, (album: NavidromeRestAlbum) => album.id)
  3928. } else if (this.selectedTab === 3) {
  3929. // 歌单瀑布流
  3930. LazyForEach(this.playlistDataSource, (playlist: NavidromeRestPlaylist) => {
  3931. FlowItem() {
  3932. this.buildPlaylistWaterCardItem(playlist)
  3933. }
  3934. .width('100%')
  3935. .clickEffect({ level: ClickEffectLevel.LIGHT, scale: 0.9 })
  3936. }, (playlist: NavidromeRestPlaylist) => playlist.id)
  3937. }
  3938. }
  3939. .id('waterflow') // 设置id用于截图
  3940. .columnsTemplate('1fr '.repeat(this.columns)) // 动态生成列模板,如:'1fr 1fr 1fr'表示3列等宽
  3941. .columnsGap(12) // 列间距
  3942. .rowsGap(16) // 行间距
  3943. .cachedCount(6)
  3944. .padding({bottom:this.bottomSafeHeight+52})
  3945. .scrollBar(BarState.Off)
  3946. .edgeEffect(EdgeEffect.Spring, { alwaysEnabled: true })
  3947. .width('90%')
  3948. .height('100%')
  3949. .onReachEnd(() => {
  3950. // 触底加载下一页
  3951. Logger.info('heanup RemoteMusicPage', `WaterFlow onReachEnd`);
  3952. void this.handleReachEnd();
  3953. })
  3954. .onAppear(() => {
  3955. this.scroller.scrollEdge(Edge.Top)
  3956. })
  3957. .nestedScroll({
  3958. scrollForward: NestedScrollMode.PARENT_FIRST,
  3959. scrollBackward: NestedScrollMode.SELF_FIRST
  3960. })
  3961. .onScrollFrameBegin((offset: number) => {
  3962. // 获取当前滚动偏移量
  3963. this.isWaterFlowScrolling = true
  3964. if(this.autoHideTitle){
  3965. const currentOffsetY = this.waterScroller.currentOffset().yOffset;
  3966. // 判断滚动方向
  3967. if (currentOffsetY > this.prevOffsetY) {
  3968. // console.log("onecold 向上滚动");
  3969. this.isShowTitleBar = false
  3970. } else if (currentOffsetY < this.prevOffsetY) {
  3971. // console.log("onecold 向下滚动");
  3972. this.isShowTitleBar = true
  3973. }
  3974. // 更新前一次偏移量
  3975. this.prevOffsetY = currentOffsetY;
  3976. }
  3977. return { offsetRemain: offset };
  3978. })
  3979. .onScrollStop(() => {
  3980. // 滚动停止
  3981. this.isWaterFlowScrolling = false
  3982. })
  3983. .priorityGesture(
  3984. PinchGesture()
  3985. .onActionStart((event: GestureEvent) => {
  3986. // 双指捏合手势识别成功时截图
  3987. this.pinchValue = this.scaleValue;
  3988. this.columnChanged = false;
  3989. this.oldColumn = this.columns;
  3990. this.getUIContext().getComponentSnapshot().get('waterflow', (error: Error, pixmap: PixelMap) => {
  3991. if (error) {
  3992. console.info('error:' + JSON.stringify(error));
  3993. return;
  3994. }
  3995. if ((this.oldColumn === 1 ) && event.scale > 1|| (this.oldColumn === 4 && event.scale < 1)) {
  3996. console.info("onecold onActionStart oldColumn:" + this.oldColumn)
  3997. if (this.oldColumn ===4) {
  3998. this.twoFingerType =3
  3999. this.isGridMusic = true
  4000. }else if (this.oldColumn ===1) {
  4001. this.twoFingerType =1
  4002. this.isGridMusic = false
  4003. }
  4004. PreferencesUtil.put(SettingPage.TWO_FINGER_TYPE, this.twoFingerType)
  4005. PreferencesUtil.put(SettingPage.IS_GRID_MUSIC, this.isGridMusic)
  4006. return;
  4007. }
  4008. })
  4009. })
  4010. .onActionUpdate((event: GestureEvent) => {
  4011. // 缩放比例小于1时(缩小),增加列数;大于1时(放大),减少列数
  4012. if (event.scale > 1) {
  4013. // 放大,减少列数
  4014. if (this.columns > 1 && this.columnChanged === false) {
  4015. if (event.scale > 1.25) {
  4016. this.columns = Math.max(1, this.columns - 1);
  4017. this.columnChanged = true;
  4018. console.info("onecold onActionUpdate columns111:" + this.columns)
  4019. }
  4020. }
  4021. } else {
  4022. // 缩小,增加列数
  4023. if (this.columns < 6 && this.columnChanged === false) {
  4024. if (event.scale < 0.8) {
  4025. this.columns = Math.min(6, this.columns + 1);
  4026. this.columnChanged = true;
  4027. console.info("onecold onActionUpdate columns222:" + this.columns)
  4028. }
  4029. }
  4030. }
  4031. })
  4032. .onActionEnd((event: GestureEvent) => {
  4033. const currentTimestamp: number = event.timestamp;
  4034. if (currentTimestamp - this.pinchValue < 300) {
  4035. console.info("onecold onActionEnd 快速操作,不保存");
  4036. this.columnChanged = false;
  4037. this.columns = this.oldColumn;
  4038. return;
  4039. }
  4040. if (this.columnChanged) {
  4041. if (this.columns === 1) {
  4042. this.twoFingerType = 1
  4043. this.isGridMusic = false
  4044. PreferencesUtil.put(SettingPage.TWO_FINGER_TYPE, this.twoFingerType)
  4045. PreferencesUtil.put(SettingPage.IS_GRID_MUSIC, this.isGridMusic)
  4046. } else if (this.columns === 6) {
  4047. this.twoFingerType = 3
  4048. this.isGridMusic = true
  4049. PreferencesUtil.put(SettingPage.TWO_FINGER_TYPE, this.twoFingerType)
  4050. PreferencesUtil.put(SettingPage.IS_GRID_MUSIC, this.isGridMusic)
  4051. } else {
  4052. this.twoFingerType = 4
  4053. this.isGridMusic = true
  4054. PreferencesUtil.put(SettingPage.TWO_FINGER_TYPE, this.twoFingerType)
  4055. PreferencesUtil.put(SettingPage.IS_GRID_MUSIC, this.isGridMusic)
  4056. }
  4057. Logger.info('heanup RemoteMusicPage', '列数已切换为:' + this.columns)
  4058. }
  4059. this.columnChanged = false;
  4060. })
  4061. )
  4062. }
  4063. .width('100%')
  4064. .height('100%')
  4065. }
  4066. .width('100%')
  4067. .height('100%')
  4068. .scrollBar(BarState.Off)
  4069. .edgeEffect(EdgeEffect.Spring)
  4070. .visibility(this.twoFingerType == 4 ? Visibility.Visible : Visibility.None)
  4071. }
  4072. // 歌曲瀑布流卡片项
  4073. @Builder
  4074. buildSongWaterCardItem(item: VideoItem, index: number) {
  4075. Button({ type: ButtonType.Normal, stateEffect: false }) {
  4076. Stack() {
  4077. Column() {
  4078. Image(item.pixelMapPath ? item.pixelMapPath : $r('app.media.alt'))
  4079. .backgroundImageSize(ImageSize.Auto)
  4080. .borderRadius({
  4081. topLeft: 12,
  4082. topRight: 12,
  4083. bottomLeft: 0,
  4084. bottomRight: 0
  4085. })
  4086. .draggable(false)
  4087. .autoResize(true)
  4088. .interpolation(ImageInterpolation.High)
  4089. .width('100%')
  4090. .height('auto')
  4091. .alt($r('app.media.alt'))
  4092. .objectFit(ImageFit.Auto)
  4093. .animation({
  4094. duration: 666,
  4095. curve: 'ease-in-out'
  4096. })
  4097. .margin({
  4098. left: 20,
  4099. right: 20
  4100. })
  4101. Column() {
  4102. Text(item.name.startsWith('.') ? item.name.replace(/\./g, '') : item.name)
  4103. .fontSize(this.columns == 4 || this.columns == 3 ? 12 : this.columns == 2 ? 15 : 18)
  4104. .maxLines(1)
  4105. .fontWeight(FontWeight.Bold)
  4106. .textOverflow({ overflow: TextOverflow.Ellipsis })
  4107. .animation({
  4108. duration: 555,
  4109. curve: 'Linear',
  4110. })
  4111. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor : $r('app.color.text_color'))
  4112. Row() {
  4113. Text(item.artist || '')
  4114. .fontSize(this.columns == 4 || this.columns == 3 ? 10 : this.columns == 2 ? 12 : 13)
  4115. .maxLines(1)
  4116. .textOverflow({ overflow: TextOverflow.Ellipsis })
  4117. .margin({ top: 2 })
  4118. .fontWeight(FontWeight.Medium)
  4119. .fontColor(this.currentSong?.filePath === item.filePath ? this.themeColor : $r('app.color.text_color'))
  4120. }
  4121. .alignItems(VerticalAlign.Center)
  4122. }
  4123. .height(this.columns == 4 || this.columns == 3 ? 40 : this.columns == 2 ? 48 : 58)
  4124. .width('100%')
  4125. .alignItems(HorizontalAlign.Center) // 关键:使内容水平居中
  4126. .justifyContent(FlexAlign.Center)
  4127. .margin({
  4128. left: 20,
  4129. right: 20
  4130. })
  4131. }
  4132. .width('100%')
  4133. .borderRadius(12)
  4134. .backgroundColor(this.isDarkMode ? '#141414' : '#F7F7F7')
  4135. .animation({ curve: Curve.Sharp, duration: 300 })
  4136. }
  4137. }
  4138. .reuseId('card_item')
  4139. .width('100%')
  4140. .shadow({
  4141. radius: 10,
  4142. type: ShadowType.BLUR,
  4143. color: 'on_primary'
  4144. })
  4145. .height('auto')
  4146. .onClick(() => {
  4147. this.playSong(item, index);
  4148. })
  4149. .backgroundColor(Color.Transparent)
  4150. }
  4151. // 艺术家瀑布流卡片项
  4152. @Builder
  4153. buildArtistWaterCardItem(artist: NavidromeRestArtist) {
  4154. Button({ type: ButtonType.Normal, stateEffect: false }) {
  4155. Stack() {
  4156. Column() {
  4157. Image(artist.coverUrl ?? $r('app.media.dir_alt'))
  4158. .objectFit(ImageFit.Auto)
  4159. .width('100%')
  4160. .draggable(false)
  4161. .interpolation(ImageInterpolation.High)
  4162. .autoResize(true)
  4163. .alt($r('app.media.dir_alt'))
  4164. .clip(true)
  4165. .borderRadius({
  4166. topLeft: 12,
  4167. topRight: 12,
  4168. bottomLeft: 0,
  4169. bottomRight: 0
  4170. })
  4171. .animation({
  4172. duration: 666,
  4173. curve: 'ease-in-out'
  4174. })
  4175. .sourceSize({ width: 200, height: 200 })
  4176. .fillColor(artist.coverUrl ? undefined : this.themeColor)
  4177. Column() {
  4178. Text(artist.name)
  4179. .fontSize(14)
  4180. .maxLines(1)
  4181. .fontWeight(FontWeight.Bold)
  4182. .textOverflow({ overflow: TextOverflow.Ellipsis })
  4183. .fontColor($r('app.color.text_color'))
  4184. if (artist.albumCount !== undefined) {
  4185. Text(`${artist.albumCount} 张专辑`)
  4186. .fontSize(11)
  4187. .fontColor($r('app.color.text_color'))
  4188. }
  4189. }
  4190. .padding(12)
  4191. .width('100%')
  4192. .height(48)
  4193. .alignItems(HorizontalAlign.Center)
  4194. }
  4195. .width('100%')
  4196. .borderRadius(12)
  4197. .backgroundColor(this.isDarkMode ? '#141414' : '#F7F7F7')
  4198. .animation({ curve: Curve.Sharp, duration: 300 })
  4199. }
  4200. }
  4201. .width('100%')
  4202. .shadow({
  4203. radius: 10,
  4204. type: ShadowType.BLUR,
  4205. color: 'on_primary'
  4206. })
  4207. .onClick(() => {
  4208. this.onArtistSelected(artist);
  4209. })
  4210. .backgroundColor(Color.Transparent)
  4211. }
  4212. // 专辑瀑布流卡片项
  4213. @Builder
  4214. buildAlbumWaterCardItem(album: NavidromeRestAlbum) {
  4215. Button({ type: ButtonType.Normal, stateEffect: false }) {
  4216. Stack() {
  4217. Column() {
  4218. Image(album.coverUrl ?? $r('app.media.dir_alt'))
  4219. .width('100%')
  4220. .height('auto')
  4221. .objectFit(ImageFit.Auto)
  4222. .draggable(false)
  4223. .interpolation(ImageInterpolation.High)
  4224. .autoResize(true)
  4225. .alt($r('app.media.dir_alt'))
  4226. .clip(true)
  4227. .borderRadius({
  4228. topLeft: 12,
  4229. topRight: 12,
  4230. bottomLeft: 0,
  4231. bottomRight: 0
  4232. })
  4233. .animation({
  4234. duration: 666,
  4235. curve: 'ease-in-out'
  4236. })
  4237. .sourceSize({ width: 200, height: 200 })
  4238. .fillColor(album.coverUrl ? undefined : this.themeColor)
  4239. Column() {
  4240. Text(album.name)
  4241. .fontSize(14)
  4242. .maxLines(1)
  4243. .fontWeight(FontWeight.Bold)
  4244. .textOverflow({ overflow: TextOverflow.Ellipsis })
  4245. .fontColor($r('app.color.text_color'))
  4246. Text(album.artist ?? '')
  4247. .fontSize(11)
  4248. .maxLines(1)
  4249. .textOverflow({ overflow: TextOverflow.Ellipsis })
  4250. .fontColor($r('app.color.text_color'))
  4251. }
  4252. .height(48)
  4253. .padding(12)
  4254. .width('100%')
  4255. .alignItems(HorizontalAlign.Center)
  4256. }
  4257. .width('100%')
  4258. .height('auto')
  4259. .borderRadius(12)
  4260. .backgroundColor(this.isDarkMode ? '#141414' : '#F7F7F7')
  4261. .animation({ curve: Curve.Sharp, duration: 300 })
  4262. }
  4263. }
  4264. .width('100%')
  4265. .shadow({
  4266. radius: 10,
  4267. type: ShadowType.BLUR,
  4268. color: 'on_primary'
  4269. })
  4270. .backgroundColor(Color.Transparent)
  4271. .onClick(() => {
  4272. this.onAlbumSelected(album);
  4273. })
  4274. }
  4275. // 歌单瀑布流卡片项
  4276. @Builder
  4277. buildPlaylistWaterCardItem(playlist: NavidromeRestPlaylist) {
  4278. Button({ type: ButtonType.Normal, stateEffect: false }) {
  4279. Stack() {
  4280. Column() {
  4281. Image(playlist.coverUrl ?? $r('app.media.dir_alt'))
  4282. .width('100%')
  4283. .objectFit(ImageFit.Auto)
  4284. .draggable(false)
  4285. .interpolation(ImageInterpolation.High)
  4286. .autoResize(true)
  4287. .alt($r('app.media.dir_alt'))
  4288. .clip(true)
  4289. .borderRadius({
  4290. topLeft: 12,
  4291. topRight: 12,
  4292. bottomLeft: 0,
  4293. bottomRight: 0
  4294. })
  4295. .animation({
  4296. duration: 666,
  4297. curve: 'ease-in-out'
  4298. })
  4299. .sourceSize({ width: 200, height: 200 })
  4300. .fillColor(playlist.coverUrl ? undefined : this.themeColor)
  4301. Column() {
  4302. Text(playlist.name)
  4303. .fontSize(14)
  4304. .maxLines(1)
  4305. .fontWeight(FontWeight.Bold)
  4306. .textOverflow({ overflow: TextOverflow.Ellipsis })
  4307. .fontColor($r('app.color.text_color'))
  4308. if (playlist.songCount !== undefined) {
  4309. Text(`${playlist.songCount} 首歌曲`)
  4310. .fontSize(11)
  4311. .fontColor($r('app.color.text_color'))
  4312. }
  4313. }
  4314. .padding(12)
  4315. .height(48)
  4316. .width('100%')
  4317. .alignItems(HorizontalAlign.Center)
  4318. }
  4319. .width('100%')
  4320. .borderRadius(12)
  4321. .backgroundColor(this.isDarkMode ? '#141414' : '#F7F7F7')
  4322. .animation({ curve: Curve.Sharp, duration: 300 })
  4323. }
  4324. }
  4325. .width('100%')
  4326. .shadow({
  4327. radius: 10,
  4328. type: ShadowType.BLUR,
  4329. color: 'on_primary'
  4330. })
  4331. .onClick(() => {
  4332. this.onPlaylistSelected(playlist);
  4333. })
  4334. .backgroundColor(Color.Transparent)
  4335. }
  4336. }
  4337. /**
  4338. * Navidrome 数据加载任务 (使用 taskpool 后台执行)
  4339. * 该函数在 worker 线程中运行,避免阻塞 UI 线程
  4340. */
  4341. @Concurrent
  4342. async function loadNavidromeDataTask(accountData: AccountData, ticket: number): Promise<TaskResult> {
  4343. const result: TaskResult = {
  4344. songs: [],
  4345. artists: [],
  4346. albums: [],
  4347. playlists: []
  4348. };
  4349. try {
  4350. // 从 AccountData 重建 WebDavAccount 对象 (用于 API 调用)
  4351. const account: WebDavAccount = new WebDavAccount();
  4352. account.id = accountData.id;
  4353. account.webType = accountData.webType;
  4354. account.host = accountData.host;
  4355. account.port = accountData.port;
  4356. account.account = accountData.account;
  4357. account.password = accountData.password;
  4358. account.enableHttps = accountData.enableHttps;
  4359. account.navidromeBasePath = accountData.navidromeBasePath;
  4360. account.jellyfinBasePath = accountData.jellyfinBasePath;
  4361. account.embyBasePath = accountData.embyBasePath;
  4362. account.name = accountData.name;
  4363. // 加载歌曲并转换成 VideoItem(包含封面)
  4364. let songNextStart: number | null = 0;
  4365. while (songNextStart !== null) {
  4366. const response: PagedResponse<NavidromeRestSong> = await navidromeRestApi.fetchSongPage(account, songNextStart);
  4367. const chunk: NavidromeRestSong[] = response.data ?? [];
  4368. if (chunk.length === 0) {
  4369. break;
  4370. }
  4371. // 转换歌曲为 VideoItem 并处理封面
  4372. for (let i = 0; i < chunk.length; i++) {
  4373. const song: NavidromeRestSong = chunk[i];
  4374. const title: string = song.title ?? Constants.UNKNOWN_TITLE;
  4375. // 获取库类型
  4376. let libraryType = CommonConstants.TYPE_NAVIDROME;
  4377. let libraryScheme = 'navidrome';
  4378. if (account.webType === RemoteDriveType.Jellyfin) {
  4379. libraryType = CommonConstants.TYPE_JELLYFIN;
  4380. libraryScheme = 'jellyfin';
  4381. } else if (account.webType === RemoteDriveType.Emby) {
  4382. libraryType = CommonConstants.TYPE_EMBY;
  4383. libraryScheme = 'emby';
  4384. }
  4385. const videoItem = new VideoItem(
  4386. title,
  4387. song.id,
  4388. `${libraryScheme}://${account.id ?? 0}/${song.id}`,
  4389. libraryType,
  4390. song.size ?? 0,
  4391. song.createdAt ?? '',
  4392. Utility.formatFSize(song.size ?? 0),
  4393. undefined,
  4394. song.artist ?? Constants.UNKNOWN_ARTIST,
  4395. song.album ?? '',
  4396. `${title}${song.suffix ? '.' + song.suffix : ''}`
  4397. );
  4398. // 设置时长
  4399. if (song.duration !== undefined && song.duration !== null && song.duration >= 0) {
  4400. const totalSeconds = Math.floor(song.duration);
  4401. const minutes = Math.floor(totalSeconds / 60);
  4402. const seconds = totalSeconds % 60;
  4403. const pad = (value: number) => value.toString().padStart(2, '0');
  4404. videoItem.duration = `${pad(minutes)}:${pad(seconds)}`;
  4405. }
  4406. videoItem.size = Utility.formatFSize(song.size ?? 0);
  4407. videoItem.bit_rate = song.bitRate ? song.bitRate.toString() : undefined;
  4408. videoItem.genre = song.genre;
  4409. videoItem.webdav_account_id = account.id?.toString();
  4410. videoItem.remote_rel_path = song.id;
  4411. videoItem.navArtistId = song.artistId;
  4412. videoItem.navAlbumId = song.albumId;
  4413. videoItem.lyricContent = song.lyrics;
  4414. if (song.track !== undefined && song.track !== null) {
  4415. videoItem.track = song.track.toString();
  4416. }
  4417. if (song.year !== undefined && song.year !== null) {
  4418. videoItem.year = song.year.toString();
  4419. }
  4420. if (song.contentType) {
  4421. videoItem.mimeType = song.contentType;
  4422. }
  4423. // 处理封面(在 worker 线程中调用 API)
  4424. let coverUrl: string | undefined = undefined;
  4425. try {
  4426. // 获取封面ID
  4427. const coverId = song.coverArt ?? song.coverArtId ?? song.id;
  4428. // 判断是否是 Navidrome 账号
  4429. const isNavidrome = account.webType === RemoteDriveType.Navidrome;
  4430. if (!isNavidrome) {
  4431. // Jellyfin/Emby 直接使用 albumId 或 id
  4432. const fallbackId = song.albumId ?? song.id;
  4433. coverUrl = await navidromeApi.buildCoverArtUrl(account, fallbackId, 300);
  4434. } else {
  4435. // Navidrome 优先使用直接封面路径
  4436. const embedArtPath = song.embedArtPath ?? song.coverArtPath;
  4437. if (embedArtPath) {
  4438. // 构建直接封面URL
  4439. const protocol = account.enableHttps ? 'https' : 'http';
  4440. const host = account.isUseLocalHost && account.localHost ? account.localHost : account.host;
  4441. const portPart = account.port && account.port !== 80 && account.port !== 443 ? `:${account.port}` : '';
  4442. const basePath = account.navidromeBasePath ?? '/rest';
  4443. // 移除 /rest 后缀
  4444. const apiBase = basePath.endsWith('/rest') ? basePath.slice(0, -5) : basePath;
  4445. coverUrl = `${protocol}://${host}${portPart}${apiBase}/embed/${embedArtPath}?${account.account}:${account.password}`;
  4446. } else {
  4447. // 使用封面API
  4448. coverUrl = await navidromeApi.buildCoverArtUrl(account, coverId, 300);
  4449. }
  4450. }
  4451. } catch (error) {
  4452. // 封面获取失败,忽略
  4453. }
  4454. videoItem.pixelMapPath = coverUrl;
  4455. result.songs.push(videoItem);
  4456. }
  4457. songNextStart = response.nextStart;
  4458. }
  4459. // 加载艺术家并处理封面
  4460. let artistNextStart: number | null = 0;
  4461. while (artistNextStart !== null) {
  4462. const response: PagedResponse<NavidromeRestArtist> = await navidromeRestApi.fetchArtistPage(account, artistNextStart);
  4463. const chunk: NavidromeRestArtist[] = response.data ?? [];
  4464. if (chunk.length === 0) {
  4465. break;
  4466. }
  4467. // 处理艺术家封面
  4468. for (let i = 0; i < chunk.length; i++) {
  4469. const artist = chunk[i];
  4470. // 尝试获取已有图片URL
  4471. let coverUrl: string | undefined = artist.mediumImageUrl ?? artist.largeImageUrl;
  4472. // 如果没有直接URL,生成封面URL
  4473. if (!coverUrl) {
  4474. const coverId = artist.coverArt ?? artist.coverArtId ?? (artist.id ? `ar-${artist.id}` : undefined);
  4475. try {
  4476. coverUrl = await navidromeApi.buildCoverArtUrl(account, coverId, 256);
  4477. } catch (error) {
  4478. // 封面生成失败,忽略
  4479. }
  4480. }
  4481. artist.coverUrl = coverUrl;
  4482. result.artists.push(artist);
  4483. }
  4484. artistNextStart = response.nextStart;
  4485. }
  4486. // 加载专辑并处理封面
  4487. let albumNextStart: number | null = 0;
  4488. while (albumNextStart !== null) {
  4489. const response: PagedResponse<NavidromeRestAlbum> = await navidromeRestApi.fetchAlbumPage(account, albumNextStart);
  4490. const chunk: NavidromeRestAlbum[] = response.data ?? [];
  4491. if (chunk.length === 0) {
  4492. break;
  4493. }
  4494. // 处理专辑封面
  4495. for (let i = 0; i < chunk.length; i++) {
  4496. const album = chunk[i];
  4497. // 专辑没有直接的 imageUrl 属性,需要生成封面URL
  4498. let coverUrl: string | undefined = undefined;
  4499. // 优先使用 embed 路径
  4500. if (album.embedArtPath) {
  4501. const protocol = account.enableHttps ? 'https' : 'http';
  4502. const host = account.isUseLocalHost && account.localHost ? account.localHost : account.host;
  4503. const portPart = account.port && account.port !== 80 && account.port !== 443 ? `:${account.port}` : '';
  4504. const basePath = account.navidromeBasePath ?? '/rest';
  4505. const apiBase = basePath.endsWith('/rest') ? basePath.slice(0, -5) : basePath;
  4506. coverUrl = `${protocol}://${host}${portPart}${apiBase}/embed/${album.embedArtPath}?${account.account}:${account.password}`;
  4507. }
  4508. // 如果没有 embed 路径,使用封面API
  4509. if (!coverUrl) {
  4510. const coverId = album.coverArt ?? album.coverArtId ?? album.id;
  4511. try {
  4512. coverUrl = await navidromeApi.buildCoverArtUrl(account, coverId, 300);
  4513. } catch (error) {
  4514. // 封面生成失败,忽略
  4515. }
  4516. }
  4517. album.coverUrl = coverUrl;
  4518. result.albums.push(album);
  4519. }
  4520. albumNextStart = response.nextStart;
  4521. }
  4522. // 加载歌单
  4523. let playlistNextStart: number | null = 0;
  4524. while (playlistNextStart !== null) {
  4525. const response: PagedResponse<NavidromeRestPlaylist> = await navidromeRestApi.fetchPlaylistPage(account, playlistNextStart);
  4526. const chunk: NavidromeRestPlaylist[] = response.data ?? [];
  4527. if (chunk.length === 0) {
  4528. break;
  4529. }
  4530. // 使用循环代替展开运算符
  4531. for (let i = 0; i < chunk.length; i++) {
  4532. result.playlists.push(chunk[i]);
  4533. }
  4534. playlistNextStart = response.nextStart;
  4535. }
  4536. } catch (error) {
  4537. Logger.error('NavidromeTask', `后台加载数据失败: ${(error as Error).message}`);
  4538. }
  4539. return result;
  4540. }