RemoteMusicPage.ets 200 KB

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