RemoteMusicPage.ets 206 KB

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